 define (require) ->
+  _ = require('underscore')
   Backbone = require('backbone')
 
   MEDIA_TYPES =


      @set('page', num)

      currentPage = @get('currentPage')
      currentPage.clear({silent: true}).set(currentPage.defaults) # Reset the current page
      contents = @get('contents')
      currentPage.id = contents[num-1].id
      currentPage.fetch
        success: (model, response, options) ->
          currentPage.set('title', contents[num-1].title) if contents[num-1].title

    nextPage: () ->
      currentPage = @get('currentPage')

      @set('type', type)

      if type is 'book'
        @setupToc()
        @setPage(page or 1) # Default to page 1
      else
        currentPage = @get('currentPage')
        currentPage.id = @id
        currentPage.fetch()

    # Create a flat collection to store all the pages
    setupToc: () ->
      toc = new Backbone.Collection()

      _.each @get('tree').contents, (item, index, contents) ->
        if item.contents
          _.each item.contents, (module, ind, subcol) ->
            module.parent = index # Module parents are numbered by their position in the tree
            toc.add(module)
        else
          toc.add(item)

      @set('toc', toc)
      @set('pages', toc.models.length)

    setPage: (num) ->
      if num < 1 then num = 1
