Initial implementation

Based on essentially the same function by Joe Hewitt,
lifted from Firebug March 2008 under the MIT license.