Document instancing class, and unload handling.

This allows documents to be closed and deleted from memory.
The custom document instancer also means that creating a class to handle
script tags (i.e. to embed lua) will be easier.