(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.RecordingSelectorDialog = function(app, recordings, selectedRecordings, selectCallback) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var recordingUtils = context.JK.RecordingUtils;
    var $dialog = null;
    var dialogId = 'recording-selector-dialog';
    var $screen = $('#' + dialogId);
    var $btnSelect = $screen.find(".btn-select-recordings");
    var $instructions = $screen.find('#instructions');
    var $recordings = $screen.find('.recordings');
    var feedHelper = new context.JK.Feed(app);

    function beforeShow(data) {
    }

    function afterShow(data) {

      $recordings.empty();

      $.each(recordings, function(index, val) {
        bindRecordingItem(val);
      });

      // hide the avatars
      $screen.find('.avatar-small.ib').hide();
    }

    /********* THE FOLLOWING BLOCK IS REPEATED IN feedHelper.js **********/
    function startRecordingPlay($feedItem) {
      var img = $('.play-icon', $feedItem);
      var $controls = $feedItem.find('.recording-controls');
      img.attr('src', '/assets/content/icon_pausebutton.png');
      $controls.trigger('play.listenRecording');
      $feedItem.data('playing', true);
    }

    function stopRecordingPlay($feedItem) {
      var img = $('.play-icon', $feedItem);
      var $controls = $feedItem.find('.recording-controls');
      img.attr('src', '/assets/content/icon_playbutton.png');
      $controls.trigger('pause.listenRecording');
      $feedItem.data('playing', false);
    }

    function toggleRecordingPlay() {

      var $playLink = $(this);
      var $feedItem = $playLink.closest('.feed-entry');
      var playing = $feedItem.data('playing');

      if(playing) {
        stopRecordingPlay($feedItem);
      }
      else {
        startRecordingPlay($feedItem);
      }
      return false;
    }

    function toggleRecordingDetails() {
      var $detailsLink = $(this);
      var $feedItem = $detailsLink.closest('.feed-entry');
      var $musicians = $feedItem.find('.musician-detail');
      var $description = $feedItem.find('.description');
      var $name = $feedItem.find('.name');
      var toggledOpen = $detailsLink.data('toggledOpen');

      if(toggledOpen) {
        toggleClose($feedItem, $name, $description, $musicians)
      }
      else {
        toggleOpen($feedItem, $name, $description, $musicians)
      }

      toggledOpen = !toggledOpen;
      $detailsLink.data('toggledOpen', toggledOpen);

      return false;
    }

    function stateChangeRecording(e, data) {
      var $controls = data.element;
      var $feedItem = $controls.closest('.feed-entry');

      var $sliderBar      = $('.recording-position', $feedItem);
      var $statusBar      = $('.recording-status', $feedItem);
      var $currentTime    = $('.recording-current', $feedItem);
      var $status         = $('.status-text', $feedItem);
      var $playButton     = $('.play-button', $feedItem);

      if(data.isEnd) stopRecordingPlay($feedItem);
      if(data.isError) {
        $sliderBar.hide();
        $playButton.hide();
        $currentTime.hide();
        $statusBar.show();
        $status.text(data.displayText);
      }
    }

    function toggleOpen($feedItem, $name, $description, $musicians) {
      $description.trigger('destroy.dot');
      $description.data('original-height', $description.css('height')).css('height', 'auto');
      $name.trigger('destroy.dot');
      $name.data('original-height', $name.css('height')).css('height', 'auto');
      $musicians.show();
      $feedItem.animate({'max-height': '1000px'});
    }

    function toggleClose($feedItem, $name, $description, $musicians, immediate) {
      $feedItem.css('height', $feedItem.height() + 'px')
      $feedItem.animate({'height': $feedItem.data('original-max-height')}, immediate ? 0 : 400).promise().done(function() {
        $feedItem.css('height', 'auto').css('max-height', $feedItem.data('original-max-height'));

        $musicians.hide();
        $description.css('height', $description.data('original-height'));
        $description.dotdotdot();
        $name.css('height', $name.data('original-height'));
        $name.dotdotdot();
      });
    }
    /**********************************************************/

    function bindRecordingItem(claimedRecording) {
      claimedRecording.recording.mix_info = recordingUtils.createMixInfo({state: claimedRecording.recording.mix_state});
      var options = {
        feed_item: claimedRecording.recording,
        candidate_claimed_recording: claimedRecording,
        mix_class: claimedRecording['has_mix?'] ? 'has-mix' : 'no-mix',
      };

      var $feedItem = $(context._.template($('#template-feed-recording').html(), options, {variable: 'data'}));
      var $controls = $feedItem.find('.recording-controls');

      var $titleText = $feedItem.find('.title .title-text');

      // if this item will be discarded, tack on a * to the RECORDING NAME
      var discardTime = claimedRecording.recording['when_will_be_discarded?'];
      if(discardTime) {
        context.JK.helpBubble($titleText, 'recording-discarded-soon', {discardTime: discardTime}, {});
        $titleText.text($titleText.text() + '*');
      }

      $controls.data('mix-state', claimedRecording.recording.mix_info); // for recordingUtils helper methods
      $controls.data('server-info', claimedRecording.recording.mix); // for recordingUtils helper methods
      $controls.data('view-context', 'feed');

      $('.timeago', $feedItem).timeago();
      context.JK.prettyPrintElements($('.duration', $feedItem));
      context.JK.setInstrumentAssetPath($('.instrument-icon', $feedItem));
      $('.details', $feedItem).click(toggleRecordingDetails);
      $('.details-arrow', $feedItem).click(toggleRecordingDetails);
      $('.play-button', $feedItem).click(toggleRecordingPlay);

      var checked = '';

      var match = $.grep(selectedRecordings, function(obj, index) {
        return obj.claimed_recording_id === claimedRecording.id;
      });

      if (match && match.length > 0) {
        checked = 'checked';
      }

      // put the item on the page
      $recordings.append("<div class='left'><input type='checkbox' " + checked + " data-recording-id='" + claimedRecording.id + "' data-recording-title='" + claimedRecording.name + "' />");
      $recordings.append($feedItem);

      // these routines need the item to have height to work (must be after renderFeed)
      $controls.listenRecording({recordingId: claimedRecording.recording.id, claimedRecordingId: options.candidate_claimed_recording.id, sliderSelector:'.recording-slider', sliderBarSelector: '.recording-playback', currentTimeSelector:'.recording-current'});
      $controls.bind('statechange.listenRecording', stateChangeRecording);
      $('.dotdotdot', $feedItem).dotdotdot();
      $feedItem.data('original-max-height', $feedItem.css('height'));
      context.JK.bindHoverEvents($feedItem);
      context.JK.bindProfileClickEvents($feedItem);
    }

    function afterHide() {
    }

    function showDialog() {
      return app.layout.showDialog(dialogId);
    }

    function events() {
      $btnSelect.click(function(evt) {
        evt.preventDefault();
        var preSelectedRecordings = [];
        $recordings.find('input[type=checkbox]:checked').each(function(index) {
          preSelectedRecordings.push({
            "id": $(this).attr('data-recording-id'),
            "name": $(this).attr('data-recording-title')
          });
        });

        if (selectCallback) {
          selectCallback(preSelectedRecordings);
        }

        app.layout.closeDialog(dialogId);

        return false;

      });
    }

    function initialize() {
      var dialogBindings = {
        'beforeShow' : beforeShow,
        'afterShow' : afterShow,
        'afterHide': afterHide
      };

      app.bindDialog(dialogId, dialogBindings);

      $instructions.html('Select one or more recordings and click ADD to add JamKazam recordings to your performance samples.');

      events();
    }

    this.initialize = initialize;
    this.showDialog = showDialog;
  }

  return this;
})(window,jQuery);