(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.OpenBackingTrackDialog = function(app) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var showing = false;
    var perPage = 10;
    var $dialog = null;
    var $tbody = null;
    var $paginatorHolder = null;
    var $templateOpenBackingTrackRow = null;
    var $downloadedTrackHelp = null;
    var $whatAreBackingTracks = null;
    var $displayAudioFileFolder = null;


    function emptyList() {
      $tbody.empty();
    }

    function resetPagination() {
      $dialog.find('.paginator').remove();
    }

    function beforeShow() {
      emptyList();
      resetPagination();
      showing = true;
      getBackingTracks();
      $dialog.data('result', null);
        // .done(function(data, textStatus, jqXHR) {
        //   // initialize pagination
        //   var $paginator = context.JK.Paginator.create(parseInt(jqXHR.getResponseHeader('total-entries')), perPage, 0, onPageSelected)
        //   $paginatorHolder.append($paginator);
        // });
    }

    function afterHide() {
      showing = false;
    }


    function onPageSelected(targetPage) {
      return getBackingTracks(targetPage);
    }

    function getBackingTracks(page) {

      var result = context.jamClient.getBackingTrackList();
      var backingTracks = result.backing_tracks;
          
      if (!backingTracks || backingTracks.length == 0) {
        $tbody.append("<tr><td colspan='100%'>No Tracks found</td></tr>");
      } else {
        $.each(backingTracks, function(index, backingTrack) {
          var extension = backingTrack.name
          var options = {
            backingTrackState: null,
            name: backingTrack.name,
            type: getExtension(backingTrack.name),
            length: displaySize(backingTrack.size)
          }
          var $tr = $(context._.template($templateOpenBackingTrackRow.html(), options, { variable: 'data' }));
          $tr.data('server-model', backingTrack);
          $tbody.append($tr);
        });        
      }//end      
    }

    // from http://stackoverflow.com/questions/190852/how-can-i-get-file-extensions-with-javascript
    function getExtension(filename) {
      return filename.substr((~-filename.lastIndexOf(".") >>> 0) + 2)
    }

    // from seth:
    function displaySize(length) {
      var size = (length==null || typeof(length)=='undefined') ? 0 : Number(length)
      return (Math.round(size * 10 / (1024 * 1024) ) / 10).toString() + "M"
    }    

    function registerStaticEvents() {
      $tbody.on('click', 'tr', function(e) {
        var backingTrack = $(this).data('server-model');

        // tell the server we are about to open a backing track:
        rest.openBackingTrack({id: context.SessionStore.id(), backing_track_path: backingTrack.name})
          .done(function(response) {
            var result = context.jamClient.SessionOpenBackingTrackFile(backingTrack.name, false);
            
            // TODO: Possibly actually check the result.  Investigate
            // what real client returns:
            // // if(result) {
                // let callers see which backing track was chosen
                $dialog.data('result', backingTrack);
                app.layout.closeDialog('open-backing-track-dialog');
            // }
            // else {
            //   logger.error("unable to open backing track")
            // }
            context.SessionActions.syncWithServer()

          })
          .fail(function(jqXHR) {
            app.notifyServerError(jqXHR, "Unable to Open BackingTrack For Playback");
          })

        return false;
      })

      context.JK.helpBubble($whatAreBackingTracks, 'no help yet for this topic', {}, {positions:['bottom'], offsetParent: $dialog})
      $whatAreBackingTracks.on('click', false) // no help yet

      $displayAudioFileFolder.on('click', function(e) {
        e.stopPropagation();
        context.jamClient.OpenBackingTracksDirectory();        
      })
    }

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

      app.bindDialog('open-backing-track-dialog', dialogBindings);

      $dialog = $('#open-backing-track-dialog');
      $tbody = $dialog.find('table.open-backing-tracks tbody');
      $paginatorHolder = $dialog.find('.paginator-holder');
      $templateOpenBackingTrackRow = $('#template-backing-track-row')
      $whatAreBackingTracks = $dialog.find('.what-are-backingtracks')
      $displayAudioFileFolder = $dialog.find('.display-backingtracks-folder')

      registerStaticEvents();
    };


    this.initialize = initialize;
    this.isShowing = function isShowing() { return showing; }
  }

  return this;
})(window,jQuery);