Fix TOC URL resolution and related function definition scopes in package_document.js

Hi!

This pull request fixes some last annoying bugs that were preventing TOC from working.