 class @Publication extends @Publication
+  constructor: (args...) ->
+    super args...
+
+    @_pages = null
+
   _viewport: (page) =>
     scale = 1.25
     page.page.getViewport scale
 
   _progressCallback: (progressData) =>
+    # Maybe this instance has been destroyed in meantime
+    return if @_pages is null
+
     @_progressData = progressData if progressData
 
     documentHalf = _.min [(@_progressData.loaded / @_progressData.total) / 2, 0.5]

    Session.set 'currentPublicationProgress', documentHalf + pagesHalf

  show: =>
    @destroy()

    @_pagesDone = 0
    @_pages = []

    # TODO: Handle errors as well
    PDFJS.getDocument(@url(), null, null, @_progressCallback).then (@_pdf) =>
      for pageNumber in [1..@_pdf.numPages]
        $canvas = $('<canvas/>').addClass('display-canvas').addClass('display-canvas-loading')
        $loading = $('<div/>').addClass('loading').text("Page #{ pageNumber }")
        $pageDisplay = $('<div/>').addClass('display-page').append($canvas).append($loading).appendTo('#viewer .display-wrapper')

        do ($canvas, $pageDisplay) =>
          # TODO: Handle errors as well
          @_pdf.getPage(pageNumber).then (page) =>
            viewport = @_viewport
              page: page # Dummy page object

            $canvas.removeClass('display-canvas-loading').attr
              height: viewport.height
              width: viewport.width

            @_pages[page.pageNumber - 1] =
              $canvas: $canvas
              $pageDisplay: $pageDisplay
              page: page
              rendering: false
            @_pagesDone++

    Meteor.subscribe 'annotations-by-publication', Session.get 'currentPublicationId'

Deps.autorun ->
  # TODO: Limit only to fields necessary to display publication so that it is not rerun on field changes
  publication = Publications.findOne Session.get('currentPublicationId'), Publication.SHOW_FIELDS()

  return unless publication

