(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.OpenJamTrackDialog = 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 $templateOpenJamTrackRow = null;
    var $downloadedTrackHelp = null;
    var $whatAreJamTracks = null;
    var $searchBtn = null;
    var sampleRate = null;
    var sampleRateForFilename = null;
    var searchQuery = null;
    var cookieName = 'jamtrack_session_search'

    // called by react autocomplote component
    function search(searchType, searchData) {
      window.JamTrackSearchInput = searchData;
      searchQuery = {searchType: searchType, searchData: searchData}
      $.cookie(cookieName, JSON.stringify(searchQuery))
      doSearch(searchQuery);
    }

    function userSearch(e) {
      e.preventDefault();
      searchQuery = {searchType: 'user-input', searchData: window.JamTrackSearchInput}
      $.cookie(cookieName, JSON.stringify(searchQuery))
      doSearch(searchQuery);
    }

    function doSearch(query) {
      emptyList();
      resetPagination();

      app.user().done(function(user) {

        var showSearch =  (user.purchased_jamtracks_count > perPage)

        var $autocomplete = $dialog.find('[data-react-class="JamTrackAutoComplete"]')

        if (showSearch) {
          $autocomplete.show()
          $searchBtn.show()

          // if no query specified, look in a cookie for last query
          if (!query) {
            query = $.cookie(cookieName)

            // and parse that cookie if defined
            if (query) {
              try {
                query = JSON.parse(query)
              }
              catch (e) {
                query = {searchType: 'user-input', searchData: ''}
                logger.error("unable to parse search query: " + e)
              }
            }
          }

          // if still no query (after checking cookie and what was specified in function, then default to anything
          if(!query){
            query = {searchType: 'user-input', searchData: ''}
          }
        }
        else {
          $autocomplete.hide()
          $searchBtn.hide()
        }

        getPurchasedJamTracks(0)
          .done(function (data, textStatus, jqXHR) {
            // initialize pagination
            var $paginator = context.JK.Paginator.create(parseInt(jqXHR.getResponseHeader('total-entries')), perPage, 0, onPageSelected, 20)
            $paginatorHolder.append($paginator);
          });

      })
    }

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

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

    function beforeShow() {

    }

    function afterShow() {

      $dialog.data('result', null)
      showing = true;
      sampleRate = context.jamClient.GetSampleRate()
      sampleRateForFilename = sampleRate == 48 ? '48' : '44';
      doSearch();
    }

    function afterHide() {
      showing = false;
    }


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

    function getPurchasedJamTracks(page) {

      var query = {page:page + 1, per_page:10}
      if (searchQuery && searchQuery.searchData && searchQuery.searchData.length > 0 && searchQuery.searchType && searchQuery.searchType.length > 0) {

        if (searchQuery.searchType == 'user-input') {
          query.search = searchQuery.searchData
        }
        else if(searchQuery.searchType == 'artist-select') {
          query.artist_search = searchQuery.searchData
        }
        else if(searchQuery.searchType == 'song-select') {
          query.song_search = searchQuery.searchData
        }
      }
      return rest.getPurchasedJamTracks(query)
        .done(function(purchasedJamTracks) {

          emptyList();

          $.each(purchasedJamTracks.jamtracks, function(index, jamTrack) {

            var options = {}
            options.jamTrackState = null;
            options.jamTrackId = jamTrack.id;
            options.name = jamTrack.name;
            options.artist = jamTrack.original_artist;
            var detail  = context.jamClient.JamTrackGetTrackDetail(jamTrack.id + '-' + sampleRateForFilename) || {}
            options.downloaded = detail.key_state == 'ready' ? 'Yes' : 'No'

            var $tr = $(context._.template($templateOpenJamTrackRow.html(), options, { variable: 'data' }));
            $tr.data('server-model', jamTrack);
            $tbody.append($tr);
          });
        })
        .fail(function(jqXHR, textStatus, errorMessage) {
          app.ajaxError(jqXHR, textStatus, errorMessage);
        });
    }


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

        // tell the server we are about to open a jamtrack
        rest.openJamTrack({id: context.SessionStore.id(), jam_track_id: jamTrack.id})
          .done(function(response) {
            $dialog.data('result', {success:true, jamTrack: jamTrack})
            context.SessionActions.updateSession.trigger(response);
            app.layout.closeDialog('open-jam-track-dialog');
          })
          .fail(function(jqXHR) {
            app.notifyServerError(jqXHR, "Unable to Open JamTrack For Playback");
          })

        return false;
      })

      context.JK.helpBubble($downloadedTrackHelp, 'downloaded-jamtrack', {}, {width:'400px'})
      $downloadedTrackHelp.on('click', false)

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

      $searchBtn.on('click', userSearch)
    }

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

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

      $dialog = $('#open-jam-track-dialog');
      $tbody = $dialog.find('table.open-jam-tracks tbody');
      $paginatorHolder = $dialog.find('.paginator-holder');
      $templateOpenJamTrackRow = $('#template-jam-track-row')
      $downloadedTrackHelp = $dialog.find('.downloaded-jamtrack-help')
      $whatAreJamTracks = $dialog.find('.what-are-jamtracks')
      $searchBtn = $dialog.find('.search-btn')

      registerStaticEvents();
    };


    this.initialize = initialize;
    this.isShowing = function isShowing() { return showing; }
    this.search = search; // called by react
  }

  return this;
})(window,jQuery);