diff --git a/src/allmydata/immutable/downloader/finder.py b/src/allmydata/immutable/downloader/finder.py
index 4816ccd..3309286 100644
--- a/src/allmydata/immutable/downloader/finder.py
+++ b/src/allmydata/immutable/downloader/finder.py
@@ -137,7 +137,7 @@ class ShareFinder:
                       peerid=idlib.shortnodeid_b2a(peerid),
                       level=log.NOISY, umid="Io7pyg")
         time_sent = now()
-        d_ev = self._download_status.add_dyhb_sent(peerid, time_sent)
+        d_ev = self._download_status.add_dyhb_request(peerid, time_sent)
         # TODO: get the timer from a Server object, it knows best
         self.overdue_timers[req] = reactor.callLater(self.OVERDUE_TIMEOUT,
                                                      self.overdue, req)
@@ -223,7 +223,7 @@ class ShareFinder:
         eventually(self.share_consumer.got_shares, shares)
 
     def _got_error(self, f, peerid, req, d_ev, lp):
-        d_ev.finished("error", now())
+        d_ev.error(now())
         self.log(format="got error from [%(peerid)s]",
                  peerid=idlib.shortnodeid_b2a(peerid), failure=f,
                  level=log.UNUSUAL, parent=lp, umid="zUKdCw")
diff --git a/src/allmydata/immutable/downloader/node.py b/src/allmydata/immutable/downloader/node.py
index 04482e6..f0a73eb 100644
--- a/src/allmydata/immutable/downloader/node.py
+++ b/src/allmydata/immutable/downloader/node.py
@@ -72,7 +72,7 @@ class DownloadNode:
         # things to track callers that want data
 
         # _segment_requests can have duplicates
-        self._segment_requests = [] # (segnum, d, cancel_handle, logparent)
+        self._segment_requests = [] # (segnum, d, cancel_handle, seg_ev, lp)
         self._active_segment = None # a SegmentFetcher, with .segnum
 
         self._segsize_observers = observer.OneShotObserverList()
@@ -119,14 +119,15 @@ class DownloadNode:
     # things called by outside callers, via CiphertextFileNode. get_segment()
     # may also be called by Segmentation.
 
-    def read(self, consumer, offset=0, size=None, read_ev=None):
+    def read(self, consumer, offset, size, read_ev):
         """I am the main entry point, from which FileNode.read() can get
         data. I feed the consumer with the desired range of ciphertext. I
         return a Deferred that fires (with the consumer) when the read is
         finished.
 
         Note that there is no notion of a 'file pointer': each call to read()
-        uses an independent offset= value."""
+        uses an independent offset= value.
+        """
         # for concurrent operations: each gets its own Segmentation manager
         if size is None:
             size = self._verifycap.size
@@ -148,7 +149,11 @@ class DownloadNode:
             read_ev.finished(now())
             # no data, so no producer, so no register/unregisterProducer
             return defer.succeed(consumer)
+
+        # for concurrent operations, each read() gets its own Segmentation
+        # manager
         s = Segmentation(self, offset, size, consumer, read_ev, lp)
+
         # this raises an interesting question: what segments to fetch? if
         # offset=0, always fetch the first segment, and then allow
         # Segmentation to be responsible for pulling the subsequent ones if
@@ -186,10 +191,10 @@ class DownloadNode:
                      si=base32.b2a(self._verifycap.storage_index)[:8],
                      segnum=segnum,
                      level=log.OPERATIONAL, parent=logparent, umid="UKFjDQ")
-        self._download_status.add_segment_request(segnum, now())
+        seg_ev = self._download_status.add_segment_request(segnum, now())
         d = defer.Deferred()
         c = Cancel(self._cancel_request)
-        self._segment_requests.append( (segnum, d, c, lp) )
+        self._segment_requests.append( (segnum, d, c, seg_ev, lp) )
         self._start_new_segment()
         return (d, c)
 
@@ -213,13 +218,13 @@ class DownloadNode:
 
     def _start_new_segment(self):
         if self._active_segment is None and self._segment_requests:
-            segnum = self._segment_requests[0][0]
+            (segnum, d, c, seg_ev, lp) = self._segment_requests[0]
             k = self._verifycap.needed_shares
-            lp = self._segment_requests[0][3]
             log.msg(format="%(node)s._start_new_segment: segnum=%(segnum)d",
                     node=repr(self), segnum=segnum,
                     level=log.NOISY, parent=lp, umid="wAlnHQ")
             self._active_segment = fetcher = SegmentFetcher(self, segnum, k, lp)
+            seg_ev.activate(now())
             active_shares = [s for s in self._shares if s.is_alive()]
             fetcher.add_shares(active_shares) # this triggers the loop
 
@@ -383,37 +388,49 @@ class DownloadNode:
     def fetch_failed(self, sf, f):
         assert sf is self._active_segment
         # deliver error upwards
-        for (d,c) in self._extract_requests(sf.segnum):
+        for (d,c,seg_ev) in self._extract_requests(sf.segnum):
+            seg_ev.error(now())
             eventually(self._deliver, d, c, f)
         self._active_segment = None
         self._start_new_segment()
 
     def process_blocks(self, segnum, blocks):
+        start = now()
         d = defer.maybeDeferred(self._decode_blocks, segnum, blocks)
         d.addCallback(self._check_ciphertext_hash, segnum)
         def _deliver(result):
-            ds = self._download_status
-            if isinstance(result, Failure):
-                ds.add_segment_error(segnum, now())
-            else:
-                (offset, segment, decodetime) = result
-                ds.add_segment_delivery(segnum, now(),
-                                        offset, len(segment), decodetime)
             log.msg(format="delivering segment(%(segnum)d)",
                     segnum=segnum,
                     level=log.OPERATIONAL, parent=self._lp,
                     umid="j60Ojg")
-            for (d,c) in self._extract_requests(segnum):
-                eventually(self._deliver, d, c, result)
+            when = now()
+            if isinstance(result, Failure):
+                # this catches failures in decode or ciphertext hash
+                for (d,c,seg_ev) in self._extract_requests(segnum):
+                    seg_ev.error(when)
+                    eventually(self._deliver, d, c, result)
+            else:
+                (offset, segment, decodetime) = result
+                for (d,c,seg_ev) in self._extract_requests(segnum):
+                    # when we have two requests for the same segment, the
+                    # second one will not be "activated" before the data is
+                    # delivered, so to allow the status-reporting code to see
+                    # consistent behavior, we activate them all now. The
+                    # SegmentEvent will ignore duplicate activate() calls.
+                    # Note that this will result in an infinite "receive
+                    # speed" for the second request.
+                    seg_ev.activate(when)
+                    seg_ev.deliver(when, offset, len(segment), decodetime)
+                    eventually(self._deliver, d, c, result)
+            self._download_status.add_misc_event("process_block", start, now())
             self._active_segment = None
             self._start_new_segment()
         d.addBoth(_deliver)
-        d.addErrback(lambda f:
-                     log.err("unhandled error during process_blocks",
-                             failure=f, level=log.WEIRD,
-                             parent=self._lp, umid="MkEsCg"))
+        d.addErrback(log.err, "unhandled error during process_blocks",
+                     level=log.WEIRD, parent=self._lp, umid="MkEsCg")
 
     def _decode_blocks(self, segnum, blocks):
+        start = now()
         tail = (segnum == self.num_segments-1)
         codec = self._codec
         block_size = self.block_size
@@ -434,7 +451,6 @@ class DownloadNode:
             shares.append(share)
         del blocks
 
-        start = now()
         d = codec.decode(shares, shareids)   # segment
         del shares
         def _process(buffers):
@@ -444,11 +460,13 @@ class DownloadNode:
             del buffers
             if tail:
                 segment = segment[:self.tail_segment_size]
+            self._download_status.add_misc_event("decode", start, now())
             return (segment, decodetime)
         d.addCallback(_process)
         return d
 
     def _check_ciphertext_hash(self, (segment, decodetime), segnum):
+        start = now()
         assert self._active_segment.segnum == segnum
         assert self.segment_size is not None
         offset = segnum * self.segment_size
@@ -456,6 +474,7 @@ class DownloadNode:
         h = hashutil.crypttext_segment_hash(segment)
         try:
             self.ciphertext_hash_tree.set_hashes(leaves={segnum: h})
+            self._download_status.add_misc_event("CThash", start, now())
             return (offset, segment, decodetime)
         except (BadHashError, NotEnoughHashesError):
             format = ("hash failure in ciphertext_hash_tree:"
@@ -479,7 +498,8 @@ class DownloadNode:
     def _extract_requests(self, segnum):
         """Remove matching requests and return their (d,c) tuples so that the
         caller can retire them."""
-        retire = [(d,c) for (segnum0, d, c, lp) in self._segment_requests
+        retire = [(d,c,seg_ev)
+                  for (segnum0,d,c,seg_ev,lp) in self._segment_requests
                   if segnum0 == segnum]
         self._segment_requests = [t for t in self._segment_requests
                                   if t[0] != segnum]
@@ -488,7 +508,7 @@ class DownloadNode:
     def _cancel_request(self, c):
         self._segment_requests = [t for t in self._segment_requests
                                   if t[2] != c]
-        segnums = [segnum for (segnum,d,c,lp) in self._segment_requests]
+        segnums = [segnum for (segnum,d,c,seg_ev,lp) in self._segment_requests]
         # self._active_segment might be None in rare circumstances, so make
         # sure we tolerate it
         if self._active_segment and self._active_segment.segnum not in segnums:
diff --git a/src/allmydata/immutable/downloader/segmentation.py b/src/allmydata/immutable/downloader/segmentation.py
index 7c9f5cf..84dddbe 100644
--- a/src/allmydata/immutable/downloader/segmentation.py
+++ b/src/allmydata/immutable/downloader/segmentation.py
@@ -123,6 +123,8 @@ class Segmentation:
         # the consumer might call our .pauseProducing() inside that write()
         # call, setting self._hungry=False
         self._read_ev.update(len(desired_data), 0, 0)
+        # note: filenode.DecryptingConsumer is responsible for calling
+        # _read_ev.update with how much decrypt_time was consumed
         self._maybe_fetch_next()
 
     def _retry_bad_segment(self, f):
diff --git a/src/allmydata/immutable/downloader/share.py b/src/allmydata/immutable/downloader/share.py
index 78cce8e..c4e46c3 100644
--- a/src/allmydata/immutable/downloader/share.py
+++ b/src/allmydata/immutable/downloader/share.py
@@ -244,14 +244,18 @@ class Share:
 
         # First, consume all of the information that we currently have, for
         # all the segments people currently want.
+        start = now()
         while self._get_satisfaction():
             pass
+        self._download_status.add_misc_event("satisfy", start, now())
 
         # When we get no satisfaction (from the data we've received so far),
         # we determine what data we desire (to satisfy more requests). The
         # number of segments is finite, so I can't get no satisfaction
         # forever.
+        start = now()
         wanted, needed = self._desire()
+        self._download_status.add_misc_event("desire", start, now())
 
         # Finally, send out requests for whatever we need (desire minus
         # have). You can't always get what you want, but if you try
@@ -259,11 +263,13 @@ class Share:
         self._send_requests(wanted + needed)
 
         # and sometimes you can't even get what you need
+        start = now()
         disappointment = needed & self._unavailable
         if disappointment.len():
             self.had_corruption = True
             raise DataUnavailable("need %s but will never get it" %
                                   disappointment.dump())
+        self._download_status.add_misc_event("checkdis", start, now())
 
     def _get_satisfaction(self):
         # return True if we retired a data block, and should therefore be
@@ -727,11 +733,11 @@ class Share:
                          share=repr(self),
                          start=start, length=length,
                          level=log.NOISY, parent=self._lp, umid="sgVAyA")
-            req_ev = ds.add_request_sent(self._peerid, self._shnum,
-                                         start, length, now())
+            block_ev = ds.add_block_request(self._peerid, self._shnum,
+                                            start, length, now())
             d = self._send_request(start, length)
-            d.addCallback(self._got_data, start, length, req_ev, lp)
-            d.addErrback(self._got_error, start, length, req_ev, lp)
+            d.addCallback(self._got_data, start, length, block_ev, lp)
+            d.addErrback(self._got_error, start, length, block_ev, lp)
             d.addCallback(self._trigger_loop)
             d.addErrback(lambda f:
                          log.err(format="unhandled error during send_request",
@@ -741,8 +747,8 @@ class Share:
     def _send_request(self, start, length):
         return self._rref.callRemote("read", start, length)
 
-    def _got_data(self, data, start, length, req_ev, lp):
-        req_ev.finished(len(data), now())
+    def _got_data(self, data, start, length, block_ev, lp):
+        block_ev.finished(len(data), now())
         if not self._alive:
             return
         log.msg(format="%(share)s._got_data [%(start)d:+%(length)d] -> %(datalen)d",
@@ -784,8 +790,8 @@ class Share:
         # the wanted/needed span is only "wanted" for the first pass. Once
         # the offset table arrives, it's all "needed".
 
-    def _got_error(self, f, start, length, req_ev, lp):
-        req_ev.finished("error", now())
+    def _got_error(self, f, start, length, block_ev, lp):
+        block_ev.error(now())
         log.msg(format="error requesting %(start)d+%(length)d"
                 " from %(server)s for si %(si)s",
                 start=start, length=length,
diff --git a/src/allmydata/immutable/downloader/status.py b/src/allmydata/immutable/downloader/status.py
index 4576d92..ed1fdbc 100644
--- a/src/allmydata/immutable/downloader/status.py
+++ b/src/allmydata/immutable/downloader/status.py
@@ -3,29 +3,66 @@ import itertools
 from zope.interface import implements
 from allmydata.interfaces import IDownloadStatus
 
-class RequestEvent:
-    def __init__(self, download_status, tag):
-        self._download_status = download_status
-        self._tag = tag
-    def finished(self, received, when):
-        self._download_status.add_request_finished(self._tag, received, when)
+class ReadEvent:
+    def __init__(self, ev, ds):
+        self._ev = ev
+        self._ds = ds
+    def update(self, bytes, decrypttime, pausetime):
+        self._ev["bytes_returned"] += bytes
+        self._ev["decrypt_time"] += decrypttime
+        self._ev["paused_time"] += pausetime
+    def finished(self, finishtime):
+        self._ev["finish_time"] = finishtime
+        self._ds.update_last_timestamp(finishtime)
+
+class SegmentEvent:
+    def __init__(self, ev, ds):
+        self._ev = ev
+        self._ds = ds
+    def activate(self, when):
+        if self._ev["active_time"] is None:
+            self._ev["active_time"] = when
+    def deliver(self, when, start, length, decodetime):
+        assert self._ev["active_time"] is not None
+        self._ev["finish_time"] = when
+        self._ev["success"] = True
+        self._ev["decode_time"] = decodetime
+        self._ev["segment_start"] = start
+        self._ev["segment_length"] = length
+        self._ds.update_last_timestamp(when)
+    def error(self, when):
+        self._ev["finish_time"] = when
+        self._ev["success"] = False
+        self._ds.update_last_timestamp(when)
 
 class DYHBEvent:
-    def __init__(self, download_status, tag):
-        self._download_status = download_status
-        self._tag = tag
+    def __init__(self, ev, ds):
+        self._ev = ev
+        self._ds = ds
+    def error(self, when):
+        self._ev["finish_time"] = when
+        self._ev["success"] = False
+        self._ds.update_last_timestamp(when)
     def finished(self, shnums, when):
-        self._download_status.add_dyhb_finished(self._tag, shnums, when)
+        self._ev["finish_time"] = when
+        self._ev["success"] = True
+        self._ev["response_shnums"] = shnums
+        self._ds.update_last_timestamp(when)
+
+class BlockRequestEvent:
+    def __init__(self, ev, ds):
+        self._ev = ev
+        self._ds = ds
+    def finished(self, received, when):
+        self._ev["finish_time"] = when
+        self._ev["success"] = True
+        self._ev["response_length"] = received
+        self._ds.update_last_timestamp(when)
+    def error(self, when):
+        self._ev["finish_time"] = when
+        self._ev["success"] = False
+        self._ds.update_last_timestamp(when)
 
-class ReadEvent:
-    def __init__(self, download_status, tag):
-        self._download_status = download_status
-        self._tag = tag
-    def update(self, bytes, decrypttime, pausetime):
-        self._download_status.update_read_event(self._tag, bytes,
-                                                decrypttime, pausetime)
-    def finished(self, finishtime):
-        self._download_status.finish_read_event(self._tag, finishtime)
 
 class DownloadStatus:
     # There is one DownloadStatus for each CiphertextFileNode. The status
@@ -38,110 +75,122 @@ class DownloadStatus:
         self.size = size
         self.counter = self.statusid_counter.next()
         self.helper = False
-        self.started = None
-        # self.dyhb_requests tracks "do you have a share" requests and
-        # responses. It maps serverid to a tuple of:
-        #  send time
-        #  tuple of response shnums (None if response hasn't arrived, "error")
-        #  response time (None if response hasn't arrived yet)
-        self.dyhb_requests = {}
-
-        # self.requests tracks share-data requests and responses. It maps
-        # serverid to a tuple of:
-        #  shnum,
-        #  start,length,  (of data requested)
-        #  send time
-        #  response length (None if reponse hasn't arrived yet, or "error")
-        #  response time (None if response hasn't arrived)
-        self.requests = {}
-
-        # self.segment_events tracks segment requests and delivery. It is a
-        # list of:
-        #  type ("request", "delivery", "error")
-        #  segment number
-        #  event time
-        #  segment start (file offset of first byte, None except in "delivery")
-        #  segment length (only in "delivery")
-        #  time spent in decode (only in "delivery")
-        self.segment_events = []
 
-        # self.read_events tracks read() requests. It is a list of:
+        self.first_timestamp = None
+        self.last_timestamp = None
+
+        # all four of these _events lists are sorted by start_time, because
+        # they are strictly append-only (some elements are later mutated in
+        # place, but none are removed or inserted in the middle).
+
+        # self.read_events tracks read() requests. It is a list of dicts,
+        # each with the following keys:
         #  start,length  (of data requested)
-        #  request time
-        #  finish time (None until finished)
-        #  bytes returned (starts at 0, grows as segments are delivered)
-        #  time spent in decrypt (None for ciphertext-only reads)
-        #  time spent paused
+        #  start_time
+        #  finish_time (None until finished)
+        #  bytes_returned (starts at 0, grows as segments are delivered)
+        #  decrypt_time (time spent in decrypt, None for ciphertext-only reads)
+        #  paused_time (time spent paused by client via pauseProducing)
         self.read_events = []
 
+        # self.segment_events tracks segment requests and their resolution.
+        # It is a list of dicts:
+        #  segment_number
+        #  start_time
+        #  active_time (None until work has begun)
+        #  decode_time (time spent in decode, None until delievered)
+        #  finish_time (None until resolved)
+        #  success (None until resolved, then boolean)
+        #  segment_start (file offset of first byte, None until delivered)
+        #  segment_length (None until delivered)
+        self.segment_events = []
+
+        # self.dyhb_requests tracks "do you have a share" requests and
+        # responses. It is a list of dicts:
+        #  serverid (binary)
+        #  start_time
+        #  success (None until resolved, then boolean)
+        #  response_shnums (tuple, None until successful)
+        #  finish_time (None until resolved)
+        self.dyhb_requests = []
+
+        # self.block_requests tracks share-data requests and responses. It is
+        # a list of dicts:
+        #  serverid (binary),
+        #  shnum,
+        #  start,length,  (of data requested)
+        #  start_time
+        #  finish_time (None until resolved)
+        #  success (None until resolved, then bool)
+        #  response_length (None until success)
+        self.block_requests = []
+
         self.known_shares = [] # (serverid, shnum)
         self.problems = []
 
+        self.misc_events = []
+
+    def add_misc_event(self, what, start, finish=None):
+        self.misc_events.append( {"what": what,
+                                  "start_time": start,
+                                  "finish_time": finish,
+                                  } )
 
-    def add_dyhb_sent(self, serverid, when):
-        r = (when, None, None)
-        if serverid not in self.dyhb_requests:
-            self.dyhb_requests[serverid] = []
-        self.dyhb_requests[serverid].append(r)
-        tag = (serverid, len(self.dyhb_requests[serverid])-1)
-        return DYHBEvent(self, tag)
-
-    def add_dyhb_finished(self, tag, shnums, when):
-        # received="error" on error, else tuple(shnums)
-        (serverid, index) = tag
-        r = self.dyhb_requests[serverid][index]
-        (sent, _, _) = r
-        r = (sent, shnums, when)
-        self.dyhb_requests[serverid][index] = r
-
-    def add_request_sent(self, serverid, shnum, start, length, when):
-        r = (shnum, start, length, when, None, None)
-        if serverid not in self.requests:
-            self.requests[serverid] = []
-        self.requests[serverid].append(r)
-        tag = (serverid, len(self.requests[serverid])-1)
-        return RequestEvent(self, tag)
-
-    def add_request_finished(self, tag, received, when):
-        # received="error" on error, else len(data)
-        (serverid, index) = tag
-        r = self.requests[serverid][index]
-        (shnum, start, length, sent, _, _) = r
-        r = (shnum, start, length, sent, received, when)
-        self.requests[serverid][index] = r
+    def add_read_event(self, start, length, when):
+        if self.first_timestamp is None:
+            self.first_timestamp = when
+        r = { "start": start,
+              "length": length,
+              "start_time": when,
+              "finish_time": None,
+              "bytes_returned": 0,
+              "decrypt_time": 0,
+              "paused_time": 0,
+              }
+        self.read_events.append(r)
+        return ReadEvent(r, self)
 
     def add_segment_request(self, segnum, when):
-        if self.started is None:
-            self.started = when
-        r = ("request", segnum, when, None, None, None)
-        self.segment_events.append(r)
-    def add_segment_delivery(self, segnum, when, start, length, decodetime):
-        r = ("delivery", segnum, when, start, length, decodetime)
-        self.segment_events.append(r)
-    def add_segment_error(self, segnum, when):
-        r = ("error", segnum, when, None, None, None)
+        if self.first_timestamp is None:
+            self.first_timestamp = when
+        r = { "segment_number": segnum,
+              "start_time": when,
+              "active_time": None,
+              "finish_time": None,
+              "success": None,
+              "decode_time": None,
+              "segment_start": None,
+              "segment_length": None,
+              }
         self.segment_events.append(r)
+        return SegmentEvent(r, self)
 
-    def add_read_event(self, start, length, when):
-        if self.started is None:
-            self.started = when
-        r = (start, length, when, None, 0, 0, 0)
-        self.read_events.append(r)
-        tag = len(self.read_events)-1
-        return ReadEvent(self, tag)
-    def update_read_event(self, tag, bytes_d, decrypt_d, paused_d):
-        r = self.read_events[tag]
-        (start, length, requesttime, finishtime, bytes, decrypt, paused) = r
-        bytes += bytes_d
-        decrypt += decrypt_d
-        paused += paused_d
-        r = (start, length, requesttime, finishtime, bytes, decrypt, paused)
-        self.read_events[tag] = r
-    def finish_read_event(self, tag, finishtime):
-        r = self.read_events[tag]
-        (start, length, requesttime, _, bytes, decrypt, paused) = r
-        r = (start, length, requesttime, finishtime, bytes, decrypt, paused)
-        self.read_events[tag] = r
+    def add_dyhb_request(self, serverid, when):
+        r = { "serverid": serverid,
+              "start_time": when,
+              "success": None,
+              "response_shnums": None,
+              "finish_time": None,
+              }
+        self.dyhb_requests.append(r)
+        return DYHBEvent(r, self)
+
+    def add_block_request(self, serverid, shnum, start, length, when):
+        r = { "serverid": serverid,
+              "shnum": shnum,
+              "start": start,
+              "length": length,
+              "start_time": when,
+              "finish_time": None,
+              "success": None,
+              "response_length": None,
+              }
+        self.block_requests.append(r)
+        return BlockRequestEvent(r, self)
+
+    def update_last_timestamp(self, when):
+        if self.last_timestamp is None or when > self.last_timestamp:
+            self.last_timestamp = when
 
     def add_known_share(self, serverid, shnum):
         self.known_shares.append( (serverid, shnum) )
@@ -160,15 +209,12 @@ class DownloadStatus:
         # mention all outstanding segment requests
         outstanding = set()
         errorful = set()
-        for s_ev in self.segment_events:
-            (etype, segnum, when, segstart, seglen, decodetime) = s_ev
-            if etype == "request":
-                outstanding.add(segnum)
-            elif etype == "delivery":
-                outstanding.remove(segnum)
-            else: # "error"
-                outstanding.remove(segnum)
-                errorful.add(segnum)
+        outstanding = set([s_ev["segment_number"]
+                           for s_ev in self.segment_events
+                           if s_ev["finish_time"] is None])
+        errorful = set([s_ev["segment_number"]
+                        for s_ev in self.segment_events
+                        if s_ev["success"] is False])
         def join(segnums):
             if len(segnums) == 1:
                 return "segment %s" % list(segnums)[0]
@@ -191,10 +237,9 @@ class DownloadStatus:
             return 0.0
         total_outstanding, total_received = 0, 0
         for r_ev in self.read_events:
-            (start, length, ign1, finishtime, bytes, ign2, ign3) = r_ev
-            if finishtime is None:
-                total_outstanding += length
-                total_received += bytes
+            if r_ev["finish_time"] is None:
+                total_outstanding += r_ev["length"]
+                total_received += r_ev["bytes_returned"]
             # else ignore completed requests
         if not total_outstanding:
             return 1.0
@@ -207,12 +252,11 @@ class DownloadStatus:
         # a download is considered active if it has at least one outstanding
         # read() call
         for r_ev in self.read_events:
-            (ign1, ign2, ign3, finishtime, ign4, ign5, ign6) = r_ev
-            if finishtime is None:
+            if r_ev["finish_time"] is None:
                 return True
         return False
 
     def get_started(self):
-        return self.started
+        return self.first_timestamp
     def get_results(self):
         return None # TODO
diff --git a/src/allmydata/immutable/filenode.py b/src/allmydata/immutable/filenode.py
index ed3785b..2adc69b 100644
--- a/src/allmydata/immutable/filenode.py
+++ b/src/allmydata/immutable/filenode.py
@@ -55,13 +55,14 @@ class CiphertextFileNode:
         return a Deferred that fires (with the consumer) when the read is
         finished."""
         self._maybe_create_download_node()
-        actual_size = size
-        if actual_size is None:
-            actual_size = self._verifycap.size - offset
-        read_ev = self._download_status.add_read_event(offset, actual_size,
-                                                       now())
+        if size is None:
+            size = self._verifycap.size
+        # clip size so offset+size does not go past EOF
+        size = min(size, self._verifycap.size-offset)
+        read_ev = self._download_status.add_read_event(offset, size, now())
         if IDownloadStatusHandlingConsumer.providedBy(consumer):
             consumer.set_download_status_read_event(read_ev)
+            consumer.set_download_status(self._download_status)
         return self._node.read(consumer, offset, size, read_ev)
 
     def get_segment(self, segnum):
@@ -177,7 +178,8 @@ class DecryptingConsumer:
 
     def __init__(self, consumer, readkey, offset):
         self._consumer = consumer
-        self._read_event = None
+        self._read_ev = None
+        self._download_status = None
         # TODO: pycryptopp CTR-mode needs random-access operations: I want
         # either a=AES(readkey, offset) or better yet both of:
         #  a=AES(readkey, offset=0)
@@ -190,7 +192,9 @@ class DecryptingConsumer:
         self._decryptor.process("\x00"*offset_small)
 
     def set_download_status_read_event(self, read_ev):
-        self._read_event = read_ev
+        self._read_ev = read_ev
+    def set_download_status(self, ds):
+        self._download_status = ds
 
     def registerProducer(self, producer, streaming):
         # this passes through, so the real consumer can flow-control the real
@@ -203,9 +207,11 @@ class DecryptingConsumer:
     def write(self, ciphertext):
         started = now()
         plaintext = self._decryptor.process(ciphertext)
-        if self._read_event:
+        if self._read_ev:
             elapsed = now() - started
-            self._read_event.update(0, elapsed, 0)
+            self._read_ev.update(0, elapsed, 0)
+        if self._download_status:
+            self._download_status.add_misc_event("AES", started, now())
         self._consumer.write(plaintext)
 
 class ImmutableFileNode:
diff --git a/src/allmydata/test/test_download.py b/src/allmydata/test/test_download.py
index 3a69220..4d0e364 100644
--- a/src/allmydata/test/test_download.py
+++ b/src/allmydata/test/test_download.py
@@ -1214,14 +1214,16 @@ class Status(unittest.TestCase):
         now = 12345.1
         ds = DownloadStatus("si-1", 123)
         self.failUnlessEqual(ds.get_status(), "idle")
-        ds.add_segment_request(0, now)
+        ev0 = ds.add_segment_request(0, now)
         self.failUnlessEqual(ds.get_status(), "fetching segment 0")
-        ds.add_segment_delivery(0, now+1, 0, 1000, 2.0)
+        ev0.activate(now+0.5)
+        ev0.deliver(now+1, 0, 1000, 2.0)
         self.failUnlessEqual(ds.get_status(), "idle")
-        ds.add_segment_request(2, now+2)
-        ds.add_segment_request(1, now+2)
+        ev2 = ds.add_segment_request(2, now+2)
+        del ev2 # hush pyflakes
+        ev1 = ds.add_segment_request(1, now+2)
         self.failUnlessEqual(ds.get_status(), "fetching segments 1,2")
-        ds.add_segment_error(1, now+3)
+        ev1.error(now+3)
         self.failUnlessEqual(ds.get_status(),
                              "fetching segment 2; errors on segment 1")
 
diff --git a/src/allmydata/test/test_web.py b/src/allmydata/test/test_web.py
index f68e98d..b4b8bdc 100644
--- a/src/allmydata/test/test_web.py
+++ b/src/allmydata/test/test_web.py
@@ -19,7 +19,7 @@ from allmydata.nodemaker import NodeMaker
 from allmydata.unknown import UnknownNode
 from allmydata.web import status, common
 from allmydata.scripts.debug import CorruptShareOptions, corrupt_share
-from allmydata.util import fileutil, base32
+from allmydata.util import fileutil, base32, hashutil
 from allmydata.util.consumer import download_to_data
 from allmydata.util.netstring import split_netstring
 from allmydata.util.encodingutil import to_str
@@ -78,34 +78,38 @@ def build_one_ds():
     ds = DownloadStatus("storage_index", 1234)
     now = time.time()
 
-    ds.add_segment_request(0, now)
-    # segnum, when, start,len, decodetime
-    ds.add_segment_delivery(0, now+1, 0, 100, 0.5)
-    ds.add_segment_request(1, now+2)
-    ds.add_segment_error(1, now+3)
+    serverid_a = hashutil.tagged_hash("foo", "serverid_a")[:20]
+    serverid_b = hashutil.tagged_hash("foo", "serverid_b")[:20]
+    storage_index = hashutil.storage_index_hash("SI")
+    e0 = ds.add_segment_request(0, now)
+    e0.activate(now+0.5)
+    e0.deliver(now+1, 0, 100, 0.5) # when, start,len, decodetime
+    e1 = ds.add_segment_request(1, now+2)
+    e1.error(now+3)
     # two outstanding requests
-    ds.add_segment_request(2, now+4)
-    ds.add_segment_request(3, now+5)
+    e2 = ds.add_segment_request(2, now+4)
+    e3 = ds.add_segment_request(3, now+5)
 
     # simulate a segment which gets delivered faster than a system clock tick (ticket #1166)
-    ds.add_segment_request(4, now)
-    ds.add_segment_delivery(4, now, 0, 140, 0.5)
+    e = ds.add_segment_request(4, now)
+    e.activate(now)
+    e.deliver(now, 0, 140, 0.5)
 
-    e = ds.add_dyhb_sent("serverid_a", now)
+    e = ds.add_dyhb_request(serverid_a, now)
     e.finished([1,2], now+1)
-    e = ds.add_dyhb_sent("serverid_b", now+2) # left unfinished
+    e = ds.add_dyhb_request(serverid_b, now+2) # left unfinished
 
     e = ds.add_read_event(0, 120, now)
     e.update(60, 0.5, 0.1) # bytes, decrypttime, pausetime
     e.finished(now+1)
     e = ds.add_read_event(120, 30, now+2) # left unfinished
 
-    e = ds.add_request_sent("serverid_a", 1, 100, 20, now)
+    e = ds.add_block_request(serverid_a, 1, 100, 20, now)
     e.finished(20, now+1)
-    e = ds.add_request_sent("serverid_a", 1, 120, 30, now+1) # left unfinished
+    e = ds.add_block_request(serverid_a, 1, 120, 30, now+1) # left unfinished
 
     # make sure that add_read_event() can come first too
-    ds1 = DownloadStatus("storage_index", 1234)
+    ds1 = DownloadStatus(storage_index, 1234)
     e = ds1.add_read_event(0, 120, now)
     e.update(60, 0.5, 0.1) # bytes, decrypttime, pausetime
     e.finished(now+1)
@@ -554,10 +558,25 @@ class Web(WebMixin, WebErrorMixin, testutil.StallMixin, testutil.ReallyEqualMixi
         def _check_dl(res):
             self.failUnless("File Download Status" in res, res)
         d.addCallback(_check_dl)
-        d.addCallback(lambda res: self.GET("/status/down-%d?t=json" % dl_num))
+        d.addCallback(lambda res: self.GET("/status/down-%d/event_json" % dl_num))
         def _check_dl_json(res):
             data = simplejson.loads(res)
             self.failUnless(isinstance(data, dict))
+            self.failUnless("read" in data)
+            self.failUnlessEqual(data["read"][0]["length"], 120)
+            self.failUnlessEqual(data["segment"][0]["segment_length"], 100)
+            self.failUnlessEqual(data["segment"][2]["segment_number"], 2)
+            self.failUnlessEqual(data["segment"][2]["finish_time"], None)
+            phwr_id = base32.b2a(hashutil.tagged_hash("foo", "serverid_a")[:20])
+            cmpu_id = base32.b2a(hashutil.tagged_hash("foo", "serverid_b")[:20])
+            # serverids[] keys are strings, since that's what JSON does, but
+            # we'd really like them to be ints
+            self.failUnlessEqual(data["serverids"]["0"], "phwr")
+            self.failUnlessEqual(data["serverids"]["1"], "cmpu")
+            self.failUnlessEqual(data["server_info"][phwr_id]["short"], "phwr")
+            self.failUnlessEqual(data["server_info"][cmpu_id]["short"], "cmpu")
+            self.failUnless("dyhb" in data)
+            self.failUnless("misc" in data)
         d.addCallback(_check_dl_json)
         d.addCallback(lambda res: self.GET("/status/up-%d" % ul_num))
         def _check_ul(res):
diff --git a/src/allmydata/web/download-status-timeline.xhtml b/src/allmydata/web/download-status-timeline.xhtml
new file mode 100644
index 0000000..ff893db
--- /dev/null
+++ b/src/allmydata/web/download-status-timeline.xhtml
@@ -0,0 +1,34 @@
+<html xmlns:n="http://nevow.com/ns/nevow/0.1">
+  <head>
+    <title>AllMyData - Tahoe - File Download Status Timeline</title>
+    <link href="/tahoe_css" rel="stylesheet" type="text/css"/>
+    <link href="/webform_css" rel="stylesheet" type="text/css"/>
+    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+    <script type="text/javascript" src="/jquery.js"></script>
+    <script type="text/javascript" src="/protovis-d3.2.js"></script>
+    <script type="text/javascript" src="/download_status_timeline.js"></script>
+  </head>
+  <body>
+
+<h1>File Download Status</h1>
+
+<ul>
+  <li>Started: <span n:render="started"/></li>
+  <li>Storage Index: <span n:render="si"/></li>
+  <li>Helper?: <span n:render="helper"/></li>
+  <li>Total Size: <span n:render="total_size"/></li>
+  <li>Progress: <span n:render="progress"/></li>
+  <li>Status: <span n:render="status"/></li>
+</ul>
+
+
+<div style="">
+  <a id="zoomin" href="#">ZOOMIN</a> <a id="zoomout" href="#">ZOOMOUT</a>
+  <div id="overview" style="float:right;width:166px;height:100px; border: 1px solid #ddd">overview</div>
+  <div id="timeline" style="width:600px;border: 1px solid #aaa">Timeline</div>
+</div>
+
+<div>Return to the <a href="/">Welcome Page</a></div>
+
+  </body>
+</html>
diff --git a/src/allmydata/web/download-status.xhtml b/src/allmydata/web/download-status.xhtml
index 30abfca..b3560ed 100644
--- a/src/allmydata/web/download-status.xhtml
+++ b/src/allmydata/web/download-status.xhtml
@@ -16,6 +16,7 @@
   <li>Total Size: <span n:render="total_size"/></li>
   <li>Progress: <span n:render="progress"/></li>
   <li>Status: <span n:render="status"/></li>
+  <li><span n:render="timeline_link"/></li>
 </ul>
 
 <div n:render="events"></div>
diff --git a/src/allmydata/web/download_status_timeline.js b/src/allmydata/web/download_status_timeline.js
new file mode 100644
index 0000000..e5150e9
--- /dev/null
+++ b/src/allmydata/web/download_status_timeline.js
@@ -0,0 +1,184 @@
+
+$(function() {
+
+      function onDataReceived(data) {
+          var bounds = { min: data.bounds.min,
+                         max: data.bounds.max
+                       };
+          //bounds.max = data.dyhb[data.dyhb.length-1].finish_time;
+          var duration = bounds.max - bounds.min;
+          var WIDTH = 600;
+          var vis = new pv.Panel().canvas("timeline").margin(30);
+
+          var dyhb_top = 0;
+          //var read_top = dyhb_top + 30*data.dyhb.length+60;
+          var read_top = dyhb_top + 30*pv.max(data.dyhb,
+                                              function(d) {return d.row;})+60;
+          var segment_top = read_top + 30*data.read[data.read.length-1].row+60;
+          var misc_top = segment_top + 30*data.segment[data.segment.length-1].row+60;
+          var block_top = misc_top + 50;
+          var block_row_to_y = {};
+          var row_y=0;
+          for (var group=0; group < data.block_rownums.length; group++) {
+              for (var row=0; row < data.block_rownums[group]; row++) {
+                  block_row_to_y[group+"-"+row] = row_y;
+                  row_y += 10;
+              }
+              row_y += 5;
+          }
+          var height = block_top + row_y;
+
+          var kx = bounds.min;
+          var ky = 1;
+          var x = pv.Scale.linear(bounds.min, bounds.max).range(0, WIDTH-40);
+          var relx = pv.Scale.linear(0, duration).range(0, WIDTH-40);
+          //var y = pv.Scale.linear(-ky,ky).range(0, height);
+          //x.nice(); relx.nice();
+
+          /* add the invisible panel now, at the bottom of the stack, so that
+          it won't steal mouseover events and prevent tooltips from
+          working. */
+          var zoomer = vis.add(pv.Panel)
+              .events("all")
+              .event("mousedown", pv.Behavior.pan())
+              .event("mousewheel", pv.Behavior.zoom())
+              .event("pan", transform)
+              .event("zoom", transform)
+          ;
+
+          vis.anchor("top").top(-20).add(pv.Label).text("DYHB Requests");
+
+          vis.add(pv.Bar)
+              .data(data.dyhb)
+              .height(20)
+              .top(function (d) {return 30*d.row;})
+              .left(function(d){return x(d.start_time);})
+              .width(function(d){return x(d.finish_time)-x(d.start_time);})
+              .title(function(d){return "shnums: "+d.response_shnums;})
+              .fillStyle(function(d){return data.server_info[d.serverid].color;})
+              .strokeStyle("black").lineWidth(1)
+          .anchor("left").add(pv.Label).text(function(d){return d.serverid.slice(0,4);})
+          ;
+
+          vis.add(pv.Rule)
+              .data(data.dyhb)
+              .top(function(d){return 30*d.row + 20/2;})
+              .left(0).width(0)
+              .strokeStyle("#888")
+              .anchor("left").add(pv.Label)
+              .text(function(d){return d.serverid.slice(0,4);})
+          ;
+
+          /* we use a function for data=relx.ticks() here instead of
+           simply .data(relx.ticks()) so that it will be recalculated when
+           the scales change (by pan/zoom) */
+          var xaxis = vis.add(pv.Rule)
+              .data(function() {return relx.ticks();})
+              .strokeStyle("#ccc")
+              .left(relx)
+              .anchor("bottom").add(pv.Label)
+              .text(function(d){return relx.tickFormat(d)+"s";});
+
+          var read = vis.add(pv.Panel).top(read_top);
+          read.anchor("top").top(-20).add(pv.Label).text("read() requests");
+
+          read.add(pv.Bar)
+              .data(data.read)
+              .height(20)
+              .top(function (d) {return 30*d.row;})
+              .left(function(d){return x(d.start_time);})
+              .width(function(d){return x(d.finish_time)-x(d.start_time);})
+              .title(function(d){return "read(start="+d.start+", len="+d.length+") -> "+d.bytes_returned+" bytes";})
+              .fillStyle("red")
+              .strokeStyle("black").lineWidth(1);
+
+          var segment = vis.add(pv.Panel).top(segment_top);
+          segment.anchor("top").top(-20).add(pv.Label).text("segment() requests");
+
+          segment.add(pv.Bar)
+              .data(data.segment)
+              .height(20)
+              .top(function (d) {return 30*d.row;})
+              .left(function(d){return x(d.start_time);})
+              .width(function(d){return x(d.finish_time)-x(d.start_time);})
+              .title(function(d){return "seg"+d.segment_number+" ["+d.segment_start+":+"+d.segment_length+"] (took "+(d.finish_time-d.start_time)+")";})
+              .fillStyle(function(d){if (d.success) return "#c0ffc0";
+                                    else return "#ffc0c0";})
+              .strokeStyle("black").lineWidth(1)
+              .anchor("center").add(pv.Label).text(function(d){return d.segment_number;});
+
+          var block = vis.add(pv.Panel).top(block_top);
+          block.anchor("top").top(-20).add(pv.Label).text("block requests");
+
+          var shnum_colors = pv.Colors.category10();
+          block.add(pv.Bar)
+              .data(data.block)
+              .height(10)
+              .top(function (d) {return block_row_to_y[d.row[0]+"-"+d.row[1]];})
+              .left(function(d){return x(d.start_time);})
+              .width(function(d){return x(d.finish_time)-x(d.start_time);})
+              .title(function(d){return "sh"+d.shnum+"-on-"+d.serverid.slice(0,4)+" ["+d.start+":+"+d.length+"] -> "+d.response_length;})
+              .fillStyle(function(d){return data.server_info[d.serverid].color;})
+              .strokeStyle(function(d){return shnum_colors(d.shnum).color;})
+              .lineWidth(function(d)
+                         {if (d.response_length > 100) return 3;
+                         else return 1;
+                          })
+          ;
+
+          var misc = vis.add(pv.Panel).top(misc_top);
+          misc.anchor("top").top(-20).add(pv.Label).text("misc");
+          misc.add(pv.Bar)
+              .data(data.misc)
+              .height(20)
+              .top(function(d){return 25*d.row;})
+              .left(function(d){return x(d.start_time);})
+              .width(function(d){return x(d.finish_time)-x(d.start_time);})
+              .title(function(d)
+                     {return "start="+d.start_time+"  finish="+d.finish_time+"  duration="+(d.finish_time-d.start_time);})
+              .fillStyle("#eee")
+              .strokeStyle("#444")
+          .anchor("top").add(pv.Label).text(function(d){return d.what;})
+          ;
+
+
+          vis.height(height);
+
+          function zoomin() {
+              var t = zoomer.transform().invert();
+              t.k = t.k/1.5;
+              zoomer.transform(t.invert());
+              zoompan(t);
+          }
+
+          function zoomout() {
+              var t = zoomer.transform().invert();
+              t.k = t.k*1.5;
+              zoomer.transform(t.invert());
+              zoompan(t);
+          }
+
+          function transform() {
+              var t = this.transform().invert();
+              zoompan(t);
+          }
+          function zoompan(t) {
+              // when t.x=0 and t.k=1.0, left should be bounds.min
+              x.domain(bounds.min + (t.x/WIDTH)*duration,
+                       bounds.min + t.k*duration + (t.x/WIDTH)*duration);
+              relx.domain(0 + t.x/WIDTH*duration,
+                          t.k*duration + (t.x/WIDTH)*duration);
+              vis.render();
+          }
+
+          vis.render();
+          $("#zoomin").click(zoomin);
+          $("#zoomout").click(zoomout);
+      }
+
+      $.ajax({url: "event_json",
+              method: 'GET',
+              dataType: 'json',
+              success: onDataReceived });
+});
+
diff --git a/src/allmydata/web/jquery.js b/src/allmydata/web/jquery.js
new file mode 100644
index 0000000..9263574
--- /dev/null
+++ b/src/allmydata/web/jquery.js
@@ -0,0 +1,4376 @@
+/*!
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){
+
+var 
+	// Will speed up references to window, and allows munging its name.
+	window = this,
+	// Will speed up references to undefined, and allows munging its name.
+	undefined,
+	// Map over jQuery in case of overwrite
+	_jQuery = window.jQuery,
+	// Map over the $ in case of overwrite
+	_$ = window.$,
+
+	jQuery = window.jQuery = window.$ = function( selector, context ) {
+		// The jQuery object is actually just the init constructor 'enhanced'
+		return new jQuery.fn.init( selector, context );
+	},
+
+	// A simple way to check for HTML strings or ID strings
+	// (both of which we optimize for)
+	quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
+	// Is it a simple selector
+	isSimple = /^.[^:#\[\.,]*$/;
+
+jQuery.fn = jQuery.prototype = {
+	init: function( selector, context ) {
+		// Make sure that a selection was provided
+		selector = selector || document;
+
+		// Handle $(DOMElement)
+		if ( selector.nodeType ) {
+			this[0] = selector;
+			this.length = 1;
+			this.context = selector;
+			return this;
+		}
+		// Handle HTML strings
+		if ( typeof selector === "string" ) {
+			// Are we dealing with HTML string or an ID?
+			var match = quickExpr.exec( selector );
+
+			// Verify a match, and that no context was specified for #id
+			if ( match && (match[1] || !context) ) {
+
+				// HANDLE: $(html) -> $(array)
+				if ( match[1] )
+					selector = jQuery.clean( [ match[1] ], context );
+
+				// HANDLE: $("#id")
+				else {
+					var elem = document.getElementById( match[3] );
+
+					// Handle the case where IE and Opera return items
+					// by name instead of ID
+					if ( elem && elem.id != match[3] )
+						return jQuery().find( selector );
+
+					// Otherwise, we inject the element directly into the jQuery object
+					var ret = jQuery( elem || [] );
+					ret.context = document;
+					ret.selector = selector;
+					return ret;
+				}
+
+			// HANDLE: $(expr, [context])
+			// (which is just equivalent to: $(content).find(expr)
+			} else
+				return jQuery( context ).find( selector );
+
+		// HANDLE: $(function)
+		// Shortcut for document ready
+		} else if ( jQuery.isFunction( selector ) )
+			return jQuery( document ).ready( selector );
+
+		// Make sure that old selector state is passed along
+		if ( selector.selector && selector.context ) {
+			this.selector = selector.selector;
+			this.context = selector.context;
+		}
+
+		return this.setArray(jQuery.isArray( selector ) ?
+			selector :
+			jQuery.makeArray(selector));
+	},
+
+	// Start with an empty selector
+	selector: "",
+
+	// The current version of jQuery being used
+	jquery: "1.3.2",
+
+	// The number of elements contained in the matched element set
+	size: function() {
+		return this.length;
+	},
+
+	// Get the Nth element in the matched element set OR
+	// Get the whole matched element set as a clean array
+	get: function( num ) {
+		return num === undefined ?
+
+			// Return a 'clean' array
+			Array.prototype.slice.call( this ) :
+
+			// Return just the object
+			this[ num ];
+	},
+
+	// Take an array of elements and push it onto the stack
+	// (returning the new matched element set)
+	pushStack: function( elems, name, selector ) {
+		// Build a new jQuery matched element set
+		var ret = jQuery( elems );
+
+		// Add the old object onto the stack (as a reference)
+		ret.prevObject = this;
+
+		ret.context = this.context;
+
+		if ( name === "find" )
+			ret.selector = this.selector + (this.selector ? " " : "") + selector;
+		else if ( name )
+			ret.selector = this.selector + "." + name + "(" + selector + ")";
+
+		// Return the newly-formed element set
+		return ret;
+	},
+
+	// Force the current matched set of elements to become
+	// the specified array of elements (destroying the stack in the process)
+	// You should use pushStack() in order to do this, but maintain the stack
+	setArray: function( elems ) {
+		// Resetting the length to 0, then using the native Array push
+		// is a super-fast way to populate an object with array-like properties
+		this.length = 0;
+		Array.prototype.push.apply( this, elems );
+
+		return this;
+	},
+
+	// Execute a callback for every element in the matched set.
+	// (You can seed the arguments with an array of args, but this is
+	// only used internally.)
+	each: function( callback, args ) {
+		return jQuery.each( this, callback, args );
+	},
+
+	// Determine the position of an element within
+	// the matched set of elements
+	index: function( elem ) {
+		// Locate the position of the desired element
+		return jQuery.inArray(
+			// If it receives a jQuery object, the first element is used
+			elem && elem.jquery ? elem[0] : elem
+		, this );
+	},
+
+	attr: function( name, value, type ) {
+		var options = name;
+
+		// Look for the case where we're accessing a style value
+		if ( typeof name === "string" )
+			if ( value === undefined )
+				return this[0] && jQuery[ type || "attr" ]( this[0], name );
+
+			else {
+				options = {};
+				options[ name ] = value;
+			}
+
+		// Check to see if we're setting style values
+		return this.each(function(i){
+			// Set all the styles
+			for ( name in options )
+				jQuery.attr(
+					type ?
+						this.style :
+						this,
+					name, jQuery.prop( this, options[ name ], type, i, name )
+				);
+		});
+	},
+
+	css: function( key, value ) {
+		// ignore negative width and height values
+		if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
+			value = undefined;
+		return this.attr( key, value, "curCSS" );
+	},
+
+	text: function( text ) {
+		if ( typeof text !== "object" && text != null )
+			return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+
+		var ret = "";
+
+		jQuery.each( text || this, function(){
+			jQuery.each( this.childNodes, function(){
+				if ( this.nodeType != 8 )
+					ret += this.nodeType != 1 ?
+						this.nodeValue :
+						jQuery.fn.text( [ this ] );
+			});
+		});
+
+		return ret;
+	},
+
+	wrapAll: function( html ) {
+		if ( this[0] ) {
+			// The elements to wrap the target around
+			var wrap = jQuery( html, this[0].ownerDocument ).clone();
+
+			if ( this[0].parentNode )
+				wrap.insertBefore( this[0] );
+
+			wrap.map(function(){
+				var elem = this;
+
+				while ( elem.firstChild )
+					elem = elem.firstChild;
+
+				return elem;
+			}).append(this);
+		}
+
+		return this;
+	},
+
+	wrapInner: function( html ) {
+		return this.each(function(){
+			jQuery( this ).contents().wrapAll( html );
+		});
+	},
+
+	wrap: function( html ) {
+		return this.each(function(){
+			jQuery( this ).wrapAll( html );
+		});
+	},
+
+	append: function() {
+		return this.domManip(arguments, true, function(elem){
+			if (this.nodeType == 1)
+				this.appendChild( elem );
+		});
+	},
+
+	prepend: function() {
+		return this.domManip(arguments, true, function(elem){
+			if (this.nodeType == 1)
+				this.insertBefore( elem, this.firstChild );
+		});
+	},
+
+	before: function() {
+		return this.domManip(arguments, false, function(elem){
+			this.parentNode.insertBefore( elem, this );
+		});
+	},
+
+	after: function() {
+		return this.domManip(arguments, false, function(elem){
+			this.parentNode.insertBefore( elem, this.nextSibling );
+		});
+	},
+
+	end: function() {
+		return this.prevObject || jQuery( [] );
+	},
+
+	// For internal use only.
+	// Behaves like an Array's method, not like a jQuery method.
+	push: [].push,
+	sort: [].sort,
+	splice: [].splice,
+
+	find: function( selector ) {
+		if ( this.length === 1 ) {
+			var ret = this.pushStack( [], "find", selector );
+			ret.length = 0;
+			jQuery.find( selector, this[0], ret );
+			return ret;
+		} else {
+			return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
+				return jQuery.find( selector, elem );
+			})), "find", selector );
+		}
+	},
+
+	clone: function( events ) {
+		// Do the clone
+		var ret = this.map(function(){
+			if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
+				// IE copies events bound via attachEvent when
+				// using cloneNode. Calling detachEvent on the
+				// clone will also remove the events from the orignal
+				// In order to get around this, we use innerHTML.
+				// Unfortunately, this means some modifications to
+				// attributes in IE that are actually only stored
+				// as properties will not be copied (such as the
+				// the name attribute on an input).
+				var html = this.outerHTML;
+				if ( !html ) {
+					var div = this.ownerDocument.createElement("div");
+					div.appendChild( this.cloneNode(true) );
+					html = div.innerHTML;
+				}
+
+				return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
+			} else
+				return this.cloneNode(true);
+		});
+
+		// Copy the events from the original to the clone
+		if ( events === true ) {
+			var orig = this.find("*").andSelf(), i = 0;
+
+			ret.find("*").andSelf().each(function(){
+				if ( this.nodeName !== orig[i].nodeName )
+					return;
+
+				var events = jQuery.data( orig[i], "events" );
+
+				for ( var type in events ) {
+					for ( var handler in events[ type ] ) {
+						jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
+					}
+				}
+
+				i++;
+			});
+		}
+
+		// Return the cloned set
+		return ret;
+	},
+
+	filter: function( selector ) {
+		return this.pushStack(
+			jQuery.isFunction( selector ) &&
+			jQuery.grep(this, function(elem, i){
+				return selector.call( elem, i );
+			}) ||
+
+			jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
+				return elem.nodeType === 1;
+			}) ), "filter", selector );
+	},
+
+	closest: function( selector ) {
+		var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
+			closer = 0;
+
+		return this.map(function(){
+			var cur = this;
+			while ( cur && cur.ownerDocument ) {
+				if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
+					jQuery.data(cur, "closest", closer);
+					return cur;
+				}
+				cur = cur.parentNode;
+				closer++;
+			}
+		});
+	},
+
+	not: function( selector ) {
+		if ( typeof selector === "string" )
+			// test special case where just one selector is passed in
+			if ( isSimple.test( selector ) )
+				return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
+			else
+				selector = jQuery.multiFilter( selector, this );
+
+		var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
+		return this.filter(function() {
+			return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
+		});
+	},
+
+	add: function( selector ) {
+		return this.pushStack( jQuery.unique( jQuery.merge(
+			this.get(),
+			typeof selector === "string" ?
+				jQuery( selector ) :
+				jQuery.makeArray( selector )
+		)));
+	},
+
+	is: function( selector ) {
+		return !!selector && jQuery.multiFilter( selector, this ).length > 0;
+	},
+
+	hasClass: function( selector ) {
+		return !!selector && this.is( "." + selector );
+	},
+
+	val: function( value ) {
+		if ( value === undefined ) {			
+			var elem = this[0];
+
+			if ( elem ) {
+				if( jQuery.nodeName( elem, 'option' ) )
+					return (elem.attributes.value || {}).specified ? elem.value : elem.text;
+				
+				// We need to handle select boxes special
+				if ( jQuery.nodeName( elem, "select" ) ) {
+					var index = elem.selectedIndex,
+						values = [],
+						options = elem.options,
+						one = elem.type == "select-one";
+
+					// Nothing was selected
+					if ( index < 0 )
+						return null;
+
+					// Loop through all the selected options
+					for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+						var option = options[ i ];
+
+						if ( option.selected ) {
+							// Get the specifc value for the option
+							value = jQuery(option).val();
+
+							// We don't need an array for one selects
+							if ( one )
+								return value;
+
+							// Multi-Selects return an array
+							values.push( value );
+						}
+					}
+
+					return values;				
+				}
+
+				// Everything else, we just grab the value
+				return (elem.value || "").replace(/\r/g, "");
+
+			}
+
+			return undefined;
+		}
+
+		if ( typeof value === "number" )
+			value += '';
+
+		return this.each(function(){
+			if ( this.nodeType != 1 )
+				return;
+
+			if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
+				this.checked = (jQuery.inArray(this.value, value) >= 0 ||
+					jQuery.inArray(this.name, value) >= 0);
+
+			else if ( jQuery.nodeName( this, "select" ) ) {
+				var values = jQuery.makeArray(value);
+
+				jQuery( "option", this ).each(function(){
+					this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
+						jQuery.inArray( this.text, values ) >= 0);
+				});
+
+				if ( !values.length )
+					this.selectedIndex = -1;
+
+			} else
+				this.value = value;
+		});
+	},
+
+	html: function( value ) {
+		return value === undefined ?
+			(this[0] ?
+				this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
+				null) :
+			this.empty().append( value );
+	},
+
+	replaceWith: function( value ) {
+		return this.after( value ).remove();
+	},
+
+	eq: function( i ) {
+		return this.slice( i, +i + 1 );
+	},
+
+	slice: function() {
+		return this.pushStack( Array.prototype.slice.apply( this, arguments ),
+			"slice", Array.prototype.slice.call(arguments).join(",") );
+	},
+
+	map: function( callback ) {
+		return this.pushStack( jQuery.map(this, function(elem, i){
+			return callback.call( elem, i, elem );
+		}));
+	},
+
+	andSelf: function() {
+		return this.add( this.prevObject );
+	},
+
+	domManip: function( args, table, callback ) {
+		if ( this[0] ) {
+			var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
+				scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
+				first = fragment.firstChild;
+
+			if ( first )
+				for ( var i = 0, l = this.length; i < l; i++ )
+					callback.call( root(this[i], first), this.length > 1 || i > 0 ?
+							fragment.cloneNode(true) : fragment );
+		
+			if ( scripts )
+				jQuery.each( scripts, evalScript );
+		}
+
+		return this;
+		
+		function root( elem, cur ) {
+			return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
+				(elem.getElementsByTagName("tbody")[0] ||
+				elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
+				elem;
+		}
+	}
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+function evalScript( i, elem ) {
+	if ( elem.src )
+		jQuery.ajax({
+			url: elem.src,
+			async: false,
+			dataType: "script"
+		});
+
+	else
+		jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
+
+	if ( elem.parentNode )
+		elem.parentNode.removeChild( elem );
+}
+
+function now(){
+	return +new Date;
+}
+
+jQuery.extend = jQuery.fn.extend = function() {
+	// copy reference to target object
+	var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
+
+	// Handle a deep copy situation
+	if ( typeof target === "boolean" ) {
+		deep = target;
+		target = arguments[1] || {};
+		// skip the boolean and the target
+		i = 2;
+	}
+
+	// Handle case when target is a string or something (possible in deep copy)
+	if ( typeof target !== "object" && !jQuery.isFunction(target) )
+		target = {};
+
+	// extend jQuery itself if only one argument is passed
+	if ( length == i ) {
+		target = this;
+		--i;
+	}
+
+	for ( ; i < length; i++ )
+		// Only deal with non-null/undefined values
+		if ( (options = arguments[ i ]) != null )
+			// Extend the base object
+			for ( var name in options ) {
+				var src = target[ name ], copy = options[ name ];
+
+				// Prevent never-ending loop
+				if ( target === copy )
+					continue;
+
+				// Recurse if we're merging object values
+				if ( deep && copy && typeof copy === "object" && !copy.nodeType )
+					target[ name ] = jQuery.extend( deep, 
+						// Never move original objects, clone them
+						src || ( copy.length != null ? [ ] : { } )
+					, copy );
+
+				// Don't bring in undefined values
+				else if ( copy !== undefined )
+					target[ name ] = copy;
+
+			}
+
+	// Return the modified object
+	return target;
+};
+
+// exclude the following css properties to add px
+var	exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
+	// cache defaultView
+	defaultView = document.defaultView || {},
+	toString = Object.prototype.toString;
+
+jQuery.extend({
+	noConflict: function( deep ) {
+		window.$ = _$;
+
+		if ( deep )
+			window.jQuery = _jQuery;
+
+		return jQuery;
+	},
+
+	// See test/unit/core.js for details concerning isFunction.
+	// Since version 1.3, DOM methods and functions like alert
+	// aren't supported. They return false on IE (#2968).
+	isFunction: function( obj ) {
+		return toString.call(obj) === "[object Function]";
+	},
+
+	isArray: function( obj ) {
+		return toString.call(obj) === "[object Array]";
+	},
+
+	// check if an element is in a (or is an) XML document
+	isXMLDoc: function( elem ) {
+		return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
+			!!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
+	},
+
+	// Evalulates a script in a global context
+	globalEval: function( data ) {
+		if ( data && /\S/.test(data) ) {
+			// Inspired by code by Andrea Giammarchi
+			// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+			var head = document.getElementsByTagName("head")[0] || document.documentElement,
+				script = document.createElement("script");
+
+			script.type = "text/javascript";
+			if ( jQuery.support.scriptEval )
+				script.appendChild( document.createTextNode( data ) );
+			else
+				script.text = data;
+
+			// Use insertBefore instead of appendChild  to circumvent an IE6 bug.
+			// This arises when a base node is used (#2709).
+			head.insertBefore( script, head.firstChild );
+			head.removeChild( script );
+		}
+	},
+
+	nodeName: function( elem, name ) {
+		return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
+	},
+
+	// args is for internal usage only
+	each: function( object, callback, args ) {
+		var name, i = 0, length = object.length;
+
+		if ( args ) {
+			if ( length === undefined ) {
+				for ( name in object )
+					if ( callback.apply( object[ name ], args ) === false )
+						break;
+			} else
+				for ( ; i < length; )
+					if ( callback.apply( object[ i++ ], args ) === false )
+						break;
+
+		// A special, fast, case for the most common use of each
+		} else {
+			if ( length === undefined ) {
+				for ( name in object )
+					if ( callback.call( object[ name ], name, object[ name ] ) === false )
+						break;
+			} else
+				for ( var value = object[0];
+					i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
+		}
+
+		return object;
+	},
+
+	prop: function( elem, value, type, i, name ) {
+		// Handle executable functions
+		if ( jQuery.isFunction( value ) )
+			value = value.call( elem, i );
+
+		// Handle passing in a number to a CSS property
+		return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
+			value + "px" :
+			value;
+	},
+
+	className: {
+		// internal only, use addClass("class")
+		add: function( elem, classNames ) {
+			jQuery.each((classNames || "").split(/\s+/), function(i, className){
+				if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
+					elem.className += (elem.className ? " " : "") + className;
+			});
+		},
+
+		// internal only, use removeClass("class")
+		remove: function( elem, classNames ) {
+			if (elem.nodeType == 1)
+				elem.className = classNames !== undefined ?
+					jQuery.grep(elem.className.split(/\s+/), function(className){
+						return !jQuery.className.has( classNames, className );
+					}).join(" ") :
+					"";
+		},
+
+		// internal only, use hasClass("class")
+		has: function( elem, className ) {
+			return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
+		}
+	},
+
+	// A method for quickly swapping in/out CSS properties to get correct calculations
+	swap: function( elem, options, callback ) {
+		var old = {};
+		// Remember the old values, and insert the new ones
+		for ( var name in options ) {
+			old[ name ] = elem.style[ name ];
+			elem.style[ name ] = options[ name ];
+		}
+
+		callback.call( elem );
+
+		// Revert the old values
+		for ( var name in options )
+			elem.style[ name ] = old[ name ];
+	},
+
+	css: function( elem, name, force, extra ) {
+		if ( name == "width" || name == "height" ) {
+			var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
+
+			function getWH() {
+				val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
+
+				if ( extra === "border" )
+					return;
+
+				jQuery.each( which, function() {
+					if ( !extra )
+						val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
+					if ( extra === "margin" )
+						val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
+					else
+						val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
+				});
+			}
+
+			if ( elem.offsetWidth !== 0 )
+				getWH();
+			else
+				jQuery.swap( elem, props, getWH );
+
+			return Math.max(0, Math.round(val));
+		}
+
+		return jQuery.curCSS( elem, name, force );
+	},
+
+	curCSS: function( elem, name, force ) {
+		var ret, style = elem.style;
+
+		// We need to handle opacity special in IE
+		if ( name == "opacity" && !jQuery.support.opacity ) {
+			ret = jQuery.attr( style, "opacity" );
+
+			return ret == "" ?
+				"1" :
+				ret;
+		}
+
+		// Make sure we're using the right name for getting the float value
+		if ( name.match( /float/i ) )
+			name = styleFloat;
+
+		if ( !force && style && style[ name ] )
+			ret = style[ name ];
+
+		else if ( defaultView.getComputedStyle ) {
+
+			// Only "float" is needed here
+			if ( name.match( /float/i ) )
+				name = "float";
+
+			name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
+
+			var computedStyle = defaultView.getComputedStyle( elem, null );
+
+			if ( computedStyle )
+				ret = computedStyle.getPropertyValue( name );
+
+			// We should always get a number back from opacity
+			if ( name == "opacity" && ret == "" )
+				ret = "1";
+
+		} else if ( elem.currentStyle ) {
+			var camelCase = name.replace(/\-(\w)/g, function(all, letter){
+				return letter.toUpperCase();
+			});
+
+			ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
+
+			// From the awesome hack by Dean Edwards
+			// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+			// If we're not dealing with a regular pixel number
+			// but a number that has a weird ending, we need to convert it to pixels
+			if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
+				// Remember the original values
+				var left = style.left, rsLeft = elem.runtimeStyle.left;
+
+				// Put in the new values to get a computed value out
+				elem.runtimeStyle.left = elem.currentStyle.left;
+				style.left = ret || 0;
+				ret = style.pixelLeft + "px";
+
+				// Revert the changed values
+				style.left = left;
+				elem.runtimeStyle.left = rsLeft;
+			}
+		}
+
+		return ret;
+	},
+
+	clean: function( elems, context, fragment ) {
+		context = context || document;
+
+		// !context.createElement fails in IE with an error but returns typeof 'object'
+		if ( typeof context.createElement === "undefined" )
+			context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+
+		// If a single string is passed in and it's a single tag
+		// just do a createElement and skip the rest
+		if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
+			var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
+			if ( match )
+				return [ context.createElement( match[1] ) ];
+		}
+
+		var ret = [], scripts = [], div = context.createElement("div");
+
+		jQuery.each(elems, function(i, elem){
+			if ( typeof elem === "number" )
+				elem += '';
+
+			if ( !elem )
+				return;
+
+			// Convert html string into DOM nodes
+			if ( typeof elem === "string" ) {
+				// Fix "XHTML"-style tags in all browsers
+				elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
+					return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
+						all :
+						front + "></" + tag + ">";
+				});
+
+				// Trim whitespace, otherwise indexOf won't work as expected
+				var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();
+
+				var wrap =
+					// option or optgroup
+					!tags.indexOf("<opt") &&
+					[ 1, "<select multiple='multiple'>", "</select>" ] ||
+
+					!tags.indexOf("<leg") &&
+					[ 1, "<fieldset>", "</fieldset>" ] ||
+
+					tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
+					[ 1, "<table>", "</table>" ] ||
+
+					!tags.indexOf("<tr") &&
+					[ 2, "<table><tbody>", "</tbody></table>" ] ||
+
+				 	// <thead> matched above
+					(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
+					[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
+
+					!tags.indexOf("<col") &&
+					[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
+
+					// IE can't serialize <link> and <script> tags normally
+					!jQuery.support.htmlSerialize &&
+					[ 1, "div<div>", "</div>" ] ||
+
+					[ 0, "", "" ];
+
+				// Go to html and back, then peel off extra wrappers
+				div.innerHTML = wrap[1] + elem + wrap[2];
+
+				// Move to the right depth
+				while ( wrap[0]-- )
+					div = div.lastChild;
+
+				// Remove IE's autoinserted <tbody> from table fragments
+				if ( !jQuery.support.tbody ) {
+
+					// String was a <table>, *may* have spurious <tbody>
+					var hasBody = /<tbody/i.test(elem),
+						tbody = !tags.indexOf("<table") && !hasBody ?
+							div.firstChild && div.firstChild.childNodes :
+
+						// String was a bare <thead> or <tfoot>
+						wrap[1] == "<table>" && !hasBody ?
+							div.childNodes :
+							[];
+
+					for ( var j = tbody.length - 1; j >= 0 ; --j )
+						if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
+							tbody[ j ].parentNode.removeChild( tbody[ j ] );
+
+					}
+
+				// IE completely kills leading whitespace when innerHTML is used
+				if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
+					div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
+				
+				elem = jQuery.makeArray( div.childNodes );
+			}
+
+			if ( elem.nodeType )
+				ret.push( elem );
+			else
+				ret = jQuery.merge( ret, elem );
+
+		});
+
+		if ( fragment ) {
+			for ( var i = 0; ret[i]; i++ ) {
+				if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
+					scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
+				} else {
+					if ( ret[i].nodeType === 1 )
+						ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
+					fragment.appendChild( ret[i] );
+				}
+			}
+			
+			return scripts;
+		}
+
+		return ret;
+	},
+
+	attr: function( elem, name, value ) {
+		// don't set attributes on text and comment nodes
+		if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
+			return undefined;
+
+		var notxml = !jQuery.isXMLDoc( elem ),
+			// Whether we are setting (or getting)
+			set = value !== undefined;
+
+		// Try to normalize/fix the name
+		name = notxml && jQuery.props[ name ] || name;
+
+		// Only do all the following if this is a node (faster for style)
+		// IE elem.getAttribute passes even for style
+		if ( elem.tagName ) {
+
+			// These attributes require special treatment
+			var special = /href|src|style/.test( name );
+
+			// Safari mis-reports the default selected property of a hidden option
+			// Accessing the parent's selectedIndex property fixes it
+			if ( name == "selected" && elem.parentNode )
+				elem.parentNode.selectedIndex;
+
+			// If applicable, access the attribute via the DOM 0 way
+			if ( name in elem && notxml && !special ) {
+				if ( set ){
+					// We can't allow the type property to be changed (since it causes problems in IE)
+					if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
+						throw "type property can't be changed";
+
+					elem[ name ] = value;
+				}
+
+				// browsers index elements by id/name on forms, give priority to attributes.
+				if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
+					return elem.getAttributeNode( name ).nodeValue;
+
+				// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+				// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+				if ( name == "tabIndex" ) {
+					var attributeNode = elem.getAttributeNode( "tabIndex" );
+					return attributeNode && attributeNode.specified
+						? attributeNode.value
+						: elem.nodeName.match(/(button|input|object|select|textarea)/i)
+							? 0
+							: elem.nodeName.match(/^(a|area)$/i) && elem.href
+								? 0
+								: undefined;
+				}
+
+				return elem[ name ];
+			}
+
+			if ( !jQuery.support.style && notxml &&  name == "style" )
+				return jQuery.attr( elem.style, "cssText", value );
+
+			if ( set )
+				// convert the value to a string (all browsers do this but IE) see #1070
+				elem.setAttribute( name, "" + value );
+
+			var attr = !jQuery.support.hrefNormalized && notxml && special
+					// Some attributes require a special call on IE
+					? elem.getAttribute( name, 2 )
+					: elem.getAttribute( name );
+
+			// Non-existent attributes return null, we normalize to undefined
+			return attr === null ? undefined : attr;
+		}
+
+		// elem is actually elem.style ... set the style
+
+		// IE uses filters for opacity
+		if ( !jQuery.support.opacity && name == "opacity" ) {
+			if ( set ) {
+				// IE has trouble with opacity if it does not have layout
+				// Force it by setting the zoom level
+				elem.zoom = 1;
+
+				// Set the alpha filter to set the opacity
+				elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
+					(parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
+			}
+
+			return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
+				(parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
+				"";
+		}
+
+		name = name.replace(/-([a-z])/ig, function(all, letter){
+			return letter.toUpperCase();
+		});
+
+		if ( set )
+			elem[ name ] = value;
+
+		return elem[ name ];
+	},
+
+	trim: function( text ) {
+		return (text || "").replace( /^\s+|\s+$/g, "" );
+	},
+
+	makeArray: function( array ) {
+		var ret = [];
+
+		if( array != null ){
+			var i = array.length;
+			// The window, strings (and functions) also have 'length'
+			if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
+				ret[0] = array;
+			else
+				while( i )
+					ret[--i] = array[i];
+		}
+
+		return ret;
+	},
+
+	inArray: function( elem, array ) {
+		for ( var i = 0, length = array.length; i < length; i++ )
+		// Use === because on IE, window == document
+			if ( array[ i ] === elem )
+				return i;
+
+		return -1;
+	},
+
+	merge: function( first, second ) {
+		// We have to loop this way because IE & Opera overwrite the length
+		// expando of getElementsByTagName
+		var i = 0, elem, pos = first.length;
+		// Also, we need to make sure that the correct elements are being returned
+		// (IE returns comment nodes in a '*' query)
+		if ( !jQuery.support.getAll ) {
+			while ( (elem = second[ i++ ]) != null )
+				if ( elem.nodeType != 8 )
+					first[ pos++ ] = elem;
+
+		} else
+			while ( (elem = second[ i++ ]) != null )
+				first[ pos++ ] = elem;
+
+		return first;
+	},
+
+	unique: function( array ) {
+		var ret = [], done = {};
+
+		try {
+
+			for ( var i = 0, length = array.length; i < length; i++ ) {
+				var id = jQuery.data( array[ i ] );
+
+				if ( !done[ id ] ) {
+					done[ id ] = true;
+					ret.push( array[ i ] );
+				}
+			}
+
+		} catch( e ) {
+			ret = array;
+		}
+
+		return ret;
+	},
+
+	grep: function( elems, callback, inv ) {
+		var ret = [];
+
+		// Go through the array, only saving the items
+		// that pass the validator function
+		for ( var i = 0, length = elems.length; i < length; i++ )
+			if ( !inv != !callback( elems[ i ], i ) )
+				ret.push( elems[ i ] );
+
+		return ret;
+	},
+
+	map: function( elems, callback ) {
+		var ret = [];
+
+		// Go through the array, translating each of the items to their
+		// new value (or values).
+		for ( var i = 0, length = elems.length; i < length; i++ ) {
+			var value = callback( elems[ i ], i );
+
+			if ( value != null )
+				ret[ ret.length ] = value;
+		}
+
+		return ret.concat.apply( [], ret );
+	}
+});
+
+// Use of jQuery.browser is deprecated.
+// It's included for backwards compatibility and plugins,
+// although they should work to migrate away.
+
+var userAgent = navigator.userAgent.toLowerCase();
+
+// Figure out what browser is being used
+jQuery.browser = {
+	version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
+	safari: /webkit/.test( userAgent ),
+	opera: /opera/.test( userAgent ),
+	msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
+	mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
+};
+
+jQuery.each({
+	parent: function(elem){return elem.parentNode;},
+	parents: function(elem){return jQuery.dir(elem,"parentNode");},
+	next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
+	prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
+	nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
+	prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
+	siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
+	children: function(elem){return jQuery.sibling(elem.firstChild);},
+	contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
+}, function(name, fn){
+	jQuery.fn[ name ] = function( selector ) {
+		var ret = jQuery.map( this, fn );
+
+		if ( selector && typeof selector == "string" )
+			ret = jQuery.multiFilter( selector, ret );
+
+		return this.pushStack( jQuery.unique( ret ), name, selector );
+	};
+});
+
+jQuery.each({
+	appendTo: "append",
+	prependTo: "prepend",
+	insertBefore: "before",
+	insertAfter: "after",
+	replaceAll: "replaceWith"
+}, function(name, original){
+	jQuery.fn[ name ] = function( selector ) {
+		var ret = [], insert = jQuery( selector );
+
+		for ( var i = 0, l = insert.length; i < l; i++ ) {
+			var elems = (i > 0 ? this.clone(true) : this).get();
+			jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
+			ret = ret.concat( elems );
+		}
+
+		return this.pushStack( ret, name, selector );
+	};
+});
+
+jQuery.each({
+	removeAttr: function( name ) {
+		jQuery.attr( this, name, "" );
+		if (this.nodeType == 1)
+			this.removeAttribute( name );
+	},
+
+	addClass: function( classNames ) {
+		jQuery.className.add( this, classNames );
+	},
+
+	removeClass: function( classNames ) {
+		jQuery.className.remove( this, classNames );
+	},
+
+	toggleClass: function( classNames, state ) {
+		if( typeof state !== "boolean" )
+			state = !jQuery.className.has( this, classNames );
+		jQuery.className[ state ? "add" : "remove" ]( this, classNames );
+	},
+
+	remove: function( selector ) {
+		if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
+			// Prevent memory leaks
+			jQuery( "*", this ).add([this]).each(function(){
+				jQuery.event.remove(this);
+				jQuery.removeData(this);
+			});
+			if (this.parentNode)
+				this.parentNode.removeChild( this );
+		}
+	},
+
+	empty: function() {
+		// Remove element nodes and prevent memory leaks
+		jQuery(this).children().remove();
+
+		// Remove any remaining nodes
+		while ( this.firstChild )
+			this.removeChild( this.firstChild );
+	}
+}, function(name, fn){
+	jQuery.fn[ name ] = function(){
+		return this.each( fn, arguments );
+	};
+});
+
+// Helper function used by the dimensions and offset modules
+function num(elem, prop) {
+	return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
+}
+var expando = "jQuery" + now(), uuid = 0, windowData = {};
+
+jQuery.extend({
+	cache: {},
+
+	data: function( elem, name, data ) {
+		elem = elem == window ?
+			windowData :
+			elem;
+
+		var id = elem[ expando ];
+
+		// Compute a unique ID for the element
+		if ( !id )
+			id = elem[ expando ] = ++uuid;
+
+		// Only generate the data cache if we're
+		// trying to access or manipulate it
+		if ( name && !jQuery.cache[ id ] )
+			jQuery.cache[ id ] = {};
+
+		// Prevent overriding the named cache with undefined values
+		if ( data !== undefined )
+			jQuery.cache[ id ][ name ] = data;
+
+		// Return the named cache data, or the ID for the element
+		return name ?
+			jQuery.cache[ id ][ name ] :
+			id;
+	},
+
+	removeData: function( elem, name ) {
+		elem = elem == window ?
+			windowData :
+			elem;
+
+		var id = elem[ expando ];
+
+		// If we want to remove a specific section of the element's data
+		if ( name ) {
+			if ( jQuery.cache[ id ] ) {
+				// Remove the section of cache data
+				delete jQuery.cache[ id ][ name ];
+
+				// If we've removed all the data, remove the element's cache
+				name = "";
+
+				for ( name in jQuery.cache[ id ] )
+					break;
+
+				if ( !name )
+					jQuery.removeData( elem );
+			}
+
+		// Otherwise, we want to remove all of the element's data
+		} else {
+			// Clean up the element expando
+			try {
+				delete elem[ expando ];
+			} catch(e){
+				// IE has trouble directly removing the expando
+				// but it's ok with using removeAttribute
+				if ( elem.removeAttribute )
+					elem.removeAttribute( expando );
+			}
+
+			// Completely remove the data cache
+			delete jQuery.cache[ id ];
+		}
+	},
+	queue: function( elem, type, data ) {
+		if ( elem ){
+	
+			type = (type || "fx") + "queue";
+	
+			var q = jQuery.data( elem, type );
+	
+			if ( !q || jQuery.isArray(data) )
+				q = jQuery.data( elem, type, jQuery.makeArray(data) );
+			else if( data )
+				q.push( data );
+	
+		}
+		return q;
+	},
+
+	dequeue: function( elem, type ){
+		var queue = jQuery.queue( elem, type ),
+			fn = queue.shift();
+		
+		if( !type || type === "fx" )
+			fn = queue[0];
+			
+		if( fn !== undefined )
+			fn.call(elem);
+	}
+});
+
+jQuery.fn.extend({
+	data: function( key, value ){
+		var parts = key.split(".");
+		parts[1] = parts[1] ? "." + parts[1] : "";
+
+		if ( value === undefined ) {
+			var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+			if ( data === undefined && this.length )
+				data = jQuery.data( this[0], key );
+
+			return data === undefined && parts[1] ?
+				this.data( parts[0] ) :
+				data;
+		} else
+			return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
+				jQuery.data( this, key, value );
+			});
+	},
+
+	removeData: function( key ){
+		return this.each(function(){
+			jQuery.removeData( this, key );
+		});
+	},
+	queue: function(type, data){
+		if ( typeof type !== "string" ) {
+			data = type;
+			type = "fx";
+		}
+
+		if ( data === undefined )
+			return jQuery.queue( this[0], type );
+
+		return this.each(function(){
+			var queue = jQuery.queue( this, type, data );
+			
+			 if( type == "fx" && queue.length == 1 )
+				queue[0].call(this);
+		});
+	},
+	dequeue: function(type){
+		return this.each(function(){
+			jQuery.dequeue( this, type );
+		});
+	}
+});/*!
+ * Sizzle CSS Selector Engine - v0.9.3
+ *  Copyright 2009, The Dojo Foundation
+ *  Released under the MIT, BSD, and GPL Licenses.
+ *  More information: http://sizzlejs.com/
+ */
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
+	done = 0,
+	toString = Object.prototype.toString;
+
+var Sizzle = function(selector, context, results, seed) {
+	results = results || [];
+	context = context || document;
+
+	if ( context.nodeType !== 1 && context.nodeType !== 9 )
+		return [];
+	
+	if ( !selector || typeof selector !== "string" ) {
+		return results;
+	}
+
+	var parts = [], m, set, checkSet, check, mode, extra, prune = true;
+	
+	// Reset the position of the chunker regexp (start from head)
+	chunker.lastIndex = 0;
+	
+	while ( (m = chunker.exec(selector)) !== null ) {
+		parts.push( m[1] );
+		
+		if ( m[2] ) {
+			extra = RegExp.rightContext;
+			break;
+		}
+	}
+
+	if ( parts.length > 1 && origPOS.exec( selector ) ) {
+		if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+			set = posProcess( parts[0] + parts[1], context );
+		} else {
+			set = Expr.relative[ parts[0] ] ?
+				[ context ] :
+				Sizzle( parts.shift(), context );
+
+			while ( parts.length ) {
+				selector = parts.shift();
+
+				if ( Expr.relative[ selector ] )
+					selector += parts.shift();
+
+				set = posProcess( selector, set );
+			}
+		}
+	} else {
+		var ret = seed ?
+			{ expr: parts.pop(), set: makeArray(seed) } :
+			Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
+		set = Sizzle.filter( ret.expr, ret.set );
+
+		if ( parts.length > 0 ) {
+			checkSet = makeArray(set);
+		} else {
+			prune = false;
+		}
+
+		while ( parts.length ) {
+			var cur = parts.pop(), pop = cur;
+
+			if ( !Expr.relative[ cur ] ) {
+				cur = "";
+			} else {
+				pop = parts.pop();
+			}
+
+			if ( pop == null ) {
+				pop = context;
+			}
+
+			Expr.relative[ cur ]( checkSet, pop, isXML(context) );
+		}
+	}
+
+	if ( !checkSet ) {
+		checkSet = set;
+	}
+
+	if ( !checkSet ) {
+		throw "Syntax error, unrecognized expression: " + (cur || selector);
+	}
+
+	if ( toString.call(checkSet) === "[object Array]" ) {
+		if ( !prune ) {
+			results.push.apply( results, checkSet );
+		} else if ( context.nodeType === 1 ) {
+			for ( var i = 0; checkSet[i] != null; i++ ) {
+				if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
+					results.push( set[i] );
+				}
+			}
+		} else {
+			for ( var i = 0; checkSet[i] != null; i++ ) {
+				if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+					results.push( set[i] );
+				}
+			}
+		}
+	} else {
+		makeArray( checkSet, results );
+	}
+
+	if ( extra ) {
+		Sizzle( extra, context, results, seed );
+
+		if ( sortOrder ) {
+			hasDuplicate = false;
+			results.sort(sortOrder);
+
+			if ( hasDuplicate ) {
+				for ( var i = 1; i < results.length; i++ ) {
+					if ( results[i] === results[i-1] ) {
+						results.splice(i--, 1);
+					}
+				}
+			}
+		}
+	}
+
+	return results;
+};
+
+Sizzle.matches = function(expr, set){
+	return Sizzle(expr, null, null, set);
+};
+
+Sizzle.find = function(expr, context, isXML){
+	var set, match;
+
+	if ( !expr ) {
+		return [];
+	}
+
+	for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+		var type = Expr.order[i], match;
+		
+		if ( (match = Expr.match[ type ].exec( expr )) ) {
+			var left = RegExp.leftContext;
+
+			if ( left.substr( left.length - 1 ) !== "\\" ) {
+				match[1] = (match[1] || "").replace(/\\/g, "");
+				set = Expr.find[ type ]( match, context, isXML );
+				if ( set != null ) {
+					expr = expr.replace( Expr.match[ type ], "" );
+					break;
+				}
+			}
+		}
+	}
+
+	if ( !set ) {
+		set = context.getElementsByTagName("*");
+	}
+
+	return {set: set, expr: expr};
+};
+
+Sizzle.filter = function(expr, set, inplace, not){
+	var old = expr, result = [], curLoop = set, match, anyFound,
+		isXMLFilter = set && set[0] && isXML(set[0]);
+
+	while ( expr && set.length ) {
+		for ( var type in Expr.filter ) {
+			if ( (match = Expr.match[ type ].exec( expr )) != null ) {
+				var filter = Expr.filter[ type ], found, item;
+				anyFound = false;
+
+				if ( curLoop == result ) {
+					result = [];
+				}
+
+				if ( Expr.preFilter[ type ] ) {
+					match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
+
+					if ( !match ) {
+						anyFound = found = true;
+					} else if ( match === true ) {
+						continue;
+					}
+				}
+
+				if ( match ) {
+					for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+						if ( item ) {
+							found = filter( item, match, i, curLoop );
+							var pass = not ^ !!found;
+
+							if ( inplace && found != null ) {
+								if ( pass ) {
+									anyFound = true;
+								} else {
+									curLoop[i] = false;
+								}
+							} else if ( pass ) {
+								result.push( item );
+								anyFound = true;
+							}
+						}
+					}
+				}
+
+				if ( found !== undefined ) {
+					if ( !inplace ) {
+						curLoop = result;
+					}
+
+					expr = expr.replace( Expr.match[ type ], "" );
+
+					if ( !anyFound ) {
+						return [];
+					}
+
+					break;
+				}
+			}
+		}
+
+		// Improper expression
+		if ( expr == old ) {
+			if ( anyFound == null ) {
+				throw "Syntax error, unrecognized expression: " + expr;
+			} else {
+				break;
+			}
+		}
+
+		old = expr;
+	}
+
+	return curLoop;
+};
+
+var Expr = Sizzle.selectors = {
+	order: [ "ID", "NAME", "TAG" ],
+	match: {
+		ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
+		CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
+		NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
+		ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
+		TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
+		CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
+		POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
+		PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
+	},
+	attrMap: {
+		"class": "className",
+		"for": "htmlFor"
+	},
+	attrHandle: {
+		href: function(elem){
+			return elem.getAttribute("href");
+		}
+	},
+	relative: {
+		"+": function(checkSet, part, isXML){
+			var isPartStr = typeof part === "string",
+				isTag = isPartStr && !/\W/.test(part),
+				isPartStrNotTag = isPartStr && !isTag;
+
+			if ( isTag && !isXML ) {
+				part = part.toUpperCase();
+			}
+
+			for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
+				if ( (elem = checkSet[i]) ) {
+					while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
+
+					checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
+						elem || false :
+						elem === part;
+				}
+			}
+
+			if ( isPartStrNotTag ) {
+				Sizzle.filter( part, checkSet, true );
+			}
+		},
+		">": function(checkSet, part, isXML){
+			var isPartStr = typeof part === "string";
+
+			if ( isPartStr && !/\W/.test(part) ) {
+				part = isXML ? part : part.toUpperCase();
+
+				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+					var elem = checkSet[i];
+					if ( elem ) {
+						var parent = elem.parentNode;
+						checkSet[i] = parent.nodeName === part ? parent : false;
+					}
+				}
+			} else {
+				for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+					var elem = checkSet[i];
+					if ( elem ) {
+						checkSet[i] = isPartStr ?
+							elem.parentNode :
+							elem.parentNode === part;
+					}
+				}
+
+				if ( isPartStr ) {
+					Sizzle.filter( part, checkSet, true );
+				}
+			}
+		},
+		"": function(checkSet, part, isXML){
+			var doneName = done++, checkFn = dirCheck;
+
+			if ( !part.match(/\W/) ) {
+				var nodeCheck = part = isXML ? part : part.toUpperCase();
+				checkFn = dirNodeCheck;
+			}
+
+			checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
+		},
+		"~": function(checkSet, part, isXML){
+			var doneName = done++, checkFn = dirCheck;
+
+			if ( typeof part === "string" && !part.match(/\W/) ) {
+				var nodeCheck = part = isXML ? part : part.toUpperCase();
+				checkFn = dirNodeCheck;
+			}
+
+			checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
+		}
+	},
+	find: {
+		ID: function(match, context, isXML){
+			if ( typeof context.getElementById !== "undefined" && !isXML ) {
+				var m = context.getElementById(match[1]);
+				return m ? [m] : [];
+			}
+		},
+		NAME: function(match, context, isXML){
+			if ( typeof context.getElementsByName !== "undefined" ) {
+				var ret = [], results = context.getElementsByName(match[1]);
+
+				for ( var i = 0, l = results.length; i < l; i++ ) {
+					if ( results[i].getAttribute("name") === match[1] ) {
+						ret.push( results[i] );
+					}
+				}
+
+				return ret.length === 0 ? null : ret;
+			}
+		},
+		TAG: function(match, context){
+			return context.getElementsByTagName(match[1]);
+		}
+	},
+	preFilter: {
+		CLASS: function(match, curLoop, inplace, result, not, isXML){
+			match = " " + match[1].replace(/\\/g, "") + " ";
+
+			if ( isXML ) {
+				return match;
+			}
+
+			for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
+				if ( elem ) {
+					if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
+						if ( !inplace )
+							result.push( elem );
+					} else if ( inplace ) {
+						curLoop[i] = false;
+					}
+				}
+			}
+
+			return false;
+		},
+		ID: function(match){
+			return match[1].replace(/\\/g, "");
+		},
+		TAG: function(match, curLoop){
+			for ( var i = 0; curLoop[i] === false; i++ ){}
+			return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
+		},
+		CHILD: function(match){
+			if ( match[1] == "nth" ) {
+				// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+				var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+					match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
+					!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+				// calculate the numbers (first)n+(last) including if they are negative
+				match[2] = (test[1] + (test[2] || 1)) - 0;
+				match[3] = test[3] - 0;
+			}
+
+			// TODO: Move to normal caching system
+			match[0] = done++;
+
+			return match;
+		},
+		ATTR: function(match, curLoop, inplace, result, not, isXML){
+			var name = match[1].replace(/\\/g, "");
+			
+			if ( !isXML && Expr.attrMap[name] ) {
+				match[1] = Expr.attrMap[name];
+			}
+
+			if ( match[2] === "~=" ) {
+				match[4] = " " + match[4] + " ";
+			}
+
+			return match;
+		},
+		PSEUDO: function(match, curLoop, inplace, result, not){
+			if ( match[1] === "not" ) {
+				// If we're dealing with a complex expression, or a simple one
+				if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
+					match[3] = Sizzle(match[3], null, null, curLoop);
+				} else {
+					var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+					if ( !inplace ) {
+						result.push.apply( result, ret );
+					}
+					return false;
+				}
+			} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
+				return true;
+			}
+			
+			return match;
+		},
+		POS: function(match){
+			match.unshift( true );
+			return match;
+		}
+	},
+	filters: {
+		enabled: function(elem){
+			return elem.disabled === false && elem.type !== "hidden";
+		},
+		disabled: function(elem){
+			return elem.disabled === true;
+		},
+		checked: function(elem){
+			return elem.checked === true;
+		},
+		selected: function(elem){
+			// Accessing this property makes selected-by-default
+			// options in Safari work properly
+			elem.parentNode.selectedIndex;
+			return elem.selected === true;
+		},
+		parent: function(elem){
+			return !!elem.firstChild;
+		},
+		empty: function(elem){
+			return !elem.firstChild;
+		},
+		has: function(elem, i, match){
+			return !!Sizzle( match[3], elem ).length;
+		},
+		header: function(elem){
+			return /h\d/i.test( elem.nodeName );
+		},
+		text: function(elem){
+			return "text" === elem.type;
+		},
+		radio: function(elem){
+			return "radio" === elem.type;
+		},
+		checkbox: function(elem){
+			return "checkbox" === elem.type;
+		},
+		file: function(elem){
+			return "file" === elem.type;
+		},
+		password: function(elem){
+			return "password" === elem.type;
+		},
+		submit: function(elem){
+			return "submit" === elem.type;
+		},
+		image: function(elem){
+			return "image" === elem.type;
+		},
+		reset: function(elem){
+			return "reset" === elem.type;
+		},
+		button: function(elem){
+			return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
+		},
+		input: function(elem){
+			return /input|select|textarea|button/i.test(elem.nodeName);
+		}
+	},
+	setFilters: {
+		first: function(elem, i){
+			return i === 0;
+		},
+		last: function(elem, i, match, array){
+			return i === array.length - 1;
+		},
+		even: function(elem, i){
+			return i % 2 === 0;
+		},
+		odd: function(elem, i){
+			return i % 2 === 1;
+		},
+		lt: function(elem, i, match){
+			return i < match[3] - 0;
+		},
+		gt: function(elem, i, match){
+			return i > match[3] - 0;
+		},
+		nth: function(elem, i, match){
+			return match[3] - 0 == i;
+		},
+		eq: function(elem, i, match){
+			return match[3] - 0 == i;
+		}
+	},
+	filter: {
+		PSEUDO: function(elem, match, i, array){
+			var name = match[1], filter = Expr.filters[ name ];
+
+			if ( filter ) {
+				return filter( elem, i, match, array );
+			} else if ( name === "contains" ) {
+				return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
+			} else if ( name === "not" ) {
+				var not = match[3];
+
+				for ( var i = 0, l = not.length; i < l; i++ ) {
+					if ( not[i] === elem ) {
+						return false;
+					}
+				}
+
+				return true;
+			}
+		},
+		CHILD: function(elem, match){
+			var type = match[1], node = elem;
+			switch (type) {
+				case 'only':
+				case 'first':
+					while (node = node.previousSibling)  {
+						if ( node.nodeType === 1 ) return false;
+					}
+					if ( type == 'first') return true;
+					node = elem;
+				case 'last':
+					while (node = node.nextSibling)  {
+						if ( node.nodeType === 1 ) return false;
+					}
+					return true;
+				case 'nth':
+					var first = match[2], last = match[3];
+
+					if ( first == 1 && last == 0 ) {
+						return true;
+					}
+					
+					var doneName = match[0],
+						parent = elem.parentNode;
+	
+					if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
+						var count = 0;
+						for ( node = parent.firstChild; node; node = node.nextSibling ) {
+							if ( node.nodeType === 1 ) {
+								node.nodeIndex = ++count;
+							}
+						} 
+						parent.sizcache = doneName;
+					}
+					
+					var diff = elem.nodeIndex - last;
+					if ( first == 0 ) {
+						return diff == 0;
+					} else {
+						return ( diff % first == 0 && diff / first >= 0 );
+					}
+			}
+		},
+		ID: function(elem, match){
+			return elem.nodeType === 1 && elem.getAttribute("id") === match;
+		},
+		TAG: function(elem, match){
+			return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
+		},
+		CLASS: function(elem, match){
+			return (" " + (elem.className || elem.getAttribute("class")) + " ")
+				.indexOf( match ) > -1;
+		},
+		ATTR: function(elem, match){
+			var name = match[1],
+				result = Expr.attrHandle[ name ] ?
+					Expr.attrHandle[ name ]( elem ) :
+					elem[ name ] != null ?
+						elem[ name ] :
+						elem.getAttribute( name ),
+				value = result + "",
+				type = match[2],
+				check = match[4];
+
+			return result == null ?
+				type === "!=" :
+				type === "=" ?
+				value === check :
+				type === "*=" ?
+				value.indexOf(check) >= 0 :
+				type === "~=" ?
+				(" " + value + " ").indexOf(check) >= 0 :
+				!check ?
+				value && result !== false :
+				type === "!=" ?
+				value != check :
+				type === "^=" ?
+				value.indexOf(check) === 0 :
+				type === "$=" ?
+				value.substr(value.length - check.length) === check :
+				type === "|=" ?
+				value === check || value.substr(0, check.length + 1) === check + "-" :
+				false;
+		},
+		POS: function(elem, match, i, array){
+			var name = match[2], filter = Expr.setFilters[ name ];
+
+			if ( filter ) {
+				return filter( elem, i, match, array );
+			}
+		}
+	}
+};
+
+var origPOS = Expr.match.POS;
+
+for ( var type in Expr.match ) {
+	Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
+}
+
+var makeArray = function(array, results) {
+	array = Array.prototype.slice.call( array );
+
+	if ( results ) {
+		results.push.apply( results, array );
+		return results;
+	}
+	
+	return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+try {
+	Array.prototype.slice.call( document.documentElement.childNodes );
+
+// Provide a fallback method if it does not work
+} catch(e){
+	makeArray = function(array, results) {
+		var ret = results || [];
+
+		if ( toString.call(array) === "[object Array]" ) {
+			Array.prototype.push.apply( ret, array );
+		} else {
+			if ( typeof array.length === "number" ) {
+				for ( var i = 0, l = array.length; i < l; i++ ) {
+					ret.push( array[i] );
+				}
+			} else {
+				for ( var i = 0; array[i]; i++ ) {
+					ret.push( array[i] );
+				}
+			}
+		}
+
+		return ret;
+	};
+}
+
+var sortOrder;
+
+if ( document.documentElement.compareDocumentPosition ) {
+	sortOrder = function( a, b ) {
+		var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
+		if ( ret === 0 ) {
+			hasDuplicate = true;
+		}
+		return ret;
+	};
+} else if ( "sourceIndex" in document.documentElement ) {
+	sortOrder = function( a, b ) {
+		var ret = a.sourceIndex - b.sourceIndex;
+		if ( ret === 0 ) {
+			hasDuplicate = true;
+		}
+		return ret;
+	};
+} else if ( document.createRange ) {
+	sortOrder = function( a, b ) {
+		var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
+		aRange.selectNode(a);
+		aRange.collapse(true);
+		bRange.selectNode(b);
+		bRange.collapse(true);
+		var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
+		if ( ret === 0 ) {
+			hasDuplicate = true;
+		}
+		return ret;
+	};
+}
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+	// We're going to inject a fake input element with a specified name
+	var form = document.createElement("form"),
+		id = "script" + (new Date).getTime();
+	form.innerHTML = "<input name='" + id + "'/>";
+
+	// Inject it into the root element, check its status, and remove it quickly
+	var root = document.documentElement;
+	root.insertBefore( form, root.firstChild );
+
+	// The workaround has to do additional checks after a getElementById
+	// Which slows things down for other browsers (hence the branching)
+	if ( !!document.getElementById( id ) ) {
+		Expr.find.ID = function(match, context, isXML){
+			if ( typeof context.getElementById !== "undefined" && !isXML ) {
+				var m = context.getElementById(match[1]);
+				return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
+			}
+		};
+
+		Expr.filter.ID = function(elem, match){
+			var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+			return elem.nodeType === 1 && node && node.nodeValue === match;
+		};
+	}
+
+	root.removeChild( form );
+})();
+
+(function(){
+	// Check to see if the browser returns only elements
+	// when doing getElementsByTagName("*")
+
+	// Create a fake element
+	var div = document.createElement("div");
+	div.appendChild( document.createComment("") );
+
+	// Make sure no comments are found
+	if ( div.getElementsByTagName("*").length > 0 ) {
+		Expr.find.TAG = function(match, context){
+			var results = context.getElementsByTagName(match[1]);
+
+			// Filter out possible comments
+			if ( match[1] === "*" ) {
+				var tmp = [];
+
+				for ( var i = 0; results[i]; i++ ) {
+					if ( results[i].nodeType === 1 ) {
+						tmp.push( results[i] );
+					}
+				}
+
+				results = tmp;
+			}
+
+			return results;
+		};
+	}
+
+	// Check to see if an attribute returns normalized href attributes
+	div.innerHTML = "<a href='#'></a>";
+	if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+			div.firstChild.getAttribute("href") !== "#" ) {
+		Expr.attrHandle.href = function(elem){
+			return elem.getAttribute("href", 2);
+		};
+	}
+})();
+
+if ( document.querySelectorAll ) (function(){
+	var oldSizzle = Sizzle, div = document.createElement("div");
+	div.innerHTML = "<p class='TEST'></p>";
+
+	// Safari can't handle uppercase or unicode characters when
+	// in quirks mode.
+	if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+		return;
+	}
+	
+	Sizzle = function(query, context, extra, seed){
+		context = context || document;
+
+		// Only use querySelectorAll on non-XML documents
+		// (ID selectors don't work in non-HTML documents)
+		if ( !seed && context.nodeType === 9 && !isXML(context) ) {
+			try {
+				return makeArray( context.querySelectorAll(query), extra );
+			} catch(e){}
+		}
+		
+		return oldSizzle(query, context, extra, seed);
+	};
+
+	Sizzle.find = oldSizzle.find;
+	Sizzle.filter = oldSizzle.filter;
+	Sizzle.selectors = oldSizzle.selectors;
+	Sizzle.matches = oldSizzle.matches;
+})();
+
+if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
+	var div = document.createElement("div");
+	div.innerHTML = "<div class='test e'></div><div class='test'></div>";
+
+	// Opera can't find a second classname (in 9.6)
+	if ( div.getElementsByClassName("e").length === 0 )
+		return;
+
+	// Safari caches class attributes, doesn't catch changes (in 3.2)
+	div.lastChild.className = "e";
+
+	if ( div.getElementsByClassName("e").length === 1 )
+		return;
+
+	Expr.order.splice(1, 0, "CLASS");
+	Expr.find.CLASS = function(match, context, isXML) {
+		if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
+			return context.getElementsByClassName(match[1]);
+		}
+	};
+})();
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+	var sibDir = dir == "previousSibling" && !isXML;
+	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+		var elem = checkSet[i];
+		if ( elem ) {
+			if ( sibDir && elem.nodeType === 1 ){
+				elem.sizcache = doneName;
+				elem.sizset = i;
+			}
+			elem = elem[dir];
+			var match = false;
+
+			while ( elem ) {
+				if ( elem.sizcache === doneName ) {
+					match = checkSet[elem.sizset];
+					break;
+				}
+
+				if ( elem.nodeType === 1 && !isXML ){
+					elem.sizcache = doneName;
+					elem.sizset = i;
+				}
+
+				if ( elem.nodeName === cur ) {
+					match = elem;
+					break;
+				}
+
+				elem = elem[dir];
+			}
+
+			checkSet[i] = match;
+		}
+	}
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+	var sibDir = dir == "previousSibling" && !isXML;
+	for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+		var elem = checkSet[i];
+		if ( elem ) {
+			if ( sibDir && elem.nodeType === 1 ) {
+				elem.sizcache = doneName;
+				elem.sizset = i;
+			}
+			elem = elem[dir];
+			var match = false;
+
+			while ( elem ) {
+				if ( elem.sizcache === doneName ) {
+					match = checkSet[elem.sizset];
+					break;
+				}
+
+				if ( elem.nodeType === 1 ) {
+					if ( !isXML ) {
+						elem.sizcache = doneName;
+						elem.sizset = i;
+					}
+					if ( typeof cur !== "string" ) {
+						if ( elem === cur ) {
+							match = true;
+							break;
+						}
+
+					} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+						match = elem;
+						break;
+					}
+				}
+
+				elem = elem[dir];
+			}
+
+			checkSet[i] = match;
+		}
+	}
+}
+
+var contains = document.compareDocumentPosition ?  function(a, b){
+	return a.compareDocumentPosition(b) & 16;
+} : function(a, b){
+	return a !== b && (a.contains ? a.contains(b) : true);
+};
+
+var isXML = function(elem){
+	return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
+		!!elem.ownerDocument && isXML( elem.ownerDocument );
+};
+
+var posProcess = function(selector, context){
+	var tmpSet = [], later = "", match,
+		root = context.nodeType ? [context] : context;
+
+	// Position selectors must be done after the filter
+	// And so must :not(positional) so we move all PSEUDOs to the end
+	while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+		later += match[0];
+		selector = selector.replace( Expr.match.PSEUDO, "" );
+	}
+
+	selector = Expr.relative[selector] ? selector + "*" : selector;
+
+	for ( var i = 0, l = root.length; i < l; i++ ) {
+		Sizzle( selector, root[i], tmpSet );
+	}
+
+	return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.filter = Sizzle.filter;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+
+Sizzle.selectors.filters.hidden = function(elem){
+	return elem.offsetWidth === 0 || elem.offsetHeight === 0;
+};
+
+Sizzle.selectors.filters.visible = function(elem){
+	return elem.offsetWidth > 0 || elem.offsetHeight > 0;
+};
+
+Sizzle.selectors.filters.animated = function(elem){
+	return jQuery.grep(jQuery.timers, function(fn){
+		return elem === fn.elem;
+	}).length;
+};
+
+jQuery.multiFilter = function( expr, elems, not ) {
+	if ( not ) {
+		expr = ":not(" + expr + ")";
+	}
+
+	return Sizzle.matches(expr, elems);
+};
+
+jQuery.dir = function( elem, dir ){
+	var matched = [], cur = elem[dir];
+	while ( cur && cur != document ) {
+		if ( cur.nodeType == 1 )
+			matched.push( cur );
+		cur = cur[dir];
+	}
+	return matched;
+};
+
+jQuery.nth = function(cur, result, dir, elem){
+	result = result || 1;
+	var num = 0;
+
+	for ( ; cur; cur = cur[dir] )
+		if ( cur.nodeType == 1 && ++num == result )
+			break;
+
+	return cur;
+};
+
+jQuery.sibling = function(n, elem){
+	var r = [];
+
+	for ( ; n; n = n.nextSibling ) {
+		if ( n.nodeType == 1 && n != elem )
+			r.push( n );
+	}
+
+	return r;
+};
+
+return;
+
+window.Sizzle = Sizzle;
+
+})();
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+	// Bind an event to an element
+	// Original by Dean Edwards
+	add: function(elem, types, handler, data) {
+		if ( elem.nodeType == 3 || elem.nodeType == 8 )
+			return;
+
+		// For whatever reason, IE has trouble passing the window object
+		// around, causing it to be cloned in the process
+		if ( elem.setInterval && elem != window )
+			elem = window;
+
+		// Make sure that the function being executed has a unique ID
+		if ( !handler.guid )
+			handler.guid = this.guid++;
+
+		// if data is passed, bind to handler
+		if ( data !== undefined ) {
+			// Create temporary function pointer to original handler
+			var fn = handler;
+
+			// Create unique handler function, wrapped around original handler
+			handler = this.proxy( fn );
+
+			// Store data in unique handler
+			handler.data = data;
+		}
+
+		// Init the element's event structure
+		var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
+			handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
+				// Handle the second event of a trigger and when
+				// an event is called after a page has unloaded
+				return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
+					jQuery.event.handle.apply(arguments.callee.elem, arguments) :
+					undefined;
+			});
+		// Add elem as a property of the handle function
+		// This is to prevent a memory leak with non-native
+		// event in IE.
+		handle.elem = elem;
+
+		// Handle multiple events separated by a space
+		// jQuery(...).bind("mouseover mouseout", fn);
+		jQuery.each(types.split(/\s+/), function(index, type) {
+			// Namespaced event handlers
+			var namespaces = type.split(".");
+			type = namespaces.shift();
+			handler.type = namespaces.slice().sort().join(".");
+
+			// Get the current list of functions bound to this event
+			var handlers = events[type];
+			
+			if ( jQuery.event.specialAll[type] )
+				jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
+
+			// Init the event handler queue
+			if (!handlers) {
+				handlers = events[type] = {};
+
+				// Check for a special event handler
+				// Only use addEventListener/attachEvent if the special
+				// events handler returns false
+				if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
+					// Bind the global event handler to the element
+					if (elem.addEventListener)
+						elem.addEventListener(type, handle, false);
+					else if (elem.attachEvent)
+						elem.attachEvent("on" + type, handle);
+				}
+			}
+
+			// Add the function to the element's handler list
+			handlers[handler.guid] = handler;
+
+			// Keep track of which events have been used, for global triggering
+			jQuery.event.global[type] = true;
+		});
+
+		// Nullify elem to prevent memory leaks in IE
+		elem = null;
+	},
+
+	guid: 1,
+	global: {},
+
+	// Detach an event or set of events from an element
+	remove: function(elem, types, handler) {
+		// don't do events on text and comment nodes
+		if ( elem.nodeType == 3 || elem.nodeType == 8 )
+			return;
+
+		var events = jQuery.data(elem, "events"), ret, index;
+
+		if ( events ) {
+			// Unbind all events for the element
+			if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
+				for ( var type in events )
+					this.remove( elem, type + (types || "") );
+			else {
+				// types is actually an event object here
+				if ( types.type ) {
+					handler = types.handler;
+					types = types.type;
+				}
+
+				// Handle multiple events seperated by a space
+				// jQuery(...).unbind("mouseover mouseout", fn);
+				jQuery.each(types.split(/\s+/), function(index, type){
+					// Namespaced event handlers
+					var namespaces = type.split(".");
+					type = namespaces.shift();
+					var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
+
+					if ( events[type] ) {
+						// remove the given handler for the given type
+						if ( handler )
+							delete events[type][handler.guid];
+
+						// remove all handlers for the given type
+						else
+							for ( var handle in events[type] )
+								// Handle the removal of namespaced events
+								if ( namespace.test(events[type][handle].type) )
+									delete events[type][handle];
+									
+						if ( jQuery.event.specialAll[type] )
+							jQuery.event.specialAll[type].teardown.call(elem, namespaces);
+
+						// remove generic event handler if no more handlers exist
+						for ( ret in events[type] ) break;
+						if ( !ret ) {
+							if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
+								if (elem.removeEventListener)
+									elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
+								else if (elem.detachEvent)
+									elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
+							}
+							ret = null;
+							delete events[type];
+						}
+					}
+				});
+			}
+
+			// Remove the expando if it's no longer used
+			for ( ret in events ) break;
+			if ( !ret ) {
+				var handle = jQuery.data( elem, "handle" );
+				if ( handle ) handle.elem = null;
+				jQuery.removeData( elem, "events" );
+				jQuery.removeData( elem, "handle" );
+			}
+		}
+	},
+
+	// bubbling is internal
+	trigger: function( event, data, elem, bubbling ) {
+		// Event object or event type
+		var type = event.type || event;
+
+		if( !bubbling ){
+			event = typeof event === "object" ?
+				// jQuery.Event object
+				event[expando] ? event :
+				// Object literal
+				jQuery.extend( jQuery.Event(type), event ) :
+				// Just the event type (string)
+				jQuery.Event(type);
+
+			if ( type.indexOf("!") >= 0 ) {
+				event.type = type = type.slice(0, -1);
+				event.exclusive = true;
+			}
+
+			// Handle a global trigger
+			if ( !elem ) {
+				// Don't bubble custom events when global (to avoid too much overhead)
+				event.stopPropagation();
+				// Only trigger if we've ever bound an event for it
+				if ( this.global[type] )
+					jQuery.each( jQuery.cache, function(){
+						if ( this.events && this.events[type] )
+							jQuery.event.trigger( event, data, this.handle.elem );
+					});
+			}
+
+			// Handle triggering a single element
+
+			// don't do events on text and comment nodes
+			if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
+				return undefined;
+			
+			// Clean up in case it is reused
+			event.result = undefined;
+			event.target = elem;
+			
+			// Clone the incoming data, if any
+			data = jQuery.makeArray(data);
+			data.unshift( event );
+		}
+
+		event.currentTarget = elem;
+
+		// Trigger the event, it is assumed that "handle" is a function
+		var handle = jQuery.data(elem, "handle");
+		if ( handle )
+			handle.apply( elem, data );
+
+		// Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
+		if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
+			event.result = false;
+
+		// Trigger the native events (except for clicks on links)
+		if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
+			this.triggered = true;
+			try {
+				elem[ type ]();
+			// prevent IE from throwing an error for some hidden elements
+			} catch (e) {}
+		}
+
+		this.triggered = false;
+
+		if ( !event.isPropagationStopped() ) {
+			var parent = elem.parentNode || elem.ownerDocument;
+			if ( parent )
+				jQuery.event.trigger(event, data, parent, true);
+		}
+	},
+
+	handle: function(event) {
+		// returned undefined or false
+		var all, handlers;
+
+		event = arguments[0] = jQuery.event.fix( event || window.event );
+		event.currentTarget = this;
+		
+		// Namespaced event handlers
+		var namespaces = event.type.split(".");
+		event.type = namespaces.shift();
+
+		// Cache this now, all = true means, any handler
+		all = !namespaces.length && !event.exclusive;
+		
+		var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
+
+		handlers = ( jQuery.data(this, "events") || {} )[event.type];
+
+		for ( var j in handlers ) {
+			var handler = handlers[j];
+
+			// Filter the functions by class
+			if ( all || namespace.test(handler.type) ) {
+				// Pass in a reference to the handler function itself
+				// So that we can later remove it
+				event.handler = handler;
+				event.data = handler.data;
+
+				var ret = handler.apply(this, arguments);
+
+				if( ret !== undefined ){
+					event.result = ret;
+					if ( ret === false ) {
+						event.preventDefault();
+						event.stopPropagation();
+					}
+				}
+
+				if( event.isImmediatePropagationStopped() )
+					break;
+
+			}
+		}
+	},
+
+	props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+	fix: function(event) {
+		if ( event[expando] )
+			return event;
+
+		// store a copy of the original event object
+		// and "clone" to set read-only properties
+		var originalEvent = event;
+		event = jQuery.Event( originalEvent );
+
+		for ( var i = this.props.length, prop; i; ){
+			prop = this.props[ --i ];
+			event[ prop ] = originalEvent[ prop ];
+		}
+
+		// Fix target property, if necessary
+		if ( !event.target )
+			event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
+
+		// check if target is a textnode (safari)
+		if ( event.target.nodeType == 3 )
+			event.target = event.target.parentNode;
+
+		// Add relatedTarget, if necessary
+		if ( !event.relatedTarget && event.fromElement )
+			event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
+
+		// Calculate pageX/Y if missing and clientX/Y available
+		if ( event.pageX == null && event.clientX != null ) {
+			var doc = document.documentElement, body = document.body;
+			event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
+			event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
+		}
+
+		// Add which for key events
+		if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
+			event.which = event.charCode || event.keyCode;
+
+		// Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+		if ( !event.metaKey && event.ctrlKey )
+			event.metaKey = event.ctrlKey;
+
+		// Add which for click: 1 == left; 2 == middle; 3 == right
+		// Note: button is not normalized, so don't use it
+		if ( !event.which && event.button )
+			event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+
+		return event;
+	},
+
+	proxy: function( fn, proxy ){
+		proxy = proxy || function(){ return fn.apply(this, arguments); };
+		// Set the guid of unique handler to the same of original handler, so it can be removed
+		proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
+		// So proxy can be declared as an argument
+		return proxy;
+	},
+
+	special: {
+		ready: {
+			// Make sure the ready event is setup
+			setup: bindReady,
+			teardown: function() {}
+		}
+	},
+	
+	specialAll: {
+		live: {
+			setup: function( selector, namespaces ){
+				jQuery.event.add( this, namespaces[0], liveHandler );
+			},
+			teardown:  function( namespaces ){
+				if ( namespaces.length ) {
+					var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
+					
+					jQuery.each( (jQuery.data(this, "events").live || {}), function(){
+						if ( name.test(this.type) )
+							remove++;
+					});
+					
+					if ( remove < 1 )
+						jQuery.event.remove( this, namespaces[0], liveHandler );
+				}
+			}
+		}
+	}
+};
+
+jQuery.Event = function( src ){
+	// Allow instantiation without the 'new' keyword
+	if( !this.preventDefault )
+		return new jQuery.Event(src);
+	
+	// Event object
+	if( src && src.type ){
+		this.originalEvent = src;
+		this.type = src.type;
+	// Event type
+	}else
+		this.type = src;
+
+	// timeStamp is buggy for some events on Firefox(#3843)
+	// So we won't rely on the native value
+	this.timeStamp = now();
+	
+	// Mark it as fixed
+	this[expando] = true;
+};
+
+function returnFalse(){
+	return false;
+}
+function returnTrue(){
+	return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+	preventDefault: function() {
+		this.isDefaultPrevented = returnTrue;
+
+		var e = this.originalEvent;
+		if( !e )
+			return;
+		// if preventDefault exists run it on the original event
+		if (e.preventDefault)
+			e.preventDefault();
+		// otherwise set the returnValue property of the original event to false (IE)
+		e.returnValue = false;
+	},
+	stopPropagation: function() {
+		this.isPropagationStopped = returnTrue;
+
+		var e = this.originalEvent;
+		if( !e )
+			return;
+		// if stopPropagation exists run it on the original event
+		if (e.stopPropagation)
+			e.stopPropagation();
+		// otherwise set the cancelBubble property of the original event to true (IE)
+		e.cancelBubble = true;
+	},
+	stopImmediatePropagation:function(){
+		this.isImmediatePropagationStopped = returnTrue;
+		this.stopPropagation();
+	},
+	isDefaultPrevented: returnFalse,
+	isPropagationStopped: returnFalse,
+	isImmediatePropagationStopped: returnFalse
+};
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function(event) {
+	// Check if mouse(over|out) are still within the same parent element
+	var parent = event.relatedTarget;
+	// Traverse up the tree
+	while ( parent && parent != this )
+		try { parent = parent.parentNode; }
+		catch(e) { parent = this; }
+	
+	if( parent != this ){
+		// set the correct event type
+		event.type = event.data;
+		// handle event if we actually just moused on to a non sub-element
+		jQuery.event.handle.apply( this, arguments );
+	}
+};
+	
+jQuery.each({ 
+	mouseover: 'mouseenter', 
+	mouseout: 'mouseleave'
+}, function( orig, fix ){
+	jQuery.event.special[ fix ] = {
+		setup: function(){
+			jQuery.event.add( this, orig, withinElement, fix );
+		},
+		teardown: function(){
+			jQuery.event.remove( this, orig, withinElement );
+		}
+	};			   
+});
+
+jQuery.fn.extend({
+	bind: function( type, data, fn ) {
+		return type == "unload" ? this.one(type, data, fn) : this.each(function(){
+			jQuery.event.add( this, type, fn || data, fn && data );
+		});
+	},
+
+	one: function( type, data, fn ) {
+		var one = jQuery.event.proxy( fn || data, function(event) {
+			jQuery(this).unbind(event, one);
+			return (fn || data).apply( this, arguments );
+		});
+		return this.each(function(){
+			jQuery.event.add( this, type, one, fn && data);
+		});
+	},
+
+	unbind: function( type, fn ) {
+		return this.each(function(){
+			jQuery.event.remove( this, type, fn );
+		});
+	},
+
+	trigger: function( type, data ) {
+		return this.each(function(){
+			jQuery.event.trigger( type, data, this );
+		});
+	},
+
+	triggerHandler: function( type, data ) {
+		if( this[0] ){
+			var event = jQuery.Event(type);
+			event.preventDefault();
+			event.stopPropagation();
+			jQuery.event.trigger( event, data, this[0] );
+			return event.result;
+		}		
+	},
+
+	toggle: function( fn ) {
+		// Save reference to arguments for access in closure
+		var args = arguments, i = 1;
+
+		// link all the functions, so any of them can unbind this click handler
+		while( i < args.length )
+			jQuery.event.proxy( fn, args[i++] );
+
+		return this.click( jQuery.event.proxy( fn, function(event) {
+			// Figure out which function to execute
+			this.lastToggle = ( this.lastToggle || 0 ) % i;
+
+			// Make sure that clicks stop
+			event.preventDefault();
+
+			// and execute the function
+			return args[ this.lastToggle++ ].apply( this, arguments ) || false;
+		}));
+	},
+
+	hover: function(fnOver, fnOut) {
+		return this.mouseenter(fnOver).mouseleave(fnOut);
+	},
+
+	ready: function(fn) {
+		// Attach the listeners
+		bindReady();
+
+		// If the DOM is already ready
+		if ( jQuery.isReady )
+			// Execute the function immediately
+			fn.call( document, jQuery );
+
+		// Otherwise, remember the function for later
+		else
+			// Add the function to the wait list
+			jQuery.readyList.push( fn );
+
+		return this;
+	},
+	
+	live: function( type, fn ){
+		var proxy = jQuery.event.proxy( fn );
+		proxy.guid += this.selector + type;
+
+		jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );
+
+		return this;
+	},
+	
+	die: function( type, fn ){
+		jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
+		return this;
+	}
+});
+
+function liveHandler( event ){
+	var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
+		stop = true,
+		elems = [];
+
+	jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
+		if ( check.test(fn.type) ) {
+			var elem = jQuery(event.target).closest(fn.data)[0];
+			if ( elem )
+				elems.push({ elem: elem, fn: fn });
+		}
+	});
+
+	elems.sort(function(a,b) {
+		return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
+	});
+	
+	jQuery.each(elems, function(){
+		if ( this.fn.call(this.elem, event, this.fn.data) === false )
+			return (stop = false);
+	});
+
+	return stop;
+}
+
+function liveConvert(type, selector){
+	return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
+}
+
+jQuery.extend({
+	isReady: false,
+	readyList: [],
+	// Handle when the DOM is ready
+	ready: function() {
+		// Make sure that the DOM is not already loaded
+		if ( !jQuery.isReady ) {
+			// Remember that the DOM is ready
+			jQuery.isReady = true;
+
+			// If there are functions bound, to execute
+			if ( jQuery.readyList ) {
+				// Execute all of them
+				jQuery.each( jQuery.readyList, function(){
+					this.call( document, jQuery );
+				});
+
+				// Reset the list of functions
+				jQuery.readyList = null;
+			}
+
+			// Trigger any bound ready events
+			jQuery(document).triggerHandler("ready");
+		}
+	}
+});
+
+var readyBound = false;
+
+function bindReady(){
+	if ( readyBound ) return;
+	readyBound = true;
+
+	// Mozilla, Opera and webkit nightlies currently support this event
+	if ( document.addEventListener ) {
+		// Use the handy event callback
+		document.addEventListener( "DOMContentLoaded", function(){
+			document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
+			jQuery.ready();
+		}, false );
+
+	// If IE event model is used
+	} else if ( document.attachEvent ) {
+		// ensure firing before onload,
+		// maybe late but safe also for iframes
+		document.attachEvent("onreadystatechange", function(){
+			if ( document.readyState === "complete" ) {
+				document.detachEvent( "onreadystatechange", arguments.callee );
+				jQuery.ready();
+			}
+		});
+
+		// If IE and not an iframe
+		// continually check to see if the document is ready
+		if ( document.documentElement.doScroll && window == window.top ) (function(){
+			if ( jQuery.isReady ) return;
+
+			try {
+				// If IE is used, use the trick by Diego Perini
+				// http://javascript.nwbox.com/IEContentLoaded/
+				document.documentElement.doScroll("left");
+			} catch( error ) {
+				setTimeout( arguments.callee, 0 );
+				return;
+			}
+
+			// and execute any waiting functions
+			jQuery.ready();
+		})();
+	}
+
+	// A fallback to window.onload, that will always work
+	jQuery.event.add( window, "load", jQuery.ready );
+}
+
+jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
+	"mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
+	"change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
+
+	// Handle event binding
+	jQuery.fn[name] = function(fn){
+		return fn ? this.bind(name, fn) : this.trigger(name);
+	};
+});
+
+// Prevent memory leaks in IE
+// And prevent errors on refresh with events like mouseover in other browsers
+// Window isn't included so as not to unbind existing unload events
+jQuery( window ).bind( 'unload', function(){ 
+	for ( var id in jQuery.cache )
+		// Skip the window
+		if ( id != 1 && jQuery.cache[ id ].handle )
+			jQuery.event.remove( jQuery.cache[ id ].handle.elem );
+}); 
+(function(){
+
+	jQuery.support = {};
+
+	var root = document.documentElement,
+		script = document.createElement("script"),
+		div = document.createElement("div"),
+		id = "script" + (new Date).getTime();
+
+	div.style.display = "none";
+	div.innerHTML = '   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
+
+	var all = div.getElementsByTagName("*"),
+		a = div.getElementsByTagName("a")[0];
+
+	// Can't get basic test support
+	if ( !all || !all.length || !a ) {
+		return;
+	}
+
+	jQuery.support = {
+		// IE strips leading whitespace when .innerHTML is used
+		leadingWhitespace: div.firstChild.nodeType == 3,
+		
+		// Make sure that tbody elements aren't automatically inserted
+		// IE will insert them into empty tables
+		tbody: !div.getElementsByTagName("tbody").length,
+		
+		// Make sure that you can get all elements in an <object> element
+		// IE 7 always returns no results
+		objectAll: !!div.getElementsByTagName("object")[0]
+			.getElementsByTagName("*").length,
+		
+		// Make sure that link elements get serialized correctly by innerHTML
+		// This requires a wrapper element in IE
+		htmlSerialize: !!div.getElementsByTagName("link").length,
+		
+		// Get the style information from getAttribute
+		// (IE uses .cssText insted)
+		style: /red/.test( a.getAttribute("style") ),
+		
+		// Make sure that URLs aren't manipulated
+		// (IE normalizes it by default)
+		hrefNormalized: a.getAttribute("href") === "/a",
+		
+		// Make sure that element opacity exists
+		// (IE uses filter instead)
+		opacity: a.style.opacity === "0.5",
+		
+		// Verify style float existence
+		// (IE uses styleFloat instead of cssFloat)
+		cssFloat: !!a.style.cssFloat,
+
+		// Will be defined later
+		scriptEval: false,
+		noCloneEvent: true,
+		boxModel: null
+	};
+	
+	script.type = "text/javascript";
+	try {
+		script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
+	} catch(e){}
+
+	root.insertBefore( script, root.firstChild );
+	
+	// Make sure that the execution of code works by injecting a script
+	// tag with appendChild/createTextNode
+	// (IE doesn't support this, fails, and uses .text instead)
+	if ( window[ id ] ) {
+		jQuery.support.scriptEval = true;
+		delete window[ id ];
+	}
+
+	root.removeChild( script );
+
+	if ( div.attachEvent && div.fireEvent ) {
+		div.attachEvent("onclick", function(){
+			// Cloning a node shouldn't copy over any
+			// bound event handlers (IE does this)
+			jQuery.support.noCloneEvent = false;
+			div.detachEvent("onclick", arguments.callee);
+		});
+		div.cloneNode(true).fireEvent("onclick");
+	}
+
+	// Figure out if the W3C box model works as expected
+	// document.body must exist before we can do this
+	jQuery(function(){
+		var div = document.createElement("div");
+		div.style.width = div.style.paddingLeft = "1px";
+
+		document.body.appendChild( div );
+		jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
+		document.body.removeChild( div ).style.display = 'none';
+	});
+})();
+
+var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
+
+jQuery.props = {
+	"for": "htmlFor",
+	"class": "className",
+	"float": styleFloat,
+	cssFloat: styleFloat,
+	styleFloat: styleFloat,
+	readonly: "readOnly",
+	maxlength: "maxLength",
+	cellspacing: "cellSpacing",
+	rowspan: "rowSpan",
+	tabindex: "tabIndex"
+};
+jQuery.fn.extend({
+	// Keep a copy of the old load
+	_load: jQuery.fn.load,
+
+	load: function( url, params, callback ) {
+		if ( typeof url !== "string" )
+			return this._load( url );
+
+		var off = url.indexOf(" ");
+		if ( off >= 0 ) {
+			var selector = url.slice(off, url.length);
+			url = url.slice(0, off);
+		}
+
+		// Default to a GET request
+		var type = "GET";
+
+		// If the second parameter was provided
+		if ( params )
+			// If it's a function
+			if ( jQuery.isFunction( params ) ) {
+				// We assume that it's the callback
+				callback = params;
+				params = null;
+
+			// Otherwise, build a param string
+			} else if( typeof params === "object" ) {
+				params = jQuery.param( params );
+				type = "POST";
+			}
+
+		var self = this;
+
+		// Request the remote document
+		jQuery.ajax({
+			url: url,
+			type: type,
+			dataType: "html",
+			data: params,
+			complete: function(res, status){
+				// If successful, inject the HTML into all the matched elements
+				if ( status == "success" || status == "notmodified" )
+					// See if a selector was specified
+					self.html( selector ?
+						// Create a dummy div to hold the results
+						jQuery("<div/>")
+							// inject the contents of the document in, removing the scripts
+							// to avoid any 'Permission Denied' errors in IE
+							.append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
+
+							// Locate the specified elements
+							.find(selector) :
+
+						// If not, just inject the full result
+						res.responseText );
+
+				if( callback )
+					self.each( callback, [res.responseText, status, res] );
+			}
+		});
+		return this;
+	},
+
+	serialize: function() {
+		return jQuery.param(this.serializeArray());
+	},
+	serializeArray: function() {
+		return this.map(function(){
+			return this.elements ? jQuery.makeArray(this.elements) : this;
+		})
+		.filter(function(){
+			return this.name && !this.disabled &&
+				(this.checked || /select|textarea/i.test(this.nodeName) ||
+					/text|hidden|password|search/i.test(this.type));
+		})
+		.map(function(i, elem){
+			var val = jQuery(this).val();
+			return val == null ? null :
+				jQuery.isArray(val) ?
+					jQuery.map( val, function(val, i){
+						return {name: elem.name, value: val};
+					}) :
+					{name: elem.name, value: val};
+		}).get();
+	}
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
+	jQuery.fn[o] = function(f){
+		return this.bind(o, f);
+	};
+});
+
+var jsc = now();
+
+jQuery.extend({
+  
+	get: function( url, data, callback, type ) {
+		// shift arguments if data argument was ommited
+		if ( jQuery.isFunction( data ) ) {
+			callback = data;
+			data = null;
+		}
+
+		return jQuery.ajax({
+			type: "GET",
+			url: url,
+			data: data,
+			success: callback,
+			dataType: type
+		});
+	},
+
+	getScript: function( url, callback ) {
+		return jQuery.get(url, null, callback, "script");
+	},
+
+	getJSON: function( url, data, callback ) {
+		return jQuery.get(url, data, callback, "json");
+	},
+
+	post: function( url, data, callback, type ) {
+		if ( jQuery.isFunction( data ) ) {
+			callback = data;
+			data = {};
+		}
+
+		return jQuery.ajax({
+			type: "POST",
+			url: url,
+			data: data,
+			success: callback,
+			dataType: type
+		});
+	},
+
+	ajaxSetup: function( settings ) {
+		jQuery.extend( jQuery.ajaxSettings, settings );
+	},
+
+	ajaxSettings: {
+		url: location.href,
+		global: true,
+		type: "GET",
+		contentType: "application/x-www-form-urlencoded",
+		processData: true,
+		async: true,
+		/*
+		timeout: 0,
+		data: null,
+		username: null,
+		password: null,
+		*/
+		// Create the request object; Microsoft failed to properly
+		// implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
+		// This function can be overriden by calling jQuery.ajaxSetup
+		xhr:function(){
+			return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
+		},
+		accepts: {
+			xml: "application/xml, text/xml",
+			html: "text/html",
+			script: "text/javascript, application/javascript",
+			json: "application/json, text/javascript",
+			text: "text/plain",
+			_default: "*/*"
+		}
+	},
+
+	// Last-Modified header cache for next request
+	lastModified: {},
+
+	ajax: function( s ) {
+		// Extend the settings, but re-extend 's' so that it can be
+		// checked again later (in the test suite, specifically)
+		s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
+
+		var jsonp, jsre = /=\?(&|$)/g, status, data,
+			type = s.type.toUpperCase();
+
+		// convert data if not already a string
+		if ( s.data && s.processData && typeof s.data !== "string" )
+			s.data = jQuery.param(s.data);
+
+		// Handle JSONP Parameter Callbacks
+		if ( s.dataType == "jsonp" ) {
+			if ( type == "GET" ) {
+				if ( !s.url.match(jsre) )
+					s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
+			} else if ( !s.data || !s.data.match(jsre) )
+				s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
+			s.dataType = "json";
+		}
+
+		// Build temporary JSONP function
+		if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
+			jsonp = "jsonp" + jsc++;
+
+			// Replace the =? sequence both in the query string and the data
+			if ( s.data )
+				s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+			s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+
+			// We need to make sure
+			// that a JSONP style response is executed properly
+			s.dataType = "script";
+
+			// Handle JSONP-style loading
+			window[ jsonp ] = function(tmp){
+				data = tmp;
+				success();
+				complete();
+				// Garbage collect
+				window[ jsonp ] = undefined;
+				try{ delete window[ jsonp ]; } catch(e){}
+				if ( head )
+					head.removeChild( script );
+			};
+		}
+
+		if ( s.dataType == "script" && s.cache == null )
+			s.cache = false;
+
+		if ( s.cache === false && type == "GET" ) {
+			var ts = now();
+			// try replacing _= if it is there
+			var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
+			// if nothing was replaced, add timestamp to the end
+			s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
+		}
+
+		// If data is available, append data to url for get requests
+		if ( s.data && type == "GET" ) {
+			s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
+
+			// IE likes to send both get and post data, prevent this
+			s.data = null;
+		}
+
+		// Watch for a new set of requests
+		if ( s.global && ! jQuery.active++ )
+			jQuery.event.trigger( "ajaxStart" );
+
+		// Matches an absolute URL, and saves the domain
+		var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
+
+		// If we're requesting a remote document
+		// and trying to load JSON or Script with a GET
+		if ( s.dataType == "script" && type == "GET" && parts
+			&& ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
+
+			var head = document.getElementsByTagName("head")[0];
+			var script = document.createElement("script");
+			script.src = s.url;
+			if (s.scriptCharset)
+				script.charset = s.scriptCharset;
+
+			// Handle Script loading
+			if ( !jsonp ) {
+				var done = false;
+
+				// Attach handlers for all browsers
+				script.onload = script.onreadystatechange = function(){
+					if ( !done && (!this.readyState ||
+							this.readyState == "loaded" || this.readyState == "complete") ) {
+						done = true;
+						success();
+						complete();
+
+						// Handle memory leak in IE
+						script.onload = script.onreadystatechange = null;
+						head.removeChild( script );
+					}
+				};
+			}
+
+			head.appendChild(script);
+
+			// We handle everything using the script element injection
+			return undefined;
+		}
+
+		var requestDone = false;
+
+		// Create the request object
+		var xhr = s.xhr();
+
+		// Open the socket
+		// Passing null username, generates a login popup on Opera (#2865)
+		if( s.username )
+			xhr.open(type, s.url, s.async, s.username, s.password);
+		else
+			xhr.open(type, s.url, s.async);
+
+		// Need an extra try/catch for cross domain requests in Firefox 3
+		try {
+			// Set the correct header, if data is being sent
+			if ( s.data )
+				xhr.setRequestHeader("Content-Type", s.contentType);
+
+			// Set the If-Modified-Since header, if ifModified mode.
+			if ( s.ifModified )
+				xhr.setRequestHeader("If-Modified-Since",
+					jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
+
+			// Set header so the called script knows that it's an XMLHttpRequest
+			xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+
+			// Set the Accepts header for the server, depending on the dataType
+			xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
+				s.accepts[ s.dataType ] + ", */*" :
+				s.accepts._default );
+		} catch(e){}
+
+		// Allow custom headers/mimetypes and early abort
+		if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
+			// Handle the global AJAX counter
+			if ( s.global && ! --jQuery.active )
+				jQuery.event.trigger( "ajaxStop" );
+			// close opended socket
+			xhr.abort();
+			return false;
+		}
+
+		if ( s.global )
+			jQuery.event.trigger("ajaxSend", [xhr, s]);
+
+		// Wait for a response to come back
+		var onreadystatechange = function(isTimeout){
+			// The request was aborted, clear the interval and decrement jQuery.active
+			if (xhr.readyState == 0) {
+				if (ival) {
+					// clear poll interval
+					clearInterval(ival);
+					ival = null;
+					// Handle the global AJAX counter
+					if ( s.global && ! --jQuery.active )
+						jQuery.event.trigger( "ajaxStop" );
+				}
+			// The transfer is complete and the data is available, or the request timed out
+			} else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
+				requestDone = true;
+
+				// clear poll interval
+				if (ival) {
+					clearInterval(ival);
+					ival = null;
+				}
+
+				status = isTimeout == "timeout" ? "timeout" :
+					!jQuery.httpSuccess( xhr ) ? "error" :
+					s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
+					"success";
+
+				if ( status == "success" ) {
+					// Watch for, and catch, XML document parse errors
+					try {
+						// process the data (runs the xml through httpData regardless of callback)
+						data = jQuery.httpData( xhr, s.dataType, s );
+					} catch(e) {
+						status = "parsererror";
+					}
+				}
+
+				// Make sure that the request was successful or notmodified
+				if ( status == "success" ) {
+					// Cache Last-Modified header, if ifModified mode.
+					var modRes;
+					try {
+						modRes = xhr.getResponseHeader("Last-Modified");
+					} catch(e) {} // swallow exception thrown by FF if header is not available
+
+					if ( s.ifModified && modRes )
+						jQuery.lastModified[s.url] = modRes;
+
+					// JSONP handles its own success callback
+					if ( !jsonp )
+						success();
+				} else
+					jQuery.handleError(s, xhr, status);
+
+				// Fire the complete handlers
+				complete();
+
+				if ( isTimeout )
+					xhr.abort();
+
+				// Stop memory leaks
+				if ( s.async )
+					xhr = null;
+			}
+		};
+
+		if ( s.async ) {
+			// don't attach the handler to the request, just poll it instead
+			var ival = setInterval(onreadystatechange, 13);
+
+			// Timeout checker
+			if ( s.timeout > 0 )
+				setTimeout(function(){
+					// Check to see if the request is still happening
+					if ( xhr && !requestDone )
+						onreadystatechange( "timeout" );
+				}, s.timeout);
+		}
+
+		// Send the data
+		try {
+			xhr.send(s.data);
+		} catch(e) {
+			jQuery.handleError(s, xhr, null, e);
+		}
+
+		// firefox 1.5 doesn't fire statechange for sync requests
+		if ( !s.async )
+			onreadystatechange();
+
+		function success(){
+			// If a local callback was specified, fire it and pass it the data
+			if ( s.success )
+				s.success( data, status );
+
+			// Fire the global callback
+			if ( s.global )
+				jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
+		}
+
+		function complete(){
+			// Process result
+			if ( s.complete )
+				s.complete(xhr, status);
+
+			// The request was completed
+			if ( s.global )
+				jQuery.event.trigger( "ajaxComplete", [xhr, s] );
+
+			// Handle the global AJAX counter
+			if ( s.global && ! --jQuery.active )
+				jQuery.event.trigger( "ajaxStop" );
+		}
+
+		// return XMLHttpRequest to allow aborting the request etc.
+		return xhr;
+	},
+
+	handleError: function( s, xhr, status, e ) {
+		// If a local callback was specified, fire it
+		if ( s.error ) s.error( xhr, status, e );
+
+		// Fire the global callback
+		if ( s.global )
+			jQuery.event.trigger( "ajaxError", [xhr, s, e] );
+	},
+
+	// Counter for holding the number of active queries
+	active: 0,
+
+	// Determines if an XMLHttpRequest was successful or not
+	httpSuccess: function( xhr ) {
+		try {
+			// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
+			return !xhr.status && location.protocol == "file:" ||
+				( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
+		} catch(e){}
+		return false;
+	},
+
+	// Determines if an XMLHttpRequest returns NotModified
+	httpNotModified: function( xhr, url ) {
+		try {
+			var xhrRes = xhr.getResponseHeader("Last-Modified");
+
+			// Firefox always returns 200. check Last-Modified date
+			return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
+		} catch(e){}
+		return false;
+	},
+
+	httpData: function( xhr, type, s ) {
+		var ct = xhr.getResponseHeader("content-type"),
+			xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
+			data = xml ? xhr.responseXML : xhr.responseText;
+
+		if ( xml && data.documentElement.tagName == "parsererror" )
+			throw "parsererror";
+			
+		// Allow a pre-filtering function to sanitize the response
+		// s != null is checked to keep backwards compatibility
+		if( s && s.dataFilter )
+			data = s.dataFilter( data, type );
+
+		// The filter can actually parse the response
+		if( typeof data === "string" ){
+
+			// If the type is "script", eval it in global context
+			if ( type == "script" )
+				jQuery.globalEval( data );
+
+			// Get the JavaScript object, if JSON is used.
+			if ( type == "json" )
+				data = window["eval"]("(" + data + ")");
+		}
+		
+		return data;
+	},
+
+	// Serialize an array of form elements or a set of
+	// key/values into a query string
+	param: function( a ) {
+		var s = [ ];
+
+		function add( key, value ){
+			s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
+		};
+
+		// If an array was passed in, assume that it is an array
+		// of form elements
+		if ( jQuery.isArray(a) || a.jquery )
+			// Serialize the form elements
+			jQuery.each( a, function(){
+				add( this.name, this.value );
+			});
+
+		// Otherwise, assume that it's an object of key/value pairs
+		else
+			// Serialize the key/values
+			for ( var j in a )
+				// If the value is an array then the key names need to be repeated
+				if ( jQuery.isArray(a[j]) )
+					jQuery.each( a[j], function(){
+						add( j, this );
+					});
+				else
+					add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
+
+		// Return the resulting serialization
+		return s.join("&").replace(/%20/g, "+");
+	}
+
+});
+var elemdisplay = {},
+	timerId,
+	fxAttrs = [
+		// height animations
+		[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
+		// width animations
+		[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
+		// opacity animations
+		[ "opacity" ]
+	];
+
+function genFx( type, num ){
+	var obj = {};
+	jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
+		obj[ this ] = type;
+	});
+	return obj;
+}
+
+jQuery.fn.extend({
+	show: function(speed,callback){
+		if ( speed ) {
+			return this.animate( genFx("show", 3), speed, callback);
+		} else {
+			for ( var i = 0, l = this.length; i < l; i++ ){
+				var old = jQuery.data(this[i], "olddisplay");
+				
+				this[i].style.display = old || "";
+				
+				if ( jQuery.css(this[i], "display") === "none" ) {
+					var tagName = this[i].tagName, display;
+					
+					if ( elemdisplay[ tagName ] ) {
+						display = elemdisplay[ tagName ];
+					} else {
+						var elem = jQuery("<" + tagName + " />").appendTo("body");
+						
+						display = elem.css("display");
+						if ( display === "none" )
+							display = "block";
+						
+						elem.remove();
+						
+						elemdisplay[ tagName ] = display;
+					}
+					
+					jQuery.data(this[i], "olddisplay", display);
+				}
+			}
+
+			// Set the display of the elements in a second loop
+			// to avoid the constant reflow
+			for ( var i = 0, l = this.length; i < l; i++ ){
+				this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
+			}
+			
+			return this;
+		}
+	},
+
+	hide: function(speed,callback){
+		if ( speed ) {
+			return this.animate( genFx("hide", 3), speed, callback);
+		} else {
+			for ( var i = 0, l = this.length; i < l; i++ ){
+				var old = jQuery.data(this[i], "olddisplay");
+				if ( !old && old !== "none" )
+					jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
+			}
+
+			// Set the display of the elements in a second loop
+			// to avoid the constant reflow
+			for ( var i = 0, l = this.length; i < l; i++ ){
+				this[i].style.display = "none";
+			}
+
+			return this;
+		}
+	},
+
+	// Save the old toggle function
+	_toggle: jQuery.fn.toggle,
+
+	toggle: function( fn, fn2 ){
+		var bool = typeof fn === "boolean";
+
+		return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
+			this._toggle.apply( this, arguments ) :
+			fn == null || bool ?
+				this.each(function(){
+					var state = bool ? fn : jQuery(this).is(":hidden");
+					jQuery(this)[ state ? "show" : "hide" ]();
+				}) :
+				this.animate(genFx("toggle", 3), fn, fn2);
+	},
+
+	fadeTo: function(speed,to,callback){
+		return this.animate({opacity: to}, speed, callback);
+	},
+
+	animate: function( prop, speed, easing, callback ) {
+		var optall = jQuery.speed(speed, easing, callback);
+
+		return this[ optall.queue === false ? "each" : "queue" ](function(){
+		
+			var opt = jQuery.extend({}, optall), p,
+				hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
+				self = this;
+	
+			for ( p in prop ) {
+				if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
+					return opt.complete.call(this);
+
+				if ( ( p == "height" || p == "width" ) && this.style ) {
+					// Store display property
+					opt.display = jQuery.css(this, "display");
+
+					// Make sure that nothing sneaks out
+					opt.overflow = this.style.overflow;
+				}
+			}
+
+			if ( opt.overflow != null )
+				this.style.overflow = "hidden";
+
+			opt.curAnim = jQuery.extend({}, prop);
+
+			jQuery.each( prop, function(name, val){
+				var e = new jQuery.fx( self, opt, name );
+
+				if ( /toggle|show|hide/.test(val) )
+					e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+				else {
+					var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
+						start = e.cur(true) || 0;
+
+					if ( parts ) {
+						var end = parseFloat(parts[2]),
+							unit = parts[3] || "px";
+
+						// We need to compute starting value
+						if ( unit != "px" ) {
+							self.style[ name ] = (end || 1) + unit;
+							start = ((end || 1) / e.cur(true)) * start;
+							self.style[ name ] = start + unit;
+						}
+
+						// If a +=/-= token was provided, we're doing a relative animation
+						if ( parts[1] )
+							end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
+
+						e.custom( start, end, unit );
+					} else
+						e.custom( start, val, "" );
+				}
+			});
+
+			// For JS strict compliance
+			return true;
+		});
+	},
+
+	stop: function(clearQueue, gotoEnd){
+		var timers = jQuery.timers;
+
+		if (clearQueue)
+			this.queue([]);
+
+		this.each(function(){
+			// go in reverse order so anything added to the queue during the loop is ignored
+			for ( var i = timers.length - 1; i >= 0; i-- )
+				if ( timers[i].elem == this ) {
+					if (gotoEnd)
+						// force the next step to be the last
+						timers[i](true);
+					timers.splice(i, 1);
+				}
+		});
+
+		// start the next in the queue if the last step wasn't forced
+		if (!gotoEnd)
+			this.dequeue();
+
+		return this;
+	}
+
+});
+
+// Generate shortcuts for custom animations
+jQuery.each({
+	slideDown: genFx("show", 1),
+	slideUp: genFx("hide", 1),
+	slideToggle: genFx("toggle", 1),
+	fadeIn: { opacity: "show" },
+	fadeOut: { opacity: "hide" }
+}, function( name, props ){
+	jQuery.fn[ name ] = function( speed, callback ){
+		return this.animate( props, speed, callback );
+	};
+});
+
+jQuery.extend({
+
+	speed: function(speed, easing, fn) {
+		var opt = typeof speed === "object" ? speed : {
+			complete: fn || !fn && easing ||
+				jQuery.isFunction( speed ) && speed,
+			duration: speed,
+			easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
+		};
+
+		opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+			jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
+
+		// Queueing
+		opt.old = opt.complete;
+		opt.complete = function(){
+			if ( opt.queue !== false )
+				jQuery(this).dequeue();
+			if ( jQuery.isFunction( opt.old ) )
+				opt.old.call( this );
+		};
+
+		return opt;
+	},
+
+	easing: {
+		linear: function( p, n, firstNum, diff ) {
+			return firstNum + diff * p;
+		},
+		swing: function( p, n, firstNum, diff ) {
+			return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+		}
+	},
+
+	timers: [],
+
+	fx: function( elem, options, prop ){
+		this.options = options;
+		this.elem = elem;
+		this.prop = prop;
+
+		if ( !options.orig )
+			options.orig = {};
+	}
+
+});
+
+jQuery.fx.prototype = {
+
+	// Simple function for setting a style value
+	update: function(){
+		if ( this.options.step )
+			this.options.step.call( this.elem, this.now, this );
+
+		(jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+
+		// Set display property to block for height/width animations
+		if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
+			this.elem.style.display = "block";
+	},
+
+	// Get the current size
+	cur: function(force){
+		if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
+			return this.elem[ this.prop ];
+
+		var r = parseFloat(jQuery.css(this.elem, this.prop, force));
+		return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
+	},
+
+	// Start an animation from one number to another
+	custom: function(from, to, unit){
+		this.startTime = now();
+		this.start = from;
+		this.end = to;
+		this.unit = unit || this.unit || "px";
+		this.now = this.start;
+		this.pos = this.state = 0;
+
+		var self = this;
+		function t(gotoEnd){
+			return self.step(gotoEnd);
+		}
+
+		t.elem = this.elem;
+
+		if ( t() && jQuery.timers.push(t) && !timerId ) {
+			timerId = setInterval(function(){
+				var timers = jQuery.timers;
+
+				for ( var i = 0; i < timers.length; i++ )
+					if ( !timers[i]() )
+						timers.splice(i--, 1);
+
+				if ( !timers.length ) {
+					clearInterval( timerId );
+					timerId = undefined;
+				}
+			}, 13);
+		}
+	},
+
+	// Simple 'show' function
+	show: function(){
+		// Remember where we started, so that we can go back to it later
+		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+		this.options.show = true;
+
+		// Begin the animation
+		// Make sure that we start at a small width/height to avoid any
+		// flash of content
+		this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());
+
+		// Start by showing the element
+		jQuery(this.elem).show();
+	},
+
+	// Simple 'hide' function
+	hide: function(){
+		// Remember where we started, so that we can go back to it later
+		this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+		this.options.hide = true;
+
+		// Begin the animation
+		this.custom(this.cur(), 0);
+	},
+
+	// Each step of an animation
+	step: function(gotoEnd){
+		var t = now();
+
+		if ( gotoEnd || t >= this.options.duration + this.startTime ) {
+			this.now = this.end;
+			this.pos = this.state = 1;
+			this.update();
+
+			this.options.curAnim[ this.prop ] = true;
+
+			var done = true;
+			for ( var i in this.options.curAnim )
+				if ( this.options.curAnim[i] !== true )
+					done = false;
+
+			if ( done ) {
+				if ( this.options.display != null ) {
+					// Reset the overflow
+					this.elem.style.overflow = this.options.overflow;
+
+					// Reset the display
+					this.elem.style.display = this.options.display;
+					if ( jQuery.css(this.elem, "display") == "none" )
+						this.elem.style.display = "block";
+				}
+
+				// Hide the element if the "hide" operation was done
+				if ( this.options.hide )
+					jQuery(this.elem).hide();
+
+				// Reset the properties, if the item has been hidden or shown
+				if ( this.options.hide || this.options.show )
+					for ( var p in this.options.curAnim )
+						jQuery.attr(this.elem.style, p, this.options.orig[p]);
+					
+				// Execute the complete function
+				this.options.complete.call( this.elem );
+			}
+
+			return false;
+		} else {
+			var n = t - this.startTime;
+			this.state = n / this.options.duration;
+
+			// Perform the easing function, defaults to swing
+			this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
+			this.now = this.start + ((this.end - this.start) * this.pos);
+
+			// Perform the next step of the animation
+			this.update();
+		}
+
+		return true;
+	}
+
+};
+
+jQuery.extend( jQuery.fx, {
+	speeds:{
+		slow: 600,
+ 		fast: 200,
+ 		// Default speed
+ 		_default: 400
+	},
+	step: {
+
+		opacity: function(fx){
+			jQuery.attr(fx.elem.style, "opacity", fx.now);
+		},
+
+		_default: function(fx){
+			if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
+				fx.elem.style[ fx.prop ] = fx.now + fx.unit;
+			else
+				fx.elem[ fx.prop ] = fx.now;
+		}
+	}
+});
+if ( document.documentElement["getBoundingClientRect"] )
+	jQuery.fn.offset = function() {
+		if ( !this[0] ) return { top: 0, left: 0 };
+		if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
+		var box  = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
+			clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
+			top  = box.top  + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop  || body.scrollTop ) - clientTop,
+			left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
+		return { top: top, left: left };
+	};
+else 
+	jQuery.fn.offset = function() {
+		if ( !this[0] ) return { top: 0, left: 0 };
+		if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
+		jQuery.offset.initialized || jQuery.offset.initialize();
+
+		var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
+			doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
+			body = doc.body, defaultView = doc.defaultView,
+			prevComputedStyle = defaultView.getComputedStyle(elem, null),
+			top = elem.offsetTop, left = elem.offsetLeft;
+
+		while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
+			computedStyle = defaultView.getComputedStyle(elem, null);
+			top -= elem.scrollTop, left -= elem.scrollLeft;
+			if ( elem === offsetParent ) {
+				top += elem.offsetTop, left += elem.offsetLeft;
+				if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
+					top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
+					left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
+				prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
+			}
+			if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
+				top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
+				left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
+			prevComputedStyle = computedStyle;
+		}
+
+		if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
+			top  += body.offsetTop,
+			left += body.offsetLeft;
+
+		if ( prevComputedStyle.position === "fixed" )
+			top  += Math.max(docElem.scrollTop, body.scrollTop),
+			left += Math.max(docElem.scrollLeft, body.scrollLeft);
+
+		return { top: top, left: left };
+	};
+
+jQuery.offset = {
+	initialize: function() {
+		if ( this.initialized ) return;
+		var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
+			html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';
+
+		rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
+		for ( prop in rules ) container.style[prop] = rules[prop];
+
+		container.innerHTML = html;
+		body.insertBefore(container, body.firstChild);
+		innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
+
+		this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
+		this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
+
+		innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
+		this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
+
+		body.style.marginTop = '1px';
+		this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
+		body.style.marginTop = bodyMarginTop;
+
+		body.removeChild(container);
+		this.initialized = true;
+	},
+
+	bodyOffset: function(body) {
+		jQuery.offset.initialized || jQuery.offset.initialize();
+		var top = body.offsetTop, left = body.offsetLeft;
+		if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
+			top  += parseInt( jQuery.curCSS(body, 'marginTop',  true), 10 ) || 0,
+			left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
+		return { top: top, left: left };
+	}
+};
+
+
+jQuery.fn.extend({
+	position: function() {
+		var left = 0, top = 0, results;
+
+		if ( this[0] ) {
+			// Get *real* offsetParent
+			var offsetParent = this.offsetParent(),
+
+			// Get correct offsets
+			offset       = this.offset(),
+			parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+			// Subtract element margins
+			// note: when an element has margin: auto the offsetLeft and marginLeft 
+			// are the same in Safari causing offset.left to incorrectly be 0
+			offset.top  -= num( this, 'marginTop'  );
+			offset.left -= num( this, 'marginLeft' );
+
+			// Add offsetParent borders
+			parentOffset.top  += num( offsetParent, 'borderTopWidth'  );
+			parentOffset.left += num( offsetParent, 'borderLeftWidth' );
+
+			// Subtract the two offsets
+			results = {
+				top:  offset.top  - parentOffset.top,
+				left: offset.left - parentOffset.left
+			};
+		}
+
+		return results;
+	},
+
+	offsetParent: function() {
+		var offsetParent = this[0].offsetParent || document.body;
+		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
+			offsetParent = offsetParent.offsetParent;
+		return jQuery(offsetParent);
+	}
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ['Left', 'Top'], function(i, name) {
+	var method = 'scroll' + name;
+	
+	jQuery.fn[ method ] = function(val) {
+		if (!this[0]) return null;
+
+		return val !== undefined ?
+
+			// Set the scroll offset
+			this.each(function() {
+				this == window || this == document ?
+					window.scrollTo(
+						!i ? val : jQuery(window).scrollLeft(),
+						 i ? val : jQuery(window).scrollTop()
+					) :
+					this[ method ] = val;
+			}) :
+
+			// Return the scroll offset
+			this[0] == window || this[0] == document ?
+				self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
+					jQuery.boxModel && document.documentElement[ method ] ||
+					document.body[ method ] :
+				this[0][ method ];
+	};
+});
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function(i, name){
+
+	var tl = i ? "Left"  : "Top",  // top or left
+		br = i ? "Right" : "Bottom", // bottom or right
+		lower = name.toLowerCase();
+
+	// innerHeight and innerWidth
+	jQuery.fn["inner" + name] = function(){
+		return this[0] ?
+			jQuery.css( this[0], lower, false, "padding" ) :
+			null;
+	};
+
+	// outerHeight and outerWidth
+	jQuery.fn["outer" + name] = function(margin) {
+		return this[0] ?
+			jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
+			null;
+	};
+	
+	var type = name.toLowerCase();
+
+	jQuery.fn[ type ] = function( size ) {
+		// Get window width or height
+		return this[0] == window ?
+			// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+			document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
+			document.body[ "client" + name ] :
+
+			// Get document width or height
+			this[0] == document ?
+				// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+				Math.max(
+					document.documentElement["client" + name],
+					document.body["scroll" + name], document.documentElement["scroll" + name],
+					document.body["offset" + name], document.documentElement["offset" + name]
+				) :
+
+				// Get or set width or height on the element
+				size === undefined ?
+					// Get width or height on the element
+					(this.length ? jQuery.css( this[0], type ) : null) :
+
+					// Set the width or height on the element (default to pixels if value is unitless)
+					this.css( type, typeof size === "string" ? size : size + "px" );
+	};
+
+});
+})();
diff --git a/src/allmydata/web/protovis-d3.2.js b/src/allmydata/web/protovis-d3.2.js
new file mode 100644
index 0000000..bfe5a02
--- /dev/null
+++ b/src/allmydata/web/protovis-d3.2.js
@@ -0,0 +1,15324 @@
+// fba9dc272a443cf9fdb984676a7732a6a082f4c0
+/**
+ * @class The built-in Array class.
+ * @name Array
+ */
+
+/**
+ * Creates a new array with the results of calling a provided function on every
+ * element in this array. Implemented in Javascript 1.6.
+ *
+ * @function
+ * @name Array.prototype.map
+ * @see <a
+ * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map">map</a>
+ * documentation.
+ * @param {function} f function that produces an element of the new Array from
+ * an element of the current one.
+ * @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
+ */
+if (!Array.prototype.map) Array.prototype.map = function(f, o) {
+  var n = this.length;
+  var result = new Array(n);
+  for (var i = 0; i < n; i++) {
+    if (i in this) {
+      result[i] = f.call(o, this[i], i, this);
+    }
+  }
+  return result;
+};
+
+/**
+ * Creates a new array with all elements that pass the test implemented by the
+ * provided function. Implemented in Javascript 1.6.
+ *
+ * @function
+ * @name Array.prototype.filter
+ * @see <a
+ * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter">filter</a>
+ * documentation.
+ * @param {function} f function to test each element of the array.
+ * @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
+ */
+if (!Array.prototype.filter) Array.prototype.filter = function(f, o) {
+  var n = this.length;
+  var result = new Array();
+  for (var i = 0; i < n; i++) {
+    if (i in this) {
+      var v = this[i];
+      if (f.call(o, v, i, this)) result.push(v);
+    }
+  }
+  return result;
+};
+
+/**
+ * Executes a provided function once per array element. Implemented in
+ * Javascript 1.6.
+ *
+ * @function
+ * @name Array.prototype.forEach
+ * @see <a
+ * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/ForEach">forEach</a>
+ * documentation.
+ * @param {function} f function to execute for each element.
+ * @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
+ */
+if (!Array.prototype.forEach) Array.prototype.forEach = function(f, o) {
+  var n = this.length >>> 0;
+  for (var i = 0; i < n; i++) {
+    if (i in this) f.call(o, this[i], i, this);
+  }
+};
+
+/**
+ * Apply a function against an accumulator and each value of the array (from
+ * left-to-right) as to reduce it to a single value. Implemented in Javascript
+ * 1.8.
+ *
+ * @function
+ * @name Array.prototype.reduce
+ * @see <a
+ * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Reduce">reduce</a>
+ * documentation.
+ * @param {function} f function to execute on each value in the array.
+ * @param [v] object to use as the first argument to the first call of
+ * <tt>t</tt>.
+ */
+if (!Array.prototype.reduce) Array.prototype.reduce = function(f, v) {
+  var len = this.length;
+  if (!len && (arguments.length == 1)) {
+    throw new Error("reduce: empty array, no initial value");
+  }
+
+  var i = 0;
+  if (arguments.length < 2) {
+    while (true) {
+      if (i in this) {
+        v = this[i++];
+        break;
+      }
+      if (++i >= len) {
+        throw new Error("reduce: no values, no initial value");
+      }
+    }
+  }
+
+  for (; i < len; i++) {
+    if (i in this) {
+      v = f(v, this[i], i, this);
+    }
+  }
+  return v;
+};
+/**
+ * The top-level Protovis namespace. All public methods and fields should be
+ * registered on this object. Note that core Protovis source is surrounded by an
+ * anonymous function, so any other declared globals will not be visible outside
+ * of core methods. This also allows multiple versions of Protovis to coexist,
+ * since each version will see their own <tt>pv</tt> namespace.
+ *
+ * @namespace The top-level Protovis namespace, <tt>pv</tt>.
+ */
+var pv = {};
+
+/**
+ * Protovis major and minor version numbers.
+ *
+ * @namespace Protovis major and minor version numbers.
+ */
+pv.version = {
+  /**
+   * The major version number.
+   *
+   * @type number
+   * @constant
+   */
+  major: 3,
+
+  /**
+   * The minor version number.
+   *
+   * @type number
+   * @constant
+   */
+  minor: 2
+};
+
+/**
+ * Returns the passed-in argument, <tt>x</tt>; the identity function. This method
+ * is provided for convenience since it is used as the default behavior for a
+ * number of property functions.
+ *
+ * @param x a value.
+ * @returns the value <tt>x</tt>.
+ */
+pv.identity = function(x) { return x; };
+
+/**
+ * Returns <tt>this.index</tt>. This method is provided for convenience for use
+ * with scales. For example, to color bars by their index, say:
+ *
+ * <pre>.fillStyle(pv.Colors.category10().by(pv.index))</pre>
+ *
+ * This method is equivalent to <tt>function() this.index</tt>, but more
+ * succinct. Note that the <tt>index</tt> property is also supported for
+ * accessor functions with {@link pv.max}, {@link pv.min} and other array
+ * utility methods.
+ *
+ * @see pv.Scale
+ * @see pv.Mark#index
+ */
+pv.index = function() { return this.index; };
+
+/**
+ * Returns <tt>this.childIndex</tt>. This method is provided for convenience for
+ * use with scales. For example, to color bars by their child index, say:
+ *
+ * <pre>.fillStyle(pv.Colors.category10().by(pv.child))</pre>
+ *
+ * This method is equivalent to <tt>function() this.childIndex</tt>, but more
+ * succinct.
+ *
+ * @see pv.Scale
+ * @see pv.Mark#childIndex
+ */
+pv.child = function() { return this.childIndex; };
+
+/**
+ * Returns <tt>this.parent.index</tt>. This method is provided for convenience
+ * for use with scales. This method is provided for convenience for use with
+ * scales. For example, to color bars by their parent index, say:
+ *
+ * <pre>.fillStyle(pv.Colors.category10().by(pv.parent))</pre>
+ *
+ * Tthis method is equivalent to <tt>function() this.parent.index</tt>, but more
+ * succinct.
+ *
+ * @see pv.Scale
+ * @see pv.Mark#index
+ */
+pv.parent = function() { return this.parent.index; };
+
+/**
+ * Stores the current event. This field is only set within event handlers.
+ *
+ * @type Event
+ * @name pv.event
+ */
+/**
+ * @private Returns a prototype object suitable for extending the given class
+ * <tt>f</tt>. Rather than constructing a new instance of <tt>f</tt> to serve as
+ * the prototype (which unnecessarily runs the constructor on the created
+ * prototype object, potentially polluting it), an anonymous function is
+ * generated internally that shares the same prototype:
+ *
+ * <pre>function g() {}
+ * g.prototype = f.prototype;
+ * return new g();</pre>
+ *
+ * For more details, see Douglas Crockford's essay on prototypal inheritance.
+ *
+ * @param {function} f a constructor.
+ * @returns a suitable prototype object.
+ * @see Douglas Crockford's essay on <a
+ * href="http://javascript.crockford.com/prototypal.html">prototypal
+ * inheritance</a>.
+ */
+pv.extend = function(f) {
+  function g() {}
+  g.prototype = f.prototype || f;
+  return new g();
+};
+
+try {
+  eval("pv.parse = function(x) x;"); // native support
+} catch (e) {
+
+/**
+ * @private Parses a Protovis specification, which may use JavaScript 1.8
+ * function expresses, replacing those function expressions with proper
+ * functions such that the code can be run by a JavaScript 1.6 interpreter. This
+ * hack only supports function expressions (using clumsy regular expressions, no
+ * less), and not other JavaScript 1.8 features such as let expressions.
+ *
+ * @param {string} s a Protovis specification (i.e., a string of JavaScript 1.8
+ * source code).
+ * @returns {string} a conformant JavaScript 1.6 source code.
+ */
+  pv.parse = function(js) { // hacky regex support
+    var re = new RegExp("function\\s*(\\b\\w+)?\\s*\\([^)]*\\)\\s*", "mg"), m, d, i = 0, s = "";
+    while (m = re.exec(js)) {
+      var j = m.index + m[0].length;
+      if (js.charAt(j) != '{') {
+        s += js.substring(i, j) + "{return ";
+        i = j;
+        for (var p = 0; p >= 0 && j < js.length; j++) {
+          var c = js.charAt(j);
+          switch (c) {
+            case '"': case '\'': {
+              while (++j < js.length && (d = js.charAt(j)) != c) {
+                if (d == '\\') j++;
+              }
+              break;
+            }
+            case '[': case '(': p++; break;
+            case ']': case ')': p--; break;
+            case ';':
+            case ',': if (p == 0) p--; break;
+          }
+        }
+        s += pv.parse(js.substring(i, --j)) + ";}";
+        i = j;
+      }
+      re.lastIndex = j;
+    }
+    s += js.substring(i);
+    return s;
+  };
+}
+
+/**
+ * @private Computes the value of the specified CSS property <tt>p</tt> on the
+ * specified element <tt>e</tt>.
+ *
+ * @param {string} p the name of the CSS property.
+ * @param e the element on which to compute the CSS property.
+ */
+pv.css = function(e, p) {
+  return window.getComputedStyle
+      ? window.getComputedStyle(e, null).getPropertyValue(p)
+      : e.currentStyle[p];
+};
+
+/**
+ * @private Reports the specified error to the JavaScript console. Mozilla only
+ * allows logging to the console for privileged code; if the console is
+ * unavailable, the alert dialog box is used instead.
+ *
+ * @param e the exception that triggered the error.
+ */
+pv.error = function(e) {
+  (typeof console == "undefined") ? alert(e) : console.error(e);
+};
+
+/**
+ * @private Registers the specified listener for events of the specified type on
+ * the specified target. For standards-compliant browsers, this method uses
+ * <tt>addEventListener</tt>; for Internet Explorer, <tt>attachEvent</tt>.
+ *
+ * @param target a DOM element.
+ * @param {string} type the type of event, such as "click".
+ * @param {function} the event handler callback.
+ */
+pv.listen = function(target, type, listener) {
+  listener = pv.listener(listener);
+  return target.addEventListener
+      ? target.addEventListener(type, listener, false)
+      : target.attachEvent("on" + type, listener);
+};
+
+/**
+ * @private Returns a wrapper for the specified listener function such that the
+ * {@link pv.event} is set for the duration of the listener's invocation. The
+ * wrapper is cached on the returned function, such that duplicate registrations
+ * of the wrapped event handler are ignored.
+ *
+ * @param {function} f an event handler.
+ * @returns {function} the wrapped event handler.
+ */
+pv.listener = function(f) {
+  return f.$listener || (f.$listener = function(e) {
+      try {
+        pv.event = e;
+        return f.call(this, e);
+      } finally {
+        delete pv.event;
+      }
+    });
+};
+
+/**
+ * @private Returns true iff <i>a</i> is an ancestor of <i>e</i>. This is useful
+ * for ignoring mouseout and mouseover events that are contained within the
+ * target element.
+ */
+pv.ancestor = function(a, e) {
+  while (e) {
+    if (e == a) return true;
+    e = e.parentNode;
+  }
+  return false;
+};
+
+/** @private Returns a locally-unique positive id. */
+pv.id = function() {
+  var id = 1; return function() { return id++; };
+}();
+
+/** @private Returns a function wrapping the specified constant. */
+pv.functor = function(v) {
+  return typeof v == "function" ? v : function() { return v; };
+};
+/*
+ * Parses the Protovis specifications on load, allowing the use of JavaScript
+ * 1.8 function expressions on browsers that only support JavaScript 1.6.
+ *
+ * @see pv.parse
+ */
+pv.listen(window, "load", function() {
+   /*
+    * Note: in Firefox any variables declared here are visible to the eval'd
+    * script below. Even worse, any global variables declared by the script
+    * could overwrite local variables here (such as the index, `i`)!  To protect
+    * against this, all variables are explicitly scoped on a pv.$ object.
+    */
+    pv.$ = {i:0, x:document.getElementsByTagName("script")};
+    for (; pv.$.i < pv.$.x.length; pv.$.i++) {
+      pv.$.s = pv.$.x[pv.$.i];
+      if (pv.$.s.type == "text/javascript+protovis") {
+        try {
+          window.eval(pv.parse(pv.$.s.text));
+        } catch (e) {
+          pv.error(e);
+        }
+      }
+    }
+    delete pv.$;
+  });
+/**
+ * Abstract; see an implementing class.
+ *
+ * @class Represents an abstract text formatter and parser. A <i>format</i> is a
+ * function that converts an object of a given type, such as a <tt>Date</tt>, to
+ * a human-readable string representation. The format may also have a
+ * {@link #parse} method for converting a string representation back to the
+ * given object type.
+ *
+ * <p>Because formats are themselves functions, they can be used directly as
+ * mark properties. For example, if the data associated with a label are dates,
+ * a date format can be used as label text:
+ *
+ * <pre>    .text(pv.Format.date("%m/%d/%y"))</pre>
+ *
+ * And as with scales, if the format is used in multiple places, it can be
+ * convenient to declare it as a global variable and then reference it from the
+ * appropriate property functions. For example, if the data has a <tt>date</tt>
+ * attribute, and <tt>format</tt> references a given date format:
+ *
+ * <pre>    .text(function(d) format(d.date))</pre>
+ *
+ * Similarly, to parse a string into a date:
+ *
+ * <pre>var date = format.parse("4/30/2010");</pre>
+ *
+ * Not all format implementations support parsing. See the implementing class
+ * for details.
+ *
+ * @see pv.Format.date
+ * @see pv.Format.number
+ * @see pv.Format.time
+ */
+pv.Format = {};
+
+/**
+ * Formats the specified object, returning the string representation.
+ *
+ * @function
+ * @name pv.Format.prototype.format
+ * @param {object} x the object to format.
+ * @returns {string} the formatted string.
+ */
+
+/**
+ * Parses the specified string, returning the object representation.
+ *
+ * @function
+ * @name pv.Format.prototype.parse
+ * @param {string} x the string to parse.
+ * @returns {object} the parsed object.
+ */
+
+/**
+ * @private Given a string that may be used as part of a regular expression,
+ * this methods returns an appropriately quoted version of the specified string,
+ * with any special characters escaped.
+ *
+ * @param {string} s a string to quote.
+ * @returns {string} the quoted string.
+ */
+pv.Format.re = function(s) {
+  return s.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g, "\\$&");
+};
+
+/**
+ * @private Optionally pads the specified string <i>s</i> so that it is at least
+ * <i>n</i> characters long, using the padding character <i>c</i>.
+ *
+ * @param {string} c the padding character.
+ * @param {number} n the minimum string length.
+ * @param {string} s the string to pad.
+ * @returns {string} the padded string.
+ */
+pv.Format.pad = function(c, n, s) {
+  var m = n - String(s).length;
+  return (m < 1) ? s : new Array(m + 1).join(c) + s;
+};
+/**
+ * Constructs a new date format with the specified string pattern.
+ *
+ * @class The format string is in the same format expected by the
+ * <tt>strftime</tt> function in C. The following conversion specifications are
+ * supported:<ul>
+ *
+ * <li>%a - abbreviated weekday name.</li>
+ * <li>%A - full weekday name.</li>
+ * <li>%b - abbreviated month names.</li>
+ * <li>%B - full month names.</li>
+ * <li>%c - locale's appropriate date and time.</li>
+ * <li>%C - century number.</li>
+ * <li>%d - day of month [01,31] (zero padded).</li>
+ * <li>%D - same as %m/%d/%y.</li>
+ * <li>%e - day of month [ 1,31] (space padded).</li>
+ * <li>%h - same as %b.</li>
+ * <li>%H - hour (24-hour clock) [00,23] (zero padded).</li>
+ * <li>%I - hour (12-hour clock) [01,12] (zero padded).</li>
+ * <li>%m - month number [01,12] (zero padded).</li>
+ * <li>%M - minute [0,59] (zero padded).</li>
+ * <li>%n - newline character.</li>
+ * <li>%p - locale's equivalent of a.m. or p.m.</li>
+ * <li>%r - same as %I:%M:%S %p.</li>
+ * <li>%R - same as %H:%M.</li>
+ * <li>%S - second [00,61] (zero padded).</li>
+ * <li>%t - tab character.</li>
+ * <li>%T - same as %H:%M:%S.</li>
+ * <li>%x - same as %m/%d/%y.</li>
+ * <li>%X - same as %I:%M:%S %p.</li>
+ * <li>%y - year with century [00,99] (zero padded).</li>
+ * <li>%Y - year including century.</li>
+ * <li>%% - %.</li>
+ *
+ * </ul>The following conversion specifications are currently <i>unsupported</i>
+ * for formatting:<ul>
+ *
+ * <li>%j - day number [1,366].</li>
+ * <li>%u - weekday number [1,7].</li>
+ * <li>%U - week number [00,53].</li>
+ * <li>%V - week number [01,53].</li>
+ * <li>%w - weekday number [0,6].</li>
+ * <li>%W - week number [00,53].</li>
+ * <li>%Z - timezone name or abbreviation.</li>
+ *
+ * </ul>In addition, the following conversion specifications are currently
+ * <i>unsupported</i> for parsing:<ul>
+ *
+ * <li>%a - day of week, either abbreviated or full name.</li>
+ * <li>%A - same as %a.</li>
+ * <li>%c - locale's appropriate date and time.</li>
+ * <li>%C - century number.</li>
+ * <li>%D - same as %m/%d/%y.</li>
+ * <li>%I - hour (12-hour clock) [1,12].</li>
+ * <li>%n - any white space.</li>
+ * <li>%p - locale's equivalent of a.m. or p.m.</li>
+ * <li>%r - same as %I:%M:%S %p.</li>
+ * <li>%R - same as %H:%M.</li>
+ * <li>%t - same as %n.</li>
+ * <li>%T - same as %H:%M:%S.</li>
+ * <li>%x - locale's equivalent to %m/%d/%y.</li>
+ * <li>%X - locale's equivalent to %I:%M:%S %p.</li>
+ *
+ * </ul>
+ *
+ * @see <a
+ * href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">strftime</a>
+ * documentation.
+ * @see <a
+ * href="http://www.opengroup.org/onlinepubs/007908799/xsh/strptime.html">strptime</a>
+ * documentation.
+ * @extends pv.Format
+ * @param {string} pattern the format pattern.
+ */
+pv.Format.date = function(pattern) {
+  var pad = pv.Format.pad;
+
+  /** @private */
+  function format(d) {
+    return pattern.replace(/%[a-zA-Z0-9]/g, function(s) {
+        switch (s) {
+          case '%a': return [
+              "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+            ][d.getDay()];
+          case '%A': return [
+              "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
+              "Saturday"
+            ][d.getDay()];
+          case '%h':
+          case '%b': return [
+              "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
+              "Oct", "Nov", "Dec"
+            ][d.getMonth()];
+          case '%B': return [
+              "January", "February", "March", "April", "May", "June", "July",
+              "August", "September", "October", "November", "December"
+            ][d.getMonth()];
+          case '%c': return d.toLocaleString();
+          case '%C': return pad("0", 2, Math.floor(d.getFullYear() / 100) % 100);
+          case '%d': return pad("0", 2, d.getDate());
+          case '%x':
+          case '%D': return pad("0", 2, d.getMonth() + 1)
+                    + "/" + pad("0", 2, d.getDate())
+                    + "/" + pad("0", 2, d.getFullYear() % 100);
+          case '%e': return pad(" ", 2, d.getDate());
+          case '%H': return pad("0", 2, d.getHours());
+          case '%I': {
+            var h = d.getHours() % 12;
+            return h ? pad("0", 2, h) : 12;
+          }
+          // TODO %j: day of year as a decimal number [001,366]
+          case '%m': return pad("0", 2, d.getMonth() + 1);
+          case '%M': return pad("0", 2, d.getMinutes());
+          case '%n': return "\n";
+          case '%p': return d.getHours() < 12 ? "AM" : "PM";
+          case '%T':
+          case '%X':
+          case '%r': {
+            var h = d.getHours() % 12;
+            return (h ? pad("0", 2, h) : 12)
+                    + ":" + pad("0", 2, d.getMinutes())
+                    + ":" + pad("0", 2, d.getSeconds())
+                    + " " + (d.getHours() < 12 ? "AM" : "PM");
+          }
+          case '%R': return pad("0", 2, d.getHours()) + ":" + pad("0", 2, d.getMinutes());
+          case '%S': return pad("0", 2, d.getSeconds());
+          case '%Q': return pad("0", 3, d.getMilliseconds());
+          case '%t': return "\t";
+          case '%u': {
+            var w = d.getDay();
+            return w ? w : 1;
+          }
+          // TODO %U: week number (sunday first day) [00,53]
+          // TODO %V: week number (monday first day) [01,53] ... with weirdness
+          case '%w': return d.getDay();
+          // TODO %W: week number (monday first day) [00,53] ... with weirdness
+          case '%y': return pad("0", 2, d.getFullYear() % 100);
+          case '%Y': return d.getFullYear();
+          // TODO %Z: timezone name or abbreviation
+          case '%%': return "%";
+        }
+        return s;
+      });
+  }
+
+  /**
+   * Converts a date to a string using the associated formatting pattern.
+   *
+   * @function
+   * @name pv.Format.date.prototype.format
+   * @param {Date} date a date to format.
+   * @returns {string} the formatted date as a string.
+   */
+  format.format = format;
+
+  /**
+   * Parses a date from a string using the associated formatting pattern.
+   *
+   * @function
+   * @name pv.Format.date.prototype.parse
+   * @param {string} s the string to parse as a date.
+   * @returns {Date} the parsed date.
+   */
+  format.parse = function(s) {
+    var year = 1970, month = 0, date = 1, hour = 0, minute = 0, second = 0;
+    var fields = [function() {}];
+
+    /* Register callbacks for each field in the format pattern. */
+    var re = pv.Format.re(pattern).replace(/%[a-zA-Z0-9]/g, function(s) {
+        switch (s) {
+          // TODO %a: day of week, either abbreviated or full name
+          // TODO %A: same as %a
+          case '%b': {
+            fields.push(function(x) { month = {
+                  Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7,
+                  Sep: 8, Oct: 9, Nov: 10, Dec: 11
+                }[x]; });
+            return "([A-Za-z]+)";
+          }
+          case '%h':
+          case '%B': {
+            fields.push(function(x) { month = {
+                  January: 0, February: 1, March: 2, April: 3, May: 4, June: 5,
+                  July: 6, August: 7, September: 8, October: 9, November: 10,
+                  December: 11
+                }[x]; });
+            return "([A-Za-z]+)";
+          }
+          // TODO %c: locale's appropriate date and time
+          // TODO %C: century number[0,99]
+          case '%e':
+          case '%d': {
+            fields.push(function(x) { date = x; });
+            return "([0-9]+)";
+          }
+          // TODO %D: same as %m/%d/%y
+          case '%I':
+          case '%H': {
+            fields.push(function(x) { hour = x; });
+            return "([0-9]+)";
+          }
+          // TODO %j: day number [1,366]
+          case '%m': {
+            fields.push(function(x) { month = x - 1; });
+            return "([0-9]+)";
+          }
+          case '%M': {
+            fields.push(function(x) { minute = x; });
+            return "([0-9]+)";
+          }
+          // TODO %n: any white space
+          // TODO %p: locale's equivalent of a.m. or p.m.
+          case '%p': { // TODO this is a hack
+            fields.push(function(x) {
+              if (hour == 12) {
+                if (x == "am") hour = 0;
+              } else if (x == "pm") {
+                hour = Number(hour) + 12;
+              }
+            });
+            return "(am|pm)";
+          }
+          // TODO %r: %I:%M:%S %p
+          // TODO %R: %H:%M
+          case '%S': {
+            fields.push(function(x) { second = x; });
+            return "([0-9]+)";
+          }
+          // TODO %t: any white space
+          // TODO %T: %H:%M:%S
+          // TODO %U: week number [00,53]
+          // TODO %w: weekday [0,6]
+          // TODO %W: week number [00, 53]
+          // TODO %x: locale date (%m/%d/%y)
+          // TODO %X: locale time (%I:%M:%S %p)
+          case '%y': {
+            fields.push(function(x) {
+                x = Number(x);
+                year = x + (((0 <= x) && (x < 69)) ? 2000
+                    : (((x >= 69) && (x < 100) ? 1900 : 0)));
+              });
+            return "([0-9]+)";
+          }
+          case '%Y': {
+            fields.push(function(x) { year = x; });
+            return "([0-9]+)";
+          }
+          case '%%': {
+            fields.push(function() {});
+            return "%";
+          }
+        }
+        return s;
+      });
+
+    var match = s.match(re);
+    if (match) match.forEach(function(m, i) { fields[i](m); });
+    return new Date(year, month, date, hour, minute, second);
+  };
+
+  return format;
+};
+/**
+ * Returns a time format of the given type, either "short" or "long".
+ *
+ * @class Represents a time format, converting between a <tt>number</tt>
+ * representing a duration in milliseconds, and a <tt>string</tt>. Two types of
+ * time formats are supported: "short" and "long". The <i>short</i> format type
+ * returns a string such as "3.3 days" or "12.1 minutes", while the <i>long</i>
+ * format returns "13:04:12" or similar.
+ *
+ * @extends pv.Format
+ * @param {string} type the type; "short" or "long".
+ */
+pv.Format.time = function(type) {
+  var pad = pv.Format.pad;
+
+  /*
+   * MILLISECONDS = 1
+   * SECONDS = 1e3
+   * MINUTES = 6e4
+   * HOURS = 36e5
+   * DAYS = 864e5
+   * WEEKS = 6048e5
+   * MONTHS = 2592e6
+   * YEARS = 31536e6
+   */
+
+  /** @private */
+  function format(t) {
+    t = Number(t); // force conversion from Date
+    switch (type) {
+      case "short": {
+        if (t >= 31536e6) {
+          return (t / 31536e6).toFixed(1) + " years";
+        } else if (t >= 6048e5) {
+          return (t / 6048e5).toFixed(1) + " weeks";
+        } else if (t >= 864e5) {
+          return (t / 864e5).toFixed(1) + " days";
+        } else if (t >= 36e5) {
+          return (t / 36e5).toFixed(1) + " hours";
+        } else if (t >= 6e4) {
+          return (t / 6e4).toFixed(1) + " minutes";
+        }
+        return (t / 1e3).toFixed(1) + " seconds";
+      }
+      case "long": {
+        var a = [],
+            s = ((t % 6e4) / 1e3) >> 0,
+            m = ((t % 36e5) / 6e4) >> 0;
+        a.push(pad("0", 2, s));
+        if (t >= 36e5) {
+          var h = ((t % 864e5) / 36e5) >> 0;
+          a.push(pad("0", 2, m));
+          if (t >= 864e5) {
+            a.push(pad("0", 2, h));
+            a.push(Math.floor(t / 864e5).toFixed());
+          } else {
+            a.push(h.toFixed());
+          }
+        } else {
+          a.push(m.toFixed());
+        }
+        return a.reverse().join(":");
+      }
+    }
+  }
+
+  /**
+   * Formats the specified time, returning the string representation.
+   *
+   * @function
+   * @name pv.Format.time.prototype.format
+   * @param {number} t the duration in milliseconds. May also be a <tt>Date</tt>.
+   * @returns {string} the formatted string.
+   */
+  format.format = format;
+
+  /**
+   * Parses the specified string, returning the time in milliseconds.
+   *
+   * @function
+   * @name pv.Format.time.prototype.parse
+   * @param {string} s a formatted string.
+   * @returns {number} the parsed duration in milliseconds.
+   */
+  format.parse = function(s) {
+    switch (type) {
+      case "short": {
+        var re = /([0-9,.]+)\s*([a-z]+)/g, a, t = 0;
+        while (a = re.exec(s)) {
+          var f = parseFloat(a[0].replace(",", "")), u = 0;
+          switch (a[2].toLowerCase()) {
+            case "year": case "years": u = 31536e6; break;
+            case "week": case "weeks": u = 6048e5; break;
+            case "day": case "days": u = 864e5; break;
+            case "hour": case "hours": u = 36e5; break;
+            case "minute": case "minutes": u = 6e4; break;
+            case "second": case "seconds": u = 1e3; break;
+          }
+          t += f * u;
+        }
+        return t;
+      }
+      case "long": {
+        var a = s.replace(",", "").split(":").reverse(), t = 0;
+        if (a.length) t += parseFloat(a[0]) * 1e3;
+        if (a.length > 1) t += parseFloat(a[1]) * 6e4;
+        if (a.length > 2) t += parseFloat(a[2]) * 36e5;
+        if (a.length > 3) t += parseFloat(a[3]) * 864e5;
+        return t;
+      }
+    }
+  }
+
+  return format;
+};
+/**
+ * Returns a default number format.
+ *
+ * @class Represents a number format, converting between a <tt>number</tt> and a
+ * <tt>string</tt>. This class allows numbers to be formatted with variable
+ * precision (both for the integral and fractional part of the number), optional
+ * thousands grouping, and optional padding. The thousands (",") and decimal
+ * (".") separator can be customized.
+ *
+ * @returns {pv.Format.number} a number format.
+ */
+pv.Format.number = function() {
+  var mini = 0, // default minimum integer digits
+      maxi = Infinity, // default maximum integer digits
+      mins = 0, // mini, including group separators
+      minf = 0, // default minimum fraction digits
+      maxf = 0, // default maximum fraction digits
+      maxk = 1, // 10^maxf
+      padi = "0", // default integer pad
+      padf = "0", // default fraction pad
+      padg = true, // whether group separator affects integer padding
+      decimal = ".", // default decimal separator
+      group = ","; // default group separator
+
+  /** @private */
+  function format(x) {
+    /* Round the fractional part, and split on decimal separator. */
+    if (Infinity > maxf) x = Math.round(x * maxk) / maxk;
+    var s = String(Math.abs(x)).split(".");
+
+    /* Pad, truncate and group the integral part. */
+    var i = s[0], n = (x < 0) ? "-" : "";
+    if (i.length > maxi) i = i.substring(i.length - maxi);
+    if (padg && (i.length < mini)) i = n + new Array(mini - i.length + 1).join(padi) + i;
+    if (i.length > 3) i = i.replace(/\B(?=(?:\d{3})+(?!\d))/g, group);
+    if (!padg && (i.length < mins)) i = new Array(mins - i.length + 1).join(padi) + n + i;
+    s[0] = i;
+
+    /* Pad the fractional part. */
+    var f = s[1] || "";
+    if (f.length < minf) s[1] = f + new Array(minf - f.length + 1).join(padf);
+
+    return s.join(decimal);
+  }
+
+  /**
+   * @function
+   * @name pv.Format.number.prototype.format
+   * @param {number} x
+   * @returns {string}
+   */
+  format.format = format;
+
+  /**
+   * Parses the specified string as a number. Before parsing, leading and
+   * trailing padding is removed. Group separators are also removed, and the
+   * decimal separator is replaced with the standard point ("."). The integer
+   * part is truncated per the maximum integer digits, and the fraction part is
+   * rounded per the maximum fraction digits.
+   *
+   * @function
+   * @name pv.Format.number.prototype.parse
+   * @param {string} x the string to parse.
+   * @returns {number} the parsed number.
+   */
+  format.parse = function(x) {
+    var re = pv.Format.re;
+
+    /* Remove leading and trailing padding. Split on the decimal separator. */
+    var s = String(x)
+        .replace(new RegExp("^(" + re(padi) + ")*"), "")
+        .replace(new RegExp("(" + re(padf) + ")*$"), "")
+        .split(decimal);
+
+    /* Remove grouping and truncate the integral part. */
+    var i = s[0].replace(new RegExp(re(group), "g"), "");
+    if (i.length > maxi) i = i.substring(i.length - maxi);
+
+    /* Round the fractional part. */
+    var f = s[1] ? Number("0." + s[1]) : 0;
+    if (Infinity > maxf) f = Math.round(f * maxk) / maxk;
+
+    return Math.round(i) + f;
+  };
+
+  /**
+   * Sets or gets the minimum and maximum number of integer digits. This
+   * controls the number of decimal digits to display before the decimal
+   * separator for the integral part of the number. If the number of digits is
+   * smaller than the minimum, the digits are padded; if the number of digits is
+   * larger, the digits are truncated, showing only the lower-order digits. The
+   * default range is [0, Infinity].
+   *
+   * <p>If only one argument is specified to this method, this value is used as
+   * both the minimum and maximum number. If no arguments are specified, a
+   * two-element array is returned containing the minimum and the maximum.
+   *
+   * @function
+   * @name pv.Format.number.prototype.integerDigits
+   * @param {number} [min] the minimum integer digits.
+   * @param {number} [max] the maximum integer digits.
+   * @returns {pv.Format.number} <tt>this</tt>, or the current integer digits.
+   */
+  format.integerDigits = function(min, max) {
+    if (arguments.length) {
+      mini = Number(min);
+      maxi = (arguments.length > 1) ? Number(max) : mini;
+      mins = mini + Math.floor(mini / 3) * group.length;
+      return this;
+    }
+    return [mini, maxi];
+  };
+
+  /**
+   * Sets or gets the minimum and maximum number of fraction digits. The
+   * controls the number of decimal digits to display after the decimal
+   * separator for the fractional part of the number. If the number of digits is
+   * smaller than the minimum, the digits are padded; if the number of digits is
+   * larger, the fractional part is rounded, showing only the higher-order
+   * digits. The default range is [0, 0].
+   *
+   * <p>If only one argument is specified to this method, this value is used as
+   * both the minimum and maximum number. If no arguments are specified, a
+   * two-element array is returned containing the minimum and the maximum.
+   *
+   * @function
+   * @name pv.Format.number.prototype.fractionDigits
+   * @param {number} [min] the minimum fraction digits.
+   * @param {number} [max] the maximum fraction digits.
+   * @returns {pv.Format.number} <tt>this</tt>, or the current fraction digits.
+   */
+  format.fractionDigits = function(min, max) {
+    if (arguments.length) {
+      minf = Number(min);
+      maxf = (arguments.length > 1) ? Number(max) : minf;
+      maxk = Math.pow(10, maxf);
+      return this;
+    }
+    return [minf, maxf];
+  };
+
+  /**
+   * Sets or gets the character used to pad the integer part. The integer pad is
+   * used when the number of integer digits is smaller than the minimum. The
+   * default pad character is "0" (zero).
+   *
+   * @param {string} [x] the new pad character.
+   * @returns {pv.Format.number} <tt>this</tt> or the current pad character.
+   */
+  format.integerPad = function(x) {
+    if (arguments.length) {
+      padi = String(x);
+      padg = /\d/.test(padi);
+      return this;
+    }
+    return padi;
+  };
+
+  /**
+   * Sets or gets the character used to pad the fration part. The fraction pad
+   * is used when the number of fraction digits is smaller than the minimum. The
+   * default pad character is "0" (zero).
+   *
+   * @param {string} [x] the new pad character.
+   * @returns {pv.Format.number} <tt>this</tt> or the current pad character.
+   */
+  format.fractionPad = function(x) {
+    if (arguments.length) {
+      padf = String(x);
+      return this;
+    }
+    return padf;
+  };
+
+  /**
+   * Sets or gets the character used as the decimal point, separating the
+   * integer and fraction parts of the number. The default decimal point is ".".
+   *
+   * @param {string} [x] the new decimal separator.
+   * @returns {pv.Format.number} <tt>this</tt> or the current decimal separator.
+   */
+  format.decimal = function(x) {
+    if (arguments.length) {
+      decimal = String(x);
+      return this;
+    }
+    return decimal;
+  };
+
+  /**
+   * Sets or gets the character used as the group separator, grouping integer
+   * digits by thousands. The default decimal point is ",". Grouping can be
+   * disabled by using "" for the separator.
+   *
+   * @param {string} [x] the new group separator.
+   * @returns {pv.Format.number} <tt>this</tt> or the current group separator.
+   */
+  format.group = function(x) {
+    if (arguments.length) {
+      group = x ? String(x) : "";
+      mins = mini + Math.floor(mini / 3) * group.length;
+      return this;
+    }
+    return group;
+  };
+
+  return format;
+};
+/**
+ * @private A private variant of Array.prototype.map that supports the index
+ * property.
+ */
+pv.map = function(array, f) {
+  var o = {};
+  return f
+      ? array.map(function(d, i) { o.index = i; return f.call(o, d); })
+      : array.slice();
+};
+
+/**
+ * Concatenates the specified array with itself <i>n</i> times. For example,
+ * <tt>pv.repeat([1, 2])</tt> returns [1, 2, 1, 2].
+ *
+ * @param {array} a an array.
+ * @param {number} [n] the number of times to repeat; defaults to two.
+ * @returns {array} an array that repeats the specified array.
+ */
+pv.repeat = function(array, n) {
+  if (arguments.length == 1) n = 2;
+  return pv.blend(pv.range(n).map(function() { return array; }));
+};
+
+/**
+ * Given two arrays <tt>a</tt> and <tt>b</tt>, <style
+ * type="text/css">sub{line-height:0}</style> returns an array of all possible
+ * pairs of elements [a<sub>i</sub>, b<sub>j</sub>]. The outer loop is on array
+ * <i>a</i>, while the inner loop is on <i>b</i>, such that the order of
+ * returned elements is [a<sub>0</sub>, b<sub>0</sub>], [a<sub>0</sub>,
+ * b<sub>1</sub>], ... [a<sub>0</sub>, b<sub>m</sub>], [a<sub>1</sub>,
+ * b<sub>0</sub>], [a<sub>1</sub>, b<sub>1</sub>], ... [a<sub>1</sub>,
+ * b<sub>m</sub>], ... [a<sub>n</sub>, b<sub>m</sub>]. If either array is empty,
+ * an empty array is returned.
+ *
+ * @param {array} a an array.
+ * @param {array} b an array.
+ * @returns {array} an array of pairs of elements in <tt>a</tt> and <tt>b</tt>.
+ */
+pv.cross = function(a, b) {
+  var array = [];
+  for (var i = 0, n = a.length, m = b.length; i < n; i++) {
+    for (var j = 0, x = a[i]; j < m; j++) {
+      array.push([x, b[j]]);
+    }
+  }
+  return array;
+};
+
+/**
+ * Given the specified array of arrays, concatenates the arrays into a single
+ * array. If the individual arrays are explicitly known, an alternative to blend
+ * is to use JavaScript's <tt>concat</tt> method directly. These two equivalent
+ * expressions:<ul>
+ *
+ * <li><tt>pv.blend([[1, 2, 3], ["a", "b", "c"]])</tt>
+ * <li><tt>[1, 2, 3].concat(["a", "b", "c"])</tt>
+ *
+ * </ul>return [1, 2, 3, "a", "b", "c"].
+ *
+ * @param {array[]} arrays an array of arrays.
+ * @returns {array} an array containing all the elements of each array in
+ * <tt>arrays</tt>.
+ */
+pv.blend = function(arrays) {
+  return Array.prototype.concat.apply([], arrays);
+};
+
+/**
+ * Given the specified array of arrays, <style
+ * type="text/css">sub{line-height:0}</style> transposes each element
+ * array<sub>ij</sub> with array<sub>ji</sub>. If the array has dimensions
+ * <i>n</i>&times;<i>m</i>, it will have dimensions <i>m</i>&times;<i>n</i>
+ * after this method returns. This method transposes the elements of the array
+ * in place, mutating the array, and returning a reference to the array.
+ *
+ * @param {array[]} arrays an array of arrays.
+ * @returns {array[]} the passed-in array, after transposing the elements.
+ */
+pv.transpose = function(arrays) {
+  var n = arrays.length, m = pv.max(arrays, function(d) { return d.length; });
+
+  if (m > n) {
+    arrays.length = m;
+    for (var i = n; i < m; i++) {
+      arrays[i] = new Array(n);
+    }
+    for (var i = 0; i < n; i++) {
+      for (var j = i + 1; j < m; j++) {
+        var t = arrays[i][j];
+        arrays[i][j] = arrays[j][i];
+        arrays[j][i] = t;
+      }
+    }
+  } else {
+    for (var i = 0; i < m; i++) {
+      arrays[i].length = n;
+    }
+    for (var i = 0; i < n; i++) {
+      for (var j = 0; j < i; j++) {
+        var t = arrays[i][j];
+        arrays[i][j] = arrays[j][i];
+        arrays[j][i] = t;
+      }
+    }
+  }
+
+  arrays.length = m;
+  for (var i = 0; i < m; i++) {
+    arrays[i].length = n;
+  }
+
+  return arrays;
+};
+
+/**
+ * Returns a normalized copy of the specified array, such that the sum of the
+ * returned elements sum to one. If the specified array is not an array of
+ * numbers, an optional accessor function <tt>f</tt> can be specified to map the
+ * elements to numbers. For example, if <tt>array</tt> is an array of objects,
+ * and each object has a numeric property "foo", the expression
+ *
+ * <pre>pv.normalize(array, function(d) d.foo)</pre>
+ *
+ * returns a normalized array on the "foo" property. If an accessor function is
+ * not specified, the identity function is used. Accessor functions can refer to
+ * <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number[]} an array of numbers that sums to one.
+ */
+pv.normalize = function(array, f) {
+  var norm = pv.map(array, f), sum = pv.sum(norm);
+  for (var i = 0; i < norm.length; i++) norm[i] /= sum;
+  return norm;
+};
+
+/**
+ * Returns a permutation of the specified array, using the specified array of
+ * indexes. The returned array contains the corresponding element in
+ * <tt>array</tt> for each index in <tt>indexes</tt>, in order. For example,
+ *
+ * <pre>pv.permute(["a", "b", "c"], [1, 2, 0])</pre>
+ *
+ * returns <tt>["b", "c", "a"]</tt>. It is acceptable for the array of indexes
+ * to be a different length from the array of elements, and for indexes to be
+ * duplicated or omitted. The optional accessor function <tt>f</tt> can be used
+ * to perform a simultaneous mapping of the array elements. Accessor functions
+ * can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array.
+ * @param {number[]} indexes an array of indexes into <tt>array</tt>.
+ * @param {function} [f] an optional accessor function.
+ * @returns {array} an array of elements from <tt>array</tt>; a permutation.
+ */
+pv.permute = function(array, indexes, f) {
+  if (!f) f = pv.identity;
+  var p = new Array(indexes.length), o = {};
+  indexes.forEach(function(j, i) { o.index = j; p[i] = f.call(o, array[j]); });
+  return p;
+};
+
+/**
+ * Returns a map from key to index for the specified <tt>keys</tt> array. For
+ * example,
+ *
+ * <pre>pv.numerate(["a", "b", "c"])</pre>
+ *
+ * returns <tt>{a: 0, b: 1, c: 2}</tt>. Note that since JavaScript maps only
+ * support string keys, <tt>keys</tt> must contain strings, or other values that
+ * naturally map to distinct string values. Alternatively, an optional accessor
+ * function <tt>f</tt> can be specified to compute the string key for the given
+ * element. Accessor functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} keys an array, usually of string keys.
+ * @param {function} [f] an optional key function.
+ * @returns a map from key to index.
+ */
+pv.numerate = function(keys, f) {
+  if (!f) f = pv.identity;
+  var map = {}, o = {};
+  keys.forEach(function(x, i) { o.index = i; map[f.call(o, x)] = i; });
+  return map;
+};
+
+/**
+ * Returns the unique elements in the specified array, in the order they appear.
+ * Note that since JavaScript maps only support string keys, <tt>array</tt> must
+ * contain strings, or other values that naturally map to distinct string
+ * values. Alternatively, an optional accessor function <tt>f</tt> can be
+ * specified to compute the string key for the given element. Accessor functions
+ * can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array, usually of string keys.
+ * @param {function} [f] an optional key function.
+ * @returns {array} the unique values.
+ */
+pv.uniq = function(array, f) {
+  if (!f) f = pv.identity;
+  var map = {}, keys = [], o = {}, y;
+  array.forEach(function(x, i) {
+    o.index = i;
+    y = f.call(o, x);
+    if (!(y in map)) map[y] = keys.push(y);
+  });
+  return keys;
+};
+
+/**
+ * The comparator function for natural order. This can be used in conjunction with
+ * the built-in array <tt>sort</tt> method to sort elements by their natural
+ * order, ascending. Note that if no comparator function is specified to the
+ * built-in <tt>sort</tt> method, the default order is lexicographic, <i>not</i>
+ * natural!
+ *
+ * @see <a
+ * href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort">Array.sort</a>.
+ * @param a an element to compare.
+ * @param b an element to compare.
+ * @returns {number} negative if a &lt; b; positive if a &gt; b; otherwise 0.
+ */
+pv.naturalOrder = function(a, b) {
+  return (a < b) ? -1 : ((a > b) ? 1 : 0);
+};
+
+/**
+ * The comparator function for reverse natural order. This can be used in
+ * conjunction with the built-in array <tt>sort</tt> method to sort elements by
+ * their natural order, descending. Note that if no comparator function is
+ * specified to the built-in <tt>sort</tt> method, the default order is
+ * lexicographic, <i>not</i> natural!
+ *
+ * @see #naturalOrder
+ * @param a an element to compare.
+ * @param b an element to compare.
+ * @returns {number} negative if a &lt; b; positive if a &gt; b; otherwise 0.
+ */
+pv.reverseOrder = function(b, a) {
+  return (a < b) ? -1 : ((a > b) ? 1 : 0);
+};
+
+/**
+ * Searches the specified array of numbers for the specified value using the
+ * binary search algorithm. The array must be sorted (as by the <tt>sort</tt>
+ * method) prior to making this call. If it is not sorted, the results are
+ * undefined. If the array contains multiple elements with the specified value,
+ * there is no guarantee which one will be found.
+ *
+ * <p>The <i>insertion point</i> is defined as the point at which the value
+ * would be inserted into the array: the index of the first element greater than
+ * the value, or <tt>array.length</tt>, if all elements in the array are less
+ * than the specified value. Note that this guarantees that the return value
+ * will be nonnegative if and only if the value is found.
+ *
+ * @param {number[]} array the array to be searched.
+ * @param {number} value the value to be searched for.
+ * @returns the index of the search value, if it is contained in the array;
+ * otherwise, (-(<i>insertion point</i>) - 1).
+ * @param {function} [f] an optional key function.
+ */
+pv.search = function(array, value, f) {
+  if (!f) f = pv.identity;
+  var low = 0, high = array.length - 1;
+  while (low <= high) {
+    var mid = (low + high) >> 1, midValue = f(array[mid]);
+    if (midValue < value) low = mid + 1;
+    else if (midValue > value) high = mid - 1;
+    else return mid;
+  }
+  return -low - 1;
+};
+
+pv.search.index = function(array, value, f) {
+  var i = pv.search(array, value, f);
+  return (i < 0) ? (-i - 1) : i;
+};
+/**
+ * Returns an array of numbers, starting at <tt>start</tt>, incrementing by
+ * <tt>step</tt>, until <tt>stop</tt> is reached. The stop value is
+ * exclusive. If only a single argument is specified, this value is interpeted
+ * as the <i>stop</i> value, with the <i>start</i> value as zero. If only two
+ * arguments are specified, the step value is implied to be one.
+ *
+ * <p>The method is modeled after the built-in <tt>range</tt> method from
+ * Python. See the Python documentation for more details.
+ *
+ * @see <a href="http://docs.python.org/library/functions.html#range">Python range</a>
+ * @param {number} [start] the start value.
+ * @param {number} stop the stop value.
+ * @param {number} [step] the step value.
+ * @returns {number[]} an array of numbers.
+ */
+pv.range = function(start, stop, step) {
+  if (arguments.length == 1) {
+    stop = start;
+    start = 0;
+  }
+  if (step == undefined) step = 1;
+  if ((stop - start) / step == Infinity) throw new Error("range must be finite");
+  var array = [], i = 0, j;
+  if (step < 0) {
+    while ((j = start + step * i++) > stop) {
+      array.push(j);
+    }
+  } else {
+    while ((j = start + step * i++) < stop) {
+      array.push(j);
+    }
+  }
+  return array;
+};
+
+/**
+ * Returns a random number in the range [<tt>start</tt>, <tt>stop</tt>) that is
+ * a multiple of <tt>step</tt>. More specifically, the returned number is of the
+ * form <tt>start</tt> + <i>n</i> * <tt>step</tt>, where <i>n</i> is a
+ * nonnegative integer. If <tt>step</tt> is not specified, it defaults to 1,
+ * returning a random integer if <tt>start</tt> is also an integer.
+ *
+ * @param {number} [start] the start value value.
+ * @param {number} stop the stop value.
+ * @param {number} [step] the step value.
+ * @returns {number} a random number between <i>start</i> and <i>stop</i>.
+ */
+pv.random = function(start, stop, step) {
+  if (arguments.length == 1) {
+    stop = start;
+    start = 0;
+  }
+  if (step == undefined) step = 1;
+  return step
+      ? (Math.floor(Math.random() * (stop - start) / step) * step + start)
+      : (Math.random() * (stop - start) + start);
+};
+
+/**
+ * Returns the sum of the specified array. If the specified array is not an
+ * array of numbers, an optional accessor function <tt>f</tt> can be specified
+ * to map the elements to numbers. See {@link #normalize} for an example.
+ * Accessor functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the sum of the specified array.
+ */
+pv.sum = function(array, f) {
+  var o = {};
+  return array.reduce(f
+      ? function(p, d, i) { o.index = i; return p + f.call(o, d); }
+      : function(p, d) { return p + d; }, 0);
+};
+
+/**
+ * Returns the maximum value of the specified array. If the specified array is
+ * not an array of numbers, an optional accessor function <tt>f</tt> can be
+ * specified to map the elements to numbers. See {@link #normalize} for an
+ * example. Accessor functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the maximum value of the specified array.
+ */
+pv.max = function(array, f) {
+  if (f == pv.index) return array.length - 1;
+  return Math.max.apply(null, f ? pv.map(array, f) : array);
+};
+
+/**
+ * Returns the index of the maximum value of the specified array. If the
+ * specified array is not an array of numbers, an optional accessor function
+ * <tt>f</tt> can be specified to map the elements to numbers. See
+ * {@link #normalize} for an example. Accessor functions can refer to
+ * <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the index of the maximum value of the specified array.
+ */
+pv.max.index = function(array, f) {
+  if (!array.length) return -1;
+  if (f == pv.index) return array.length - 1;
+  if (!f) f = pv.identity;
+  var maxi = 0, maxx = -Infinity, o = {};
+  for (var i = 0; i < array.length; i++) {
+    o.index = i;
+    var x = f.call(o, array[i]);
+    if (x > maxx) {
+      maxx = x;
+      maxi = i;
+    }
+  }
+  return maxi;
+}
+
+/**
+ * Returns the minimum value of the specified array of numbers. If the specified
+ * array is not an array of numbers, an optional accessor function <tt>f</tt>
+ * can be specified to map the elements to numbers. See {@link #normalize} for
+ * an example. Accessor functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the minimum value of the specified array.
+ */
+pv.min = function(array, f) {
+  if (f == pv.index) return 0;
+  return Math.min.apply(null, f ? pv.map(array, f) : array);
+};
+
+/**
+ * Returns the index of the minimum value of the specified array. If the
+ * specified array is not an array of numbers, an optional accessor function
+ * <tt>f</tt> can be specified to map the elements to numbers. See
+ * {@link #normalize} for an example. Accessor functions can refer to
+ * <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the index of the minimum value of the specified array.
+ */
+pv.min.index = function(array, f) {
+  if (!array.length) return -1;
+  if (f == pv.index) return 0;
+  if (!f) f = pv.identity;
+  var mini = 0, minx = Infinity, o = {};
+  for (var i = 0; i < array.length; i++) {
+    o.index = i;
+    var x = f.call(o, array[i]);
+    if (x < minx) {
+      minx = x;
+      mini = i;
+    }
+  }
+  return mini;
+}
+
+/**
+ * Returns the arithmetic mean, or average, of the specified array. If the
+ * specified array is not an array of numbers, an optional accessor function
+ * <tt>f</tt> can be specified to map the elements to numbers. See
+ * {@link #normalize} for an example. Accessor functions can refer to
+ * <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the mean of the specified array.
+ */
+pv.mean = function(array, f) {
+  return pv.sum(array, f) / array.length;
+};
+
+/**
+ * Returns the median of the specified array. If the specified array is not an
+ * array of numbers, an optional accessor function <tt>f</tt> can be specified
+ * to map the elements to numbers. See {@link #normalize} for an example.
+ * Accessor functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the median of the specified array.
+ */
+pv.median = function(array, f) {
+  if (f == pv.index) return (array.length - 1) / 2;
+  array = pv.map(array, f).sort(pv.naturalOrder);
+  if (array.length % 2) return array[Math.floor(array.length / 2)];
+  var i = array.length / 2;
+  return (array[i - 1] + array[i]) / 2;
+};
+
+/**
+ * Returns the unweighted variance of the specified array. If the specified
+ * array is not an array of numbers, an optional accessor function <tt>f</tt>
+ * can be specified to map the elements to numbers. See {@link #normalize} for
+ * an example. Accessor functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the variance of the specified array.
+ */
+pv.variance = function(array, f) {
+  if (array.length < 1) return NaN;
+  if (array.length == 1) return 0;
+  var mean = pv.mean(array, f), sum = 0, o = {};
+  if (!f) f = pv.identity;
+  for (var i = 0; i < array.length; i++) {
+    o.index = i;
+    var d = f.call(o, array[i]) - mean;
+    sum += d * d;
+  }
+  return sum;
+};
+
+/**
+ * Returns an unbiased estimation of the standard deviation of a population,
+ * given the specified random sample. If the specified array is not an array of
+ * numbers, an optional accessor function <tt>f</tt> can be specified to map the
+ * elements to numbers. See {@link #normalize} for an example. Accessor
+ * functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} array an array of objects, or numbers.
+ * @param {function} [f] an optional accessor function.
+ * @returns {number} the standard deviation of the specified array.
+ */
+pv.deviation = function(array, f) {
+  return Math.sqrt(pv.variance(array, f) / (array.length - 1));
+};
+
+/**
+ * Returns the logarithm with a given base value.
+ *
+ * @param {number} x the number for which to compute the logarithm.
+ * @param {number} b the base of the logarithm.
+ * @returns {number} the logarithm value.
+ */
+pv.log = function(x, b) {
+  return Math.log(x) / Math.log(b);
+};
+
+/**
+ * Computes a zero-symmetric logarithm. Computes the logarithm of the absolute
+ * value of the input, and determines the sign of the output according to the
+ * sign of the input value.
+ *
+ * @param {number} x the number for which to compute the logarithm.
+ * @param {number} b the base of the logarithm.
+ * @returns {number} the symmetric log value.
+ */
+pv.logSymmetric = function(x, b) {
+  return (x == 0) ? 0 : ((x < 0) ? -pv.log(-x, b) : pv.log(x, b));
+};
+
+/**
+ * Computes a zero-symmetric logarithm, with adjustment to values between zero
+ * and the logarithm base. This adjustment introduces distortion for values less
+ * than the base number, but enables simultaneous plotting of log-transformed
+ * data involving both positive and negative numbers.
+ *
+ * @param {number} x the number for which to compute the logarithm.
+ * @param {number} b the base of the logarithm.
+ * @returns {number} the adjusted, symmetric log value.
+ */
+pv.logAdjusted = function(x, b) {
+  if (!isFinite(x)) return x;
+  var negative = x < 0;
+  if (x < b) x += (b - x) / b;
+  return negative ? -pv.log(x, b) : pv.log(x, b);
+};
+
+/**
+ * Rounds an input value down according to its logarithm. The method takes the
+ * floor of the logarithm of the value and then uses the resulting value as an
+ * exponent for the base value.
+ *
+ * @param {number} x the number for which to compute the logarithm floor.
+ * @param {number} b the base of the logarithm.
+ * @returns {number} the rounded-by-logarithm value.
+ */
+pv.logFloor = function(x, b) {
+  return (x > 0)
+      ? Math.pow(b, Math.floor(pv.log(x, b)))
+      : -Math.pow(b, -Math.floor(-pv.log(-x, b)));
+};
+
+/**
+ * Rounds an input value up according to its logarithm. The method takes the
+ * ceiling of the logarithm of the value and then uses the resulting value as an
+ * exponent for the base value.
+ *
+ * @param {number} x the number for which to compute the logarithm ceiling.
+ * @param {number} b the base of the logarithm.
+ * @returns {number} the rounded-by-logarithm value.
+ */
+pv.logCeil = function(x, b) {
+  return (x > 0)
+      ? Math.pow(b, Math.ceil(pv.log(x, b)))
+      : -Math.pow(b, -Math.ceil(-pv.log(-x, b)));
+};
+
+(function() {
+  var radians = Math.PI / 180,
+      degrees = 180 / Math.PI;
+
+  /** Returns the number of radians corresponding to the specified degrees. */
+  pv.radians = function(degrees) { return radians * degrees; };
+
+  /** Returns the number of degrees corresponding to the specified radians. */
+  pv.degrees = function(radians) { return degrees * radians; };
+})();
+/**
+ * Returns all of the property names (keys) of the specified object (a map). The
+ * order of the returned array is not defined.
+ *
+ * @param map an object.
+ * @returns {string[]} an array of strings corresponding to the keys.
+ * @see #entries
+ */
+pv.keys = function(map) {
+  var array = [];
+  for (var key in map) {
+    array.push(key);
+  }
+  return array;
+};
+
+/**
+ * Returns all of the entries (key-value pairs) of the specified object (a
+ * map). The order of the returned array is not defined. Each key-value pair is
+ * represented as an object with <tt>key</tt> and <tt>value</tt> attributes,
+ * e.g., <tt>{key: "foo", value: 42}</tt>.
+ *
+ * @param map an object.
+ * @returns {array} an array of key-value pairs corresponding to the keys.
+ */
+pv.entries = function(map) {
+  var array = [];
+  for (var key in map) {
+    array.push({ key: key, value: map[key] });
+  }
+  return array;
+};
+
+/**
+ * Returns all of the values (attribute values) of the specified object (a
+ * map). The order of the returned array is not defined.
+ *
+ * @param map an object.
+ * @returns {array} an array of objects corresponding to the values.
+ * @see #entries
+ */
+pv.values = function(map) {
+  var array = [];
+  for (var key in map) {
+    array.push(map[key]);
+  }
+  return array;
+};
+
+/**
+ * Returns a map constructed from the specified <tt>keys</tt>, using the
+ * function <tt>f</tt> to compute the value for each key. The single argument to
+ * the value function is the key. The callback is invoked only for indexes of
+ * the array which have assigned values; it is not invoked for indexes which
+ * have been deleted or which have never been assigned values.
+ *
+ * <p>For example, this expression creates a map from strings to string length:
+ *
+ * <pre>pv.dict(["one", "three", "seventeen"], function(s) s.length)</pre>
+ *
+ * The returned value is <tt>{one: 3, three: 5, seventeen: 9}</tt>. Accessor
+ * functions can refer to <tt>this.index</tt>.
+ *
+ * @param {array} keys an array.
+ * @param {function} f a value function.
+ * @returns a map from keys to values.
+ */
+pv.dict = function(keys, f) {
+  var m = {}, o = {};
+  for (var i = 0; i < keys.length; i++) {
+    if (i in keys) {
+      var k = keys[i];
+      o.index = i;
+      m[k] = f.call(o, k);
+    }
+  }
+  return m;
+};
+/**
+ * Returns a {@link pv.Dom} operator for the given map. This is a convenience
+ * factory method, equivalent to <tt>new pv.Dom(map)</tt>. To apply the operator
+ * and retrieve the root node, call {@link pv.Dom#root}; to retrieve all nodes
+ * flattened, use {@link pv.Dom#nodes}.
+ *
+ * @see pv.Dom
+ * @param map a map from which to construct a DOM.
+ * @returns {pv.Dom} a DOM operator for the specified map.
+ */
+pv.dom = function(map) {
+  return new pv.Dom(map);
+};
+
+/**
+ * Constructs a DOM operator for the specified map. This constructor should not
+ * be invoked directly; use {@link pv.dom} instead.
+ *
+ * @class Represets a DOM operator for the specified map. This allows easy
+ * transformation of a hierarchical JavaScript object (such as a JSON map) to a
+ * W3C Document Object Model hierarchy. For more information on which attributes
+ * and methods from the specification are supported, see {@link pv.Dom.Node}.
+ *
+ * <p>Leaves in the map are determined using an associated <i>leaf</i> function;
+ * see {@link #leaf}. By default, leaves are any value whose type is not
+ * "object", such as numbers or strings.
+ *
+ * @param map a map from which to construct a DOM.
+ */
+pv.Dom = function(map) {
+  this.$map = map;
+};
+
+/** @private The default leaf function. */
+pv.Dom.prototype.$leaf = function(n) {
+  return typeof n != "object";
+};
+
+/**
+ * Sets or gets the leaf function for this DOM operator. The leaf function
+ * identifies which values in the map are leaves, and which are internal nodes.
+ * By default, objects are considered internal nodes, and primitives (such as
+ * numbers and strings) are considered leaves.
+ *
+ * @param {function} f the new leaf function.
+ * @returns the current leaf function, or <tt>this</tt>.
+ */
+pv.Dom.prototype.leaf = function(f) {
+  if (arguments.length) {
+    this.$leaf = f;
+    return this;
+  }
+  return this.$leaf;
+};
+
+/**
+ * Applies the DOM operator, returning the root node.
+ *
+ * @returns {pv.Dom.Node} the root node.
+ * @param {string} [nodeName] optional node name for the root.
+ */
+pv.Dom.prototype.root = function(nodeName) {
+  var leaf = this.$leaf, root = recurse(this.$map);
+
+  /** @private */
+  function recurse(map) {
+    var n = new pv.Dom.Node();
+    for (var k in map) {
+      var v = map[k];
+      n.appendChild(leaf(v) ? new pv.Dom.Node(v) : recurse(v)).nodeName = k;
+    }
+    return n;
+  }
+
+  root.nodeName = nodeName;
+  return root;
+};
+
+/**
+ * Applies the DOM operator, returning the array of all nodes in preorder
+ * traversal.
+ *
+ * @returns {array} the array of nodes in preorder traversal.
+ */
+pv.Dom.prototype.nodes = function() {
+  return this.root().nodes();
+};
+
+/**
+ * Constructs a DOM node for the specified value. Instances of this class are
+ * not typically created directly; instead they are generated from a JavaScript
+ * map using the {@link pv.Dom} operator.
+ *
+ * @class Represents a <tt>Node</tt> in the W3C Document Object Model.
+ */
+pv.Dom.Node = function(value) {
+  this.nodeValue = value;
+  this.childNodes = [];
+};
+
+/**
+ * The node name. When generated from a map, the node name corresponds to the
+ * key at the given level in the map. Note that the root node has no associated
+ * key, and thus has an undefined node name (and no <tt>parentNode</tt>).
+ *
+ * @type string
+ * @field pv.Dom.Node.prototype.nodeName
+ */
+
+/**
+ * The node value. When generated from a map, node value corresponds to the leaf
+ * value for leaf nodes, and is undefined for internal nodes.
+ *
+ * @field pv.Dom.Node.prototype.nodeValue
+ */
+
+/**
+ * The array of child nodes. This array is empty for leaf nodes. An easy way to
+ * check if child nodes exist is to query <tt>firstChild</tt>.
+ *
+ * @type array
+ * @field pv.Dom.Node.prototype.childNodes
+ */
+
+/**
+ * The parent node, which is null for root nodes.
+ *
+ * @type pv.Dom.Node
+ */
+pv.Dom.Node.prototype.parentNode = null;
+
+/**
+ * The first child, which is null for leaf nodes.
+ *
+ * @type pv.Dom.Node
+ */
+pv.Dom.Node.prototype.firstChild = null;
+
+/**
+ * The last child, which is null for leaf nodes.
+ *
+ * @type pv.Dom.Node
+ */
+pv.Dom.Node.prototype.lastChild = null;
+
+/**
+ * The previous sibling node, which is null for the first child.
+ *
+ * @type pv.Dom.Node
+ */
+pv.Dom.Node.prototype.previousSibling = null;
+
+/**
+ * The next sibling node, which is null for the last child.
+ *
+ * @type pv.Dom.Node
+ */
+pv.Dom.Node.prototype.nextSibling = null;
+
+/**
+ * Removes the specified child node from this node.
+ *
+ * @throws Error if the specified child is not a child of this node.
+ * @returns {pv.Dom.Node} the removed child.
+ */
+pv.Dom.Node.prototype.removeChild = function(n) {
+  var i = this.childNodes.indexOf(n);
+  if (i == -1) throw new Error("child not found");
+  this.childNodes.splice(i, 1);
+  if (n.previousSibling) n.previousSibling.nextSibling = n.nextSibling;
+  else this.firstChild = n.nextSibling;
+  if (n.nextSibling) n.nextSibling.previousSibling = n.previousSibling;
+  else this.lastChild = n.previousSibling;
+  delete n.nextSibling;
+  delete n.previousSibling;
+  delete n.parentNode;
+  return n;
+};
+
+/**
+ * Appends the specified child node to this node. If the specified child is
+ * already part of the DOM, the child is first removed before being added to
+ * this node.
+ *
+ * @returns {pv.Dom.Node} the appended child.
+ */
+pv.Dom.Node.prototype.appendChild = function(n) {
+  if (n.parentNode) n.parentNode.removeChild(n);
+  n.parentNode = this;
+  n.previousSibling = this.lastChild;
+  if (this.lastChild) this.lastChild.nextSibling = n;
+  else this.firstChild = n;
+  this.lastChild = n;
+  this.childNodes.push(n);
+  return n;
+};
+
+/**
+ * Inserts the specified child <i>n</i> before the given reference child
+ * <i>r</i> of this node. If <i>r</i> is null, this method is equivalent to
+ * {@link #appendChild}. If <i>n</i> is already part of the DOM, it is first
+ * removed before being inserted.
+ *
+ * @throws Error if <i>r</i> is non-null and not a child of this node.
+ * @returns {pv.Dom.Node} the inserted child.
+ */
+pv.Dom.Node.prototype.insertBefore = function(n, r) {
+  if (!r) return this.appendChild(n);
+  var i = this.childNodes.indexOf(r);
+  if (i == -1) throw new Error("child not found");
+  if (n.parentNode) n.parentNode.removeChild(n);
+  n.parentNode = this;
+  n.nextSibling = r;
+  n.previousSibling = r.previousSibling;
+  if (r.previousSibling) {
+    r.previousSibling.nextSibling = n;
+  } else {
+    if (r == this.lastChild) this.lastChild = n;
+    this.firstChild = n;
+  }
+  this.childNodes.splice(i, 0, n);
+  return n;
+};
+
+/**
+ * Replaces the specified child <i>r</i> of this node with the node <i>n</i>. If
+ * <i>n</i> is already part of the DOM, it is first removed before being added.
+ *
+ * @throws Error if <i>r</i> is not a child of this node.
+ */
+pv.Dom.Node.prototype.replaceChild = function(n, r) {
+  var i = this.childNodes.indexOf(r);
+  if (i == -1) throw new Error("child not found");
+  if (n.parentNode) n.parentNode.removeChild(n);
+  n.parentNode = this;
+  n.nextSibling = r.nextSibling;
+  n.previousSibling = r.previousSibling;
+  if (r.previousSibling) r.previousSibling.nextSibling = n;
+  else this.firstChild = n;
+  if (r.nextSibling) r.nextSibling.previousSibling = n;
+  else this.lastChild = n;
+  this.childNodes[i] = n;
+  return r;
+};
+
+/**
+ * Visits each node in the tree in preorder traversal, applying the specified
+ * function <i>f</i>. The arguments to the function are:<ol>
+ *
+ * <li>The current node.
+ * <li>The current depth, starting at 0 for the root node.</ol>
+ *
+ * @param {function} f a function to apply to each node.
+ */
+pv.Dom.Node.prototype.visitBefore = function(f) {
+  function visit(n, i) {
+    f(n, i);
+    for (var c = n.firstChild; c; c = c.nextSibling) {
+      visit(c, i + 1);
+    }
+  }
+  visit(this, 0);
+};
+
+/**
+ * Visits each node in the tree in postorder traversal, applying the specified
+ * function <i>f</i>. The arguments to the function are:<ol>
+ *
+ * <li>The current node.
+ * <li>The current depth, starting at 0 for the root node.</ol>
+ *
+ * @param {function} f a function to apply to each node.
+ */
+pv.Dom.Node.prototype.visitAfter = function(f) {
+  function visit(n, i) {
+    for (var c = n.firstChild; c; c = c.nextSibling) {
+      visit(c, i + 1);
+    }
+    f(n, i);
+  }
+  visit(this, 0);
+};
+
+/**
+ * Sorts child nodes of this node, and all descendent nodes recursively, using
+ * the specified comparator function <tt>f</tt>. The comparator function is
+ * passed two nodes to compare.
+ *
+ * <p>Note: during the sort operation, the comparator function should not rely
+ * on the tree being well-formed; the values of <tt>previousSibling</tt> and
+ * <tt>nextSibling</tt> for the nodes being compared are not defined during the
+ * sort operation.
+ *
+ * @param {function} f a comparator function.
+ * @returns this.
+ */
+pv.Dom.Node.prototype.sort = function(f) {
+  if (this.firstChild) {
+    this.childNodes.sort(f);
+    var p = this.firstChild = this.childNodes[0], c;
+    delete p.previousSibling;
+    for (var i = 1; i < this.childNodes.length; i++) {
+      p.sort(f);
+      c = this.childNodes[i];
+      c.previousSibling = p;
+      p = p.nextSibling = c;
+    }
+    this.lastChild = p;
+    delete p.nextSibling;
+    p.sort(f);
+  }
+  return this;
+};
+
+/**
+ * Reverses all sibling nodes.
+ *
+ * @returns this.
+ */
+pv.Dom.Node.prototype.reverse = function() {
+  var childNodes = [];
+  this.visitAfter(function(n) {
+      while (n.lastChild) childNodes.push(n.removeChild(n.lastChild));
+      for (var c; c = childNodes.pop();) n.insertBefore(c, n.firstChild);
+    });
+  return this;
+};
+
+/** Returns all descendants of this node in preorder traversal. */
+pv.Dom.Node.prototype.nodes = function() {
+  var array = [];
+
+  /** @private */
+  function flatten(node) {
+    array.push(node);
+    node.childNodes.forEach(flatten);
+  }
+
+  flatten(this, array);
+  return array;
+};
+
+/**
+ * Toggles the child nodes of this node. If this node is not yet toggled, this
+ * method removes all child nodes and appends them to a new <tt>toggled</tt>
+ * array attribute on this node. Otherwise, if this node is toggled, this method
+ * re-adds all toggled child nodes and deletes the <tt>toggled</tt> attribute.
+ *
+ * <p>This method has no effect if the node has no child nodes.
+ *
+ * @param {boolean} [recursive] whether the toggle should apply to descendants.
+ */
+pv.Dom.Node.prototype.toggle = function(recursive) {
+  if (recursive) return this.toggled
+      ? this.visitBefore(function(n) { if (n.toggled) n.toggle(); })
+      : this.visitAfter(function(n) { if (!n.toggled) n.toggle(); });
+  var n = this;
+  if (n.toggled) {
+    for (var c; c = n.toggled.pop();) n.appendChild(c);
+    delete n.toggled;
+  } else if (n.lastChild) {
+    n.toggled = [];
+    while (n.lastChild) n.toggled.push(n.removeChild(n.lastChild));
+  }
+};
+
+/**
+ * Given a flat array of values, returns a simple DOM with each value wrapped by
+ * a node that is a child of the root node.
+ *
+ * @param {array} values.
+ * @returns {array} nodes.
+ */
+pv.nodes = function(values) {
+  var root = new pv.Dom.Node();
+  for (var i = 0; i < values.length; i++) {
+    root.appendChild(new pv.Dom.Node(values[i]));
+  }
+  return root.nodes();
+};
+/**
+ * Returns a {@link pv.Tree} operator for the specified array. This is a
+ * convenience factory method, equivalent to <tt>new pv.Tree(array)</tt>.
+ *
+ * @see pv.Tree
+ * @param {array} array an array from which to construct a tree.
+ * @returns {pv.Tree} a tree operator for the specified array.
+ */
+pv.tree = function(array) {
+  return new pv.Tree(array);
+};
+
+/**
+ * Constructs a tree operator for the specified array. This constructor should
+ * not be invoked directly; use {@link pv.tree} instead.
+ *
+ * @class Represents a tree operator for the specified array. The tree operator
+ * allows a hierarchical map to be constructed from an array; it is similar to
+ * the {@link pv.Nest} operator, except the hierarchy is derived dynamically
+ * from the array elements.
+ *
+ * <p>For example, given an array of size information for ActionScript classes:
+ *
+ * <pre>{ name: "flare.flex.FlareVis", size: 4116 },
+ * { name: "flare.physics.DragForce", size: 1082 },
+ * { name: "flare.physics.GravityForce", size: 1336 }, ...</pre>
+ *
+ * To facilitate visualization, it may be useful to nest the elements by their
+ * package hierarchy:
+ *
+ * <pre>var tree = pv.tree(classes)
+ *     .keys(function(d) d.name.split("."))
+ *     .map();</pre>
+ *
+ * The resulting tree is:
+ *
+ * <pre>{ flare: {
+ *     flex: {
+ *       FlareVis: {
+ *         name: "flare.flex.FlareVis",
+ *         size: 4116 } },
+ *     physics: {
+ *       DragForce: {
+ *         name: "flare.physics.DragForce",
+ *         size: 1082 },
+ *       GravityForce: {
+ *         name: "flare.physics.GravityForce",
+ *         size: 1336 } },
+ *     ... } }</pre>
+ *
+ * By specifying a value function,
+ *
+ * <pre>var tree = pv.tree(classes)
+ *     .keys(function(d) d.name.split("."))
+ *     .value(function(d) d.size)
+ *     .map();</pre>
+ *
+ * we can further eliminate redundant data:
+ *
+ * <pre>{ flare: {
+ *     flex: {
+ *       FlareVis: 4116 },
+ *     physics: {
+ *       DragForce: 1082,
+ *       GravityForce: 1336 },
+ *   ... } }</pre>
+ *
+ * For visualizations with large data sets, performance improvements may be seen
+ * by storing the data in a tree format, and then flattening it into an array at
+ * runtime with {@link pv.Flatten}.
+ *
+ * @param {array} array an array from which to construct a tree.
+ */
+pv.Tree = function(array) {
+  this.array = array;
+};
+
+/**
+ * Assigns a <i>keys</i> function to this operator; required. The keys function
+ * returns an array of <tt>string</tt>s for each element in the associated
+ * array; these keys determine how the elements are nested in the tree. The
+ * returned keys should be unique for each element in the array; otherwise, the
+ * behavior of this operator is undefined.
+ *
+ * @param {function} k the keys function.
+ * @returns {pv.Tree} this.
+ */
+pv.Tree.prototype.keys = function(k) {
+  this.k = k;
+  return this;
+};
+
+/**
+ * Assigns a <i>value</i> function to this operator; optional. The value
+ * function specifies an optional transformation of the element in the array
+ * before it is inserted into the map. If no value function is specified, it is
+ * equivalent to using the identity function.
+ *
+ * @param {function} k the value function.
+ * @returns {pv.Tree} this.
+ */
+pv.Tree.prototype.value = function(v) {
+  this.v = v;
+  return this;
+};
+
+/**
+ * Returns a hierarchical map of values. The hierarchy is determined by the keys
+ * function; the values in the map are determined by the value function.
+ *
+ * @returns a hierarchical map of values.
+ */
+pv.Tree.prototype.map = function() {
+  var map = {}, o = {};
+  for (var i = 0; i < this.array.length; i++) {
+    o.index = i;
+    var value = this.array[i], keys = this.k.call(o, value), node = map;
+    for (var j = 0; j < keys.length - 1; j++) {
+      node = node[keys[j]] || (node[keys[j]] = {});
+    }
+    node[keys[j]] = this.v ? this.v.call(o, value) : value;
+  }
+  return map;
+};
+/**
+ * Returns a {@link pv.Nest} operator for the specified array. This is a
+ * convenience factory method, equivalent to <tt>new pv.Nest(array)</tt>.
+ *
+ * @see pv.Nest
+ * @param {array} array an array of elements to nest.
+ * @returns {pv.Nest} a nest operator for the specified array.
+ */
+pv.nest = function(array) {
+  return new pv.Nest(array);
+};
+
+/**
+ * Constructs a nest operator for the specified array. This constructor should
+ * not be invoked directly; use {@link pv.nest} instead.
+ *
+ * @class Represents a {@link Nest} operator for the specified array. Nesting
+ * allows elements in an array to be grouped into a hierarchical tree
+ * structure. The levels in the tree are specified by <i>key</i> functions. The
+ * leaf nodes of the tree can be sorted by value, while the internal nodes can
+ * be sorted by key. Finally, the tree can be returned either has a
+ * multidimensional array via {@link #entries}, or as a hierarchical map via
+ * {@link #map}. The {@link #rollup} routine similarly returns a map, collapsing
+ * the elements in each leaf node using a summary function.
+ *
+ * <p>For example, consider the following tabular data structure of Barley
+ * yields, from various sites in Minnesota during 1931-2:
+ *
+ * <pre>{ yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm" },
+ * { yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca" },
+ * { yield: 27.43, variety: "Manchuria", year: 1931, site: "Morris" }, ...</pre>
+ *
+ * To facilitate visualization, it may be useful to nest the elements first by
+ * year, and then by variety, as follows:
+ *
+ * <pre>var nest = pv.nest(yields)
+ *     .key(function(d) d.year)
+ *     .key(function(d) d.variety)
+ *     .entries();</pre>
+ *
+ * This returns a nested array. Each element of the outer array is a key-values
+ * pair, listing the values for each distinct key:
+ *
+ * <pre>{ key: 1931, values: [
+ *   { key: "Manchuria", values: [
+ *       { yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm" },
+ *       { yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca" },
+ *       { yield: 27.43, variety: "Manchuria", year: 1931, site: "Morris" },
+ *       ...
+ *     ] },
+ *   { key: "Glabron", values: [
+ *       { yield: 43.07, variety: "Glabron", year: 1931, site: "University Farm" },
+ *       { yield: 55.20, variety: "Glabron", year: 1931, site: "Waseca" },
+ *       ...
+ *     ] },
+ *   ] },
+ * { key: 1932, values: ... }</pre>
+ *
+ * Further details, including sorting and rollup, is provided below on the
+ * corresponding methods.
+ *
+ * @param {array} array an array of elements to nest.
+ */
+pv.Nest = function(array) {
+  this.array = array;
+  this.keys = [];
+};
+
+/**
+ * Nests using the specified key function. Multiple keys may be added to the
+ * nest; the array elements will be nested in the order keys are specified.
+ *
+ * @param {function} key a key function; must return a string or suitable map
+ * key.
+ * @returns {pv.Nest} this.
+ */
+pv.Nest.prototype.key = function(key) {
+  this.keys.push(key);
+  return this;
+};
+
+/**
+ * Sorts the previously-added keys. The natural sort order is used by default
+ * (see {@link pv.naturalOrder}); if an alternative order is desired,
+ * <tt>order</tt> should be a comparator function. If this method is not called
+ * (i.e., keys are <i>unsorted</i>), keys will appear in the order they appear
+ * in the underlying elements array. For example,
+ *
+ * <pre>pv.nest(yields)
+ *     .key(function(d) d.year)
+ *     .key(function(d) d.variety)
+ *     .sortKeys()
+ *     .entries()</pre>
+ *
+ * groups yield data by year, then variety, and sorts the variety groups
+ * lexicographically (since the variety attribute is a string).
+ *
+ * <p>Key sort order is only used in conjunction with {@link #entries}, which
+ * returns an array of key-values pairs. If the nest is used to construct a
+ * {@link #map} instead, keys are unsorted.
+ *
+ * @param {function} [order] an optional comparator function.
+ * @returns {pv.Nest} this.
+ */
+pv.Nest.prototype.sortKeys = function(order) {
+  this.keys[this.keys.length - 1].order = order || pv.naturalOrder;
+  return this;
+};
+
+/**
+ * Sorts the leaf values. The natural sort order is used by default (see
+ * {@link pv.naturalOrder}); if an alternative order is desired, <tt>order</tt>
+ * should be a comparator function. If this method is not called (i.e., values
+ * are <i>unsorted</i>), values will appear in the order they appear in the
+ * underlying elements array. For example,
+ *
+ * <pre>pv.nest(yields)
+ *     .key(function(d) d.year)
+ *     .key(function(d) d.variety)
+ *     .sortValues(function(a, b) a.yield - b.yield)
+ *     .entries()</pre>
+ *
+ * groups yield data by year, then variety, and sorts the values for each
+ * variety group by yield.
+ *
+ * <p>Value sort order, unlike keys, applies to both {@link #entries} and
+ * {@link #map}. It has no effect on {@link #rollup}.
+ *
+ * @param {function} [order] an optional comparator function.
+ * @returns {pv.Nest} this.
+ */
+pv.Nest.prototype.sortValues = function(order) {
+  this.order = order || pv.naturalOrder;
+  return this;
+};
+
+/**
+ * Returns a hierarchical map of values. Each key adds one level to the
+ * hierarchy. With only a single key, the returned map will have a key for each
+ * distinct value of the key function; the correspond value with be an array of
+ * elements with that key value. If a second key is added, this will be a nested
+ * map. For example:
+ *
+ * <pre>pv.nest(yields)
+ *     .key(function(d) d.variety)
+ *     .key(function(d) d.site)
+ *     .map()</pre>
+ *
+ * returns a map <tt>m</tt> such that <tt>m[variety][site]</tt> is an array, a subset of
+ * <tt>yields</tt>, with each element having the given variety and site.
+ *
+ * @returns a hierarchical map of values.
+ */
+pv.Nest.prototype.map = function() {
+  var map = {}, values = [];
+
+  /* Build the map. */
+  for (var i, j = 0; j < this.array.length; j++) {
+    var x = this.array[j];
+    var m = map;
+    for (i = 0; i < this.keys.length - 1; i++) {
+      var k = this.keys[i](x);
+      if (!m[k]) m[k] = {};
+      m = m[k];
+    }
+    k = this.keys[i](x);
+    if (!m[k]) {
+      var a = [];
+      values.push(a);
+      m[k] = a;
+    }
+    m[k].push(x);
+  }
+
+  /* Sort each leaf array. */
+  if (this.order) {
+    for (var i = 0; i < values.length; i++) {
+      values[i].sort(this.order);
+    }
+  }
+
+  return map;
+};
+
+/**
+ * Returns a hierarchical nested array. This method is similar to
+ * {@link pv.entries}, but works recursively on the entire hierarchy. Rather
+ * than returning a map like {@link #map}, this method returns a nested
+ * array. Each element of the array has a <tt>key</tt> and <tt>values</tt>
+ * field. For leaf nodes, the <tt>values</tt> array will be a subset of the
+ * underlying elements array; for non-leaf nodes, the <tt>values</tt> array will
+ * contain more key-values pairs.
+ *
+ * <p>For an example usage, see the {@link Nest} constructor.
+ *
+ * @returns a hierarchical nested array.
+ */
+pv.Nest.prototype.entries = function() {
+
+  /** Recursively extracts the entries for the given map. */
+  function entries(map) {
+    var array = [];
+    for (var k in map) {
+      var v = map[k];
+      array.push({ key: k, values: (v instanceof Array) ? v : entries(v) });
+    };
+    return array;
+  }
+
+  /** Recursively sorts the values for the given key-values array. */
+  function sort(array, i) {
+    var o = this.keys[i].order;
+    if (o) array.sort(function(a, b) { return o(a.key, b.key); });
+    if (++i < this.keys.length) {
+      for (var j = 0; j < array.length; j++) {
+        sort.call(this, array[j].values, i);
+      }
+    }
+    return array;
+  }
+
+  return sort.call(this, entries(this.map()), 0);
+};
+
+/**
+ * Returns a rollup map. The behavior of this method is the same as
+ * {@link #map}, except that the leaf values are replaced with the return value
+ * of the specified rollup function <tt>f</tt>. For example,
+ *
+ * <pre>pv.nest(yields)
+ *      .key(function(d) d.site)
+ *      .rollup(function(v) pv.median(v, function(d) d.yield))</pre>
+ *
+ * first groups yield data by site, and then returns a map from site to median
+ * yield for the given site.
+ *
+ * @see #map
+ * @param {function} f a rollup function.
+ * @returns a hierarchical map, with the leaf values computed by <tt>f</tt>.
+ */
+pv.Nest.prototype.rollup = function(f) {
+
+  /** Recursively descends to the leaf nodes (arrays) and does rollup. */
+  function rollup(map) {
+    for (var key in map) {
+      var value = map[key];
+      if (value instanceof Array) {
+        map[key] = f(value);
+      } else {
+        rollup(value);
+      }
+    }
+    return map;
+  }
+
+  return rollup(this.map());
+};
+/**
+ * Returns a {@link pv.Flatten} operator for the specified map. This is a
+ * convenience factory method, equivalent to <tt>new pv.Flatten(map)</tt>.
+ *
+ * @see pv.Flatten
+ * @param map a map to flatten.
+ * @returns {pv.Flatten} a flatten operator for the specified map.
+ */
+pv.flatten = function(map) {
+  return new pv.Flatten(map);
+};
+
+/**
+ * Constructs a flatten operator for the specified map. This constructor should
+ * not be invoked directly; use {@link pv.flatten} instead.
+ *
+ * @class Represents a flatten operator for the specified array. Flattening
+ * allows hierarchical maps to be flattened into an array. The levels in the
+ * input tree are specified by <i>key</i> functions.
+ *
+ * <p>For example, consider the following hierarchical data structure of Barley
+ * yields, from various sites in Minnesota during 1931-2:
+ *
+ * <pre>{ 1931: {
+ *     Manchuria: {
+ *       "University Farm": 27.00,
+ *       "Waseca": 48.87,
+ *       "Morris": 27.43,
+ *       ... },
+ *     Glabron: {
+ *       "University Farm": 43.07,
+ *       "Waseca": 55.20,
+ *       ... } },
+ *   1932: {
+ *     ... } }</pre>
+ *
+ * To facilitate visualization, it may be useful to flatten the tree into a
+ * tabular array:
+ *
+ * <pre>var array = pv.flatten(yields)
+ *     .key("year")
+ *     .key("variety")
+ *     .key("site")
+ *     .key("yield")
+ *     .array();</pre>
+ *
+ * This returns an array of object elements. Each element in the array has
+ * attributes corresponding to this flatten operator's keys:
+ *
+ * <pre>{ site: "University Farm", variety: "Manchuria", year: 1931, yield: 27 },
+ * { site: "Waseca", variety: "Manchuria", year: 1931, yield: 48.87 },
+ * { site: "Morris", variety: "Manchuria", year: 1931, yield: 27.43 },
+ * { site: "University Farm", variety: "Glabron", year: 1931, yield: 43.07 },
+ * { site: "Waseca", variety: "Glabron", year: 1931, yield: 55.2 }, ...</pre>
+ *
+ * <p>The flatten operator is roughly the inverse of the {@link pv.Nest} and
+ * {@link pv.Tree} operators.
+ *
+ * @param map a map to flatten.
+ */
+pv.Flatten = function(map) {
+  this.map = map;
+  this.keys = [];
+};
+
+/**
+ * Flattens using the specified key function. Multiple keys may be added to the
+ * flatten; the tiers of the underlying tree must correspond to the specified
+ * keys, in order. The order of the returned array is undefined; however, you
+ * can easily sort it.
+ *
+ * @param {string} key the key name.
+ * @param {function} [f] an optional value map function.
+ * @returns {pv.Nest} this.
+ */
+pv.Flatten.prototype.key = function(key, f) {
+  this.keys.push({name: key, value: f});
+  delete this.$leaf;
+  return this;
+};
+
+/**
+ * Flattens using the specified leaf function. This is an alternative to
+ * specifying an explicit set of keys; the tiers of the underlying tree will be
+ * determined dynamically by recursing on the values, and the resulting keys
+ * will be stored in the entries <tt>keys</tt> attribute. The leaf function must
+ * return true for leaves, and false for internal nodes.
+ *
+ * @param {function} f a leaf function.
+ * @returns {pv.Nest} this.
+ */
+pv.Flatten.prototype.leaf = function(f) {
+  this.keys.length = 0;
+  this.$leaf = f;
+  return this;
+};
+
+/**
+ * Returns the flattened array. Each entry in the array is an object; each
+ * object has attributes corresponding to this flatten operator's keys.
+ *
+ * @returns an array of elements from the flattened map.
+ */
+pv.Flatten.prototype.array = function() {
+  var entries = [], stack = [], keys = this.keys, leaf = this.$leaf;
+
+  /* Recursively visit using the leaf function. */
+  if (leaf) {
+    function recurse(value, i) {
+      if (leaf(value)) {
+        entries.push({keys: stack.slice(), value: value});
+      } else {
+        for (var key in value) {
+          stack.push(key);
+          recurse(value[key], i + 1);
+          stack.pop();
+        }
+      }
+    }
+    recurse(this.map, 0);
+    return entries;
+  }
+
+  /* Recursively visits the specified value. */
+  function visit(value, i) {
+    if (i < keys.length - 1) {
+      for (var key in value) {
+        stack.push(key);
+        visit(value[key], i + 1);
+        stack.pop();
+      }
+    } else {
+      entries.push(stack.concat(value));
+    }
+  }
+
+  visit(this.map, 0);
+  return entries.map(function(stack) {
+      var m = {};
+      for (var i = 0; i < keys.length; i++) {
+        var k = keys[i], v = stack[i];
+        m[k.name] = k.value ? k.value.call(null, v) : v;
+      }
+      return m;
+    });
+};
+/**
+ * Returns a {@link pv.Vector} for the specified <i>x</i> and <i>y</i>
+ * coordinate. This is a convenience factory method, equivalent to <tt>new
+ * pv.Vector(x, y)</tt>.
+ *
+ * @see pv.Vector
+ * @param {number} x the <i>x</i> coordinate.
+ * @param {number} y the <i>y</i> coordinate.
+ * @returns {pv.Vector} a vector for the specified coordinates.
+ */
+pv.vector = function(x, y) {
+  return new pv.Vector(x, y);
+};
+
+/**
+ * Constructs a {@link pv.Vector} for the specified <i>x</i> and <i>y</i>
+ * coordinate. This constructor should not be invoked directly; use
+ * {@link pv.vector} instead.
+ *
+ * @class Represents a two-dimensional vector; a 2-tuple <i>&#x27e8;x,
+ * y&#x27e9;</i>. The intent of this class is to simplify vector math. Note that
+ * in performance-sensitive cases it may be more efficient to represent 2D
+ * vectors as simple objects with <tt>x</tt> and <tt>y</tt> attributes, rather
+ * than using instances of this class.
+ *
+ * @param {number} x the <i>x</i> coordinate.
+ * @param {number} y the <i>y</i> coordinate.
+ */
+pv.Vector = function(x, y) {
+  this.x = x;
+  this.y = y;
+};
+
+/**
+ * Returns a vector perpendicular to this vector: <i>&#x27e8;-y, x&#x27e9;</i>.
+ *
+ * @returns {pv.Vector} a perpendicular vector.
+ */
+pv.Vector.prototype.perp = function() {
+  return new pv.Vector(-this.y, this.x);
+};
+
+/**
+ * Returns a normalized copy of this vector: a vector with the same direction,
+ * but unit length. If this vector has zero length this method returns a copy of
+ * this vector.
+ *
+ * @returns {pv.Vector} a unit vector.
+ */
+pv.Vector.prototype.norm = function() {
+  var l = this.length();
+  return this.times(l ? (1 / l) : 1);
+};
+
+/**
+ * Returns the magnitude of this vector, defined as <i>sqrt(x * x + y * y)</i>.
+ *
+ * @returns {number} a length.
+ */
+pv.Vector.prototype.length = function() {
+  return Math.sqrt(this.x * this.x + this.y * this.y);
+};
+
+/**
+ * Returns a scaled copy of this vector: <i>&#x27e8;x * k, y * k&#x27e9;</i>.
+ * To perform the equivalent divide operation, use <i>1 / k</i>.
+ *
+ * @param {number} k the scale factor.
+ * @returns {pv.Vector} a scaled vector.
+ */
+pv.Vector.prototype.times = function(k) {
+  return new pv.Vector(this.x * k, this.y * k);
+};
+
+/**
+ * Returns this vector plus the vector <i>v</i>: <i>&#x27e8;x + v.x, y +
+ * v.y&#x27e9;</i>. If only one argument is specified, it is interpreted as the
+ * vector <i>v</i>.
+ *
+ * @param {number} x the <i>x</i> coordinate to add.
+ * @param {number} y the <i>y</i> coordinate to add.
+ * @returns {pv.Vector} a new vector.
+ */
+pv.Vector.prototype.plus = function(x, y) {
+  return (arguments.length == 1)
+      ? new pv.Vector(this.x + x.x, this.y + x.y)
+      : new pv.Vector(this.x + x, this.y + y);
+};
+
+/**
+ * Returns this vector minus the vector <i>v</i>: <i>&#x27e8;x - v.x, y -
+ * v.y&#x27e9;</i>. If only one argument is specified, it is interpreted as the
+ * vector <i>v</i>.
+ *
+ * @param {number} x the <i>x</i> coordinate to subtract.
+ * @param {number} y the <i>y</i> coordinate to subtract.
+ * @returns {pv.Vector} a new vector.
+ */
+pv.Vector.prototype.minus = function(x, y) {
+  return (arguments.length == 1)
+      ? new pv.Vector(this.x - x.x, this.y - x.y)
+      : new pv.Vector(this.x - x, this.y - y);
+};
+
+/**
+ * Returns the dot product of this vector and the vector <i>v</i>: <i>x * v.x +
+ * y * v.y</i>. If only one argument is specified, it is interpreted as the
+ * vector <i>v</i>.
+ *
+ * @param {number} x the <i>x</i> coordinate to dot.
+ * @param {number} y the <i>y</i> coordinate to dot.
+ * @returns {number} a dot product.
+ */
+pv.Vector.prototype.dot = function(x, y) {
+  return (arguments.length == 1)
+      ? this.x * x.x + this.y * x.y
+      : this.x * x + this.y * y;
+};
+/**
+ * Returns a new identity transform.
+ *
+ * @class Represents a transformation matrix. The transformation matrix is
+ * limited to expressing translate and uniform scale transforms only; shearing,
+ * rotation, general affine, and other transforms are not supported.
+ *
+ * <p>The methods on this class treat the transform as immutable, returning a
+ * copy of the transformation matrix with the specified transform applied. Note,
+ * alternatively, that the matrix fields can be get and set directly.
+ */
+pv.Transform = function() {};
+pv.Transform.prototype = {k: 1, x: 0, y: 0};
+
+/**
+ * The scale magnitude; defaults to 1.
+ *
+ * @type number
+ * @name pv.Transform.prototype.k
+ */
+
+/**
+ * The x-offset; defaults to 0.
+ *
+ * @type number
+ * @name pv.Transform.prototype.x
+ */
+
+/**
+ * The y-offset; defaults to 0.
+ *
+ * @type number
+ * @name pv.Transform.prototype.y
+ */
+
+/**
+ * @private The identity transform.
+ *
+ * @type pv.Transform
+ */
+pv.Transform.identity = new pv.Transform();
+
+// k 0 x   1 0 a   k 0 ka+x
+// 0 k y * 0 1 b = 0 k kb+y
+// 0 0 1   0 0 1   0 0 1
+
+/**
+ * Returns a translated copy of this transformation matrix.
+ *
+ * @param {number} x the x-offset.
+ * @param {number} y the y-offset.
+ * @returns {pv.Transform} the translated transformation matrix.
+ */
+pv.Transform.prototype.translate = function(x, y) {
+  var v = new pv.Transform();
+  v.k = this.k;
+  v.x = this.k * x + this.x;
+  v.y = this.k * y + this.y;
+  return v;
+};
+
+// k 0 x   d 0 0   kd  0 x
+// 0 k y * 0 d 0 =  0 kd y
+// 0 0 1   0 0 1    0  0 1
+
+/**
+ * Returns a scaled copy of this transformation matrix.
+ *
+ * @param {number} k
+ * @returns {pv.Transform} the scaled transformation matrix.
+ */
+pv.Transform.prototype.scale = function(k) {
+  var v = new pv.Transform();
+  v.k = this.k * k;
+  v.x = this.x;
+  v.y = this.y;
+  return v;
+};
+
+/**
+ * Returns the inverse of this transformation matrix.
+ *
+ * @returns {pv.Transform} the inverted transformation matrix.
+ */
+pv.Transform.prototype.invert = function() {
+  var v = new pv.Transform(), k = 1 / this.k;
+  v.k = k;
+  v.x = -this.x * k;
+  v.y = -this.y * k;
+  return v;
+};
+
+// k 0 x   d 0 a   kd  0 ka+x
+// 0 k y * 0 d b =  0 kd kb+y
+// 0 0 1   0 0 1    0  0    1
+
+/**
+ * Returns this matrix post-multiplied by the specified matrix <i>m</i>.
+ *
+ * @param {pv.Transform} m
+ * @returns {pv.Transform} the post-multiplied transformation matrix.
+ */
+pv.Transform.prototype.times = function(m) {
+  var v = new pv.Transform();
+  v.k = this.k * m.k;
+  v.x = this.k * m.x + this.x;
+  v.y = this.k * m.y + this.y;
+  return v;
+};
+/**
+ * Abstract; see the various scale implementations.
+ *
+ * @class Represents a scale; a function that performs a transformation from
+ * data domain to visual range. For quantitative and quantile scales, the domain
+ * is expressed as numbers; for ordinal scales, the domain is expressed as
+ * strings (or equivalently objects with unique string representations). The
+ * "visual range" may correspond to pixel space, colors, font sizes, and the
+ * like.
+ *
+ * <p>Note that scales are functions, and thus can be used as properties
+ * directly, assuming that the data associated with a mark is a number. While
+ * this is convenient for single-use scales, frequently it is desirable to
+ * define scales globally:
+ *
+ * <pre>var y = pv.Scale.linear(0, 100).range(0, 640);</pre>
+ *
+ * The <tt>y</tt> scale can now be equivalently referenced within a property:
+ *
+ * <pre>    .height(function(d) y(d))</pre>
+ *
+ * Alternatively, if the data are not simple numbers, the appropriate value can
+ * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
+ * method similarly allows the data to be mapped to a numeric value before
+ * performing the linear transformation.
+ *
+ * @see pv.Scale.quantitative
+ * @see pv.Scale.quantile
+ * @see pv.Scale.ordinal
+ * @extends function
+ */
+pv.Scale = function() {};
+
+/**
+ * @private Returns a function that interpolators from the start value to the
+ * end value, given a parameter <i>t</i> in [0, 1].
+ *
+ * @param start the start value.
+ * @param end the end value.
+ */
+pv.Scale.interpolator = function(start, end) {
+  if (typeof start == "number") {
+    return function(t) {
+      return t * (end - start) + start;
+    };
+  }
+
+  /* For now, assume color. */
+  start = pv.color(start).rgb();
+  end = pv.color(end).rgb();
+  return function(t) {
+    var a = start.a * (1 - t) + end.a * t;
+    if (a < 1e-5) a = 0; // avoid scientific notation
+    return (start.a == 0) ? pv.rgb(end.r, end.g, end.b, a)
+        : ((end.a == 0) ? pv.rgb(start.r, start.g, start.b, a)
+        : pv.rgb(
+            Math.round(start.r * (1 - t) + end.r * t),
+            Math.round(start.g * (1 - t) + end.g * t),
+            Math.round(start.b * (1 - t) + end.b * t), a));
+  };
+};
+
+/**
+ * Returns a view of this scale by the specified accessor function <tt>f</tt>.
+ * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
+ * <tt>function(d) y(d.foo)</tt>.
+ *
+ * <p>This method is provided for convenience, such that scales can be
+ * succinctly defined inline. For example, given an array of data elements that
+ * have a <tt>score</tt> attribute with the domain [0, 1], the height property
+ * could be specified as:
+ *
+ * <pre>    .height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
+ *
+ * This is equivalent to:
+ *
+ * <pre>    .height(function(d) d.score * 480)</pre>
+ *
+ * This method should be used judiciously; it is typically more clear to invoke
+ * the scale directly, passing in the value to be scaled.
+ *
+ * @function
+ * @name pv.Scale.prototype.by
+ * @param {function} f an accessor function.
+ * @returns {pv.Scale} a view of this scale by the specified accessor function.
+ */
+/**
+ * Returns a default quantitative, linear, scale for the specified domain. The
+ * arguments to this constructor are optional, and equivalent to calling
+ * {@link #domain}. The default domain and range are [0,1].
+ *
+ * <p>This constructor is typically not used directly; see one of the
+ * quantitative scale implementations instead.
+ *
+ * @class Represents an abstract quantitative scale; a function that performs a
+ * numeric transformation. This class is typically not used directly; see one of
+ * the quantitative scale implementations (linear, log, root, etc.)
+ * instead. <style type="text/css">sub{line-height:0}</style> A quantitative
+ * scale represents a 1-dimensional transformation from a numeric domain of
+ * input data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to a numeric range of
+ * pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>]. In addition to
+ * readability, scales offer several useful features:
+ *
+ * <p>1. The range can be expressed in colors, rather than pixels. For example:
+ *
+ * <pre>    .fillStyle(pv.Scale.linear(0, 100).range("red", "green"))</pre>
+ *
+ * will fill the marks "red" on an input value of 0, "green" on an input value
+ * of 100, and some color in-between for intermediate values.
+ *
+ * <p>2. The domain and range can be subdivided for a non-uniform
+ * transformation. For example, you may want a diverging color scale that is
+ * increasingly red for negative values, and increasingly green for positive
+ * values:
+ *
+ * <pre>    .fillStyle(pv.Scale.linear(-1, 0, 1).range("red", "white", "green"))</pre>
+ *
+ * The domain can be specified as a series of <i>n</i> monotonically-increasing
+ * values; the range must also be specified as <i>n</i> values, resulting in
+ * <i>n - 1</i> contiguous linear scales.
+ *
+ * <p>3. Quantitative scales can be inverted for interaction. The
+ * {@link #invert} method takes a value in the output range, and returns the
+ * corresponding value in the input domain. This is frequently used to convert
+ * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
+ * domain. Note that inversion is only supported for numeric ranges, and not
+ * colors.
+ *
+ * <p>4. A scale can be queried for reasonable "tick" values. The {@link #ticks}
+ * method provides a convenient way to get a series of evenly-spaced rounded
+ * values in the input domain. Frequently these are used in conjunction with
+ * {@link pv.Rule} to display tick marks or grid lines.
+ *
+ * <p>5. A scale can be "niced" to extend the domain to suitable rounded
+ * numbers. If the minimum and maximum of the domain are messy because they are
+ * derived from data, you can use {@link #nice} to round these values down and
+ * up to even numbers.
+ *
+ * @param {number...} domain... optional domain values.
+ * @see pv.Scale.linear
+ * @see pv.Scale.log
+ * @see pv.Scale.root
+ * @extends pv.Scale
+ */
+pv.Scale.quantitative = function() {
+  var d = [0, 1], // default domain
+      l = [0, 1], // default transformed domain
+      r = [0, 1], // default range
+      i = [pv.identity], // default interpolators
+      type = Number, // default type
+      n = false, // whether the domain is negative
+      f = pv.identity, // default forward transform
+      g = pv.identity, // default inverse transform
+      tickFormat = String; // default tick formatting function
+
+  /** @private */
+  function newDate(x) {
+    return new Date(x);
+  }
+
+  /** @private */
+  function scale(x) {
+    var j = pv.search(d, x);
+    if (j < 0) j = -j - 2;
+    j = Math.max(0, Math.min(i.length - 1, j));
+    return i[j]((f(x) - l[j]) / (l[j + 1] - l[j]));
+  }
+
+  /** @private */
+  scale.transform = function(forward, inverse) {
+    /** @ignore */ f = function(x) { return n ? -forward(-x) : forward(x); };
+    /** @ignore */ g = function(y) { return n ? -inverse(-y) : inverse(y); };
+    l = d.map(f);
+    return this;
+  };
+
+  /**
+   * Sets or gets the input domain. This method can be invoked several ways:
+   *
+   * <p>1. <tt>domain(min, ..., max)</tt>
+   *
+   * <p>Specifying the domain as a series of numbers is the most explicit and
+   * recommended approach. Most commonly, two numbers are specified: the minimum
+   * and maximum value. However, for a diverging scale, or other subdivided
+   * non-uniform scales, multiple values can be specified. Values can be derived
+   * from data using {@link pv.min} and {@link pv.max}. For example:
+   *
+   * <pre>    .domain(0, pv.max(array))</pre>
+   *
+   * An alternative method for deriving minimum and maximum values from data
+   * follows.
+   *
+   * <p>2. <tt>domain(array, minf, maxf)</tt>
+   *
+   * <p>When both the minimum and maximum value are derived from data, the
+   * arguments to the <tt>domain</tt> method can be specified as the array of
+   * data, followed by zero, one or two accessor functions. For example, if the
+   * array of data is just an array of numbers:
+   *
+   * <pre>    .domain(array)</pre>
+   *
+   * On the other hand, if the array elements are objects representing stock
+   * values per day, and the domain should consider the stock's daily low and
+   * daily high:
+   *
+   * <pre>    .domain(array, function(d) d.low, function(d) d.high)</pre>
+   *
+   * The first method of setting the domain is preferred because it is more
+   * explicit; setting the domain using this second method should be used only
+   * if brevity is required.
+   *
+   * <p>3. <tt>domain()</tt>
+   *
+   * <p>Invoking the <tt>domain</tt> method with no arguments returns the
+   * current domain as an array of numbers.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.domain
+   * @param {number...} domain... domain values.
+   * @returns {pv.Scale.quantitative} <tt>this</tt>, or the current domain.
+   */
+  scale.domain = function(array, min, max) {
+    if (arguments.length) {
+      var o; // the object we use to infer the domain type
+      if (array instanceof Array) {
+        if (arguments.length < 2) min = pv.identity;
+        if (arguments.length < 3) max = min;
+        o = array.length && min(array[0]);
+        d = array.length ? [pv.min(array, min), pv.max(array, max)] : [];
+      } else {
+        o = array;
+        d = Array.prototype.slice.call(arguments).map(Number);
+      }
+      if (!d.length) d = [-Infinity, Infinity];
+      else if (d.length == 1) d = [d[0], d[0]];
+      n = (d[0] || d[d.length - 1]) < 0;
+      l = d.map(f);
+      type = (o instanceof Date) ? newDate : Number;
+      return this;
+    }
+    return d.map(type);
+  };
+
+  /**
+   * Sets or gets the output range. This method can be invoked several ways:
+   *
+   * <p>1. <tt>range(min, ..., max)</tt>
+   *
+   * <p>The range may be specified as a series of numbers or colors. Most
+   * commonly, two numbers are specified: the minimum and maximum pixel values.
+   * For a color scale, values may be specified as {@link pv.Color}s or
+   * equivalent strings. For a diverging scale, or other subdivided non-uniform
+   * scales, multiple values can be specified. For example:
+   *
+   * <pre>    .range("red", "white", "green")</pre>
+   *
+   * <p>Currently, only numbers and colors are supported as range values. The
+   * number of range values must exactly match the number of domain values, or
+   * the behavior of the scale is undefined.
+   *
+   * <p>2. <tt>range()</tt>
+   *
+   * <p>Invoking the <tt>range</tt> method with no arguments returns the current
+   * range as an array of numbers or colors.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.range
+   * @param {...} range... range values.
+   * @returns {pv.Scale.quantitative} <tt>this</tt>, or the current range.
+   */
+  scale.range = function() {
+    if (arguments.length) {
+      r = Array.prototype.slice.call(arguments);
+      if (!r.length) r = [-Infinity, Infinity];
+      else if (r.length == 1) r = [r[0], r[0]];
+      i = [];
+      for (var j = 0; j < r.length - 1; j++) {
+        i.push(pv.Scale.interpolator(r[j], r[j + 1]));
+      }
+      return this;
+    }
+    return r;
+  };
+
+  /**
+   * Inverts the specified value in the output range, returning the
+   * corresponding value in the input domain. This is frequently used to convert
+   * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
+   * domain. Inversion is only supported for numeric ranges, and not colors.
+   *
+   * <p>Note that this method does not do any rounding or bounds checking. If
+   * the input domain is discrete (e.g., an array index), the returned value
+   * should be rounded. If the specified <tt>y</tt> value is outside the range,
+   * the returned value may be equivalently outside the input domain.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.invert
+   * @param {number} y a value in the output range (a pixel location).
+   * @returns {number} a value in the input domain.
+   */
+  scale.invert = function(y) {
+    var j = pv.search(r, y);
+    if (j < 0) j = -j - 2;
+    j = Math.max(0, Math.min(i.length - 1, j));
+    return type(g(l[j] + (y - r[j]) / (r[j + 1] - r[j]) * (l[j + 1] - l[j])));
+  };
+
+  /**
+   * Returns an array of evenly-spaced, suitably-rounded values in the input
+   * domain. This method attempts to return between 5 and 10 tick values. These
+   * values are frequently used in conjunction with {@link pv.Rule} to display
+   * tick marks or grid lines.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.ticks
+   * @param {number} [m] optional number of desired ticks.
+   * @returns {number[]} an array input domain values to use as ticks.
+   */
+  scale.ticks = function(m) {
+    var start = d[0],
+        end = d[d.length - 1],
+        reverse = end < start,
+        min = reverse ? end : start,
+        max = reverse ? start : end,
+        span = max - min;
+
+    /* Special case: empty, invalid or infinite span. */
+    if (!span || !isFinite(span)) {
+      if (type == newDate) tickFormat = pv.Format.date("%x");
+      return [type(min)];
+    }
+
+    /* Special case: dates. */
+    if (type == newDate) {
+      /* Floor the date d given the precision p. */
+      function floor(d, p) {
+        switch (p) {
+          case 31536e6: d.setMonth(0);
+          case 2592e6: d.setDate(1);
+          case 6048e5: if (p == 6048e5) d.setDate(d.getDate() - d.getDay());
+          case 864e5: d.setHours(0);
+          case 36e5: d.setMinutes(0);
+          case 6e4: d.setSeconds(0);
+          case 1e3: d.setMilliseconds(0);
+        }
+      }
+
+      var precision, format, increment, step = 1;
+      if (span >= 3 * 31536e6) {
+        precision = 31536e6;
+        format = "%Y";
+        /** @ignore */ increment = function(d) { d.setFullYear(d.getFullYear() + step); };
+      } else if (span >= 3 * 2592e6) {
+        precision = 2592e6;
+        format = "%m/%Y";
+        /** @ignore */ increment = function(d) { d.setMonth(d.getMonth() + step); };
+      } else if (span >= 3 * 6048e5) {
+        precision = 6048e5;
+        format = "%m/%d";
+        /** @ignore */ increment = function(d) { d.setDate(d.getDate() + 7 * step); };
+      } else if (span >= 3 * 864e5) {
+        precision = 864e5;
+        format = "%m/%d";
+        /** @ignore */ increment = function(d) { d.setDate(d.getDate() + step); };
+      } else if (span >= 3 * 36e5) {
+        precision = 36e5;
+        format = "%I:%M %p";
+        /** @ignore */ increment = function(d) { d.setHours(d.getHours() + step); };
+      } else if (span >= 3 * 6e4) {
+        precision = 6e4;
+        format = "%I:%M %p";
+        /** @ignore */ increment = function(d) { d.setMinutes(d.getMinutes() + step); };
+      } else if (span >= 3 * 1e3) {
+        precision = 1e3;
+        format = "%I:%M:%S";
+        /** @ignore */ increment = function(d) { d.setSeconds(d.getSeconds() + step); };
+      } else {
+        precision = 1;
+        format = "%S.%Qs";
+        /** @ignore */ increment = function(d) { d.setTime(d.getTime() + step); };
+      }
+      tickFormat = pv.Format.date(format);
+
+      var date = new Date(min), dates = [];
+      floor(date, precision);
+
+      /* If we'd generate too many ticks, skip some!. */
+      var n = span / precision;
+      if (n > 10) {
+        switch (precision) {
+          case 36e5: {
+            step = (n > 20) ? 6 : 3;
+            date.setHours(Math.floor(date.getHours() / step) * step);
+            break;
+          }
+          case 2592e6: {
+            step = 3; // seasons
+            date.setMonth(Math.floor(date.getMonth() / step) * step);
+            break;
+          }
+          case 6e4: {
+            step = (n > 30) ? 15 : ((n > 15) ? 10 : 5);
+            date.setMinutes(Math.floor(date.getMinutes() / step) * step);
+            break;
+          }
+          case 1e3: {
+            step = (n > 90) ? 15 : ((n > 60) ? 10 : 5);
+            date.setSeconds(Math.floor(date.getSeconds() / step) * step);
+            break;
+          }
+          case 1: {
+            step = (n > 1000) ? 250 : ((n > 200) ? 100 : ((n > 100) ? 50 : ((n > 50) ? 25 : 5)));
+            date.setMilliseconds(Math.floor(date.getMilliseconds() / step) * step);
+            break;
+          }
+          default: {
+            step = pv.logCeil(n / 15, 10);
+            if (n / step < 2) step /= 5;
+            else if (n / step < 5) step /= 2;
+            date.setFullYear(Math.floor(date.getFullYear() / step) * step);
+            break;
+          }
+        }
+      }
+
+      while (true) {
+        increment(date);
+        if (date > max) break;
+        dates.push(new Date(date));
+      }
+      return reverse ? dates.reverse() : dates;
+    }
+
+    /* Normal case: numbers. */
+    if (!arguments.length) m = 10;
+    var step = pv.logFloor(span / m, 10),
+        err = m / (span / step);
+    if (err <= .15) step *= 10;
+    else if (err <= .35) step *= 5;
+    else if (err <= .75) step *= 2;
+    var start = Math.ceil(min / step) * step,
+        end = Math.floor(max / step) * step;
+    tickFormat = pv.Format.number()
+        .fractionDigits(Math.max(0, -Math.floor(pv.log(step, 10) + .01)));
+    var ticks = pv.range(start, end + step, step);
+    return reverse ? ticks.reverse() : ticks;
+  };
+
+  /**
+   * Formats the specified tick value using the appropriate precision, based on
+   * the step interval between tick marks. If {@link #ticks} has not been called,
+   * the argument is converted to a string, but no formatting is applied.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.tickFormat
+   * @param {number} t a tick value.
+   * @returns {string} a formatted tick value.
+   */
+  scale.tickFormat = function (t) { return tickFormat(t); };
+
+  /**
+   * "Nices" this scale, extending the bounds of the input domain to
+   * evenly-rounded values. Nicing is useful if the domain is computed
+   * dynamically from data, and may be irregular. For example, given a domain of
+   * [0.20147987687960267, 0.996679553296417], a call to <tt>nice()</tt> might
+   * extend the domain to [0.2, 1].
+   *
+   * <p>This method must be invoked each time after setting the domain.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.nice
+   * @returns {pv.Scale.quantitative} <tt>this</tt>.
+   */
+  scale.nice = function() {
+    if (d.length != 2) return this; // TODO support non-uniform domains
+    var start = d[0],
+        end = d[d.length - 1],
+        reverse = end < start,
+        min = reverse ? end : start,
+        max = reverse ? start : end,
+        span = max - min;
+
+    /* Special case: empty, invalid or infinite span. */
+    if (!span || !isFinite(span)) return this;
+
+    var step = Math.pow(10, Math.round(Math.log(span) / Math.log(10)) - 1);
+    d = [Math.floor(min / step) * step, Math.ceil(max / step) * step];
+    if (reverse) d.reverse();
+    l = d.map(f);
+    return this;
+  };
+
+  /**
+   * Returns a view of this scale by the specified accessor function <tt>f</tt>.
+   * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
+   * <tt>function(d) y(d.foo)</tt>.
+   *
+   * <p>This method is provided for convenience, such that scales can be
+   * succinctly defined inline. For example, given an array of data elements
+   * that have a <tt>score</tt> attribute with the domain [0, 1], the height
+   * property could be specified as:
+   *
+   * <pre>    .height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
+   *
+   * This is equivalent to:
+   *
+   * <pre>    .height(function(d) d.score * 480)</pre>
+   *
+   * This method should be used judiciously; it is typically more clear to
+   * invoke the scale directly, passing in the value to be scaled.
+   *
+   * @function
+   * @name pv.Scale.quantitative.prototype.by
+   * @param {function} f an accessor function.
+   * @returns {pv.Scale.quantitative} a view of this scale by the specified
+   * accessor function.
+   */
+  scale.by = function(f) {
+    function by() { return scale(f.apply(this, arguments)); }
+    for (var method in scale) by[method] = scale[method];
+    return by;
+  };
+
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+/**
+ * Returns a linear scale for the specified domain. The arguments to this
+ * constructor are optional, and equivalent to calling {@link #domain}.
+ * The default domain and range are [0,1].
+ *
+ * @class Represents a linear scale; a function that performs a linear
+ * transformation. <style type="text/css">sub{line-height:0}</style> Most
+ * commonly, a linear scale represents a 1-dimensional linear transformation
+ * from a numeric domain of input data [<i>d<sub>0</sub></i>,
+ * <i>d<sub>1</sub></i>] to a numeric range of pixels [<i>r<sub>0</sub></i>,
+ * <i>r<sub>1</sub></i>]. The equation for such a scale is:
+ *
+ * <blockquote><i>f(x) = (x - d<sub>0</sub>) / (d<sub>1</sub> - d<sub>0</sub>) *
+ * (r<sub>1</sub> - r<sub>0</sub>) + r<sub>0</sub></i></blockquote>
+ *
+ * For example, a linear scale from the domain [0, 100] to range [0, 640]:
+ *
+ * <blockquote><i>f(x) = (x - 0) / (100 - 0) * (640 - 0) + 0</i><br>
+ * <i>f(x) = x / 100 * 640</i><br>
+ * <i>f(x) = x * 6.4</i><br>
+ * </blockquote>
+ *
+ * Thus, saying
+ *
+ * <pre>    .height(function(d) d * 6.4)</pre>
+ *
+ * is identical to
+ *
+ * <pre>    .height(pv.Scale.linear(0, 100).range(0, 640))</pre>
+ *
+ * Note that the scale is itself a function, and thus can be used as a property
+ * directly, assuming that the data associated with a mark is a number. While
+ * this is convenient for single-use scales, frequently it is desirable to
+ * define scales globally:
+ *
+ * <pre>var y = pv.Scale.linear(0, 100).range(0, 640);</pre>
+ *
+ * The <tt>y</tt> scale can now be equivalently referenced within a property:
+ *
+ * <pre>    .height(function(d) y(d))</pre>
+ *
+ * Alternatively, if the data are not simple numbers, the appropriate value can
+ * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
+ * method similarly allows the data to be mapped to a numeric value before
+ * performing the linear transformation.
+ *
+ * @param {number...} domain... optional domain values.
+ * @extends pv.Scale.quantitative
+ */
+pv.Scale.linear = function() {
+  var scale = pv.Scale.quantitative();
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+/**
+ * Returns a log scale for the specified domain. The arguments to this
+ * constructor are optional, and equivalent to calling {@link #domain}.
+ * The default domain is [1,10] and the default range is [0,1].
+ *
+ * @class Represents a log scale. <style
+ * type="text/css">sub{line-height:0}</style> Most commonly, a log scale
+ * represents a 1-dimensional log transformation from a numeric domain of input
+ * data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to a numeric range of
+ * pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>]. The equation for such a
+ * scale is:
+ *
+ * <blockquote><i>f(x) = (log(x) - log(d<sub>0</sub>)) / (log(d<sub>1</sub>) -
+ * log(d<sub>0</sub>)) * (r<sub>1</sub> - r<sub>0</sub>) +
+ * r<sub>0</sub></i></blockquote>
+ *
+ * where <i>log(x)</i> represents the zero-symmetric logarthim of <i>x</i> using
+ * the scale's associated base (default: 10, see {@link pv.logSymmetric}). For
+ * example, a log scale from the domain [1, 100] to range [0, 640]:
+ *
+ * <blockquote><i>f(x) = (log(x) - log(1)) / (log(100) - log(1)) * (640 - 0) + 0</i><br>
+ * <i>f(x) = log(x) / 2 * 640</i><br>
+ * <i>f(x) = log(x) * 320</i><br>
+ * </blockquote>
+ *
+ * Thus, saying
+ *
+ * <pre>    .height(function(d) Math.log(d) * 138.974)</pre>
+ *
+ * is equivalent to
+ *
+ * <pre>    .height(pv.Scale.log(1, 100).range(0, 640))</pre>
+ *
+ * Note that the scale is itself a function, and thus can be used as a property
+ * directly, assuming that the data associated with a mark is a number. While
+ * this is convenient for single-use scales, frequently it is desirable to
+ * define scales globally:
+ *
+ * <pre>var y = pv.Scale.log(1, 100).range(0, 640);</pre>
+ *
+ * The <tt>y</tt> scale can now be equivalently referenced within a property:
+ *
+ * <pre>    .height(function(d) y(d))</pre>
+ *
+ * Alternatively, if the data are not simple numbers, the appropriate value can
+ * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
+ * method similarly allows the data to be mapped to a numeric value before
+ * performing the log transformation.
+ *
+ * @param {number...} domain... optional domain values.
+ * @extends pv.Scale.quantitative
+ */
+pv.Scale.log = function() {
+  var scale = pv.Scale.quantitative(1, 10),
+      b, // logarithm base
+      p, // cached Math.log(b)
+      /** @ignore */ log = function(x) { return Math.log(x) / p; },
+      /** @ignore */ pow = function(y) { return Math.pow(b, y); };
+
+  /**
+   * Returns an array of evenly-spaced, suitably-rounded values in the input
+   * domain. These values are frequently used in conjunction with
+   * {@link pv.Rule} to display tick marks or grid lines.
+   *
+   * @function
+   * @name pv.Scale.log.prototype.ticks
+   * @returns {number[]} an array input domain values to use as ticks.
+   */
+  scale.ticks = function() {
+    // TODO support non-uniform domains
+    var d = scale.domain(),
+        n = d[0] < 0,
+        i = Math.floor(n ? -log(-d[0]) : log(d[0])),
+        j = Math.ceil(n ? -log(-d[1]) : log(d[1])),
+        ticks = [];
+    if (n) {
+      ticks.push(-pow(-i));
+      for (; i++ < j;) for (var k = b - 1; k > 0; k--) ticks.push(-pow(-i) * k);
+    } else {
+      for (; i < j; i++) for (var k = 1; k < b; k++) ticks.push(pow(i) * k);
+      ticks.push(pow(i));
+    }
+    for (i = 0; ticks[i] < d[0]; i++); // strip small values
+    for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values
+    return ticks.slice(i, j);
+  };
+
+  /**
+   * Formats the specified tick value using the appropriate precision, assuming
+   * base 10.
+   *
+   * @function
+   * @name pv.Scale.log.prototype.tickFormat
+   * @param {number} t a tick value.
+   * @returns {string} a formatted tick value.
+   */
+  scale.tickFormat = function(t) {
+    return t.toPrecision(1);
+  };
+
+  /**
+   * "Nices" this scale, extending the bounds of the input domain to
+   * evenly-rounded values. This method uses {@link pv.logFloor} and
+   * {@link pv.logCeil}. Nicing is useful if the domain is computed dynamically
+   * from data, and may be irregular. For example, given a domain of
+   * [0.20147987687960267, 0.996679553296417], a call to <tt>nice()</tt> might
+   * extend the domain to [0.1, 1].
+   *
+   * <p>This method must be invoked each time after setting the domain (and
+   * base).
+   *
+   * @function
+   * @name pv.Scale.log.prototype.nice
+   * @returns {pv.Scale.log} <tt>this</tt>.
+   */
+  scale.nice = function() {
+    // TODO support non-uniform domains
+    var d = scale.domain();
+    return scale.domain(pv.logFloor(d[0], b), pv.logCeil(d[1], b));
+  };
+
+  /**
+   * Sets or gets the logarithm base. Defaults to 10.
+   *
+   * @function
+   * @name pv.Scale.log.prototype.base
+   * @param {number} [v] the new base.
+   * @returns {pv.Scale.log} <tt>this</tt>, or the current base.
+   */
+  scale.base = function(v) {
+    if (arguments.length) {
+      b = Number(v);
+      p = Math.log(b);
+      scale.transform(log, pow); // update transformed domain
+      return this;
+    }
+    return b;
+  };
+
+  scale.domain.apply(scale, arguments);
+  return scale.base(10);
+};
+/**
+ * Returns a root scale for the specified domain. The arguments to this
+ * constructor are optional, and equivalent to calling {@link #domain}.
+ * The default domain and range are [0,1].
+ *
+ * @class Represents a root scale; a function that performs a power
+ * transformation. <style type="text/css">sub{line-height:0}</style> Most
+ * commonly, a root scale represents a 1-dimensional root transformation from a
+ * numeric domain of input data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to
+ * a numeric range of pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>].
+ *
+ * <p>Note that the scale is itself a function, and thus can be used as a
+ * property directly, assuming that the data associated with a mark is a
+ * number. While this is convenient for single-use scales, frequently it is
+ * desirable to define scales globally:
+ *
+ * <pre>var y = pv.Scale.root(0, 100).range(0, 640);</pre>
+ *
+ * The <tt>y</tt> scale can now be equivalently referenced within a property:
+ *
+ * <pre>    .height(function(d) y(d))</pre>
+ *
+ * Alternatively, if the data are not simple numbers, the appropriate value can
+ * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
+ * method similarly allows the data to be mapped to a numeric value before
+ * performing the root transformation.
+ *
+ * @param {number...} domain... optional domain values.
+ * @extends pv.Scale.quantitative
+ */
+pv.Scale.root = function() {
+  var scale = pv.Scale.quantitative();
+
+  /**
+   * Sets or gets the exponent; defaults to 2.
+   *
+   * @function
+   * @name pv.Scale.root.prototype.power
+   * @param {number} [v] the new exponent.
+   * @returns {pv.Scale.root} <tt>this</tt>, or the current base.
+   */
+  scale.power = function(v) {
+    if (arguments.length) {
+      var b = Number(v), p = 1 / b;
+      scale.transform(
+        function(x) { return Math.pow(x, p); },
+        function(y) { return Math.pow(y, b); });
+      return this;
+    }
+    return b;
+  };
+
+  scale.domain.apply(scale, arguments);
+  return scale.power(2);
+};
+/**
+ * Returns an ordinal scale for the specified domain. The arguments to this
+ * constructor are optional, and equivalent to calling {@link #domain}.
+ *
+ * @class Represents an ordinal scale. <style
+ * type="text/css">sub{line-height:0}</style> An ordinal scale represents a
+ * pairwise mapping from <i>n</i> discrete values in the input domain to
+ * <i>n</i> discrete values in the output range. For example, an ordinal scale
+ * might map a domain of species ["setosa", "versicolor", "virginica"] to colors
+ * ["red", "green", "blue"]. Thus, saying
+ *
+ * <pre>    .fillStyle(function(d) {
+ *         switch (d.species) {
+ *           case "setosa": return "red";
+ *           case "versicolor": return "green";
+ *           case "virginica": return "blue";
+ *         }
+ *       })</pre>
+ *
+ * is equivalent to
+ *
+ * <pre>    .fillStyle(pv.Scale.ordinal("setosa", "versicolor", "virginica")
+ *         .range("red", "green", "blue")
+ *         .by(function(d) d.species))</pre>
+ *
+ * If the mapping from species to color does not need to be specified
+ * explicitly, the domain can be omitted. In this case it will be inferred
+ * lazily from the data:
+ *
+ * <pre>    .fillStyle(pv.colors("red", "green", "blue")
+ *         .by(function(d) d.species))</pre>
+ *
+ * When the domain is inferred, the first time the scale is invoked, the first
+ * element from the range will be returned. Subsequent calls with unique values
+ * will return subsequent elements from the range. If the inferred domain grows
+ * larger than the range, range values will be reused. However, it is strongly
+ * recommended that the domain and the range contain the same number of
+ * elements.
+ *
+ * <p>A range can be discretized from a continuous interval (e.g., for pixel
+ * positioning) by using {@link #split}, {@link #splitFlush} or
+ * {@link #splitBanded} after the domain has been set. For example, if
+ * <tt>states</tt> is an array of the fifty U.S. state names, the state name can
+ * be encoded in the left position:
+ *
+ * <pre>    .left(pv.Scale.ordinal(states)
+ *         .split(0, 640)
+ *         .by(function(d) d.state))</pre>
+ *
+ * <p>N.B.: ordinal scales are not invertible (at least not yet), since the
+ * domain and range and discontinuous. A workaround is to use a linear scale.
+ *
+ * @param {...} domain... optional domain values.
+ * @extends pv.Scale
+ * @see pv.colors
+ */
+pv.Scale.ordinal = function() {
+  var d = [], i = {}, r = [], band = 0;
+
+  /** @private */
+  function scale(x) {
+    if (!(x in i)) i[x] = d.push(x) - 1;
+    return r[i[x] % r.length];
+  }
+
+  /**
+   * Sets or gets the input domain. This method can be invoked several ways:
+   *
+   * <p>1. <tt>domain(values...)</tt>
+   *
+   * <p>Specifying the domain as a series of values is the most explicit and
+   * recommended approach. However, if the domain values are derived from data,
+   * you may find the second method more appropriate.
+   *
+   * <p>2. <tt>domain(array, f)</tt>
+   *
+   * <p>Rather than enumerating the domain values as explicit arguments to this
+   * method, you can specify a single argument of an array. In addition, you can
+   * specify an optional accessor function to extract the domain values from the
+   * array.
+   *
+   * <p>3. <tt>domain()</tt>
+   *
+   * <p>Invoking the <tt>domain</tt> method with no arguments returns the
+   * current domain as an array.
+   *
+   * @function
+   * @name pv.Scale.ordinal.prototype.domain
+   * @param {...} domain... domain values.
+   * @returns {pv.Scale.ordinal} <tt>this</tt>, or the current domain.
+   */
+  scale.domain = function(array, f) {
+    if (arguments.length) {
+      array = (array instanceof Array)
+          ? ((arguments.length > 1) ? pv.map(array, f) : array)
+          : Array.prototype.slice.call(arguments);
+
+      /* Filter the specified ordinals to their unique values. */
+      d = [];
+      var seen = {};
+      for (var j = 0; j < array.length; j++) {
+        var o = array[j];
+        if (!(o in seen)) {
+          seen[o] = true;
+          d.push(o);
+        }
+      }
+
+      i = pv.numerate(d);
+      return this;
+    }
+    return d;
+  };
+
+  /**
+   * Sets or gets the output range. This method can be invoked several ways:
+   *
+   * <p>1. <tt>range(values...)</tt>
+   *
+   * <p>Specifying the range as a series of values is the most explicit and
+   * recommended approach. However, if the range values are derived from data,
+   * you may find the second method more appropriate.
+   *
+   * <p>2. <tt>range(array, f)</tt>
+   *
+   * <p>Rather than enumerating the range values as explicit arguments to this
+   * method, you can specify a single argument of an array. In addition, you can
+   * specify an optional accessor function to extract the range values from the
+   * array.
+   *
+   * <p>3. <tt>range()</tt>
+   *
+   * <p>Invoking the <tt>range</tt> method with no arguments returns the
+   * current range as an array.
+   *
+   * @function
+   * @name pv.Scale.ordinal.prototype.range
+   * @param {...} range... range values.
+   * @returns {pv.Scale.ordinal} <tt>this</tt>, or the current range.
+   */
+  scale.range = function(array, f) {
+    if (arguments.length) {
+      r = (array instanceof Array)
+          ? ((arguments.length > 1) ? pv.map(array, f) : array)
+          : Array.prototype.slice.call(arguments);
+      if (typeof r[0] == "string") r = r.map(pv.color);
+      return this;
+    }
+    return r;
+  };
+
+  /**
+   * Sets the range from the given continuous interval. The interval
+   * [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced points,
+   * where <i>n</i> is the number of (unique) values in the domain. The first
+   * and last point are offset from the edge of the range by half the distance
+   * between points.
+   *
+   * <p>This method must be called <i>after</i> the domain is set.
+   *
+   * @function
+   * @name pv.Scale.ordinal.prototype.split
+   * @param {number} min minimum value of the output range.
+   * @param {number} max maximum value of the output range.
+   * @returns {pv.Scale.ordinal} <tt>this</tt>.
+   * @see #splitFlush
+   * @see #splitBanded
+   */
+  scale.split = function(min, max) {
+    var step = (max - min) / this.domain().length;
+    r = pv.range(min + step / 2, max, step);
+    return this;
+  };
+
+  /**
+   * Sets the range from the given continuous interval. The interval
+   * [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced points,
+   * where <i>n</i> is the number of (unique) values in the domain. The first
+   * and last point are exactly on the edge of the range.
+   *
+   * <p>This method must be called <i>after</i> the domain is set.
+   *
+   * @function
+   * @name pv.Scale.ordinal.prototype.splitFlush
+   * @param {number} min minimum value of the output range.
+   * @param {number} max maximum value of the output range.
+   * @returns {pv.Scale.ordinal} <tt>this</tt>.
+   * @see #split
+   */
+  scale.splitFlush = function(min, max) {
+    var n = this.domain().length, step = (max - min) / (n - 1);
+    r = (n == 1) ? [(min + max) / 2]
+        : pv.range(min, max + step / 2, step);
+    return this;
+  };
+
+  /**
+   * Sets the range from the given continuous interval. The interval
+   * [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced bands,
+   * where <i>n</i> is the number of (unique) values in the domain. The first
+   * and last band are offset from the edge of the range by the distance between
+   * bands.
+   *
+   * <p>The band width argument, <tt>band</tt>, is typically in the range [0, 1]
+   * and defaults to 1. This fraction corresponds to the amount of space in the
+   * range to allocate to the bands, as opposed to padding. A value of 0.5 means
+   * that the band width will be equal to the padding width. The computed
+   * absolute band width can be retrieved from the range as
+   * <tt>scale.range().band</tt>.
+   *
+   * <p>If the band width argument is negative, this method will allocate bands
+   * of a <i>fixed</i> width <tt>-band</tt>, rather than a relative fraction of
+   * the available space.
+   *
+   * <p>Tip: to inset the bands by a fixed amount <tt>p</tt>, specify a minimum
+   * value of <tt>min + p</tt> (or simply <tt>p</tt>, if <tt>min</tt> is
+   * 0). Then set the mark width to <tt>scale.range().band - p</tt>.
+   *
+   * <p>This method must be called <i>after</i> the domain is set.
+   *
+   * @function
+   * @name pv.Scale.ordinal.prototype.splitBanded
+   * @param {number} min minimum value of the output range.
+   * @param {number} max maximum value of the output range.
+   * @param {number} [band] the fractional band width in [0, 1]; defaults to 1.
+   * @returns {pv.Scale.ordinal} <tt>this</tt>.
+   * @see #split
+   */
+  scale.splitBanded = function(min, max, band) {
+    if (arguments.length < 3) band = 1;
+    if (band < 0) {
+      var n = this.domain().length,
+          total = -band * n,
+          remaining = max - min - total,
+          padding = remaining / (n + 1);
+      r = pv.range(min + padding, max, padding - band);
+      r.band = -band;
+    } else {
+      var step = (max - min) / (this.domain().length + (1 - band));
+      r = pv.range(min + step * (1 - band), max, step);
+      r.band = step * band;
+    }
+    return this;
+  };
+
+  /**
+   * Returns a view of this scale by the specified accessor function <tt>f</tt>.
+   * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
+   * <tt>function(d) y(d.foo)</tt>. This method should be used judiciously; it
+   * is typically more clear to invoke the scale directly, passing in the value
+   * to be scaled.
+   *
+   * @function
+   * @name pv.Scale.ordinal.prototype.by
+   * @param {function} f an accessor function.
+   * @returns {pv.Scale.ordinal} a view of this scale by the specified accessor
+   * function.
+   */
+  scale.by = function(f) {
+    function by() { return scale(f.apply(this, arguments)); }
+    for (var method in scale) by[method] = scale[method];
+    return by;
+  };
+
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+/**
+ * Constructs a default quantile scale. The arguments to this constructor are
+ * optional, and equivalent to calling {@link #domain}. The default domain is
+ * the empty set, and the default range is [0,1].
+ *
+ * @class Represents a quantile scale; a function that maps from a value within
+ * a sortable domain to a quantized numeric range. Typically, the domain is a
+ * set of numbers, but any sortable value (such as strings) can be used as the
+ * domain of a quantile scale. The range defaults to [0,1], with 0 corresponding
+ * to the smallest value in the domain, 1 the largest, .5 the median, etc.
+ *
+ * <p>By default, the number of quantiles in the range corresponds to the number
+ * of values in the domain. The {@link #quantiles} method can be used to specify
+ * an explicit number of quantiles; for example, <tt>quantiles(4)</tt> produces
+ * a standard quartile scale. A quartile scale's range is a set of four discrete
+ * values, such as [0, 1/3, 2/3, 1]. Calling the {@link #range} method will
+ * scale these discrete values accordingly, similar to {@link
+ * pv.Scale.ordinal#splitFlush}.
+ *
+ * <p>For example, given the strings ["c", "a", "b"], a default quantile scale:
+ *
+ * <pre>pv.Scale.quantile("c", "a", "b")</pre>
+ *
+ * will return 0 for "a", .5 for "b", and 1 for "c".
+ *
+ * @extends pv.Scale
+ */
+pv.Scale.quantile = function() {
+  var n = -1, // number of quantiles
+      j = -1, // max quantile index
+      q = [], // quantile boundaries
+      d = [], // domain
+      y = pv.Scale.linear(); // range
+
+  /** @private */
+  function scale(x) {
+    return y(Math.max(0, Math.min(j, pv.search.index(q, x) - 1)) / j);
+  }
+
+  /**
+   * Sets or gets the quantile boundaries. By default, each element in the
+   * domain is in its own quantile. If the argument to this method is a number,
+   * it specifies the number of equal-sized quantiles by which to divide the
+   * domain.
+   *
+   * <p>If no arguments are specified, this method returns the quantile
+   * boundaries; the first element is always the minimum value of the domain,
+   * and the last element is the maximum value of the domain. Thus, the length
+   * of the returned array is always one greater than the number of quantiles.
+   *
+   * @function
+   * @name pv.Scale.quantile.prototype.quantiles
+   * @param {number} x the number of quantiles.
+   */
+  scale.quantiles = function(x) {
+    if (arguments.length) {
+      n = Number(x);
+      if (n < 0) {
+        q = [d[0]].concat(d);
+        j = d.length - 1;
+      } else {
+        q = [];
+        q[0] = d[0];
+        for (var i = 1; i <= n; i++) {
+          q[i] = d[~~(i * (d.length - 1) / n)];
+        }
+        j = n - 1;
+      }
+      return this;
+    }
+    return q;
+  };
+
+  /**
+   * Sets or gets the input domain. This method can be invoked several ways:
+   *
+   * <p>1. <tt>domain(values...)</tt>
+   *
+   * <p>Specifying the domain as a series of values is the most explicit and
+   * recommended approach. However, if the domain values are derived from data,
+   * you may find the second method more appropriate.
+   *
+   * <p>2. <tt>domain(array, f)</tt>
+   *
+   * <p>Rather than enumerating the domain values as explicit arguments to this
+   * method, you can specify a single argument of an array. In addition, you can
+   * specify an optional accessor function to extract the domain values from the
+   * array.
+   *
+   * <p>3. <tt>domain()</tt>
+   *
+   * <p>Invoking the <tt>domain</tt> method with no arguments returns the
+   * current domain as an array.
+   *
+   * @function
+   * @name pv.Scale.quantile.prototype.domain
+   * @param {...} domain... domain values.
+   * @returns {pv.Scale.quantile} <tt>this</tt>, or the current domain.
+   */
+  scale.domain = function(array, f) {
+    if (arguments.length) {
+      d = (array instanceof Array)
+          ? pv.map(array, f)
+          : Array.prototype.slice.call(arguments);
+      d.sort(pv.naturalOrder);
+      scale.quantiles(n); // recompute quantiles
+      return this;
+    }
+    return d;
+  };
+
+  /**
+   * Sets or gets the output range. This method can be invoked several ways:
+   *
+   * <p>1. <tt>range(min, ..., max)</tt>
+   *
+   * <p>The range may be specified as a series of numbers or colors. Most
+   * commonly, two numbers are specified: the minimum and maximum pixel values.
+   * For a color scale, values may be specified as {@link pv.Color}s or
+   * equivalent strings. For a diverging scale, or other subdivided non-uniform
+   * scales, multiple values can be specified. For example:
+   *
+   * <pre>    .range("red", "white", "green")</pre>
+   *
+   * <p>Currently, only numbers and colors are supported as range values. The
+   * number of range values must exactly match the number of domain values, or
+   * the behavior of the scale is undefined.
+   *
+   * <p>2. <tt>range()</tt>
+   *
+   * <p>Invoking the <tt>range</tt> method with no arguments returns the current
+   * range as an array of numbers or colors.
+   *
+   * @function
+   * @name pv.Scale.quantile.prototype.range
+   * @param {...} range... range values.
+   * @returns {pv.Scale.quantile} <tt>this</tt>, or the current range.
+   */
+  scale.range = function() {
+    if (arguments.length) {
+      y.range.apply(y, arguments);
+      return this;
+    }
+    return y.range();
+  };
+
+  /**
+   * Returns a view of this scale by the specified accessor function <tt>f</tt>.
+   * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
+   * <tt>function(d) y(d.foo)</tt>.
+   *
+   * <p>This method is provided for convenience, such that scales can be
+   * succinctly defined inline. For example, given an array of data elements
+   * that have a <tt>score</tt> attribute with the domain [0, 1], the height
+   * property could be specified as:
+   *
+   * <pre>.height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
+   *
+   * This is equivalent to:
+   *
+   * <pre>.height(function(d) d.score * 480)</pre>
+   *
+   * This method should be used judiciously; it is typically more clear to
+   * invoke the scale directly, passing in the value to be scaled.
+   *
+   * @function
+   * @name pv.Scale.quantile.prototype.by
+   * @param {function} f an accessor function.
+   * @returns {pv.Scale.quantile} a view of this scale by the specified
+   * accessor function.
+   */
+  scale.by = function(f) {
+    function by() { return scale(f.apply(this, arguments)); }
+    for (var method in scale) by[method] = scale[method];
+    return by;
+  };
+
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+/**
+ * Returns a histogram operator for the specified data, with an optional
+ * accessor function. If the data specified is not an array of numbers, an
+ * accessor function must be specified to map the data to numeric values.
+ *
+ * @class Represents a histogram operator.
+ *
+ * @param {array} data an array of numbers or objects.
+ * @param {function} [f] an optional accessor function.
+ */
+pv.histogram = function(data, f) {
+  var frequency = true;
+  return {
+
+    /**
+     * Returns the computed histogram bins. An optional array of numbers,
+     * <tt>ticks</tt>, may be specified as the break points. If the ticks are
+     * not specified, default ticks will be computed using a linear scale on the
+     * data domain.
+     *
+     * <p>The returned array contains {@link pv.histogram.Bin}s. The <tt>x</tt>
+     * attribute corresponds to the bin's start value (inclusive), while the
+     * <tt>dx</tt> attribute stores the bin size (end - start). The <tt>y</tt>
+     * attribute stores either the frequency count or probability, depending on
+     * how the histogram operator has been configured.
+     *
+     * <p>The {@link pv.histogram.Bin} objects are themselves arrays, containing
+     * the data elements present in each bin, i.e., the elements in the
+     * <tt>data</tt> array (prior to invoking the accessor function, if any).
+     * For example, if the data represented countries, and the accessor function
+     * returned the GDP of each country, the returned bins would be arrays of
+     * countries (not GDPs).
+     *
+     * @function
+     * @name pv.histogram.prototype.bins
+     * @param {array} [ticks]
+     * @returns {array}
+     */ /** @private */
+    bins: function(ticks) {
+      var x = pv.map(data, f), bins = [];
+
+      /* Initialize default ticks. */
+      if (!arguments.length) ticks = pv.Scale.linear(x).ticks();
+
+      /* Initialize the bins. */
+      for (var i = 0; i < ticks.length - 1; i++) {
+        var bin = bins[i] = [];
+        bin.x = ticks[i];
+        bin.dx = ticks[i + 1] - ticks[i];
+        bin.y = 0;
+      }
+
+      /* Count the number of samples per bin. */
+      for (var i = 0; i < x.length; i++) {
+        var j = pv.search.index(ticks, x[i]) - 1,
+            bin = bins[Math.max(0, Math.min(bins.length - 1, j))];
+        bin.y++;
+        bin.push(data[i]);
+      }
+
+      /* Convert frequencies to probabilities. */
+      if (!frequency) for (var i = 0; i < bins.length; i++) {
+        bins[i].y /= x.length;
+      }
+
+      return bins;
+    },
+
+    /**
+     * Sets or gets whether this histogram operator returns frequencies or
+     * probabilities.
+     *
+     * @function
+     * @name pv.histogram.prototype.frequency
+     * @param {boolean} [x]
+     * @returns {pv.histogram} this.
+     */ /** @private */
+    frequency: function(x) {
+      if (arguments.length) {
+        frequency = Boolean(x);
+        return this;
+      }
+      return frequency;
+    }
+  };
+};
+
+/**
+ * @class Represents a bin returned by the {@link pv.histogram} operator. Bins
+ * are themselves arrays containing the data elements present in the given bin
+ * (prior to the accessor function being invoked to convert the data object to a
+ * numeric value). These bin arrays have additional attributes with meta
+ * information about the bin.
+ *
+ * @name pv.histogram.Bin
+ * @extends array
+ * @see pv.histogram
+ */
+
+/**
+ * The start value of the bin's range.
+ *
+ * @type number
+ * @name pv.histogram.Bin.prototype.x
+ */
+
+/**
+ * The magnitude value of the bin's range; end - start.
+ *
+ * @type number
+ * @name pv.histogram.Bin.prototype.dx
+ */
+
+/**
+ * The frequency or probability of the bin, depending on how the histogram
+ * operator was configured.
+ *
+ * @type number
+ * @name pv.histogram.Bin.prototype.y
+ */
+/**
+ * Returns the {@link pv.Color} for the specified color format string. Colors
+ * may have an associated opacity, or alpha channel. Color formats are specified
+ * by CSS Color Modular Level 3, using either in RGB or HSL color space. For
+ * example:<ul>
+ *
+ * <li>#f00 // #rgb
+ * <li>#ff0000 // #rrggbb
+ * <li>rgb(255, 0, 0)
+ * <li>rgb(100%, 0%, 0%)
+ * <li>hsl(0, 100%, 50%)
+ * <li>rgba(0, 0, 255, 0.5)
+ * <li>hsla(120, 100%, 50%, 1)
+ *
+ * </ul>The SVG 1.0 color keywords names are also supported, such as "aliceblue"
+ * and "yellowgreen". The "transparent" keyword is supported for fully-
+ * transparent black.
+ *
+ * <p>If the <tt>format</tt> argument is already an instance of <tt>Color</tt>,
+ * the argument is returned with no further processing.
+ *
+ * @param {string} format the color specification string, such as "#f00".
+ * @returns {pv.Color} the corresponding <tt>Color</tt>.
+ * @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
+ * keywords</a>
+ * @see <a href="http://www.w3.org/TR/css3-color/">CSS3 color module</a>
+ */
+pv.color = function(format) {
+  if (format.rgb) return format.rgb();
+
+  /* Handle hsl, rgb. */
+  var m1 = /([a-z]+)\((.*)\)/i.exec(format);
+  if (m1) {
+    var m2 = m1[2].split(","), a = 1;
+    switch (m1[1]) {
+      case "hsla":
+      case "rgba": {
+        a = parseFloat(m2[3]);
+        if (!a) return pv.Color.transparent;
+        break;
+      }
+    }
+    switch (m1[1]) {
+      case "hsla":
+      case "hsl": {
+        var h = parseFloat(m2[0]), // degrees
+            s = parseFloat(m2[1]) / 100, // percentage
+            l = parseFloat(m2[2]) / 100; // percentage
+        return (new pv.Color.Hsl(h, s, l, a)).rgb();
+      }
+      case "rgba":
+      case "rgb": {
+        function parse(c) { // either integer or percentage
+          var f = parseFloat(c);
+          return (c[c.length - 1] == '%') ? Math.round(f * 2.55) : f;
+        }
+        var r = parse(m2[0]), g = parse(m2[1]), b = parse(m2[2]);
+        return pv.rgb(r, g, b, a);
+      }
+    }
+  }
+
+  /* Named colors. */
+  var named = pv.Color.names[format];
+  if (named) return named;
+
+  /* Hexadecimal colors: #rgb and #rrggbb. */
+  if (format.charAt(0) == "#") {
+    var r, g, b;
+    if (format.length == 4) {
+      r = format.charAt(1); r += r;
+      g = format.charAt(2); g += g;
+      b = format.charAt(3); b += b;
+    } else if (format.length == 7) {
+      r = format.substring(1, 3);
+      g = format.substring(3, 5);
+      b = format.substring(5, 7);
+    }
+    return pv.rgb(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
+  }
+
+  /* Otherwise, pass-through unsupported colors. */
+  return new pv.Color(format, 1);
+};
+
+/**
+ * Constructs a color with the specified color format string and opacity. This
+ * constructor should not be invoked directly; use {@link pv.color} instead.
+ *
+ * @class Represents an abstract (possibly translucent) color. The color is
+ * divided into two parts: the <tt>color</tt> attribute, an opaque color format
+ * string, and the <tt>opacity</tt> attribute, a float in [0, 1]. The color
+ * space is dependent on the implementing class; all colors support the
+ * {@link #rgb} method to convert to RGB color space for interpolation.
+ *
+ * <p>See also the <a href="../../api/Color.html">Color guide</a>.
+ *
+ * @param {string} color an opaque color format string, such as "#f00".
+ * @param {number} opacity the opacity, in [0,1].
+ * @see pv.color
+ */
+pv.Color = function(color, opacity) {
+  /**
+   * An opaque color format string, such as "#f00".
+   *
+   * @type string
+   * @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
+   * keywords</a>
+   * @see <a href="http://www.w3.org/TR/css3-color/">CSS3 color module</a>
+   */
+  this.color = color;
+
+  /**
+   * The opacity, a float in [0, 1].
+   *
+   * @type number
+   */
+  this.opacity = opacity;
+};
+
+/**
+ * Returns a new color that is a brighter version of this color. The behavior of
+ * this method may vary slightly depending on the underlying color space.
+ * Although brighter and darker are inverse operations, the results of a series
+ * of invocations of these two methods might be inconsistent because of rounding
+ * errors.
+ *
+ * @param [k] {number} an optional scale factor; defaults to 1.
+ * @see #darker
+ * @returns {pv.Color} a brighter color.
+ */
+pv.Color.prototype.brighter = function(k) {
+  return this.rgb().brighter(k);
+};
+
+/**
+ * Returns a new color that is a brighter version of this color. The behavior of
+ * this method may vary slightly depending on the underlying color space.
+ * Although brighter and darker are inverse operations, the results of a series
+ * of invocations of these two methods might be inconsistent because of rounding
+ * errors.
+ *
+ * @param [k] {number} an optional scale factor; defaults to 1.
+ * @see #brighter
+ * @returns {pv.Color} a darker color.
+ */
+pv.Color.prototype.darker = function(k) {
+  return this.rgb().darker(k);
+};
+
+/**
+ * Constructs a new RGB color with the specified channel values.
+ *
+ * @param {number} r the red channel, an integer in [0,255].
+ * @param {number} g the green channel, an integer in [0,255].
+ * @param {number} b the blue channel, an integer in [0,255].
+ * @param {number} [a] the alpha channel, a float in [0,1].
+ * @returns pv.Color.Rgb
+ */
+pv.rgb = function(r, g, b, a) {
+  return new pv.Color.Rgb(r, g, b, (arguments.length == 4) ? a : 1);
+};
+
+/**
+ * Constructs a new RGB color with the specified channel values.
+ *
+ * @class Represents a color in RGB space.
+ *
+ * @param {number} r the red channel, an integer in [0,255].
+ * @param {number} g the green channel, an integer in [0,255].
+ * @param {number} b the blue channel, an integer in [0,255].
+ * @param {number} a the alpha channel, a float in [0,1].
+ * @extends pv.Color
+ */
+pv.Color.Rgb = function(r, g, b, a) {
+  pv.Color.call(this, a ? ("rgb(" + r + "," + g + "," + b + ")") : "none", a);
+
+  /**
+   * The red channel, an integer in [0, 255].
+   *
+   * @type number
+   */
+  this.r = r;
+
+  /**
+   * The green channel, an integer in [0, 255].
+   *
+   * @type number
+   */
+  this.g = g;
+
+  /**
+   * The blue channel, an integer in [0, 255].
+   *
+   * @type number
+   */
+  this.b = b;
+
+  /**
+   * The alpha channel, a float in [0, 1].
+   *
+   * @type number
+   */
+  this.a = a;
+};
+pv.Color.Rgb.prototype = pv.extend(pv.Color);
+
+/**
+ * Constructs a new RGB color with the same green, blue and alpha channels as
+ * this color, with the specified red channel.
+ *
+ * @param {number} r the red channel, an integer in [0,255].
+ */
+pv.Color.Rgb.prototype.red = function(r) {
+  return pv.rgb(r, this.g, this.b, this.a);
+};
+
+/**
+ * Constructs a new RGB color with the same red, blue and alpha channels as this
+ * color, with the specified green channel.
+ *
+ * @param {number} g the green channel, an integer in [0,255].
+ */
+pv.Color.Rgb.prototype.green = function(g) {
+  return pv.rgb(this.r, g, this.b, this.a);
+};
+
+/**
+ * Constructs a new RGB color with the same red, green and alpha channels as
+ * this color, with the specified blue channel.
+ *
+ * @param {number} b the blue channel, an integer in [0,255].
+ */
+pv.Color.Rgb.prototype.blue = function(b) {
+  return pv.rgb(this.r, this.g, b, this.a);
+};
+
+/**
+ * Constructs a new RGB color with the same red, green and blue channels as this
+ * color, with the specified alpha channel.
+ *
+ * @param {number} a the alpha channel, a float in [0,1].
+ */
+pv.Color.Rgb.prototype.alpha = function(a) {
+  return pv.rgb(this.r, this.g, this.b, a);
+};
+
+/**
+ * Returns the RGB color equivalent to this color. This method is abstract and
+ * must be implemented by subclasses.
+ *
+ * @returns {pv.Color.Rgb} an RGB color.
+ * @function
+ * @name pv.Color.prototype.rgb
+ */
+
+/**
+ * Returns this.
+ *
+ * @returns {pv.Color.Rgb} this.
+ */
+pv.Color.Rgb.prototype.rgb = function() { return this; };
+
+/**
+ * Returns a new color that is a brighter version of this color. This method
+ * applies an arbitrary scale factor to each of the three RGB components of this
+ * color to create a brighter version of this color. Although brighter and
+ * darker are inverse operations, the results of a series of invocations of
+ * these two methods might be inconsistent because of rounding errors.
+ *
+ * @param [k] {number} an optional scale factor; defaults to 1.
+ * @see #darker
+ * @returns {pv.Color.Rgb} a brighter color.
+ */
+pv.Color.Rgb.prototype.brighter = function(k) {
+  k = Math.pow(0.7, arguments.length ? k : 1);
+  var r = this.r, g = this.g, b = this.b, i = 30;
+  if (!r && !g && !b) return pv.rgb(i, i, i, this.a);
+  if (r && (r < i)) r = i;
+  if (g && (g < i)) g = i;
+  if (b && (b < i)) b = i;
+  return pv.rgb(
+      Math.min(255, Math.floor(r / k)),
+      Math.min(255, Math.floor(g / k)),
+      Math.min(255, Math.floor(b / k)),
+      this.a);
+};
+
+/**
+ * Returns a new color that is a darker version of this color. This method
+ * applies an arbitrary scale factor to each of the three RGB components of this
+ * color to create a darker version of this color. Although brighter and darker
+ * are inverse operations, the results of a series of invocations of these two
+ * methods might be inconsistent because of rounding errors.
+ *
+ * @param [k] {number} an optional scale factor; defaults to 1.
+ * @see #brighter
+ * @returns {pv.Color.Rgb} a darker color.
+ */
+pv.Color.Rgb.prototype.darker = function(k) {
+  k = Math.pow(0.7, arguments.length ? k : 1);
+  return pv.rgb(
+      Math.max(0, Math.floor(k * this.r)),
+      Math.max(0, Math.floor(k * this.g)),
+      Math.max(0, Math.floor(k * this.b)),
+      this.a);
+};
+
+/**
+ * Constructs a new HSL color with the specified values.
+ *
+ * @param {number} h the hue, an integer in [0, 360].
+ * @param {number} s the saturation, a float in [0, 1].
+ * @param {number} l the lightness, a float in [0, 1].
+ * @param {number} [a] the opacity, a float in [0, 1].
+ * @returns pv.Color.Hsl
+ */
+pv.hsl = function(h, s, l, a) {
+  return new pv.Color.Hsl(h, s, l,  (arguments.length == 4) ? a : 1);
+};
+
+/**
+ * Constructs a new HSL color with the specified values.
+ *
+ * @class Represents a color in HSL space.
+ *
+ * @param {number} h the hue, an integer in [0, 360].
+ * @param {number} s the saturation, a float in [0, 1].
+ * @param {number} l the lightness, a float in [0, 1].
+ * @param {number} a the opacity, a float in [0, 1].
+ * @extends pv.Color
+ */
+pv.Color.Hsl = function(h, s, l, a) {
+  pv.Color.call(this, "hsl(" + h + "," + (s * 100) + "%," + (l * 100) + "%)", a);
+
+  /**
+   * The hue, an integer in [0, 360].
+   *
+   * @type number
+   */
+  this.h = h;
+
+  /**
+   * The saturation, a float in [0, 1].
+   *
+   * @type number
+   */
+  this.s = s;
+
+  /**
+   * The lightness, a float in [0, 1].
+   *
+   * @type number
+   */
+  this.l = l;
+
+  /**
+   * The opacity, a float in [0, 1].
+   *
+   * @type number
+   */
+  this.a = a;
+};
+pv.Color.Hsl.prototype = pv.extend(pv.Color);
+
+/**
+ * Constructs a new HSL color with the same saturation, lightness and alpha as
+ * this color, and the specified hue.
+ *
+ * @param {number} h the hue, an integer in [0, 360].
+ */
+pv.Color.Hsl.prototype.hue = function(h) {
+  return pv.hsl(h, this.s, this.l, this.a);
+};
+
+/**
+ * Constructs a new HSL color with the same hue, lightness and alpha as this
+ * color, and the specified saturation.
+ *
+ * @param {number} s the saturation, a float in [0, 1].
+ */
+pv.Color.Hsl.prototype.saturation = function(s) {
+  return pv.hsl(this.h, s, this.l, this.a);
+};
+
+/**
+ * Constructs a new HSL color with the same hue, saturation and alpha as this
+ * color, and the specified lightness.
+ *
+ * @param {number} l the lightness, a float in [0, 1].
+ */
+pv.Color.Hsl.prototype.lightness = function(l) {
+  return pv.hsl(this.h, this.s, l, this.a);
+};
+
+/**
+ * Constructs a new HSL color with the same hue, saturation and lightness as
+ * this color, and the specified alpha.
+ *
+ * @param {number} a the opacity, a float in [0, 1].
+ */
+pv.Color.Hsl.prototype.alpha = function(a) {
+  return pv.hsl(this.h, this.s, this.l, a);
+};
+
+/**
+ * Returns the RGB color equivalent to this HSL color.
+ *
+ * @returns {pv.Color.Rgb} an RGB color.
+ */
+pv.Color.Hsl.prototype.rgb = function() {
+  var h = this.h, s = this.s, l = this.l;
+
+  /* Some simple corrections for h, s and l. */
+  h = h % 360; if (h < 0) h += 360;
+  s = Math.max(0, Math.min(s, 1));
+  l = Math.max(0, Math.min(l, 1));
+
+  /* From FvD 13.37, CSS Color Module Level 3 */
+  var m2 = (l <= .5) ? (l * (1 + s)) : (l + s - l * s);
+  var m1 = 2 * l - m2;
+  function v(h) {
+    if (h > 360) h -= 360;
+    else if (h < 0) h += 360;
+    if (h < 60) return m1 + (m2 - m1) * h / 60;
+    if (h < 180) return m2;
+    if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
+    return m1;
+  }
+  function vv(h) {
+    return Math.round(v(h) * 255);
+  }
+
+  return pv.rgb(vv(h + 120), vv(h), vv(h - 120), this.a);
+};
+
+/**
+ * @private SVG color keywords, per CSS Color Module Level 3.
+ *
+ * @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
+ * keywords</a>
+ */
+pv.Color.names = {
+  aliceblue: "#f0f8ff",
+  antiquewhite: "#faebd7",
+  aqua: "#00ffff",
+  aquamarine: "#7fffd4",
+  azure: "#f0ffff",
+  beige: "#f5f5dc",
+  bisque: "#ffe4c4",
+  black: "#000000",
+  blanchedalmond: "#ffebcd",
+  blue: "#0000ff",
+  blueviolet: "#8a2be2",
+  brown: "#a52a2a",
+  burlywood: "#deb887",
+  cadetblue: "#5f9ea0",
+  chartreuse: "#7fff00",
+  chocolate: "#d2691e",
+  coral: "#ff7f50",
+  cornflowerblue: "#6495ed",
+  cornsilk: "#fff8dc",
+  crimson: "#dc143c",
+  cyan: "#00ffff",
+  darkblue: "#00008b",
+  darkcyan: "#008b8b",
+  darkgoldenrod: "#b8860b",
+  darkgray: "#a9a9a9",
+  darkgreen: "#006400",
+  darkgrey: "#a9a9a9",
+  darkkhaki: "#bdb76b",
+  darkmagenta: "#8b008b",
+  darkolivegreen: "#556b2f",
+  darkorange: "#ff8c00",
+  darkorchid: "#9932cc",
+  darkred: "#8b0000",
+  darksalmon: "#e9967a",
+  darkseagreen: "#8fbc8f",
+  darkslateblue: "#483d8b",
+  darkslategray: "#2f4f4f",
+  darkslategrey: "#2f4f4f",
+  darkturquoise: "#00ced1",
+  darkviolet: "#9400d3",
+  deeppink: "#ff1493",
+  deepskyblue: "#00bfff",
+  dimgray: "#696969",
+  dimgrey: "#696969",
+  dodgerblue: "#1e90ff",
+  firebrick: "#b22222",
+  floralwhite: "#fffaf0",
+  forestgreen: "#228b22",
+  fuchsia: "#ff00ff",
+  gainsboro: "#dcdcdc",
+  ghostwhite: "#f8f8ff",
+  gold: "#ffd700",
+  goldenrod: "#daa520",
+  gray: "#808080",
+  green: "#008000",
+  greenyellow: "#adff2f",
+  grey: "#808080",
+  honeydew: "#f0fff0",
+  hotpink: "#ff69b4",
+  indianred: "#cd5c5c",
+  indigo: "#4b0082",
+  ivory: "#fffff0",
+  khaki: "#f0e68c",
+  lavender: "#e6e6fa",
+  lavenderblush: "#fff0f5",
+  lawngreen: "#7cfc00",
+  lemonchiffon: "#fffacd",
+  lightblue: "#add8e6",
+  lightcoral: "#f08080",
+  lightcyan: "#e0ffff",
+  lightgoldenrodyellow: "#fafad2",
+  lightgray: "#d3d3d3",
+  lightgreen: "#90ee90",
+  lightgrey: "#d3d3d3",
+  lightpink: "#ffb6c1",
+  lightsalmon: "#ffa07a",
+  lightseagreen: "#20b2aa",
+  lightskyblue: "#87cefa",
+  lightslategray: "#778899",
+  lightslategrey: "#778899",
+  lightsteelblue: "#b0c4de",
+  lightyellow: "#ffffe0",
+  lime: "#00ff00",
+  limegreen: "#32cd32",
+  linen: "#faf0e6",
+  magenta: "#ff00ff",
+  maroon: "#800000",
+  mediumaquamarine: "#66cdaa",
+  mediumblue: "#0000cd",
+  mediumorchid: "#ba55d3",
+  mediumpurple: "#9370db",
+  mediumseagreen: "#3cb371",
+  mediumslateblue: "#7b68ee",
+  mediumspringgreen: "#00fa9a",
+  mediumturquoise: "#48d1cc",
+  mediumvioletred: "#c71585",
+  midnightblue: "#191970",
+  mintcream: "#f5fffa",
+  mistyrose: "#ffe4e1",
+  moccasin: "#ffe4b5",
+  navajowhite: "#ffdead",
+  navy: "#000080",
+  oldlace: "#fdf5e6",
+  olive: "#808000",
+  olivedrab: "#6b8e23",
+  orange: "#ffa500",
+  orangered: "#ff4500",
+  orchid: "#da70d6",
+  palegoldenrod: "#eee8aa",
+  palegreen: "#98fb98",
+  paleturquoise: "#afeeee",
+  palevioletred: "#db7093",
+  papayawhip: "#ffefd5",
+  peachpuff: "#ffdab9",
+  peru: "#cd853f",
+  pink: "#ffc0cb",
+  plum: "#dda0dd",
+  powderblue: "#b0e0e6",
+  purple: "#800080",
+  red: "#ff0000",
+  rosybrown: "#bc8f8f",
+  royalblue: "#4169e1",
+  saddlebrown: "#8b4513",
+  salmon: "#fa8072",
+  sandybrown: "#f4a460",
+  seagreen: "#2e8b57",
+  seashell: "#fff5ee",
+  sienna: "#a0522d",
+  silver: "#c0c0c0",
+  skyblue: "#87ceeb",
+  slateblue: "#6a5acd",
+  slategray: "#708090",
+  slategrey: "#708090",
+  snow: "#fffafa",
+  springgreen: "#00ff7f",
+  steelblue: "#4682b4",
+  tan: "#d2b48c",
+  teal: "#008080",
+  thistle: "#d8bfd8",
+  tomato: "#ff6347",
+  turquoise: "#40e0d0",
+  violet: "#ee82ee",
+  wheat: "#f5deb3",
+  white: "#ffffff",
+  whitesmoke: "#f5f5f5",
+  yellow: "#ffff00",
+  yellowgreen: "#9acd32",
+  transparent: pv.Color.transparent = pv.rgb(0, 0, 0, 0)
+};
+
+/* Initialized named colors. */
+(function() {
+  var names = pv.Color.names;
+  for (var name in names) names[name] = pv.color(names[name]);
+})();
+/**
+ * Returns a new categorical color encoding using the specified colors.  The
+ * arguments to this method are an array of colors; see {@link pv.color}. For
+ * example, to create a categorical color encoding using the <tt>species</tt>
+ * attribute:
+ *
+ * <pre>pv.colors("red", "green", "blue").by(function(d) d.species)</pre>
+ *
+ * The result of this expression can be used as a fill- or stroke-style
+ * property. This assumes that the data's <tt>species</tt> attribute is a
+ * string.
+ *
+ * @param {string} colors... categorical colors.
+ * @see pv.Scale.ordinal
+ * @returns {pv.Scale.ordinal} an ordinal color scale.
+ */
+pv.colors = function() {
+  var scale = pv.Scale.ordinal();
+  scale.range.apply(scale, arguments);
+  return scale;
+};
+
+/**
+ * A collection of standard color palettes for categorical encoding.
+ *
+ * @namespace A collection of standard color palettes for categorical encoding.
+ */
+pv.Colors = {};
+
+/**
+ * Returns a new 10-color scheme. The arguments to this constructor are
+ * optional, and equivalent to calling {@link pv.Scale.OrdinalScale#domain}. The
+ * following colors are used:
+ *
+ * <div style="background:#1f77b4;">#1f77b4</div>
+ * <div style="background:#ff7f0e;">#ff7f0e</div>
+ * <div style="background:#2ca02c;">#2ca02c</div>
+ * <div style="background:#d62728;">#d62728</div>
+ * <div style="background:#9467bd;">#9467bd</div>
+ * <div style="background:#8c564b;">#8c564b</div>
+ * <div style="background:#e377c2;">#e377c2</div>
+ * <div style="background:#7f7f7f;">#7f7f7f</div>
+ * <div style="background:#bcbd22;">#bcbd22</div>
+ * <div style="background:#17becf;">#17becf</div>
+ *
+ * @param {number...} domain... domain values.
+ * @returns {pv.Scale.ordinal} a new ordinal color scale.
+ * @see pv.color
+ */
+pv.Colors.category10 = function() {
+  var scale = pv.colors(
+      "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
+      "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf");
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+
+/**
+ * Returns a new 20-color scheme. The arguments to this constructor are
+ * optional, and equivalent to calling {@link pv.Scale.OrdinalScale#domain}. The
+ * following colors are used:
+ *
+ * <div style="background:#1f77b4;">#1f77b4</div>
+ * <div style="background:#aec7e8;">#aec7e8</div>
+ * <div style="background:#ff7f0e;">#ff7f0e</div>
+ * <div style="background:#ffbb78;">#ffbb78</div>
+ * <div style="background:#2ca02c;">#2ca02c</div>
+ * <div style="background:#98df8a;">#98df8a</div>
+ * <div style="background:#d62728;">#d62728</div>
+ * <div style="background:#ff9896;">#ff9896</div>
+ * <div style="background:#9467bd;">#9467bd</div>
+ * <div style="background:#c5b0d5;">#c5b0d5</div>
+ * <div style="background:#8c564b;">#8c564b</div>
+ * <div style="background:#c49c94;">#c49c94</div>
+ * <div style="background:#e377c2;">#e377c2</div>
+ * <div style="background:#f7b6d2;">#f7b6d2</div>
+ * <div style="background:#7f7f7f;">#7f7f7f</div>
+ * <div style="background:#c7c7c7;">#c7c7c7</div>
+ * <div style="background:#bcbd22;">#bcbd22</div>
+ * <div style="background:#dbdb8d;">#dbdb8d</div>
+ * <div style="background:#17becf;">#17becf</div>
+ * <div style="background:#9edae5;">#9edae5</div>
+ *
+ * @param {number...} domain... domain values.
+ * @returns {pv.Scale.ordinal} a new ordinal color scale.
+ * @see pv.color
+*/
+pv.Colors.category20 = function() {
+  var scale = pv.colors(
+      "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c",
+      "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5",
+      "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f",
+      "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5");
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+
+/**
+ * Returns a new alternative 19-color scheme. The arguments to this constructor
+ * are optional, and equivalent to calling
+ * {@link pv.Scale.OrdinalScale#domain}. The following colors are used:
+ *
+ * <div style="background:#9c9ede;">#9c9ede</div>
+ * <div style="background:#7375b5;">#7375b5</div>
+ * <div style="background:#4a5584;">#4a5584</div>
+ * <div style="background:#cedb9c;">#cedb9c</div>
+ * <div style="background:#b5cf6b;">#b5cf6b</div>
+ * <div style="background:#8ca252;">#8ca252</div>
+ * <div style="background:#637939;">#637939</div>
+ * <div style="background:#e7cb94;">#e7cb94</div>
+ * <div style="background:#e7ba52;">#e7ba52</div>
+ * <div style="background:#bd9e39;">#bd9e39</div>
+ * <div style="background:#8c6d31;">#8c6d31</div>
+ * <div style="background:#e7969c;">#e7969c</div>
+ * <div style="background:#d6616b;">#d6616b</div>
+ * <div style="background:#ad494a;">#ad494a</div>
+ * <div style="background:#843c39;">#843c39</div>
+ * <div style="background:#de9ed6;">#de9ed6</div>
+ * <div style="background:#ce6dbd;">#ce6dbd</div>
+ * <div style="background:#a55194;">#a55194</div>
+ * <div style="background:#7b4173;">#7b4173</div>
+ *
+ * @param {number...} domain... domain values.
+ * @returns {pv.Scale.ordinal} a new ordinal color scale.
+ * @see pv.color
+ */
+pv.Colors.category19 = function() {
+  var scale = pv.colors(
+      "#9c9ede", "#7375b5", "#4a5584", "#cedb9c", "#b5cf6b",
+      "#8ca252", "#637939", "#e7cb94", "#e7ba52", "#bd9e39",
+      "#8c6d31", "#e7969c", "#d6616b", "#ad494a", "#843c39",
+      "#de9ed6", "#ce6dbd", "#a55194", "#7b4173");
+  scale.domain.apply(scale, arguments);
+  return scale;
+};
+/**
+ * Returns a linear color ramp from the specified <tt>start</tt> color to the
+ * specified <tt>end</tt> color. The color arguments may be specified either as
+ * <tt>string</tt>s or as {@link pv.Color}s. This is equivalent to:
+ *
+ * <pre>    pv.Scale.linear().domain(0, 1).range(...)</pre>
+ *
+ * @param {string} start the start color; may be a <tt>pv.Color</tt>.
+ * @param {string} end the end color; may be a <tt>pv.Color</tt>.
+ * @returns {Function} a color ramp from <tt>start</tt> to <tt>end</tt>.
+ * @see pv.Scale.linear
+ */
+pv.ramp = function(start, end) {
+  var scale = pv.Scale.linear();
+  scale.range.apply(scale, arguments);
+  return scale;
+};
+/**
+ * @private
+ * @namespace
+ */
+pv.Scene = pv.SvgScene = {
+  /* Various namespaces. */
+  svg: "http://www.w3.org/2000/svg",
+  xmlns: "http://www.w3.org/2000/xmlns",
+  xlink: "http://www.w3.org/1999/xlink",
+  xhtml: "http://www.w3.org/1999/xhtml",
+
+  /** The pre-multipled scale, based on any enclosing transforms. */
+  scale: 1,
+
+  /** The set of supported events. */
+  events: [
+    "DOMMouseScroll", // for Firefox
+    "mousewheel",
+    "mousedown",
+    "mouseup",
+    "mouseover",
+    "mouseout",
+    "mousemove",
+    "click",
+    "dblclick"
+  ],
+
+  /** Implicit values for SVG and CSS properties. */
+  implicit: {
+    svg: {
+      "shape-rendering": "auto",
+      "pointer-events": "painted",
+      "x": 0,
+      "y": 0,
+      "dy": 0,
+      "text-anchor": "start",
+      "transform": "translate(0,0)",
+      "fill": "none",
+      "fill-opacity": 1,
+      "stroke": "none",
+      "stroke-opacity": 1,
+      "stroke-width": 1.5,
+      "stroke-linejoin": "miter"
+    },
+    css: {
+      "font": "10px sans-serif"
+    }
+  }
+};
+
+/**
+ * Updates the display for the specified array of scene nodes.
+ *
+ * @param scenes {array} an array of scene nodes.
+ */
+pv.SvgScene.updateAll = function(scenes) {
+  if (scenes.length
+      && scenes[0].reverse
+      && (scenes.type != "line")
+      && (scenes.type != "area")) {
+    var reversed = pv.extend(scenes);
+    for (var i = 0, j = scenes.length - 1; j >= 0; i++, j--) {
+      reversed[i] = scenes[j];
+    }
+    scenes = reversed;
+  }
+  this.removeSiblings(this[scenes.type](scenes));
+};
+
+/**
+ * Creates a new SVG element of the specified type.
+ *
+ * @param type {string} an SVG element type, such as "rect".
+ * @returns a new SVG element.
+ */
+pv.SvgScene.create = function(type) {
+  return document.createElementNS(this.svg, type);
+};
+
+/**
+ * Expects the element <i>e</i> to be the specified type. If the element does
+ * not exist, a new one is created. If the element does exist but is the wrong
+ * type, it is replaced with the specified element.
+ *
+ * @param e the current SVG element.
+ * @param type {string} an SVG element type, such as "rect".
+ * @param attributes an optional attribute map.
+ * @param style an optional style map.
+ * @returns a new SVG element.
+ */
+pv.SvgScene.expect = function(e, type, attributes, style) {
+  if (e) {
+    if (e.tagName == "a") e = e.firstChild;
+    if (e.tagName != type) {
+      var n = this.create(type);
+      e.parentNode.replaceChild(n, e);
+      e = n;
+    }
+  } else {
+    e = this.create(type);
+  }
+  for (var name in attributes) {
+    var value = attributes[name];
+    if (value == this.implicit.svg[name]) value = null;
+    if (value == null) e.removeAttribute(name);
+    else e.setAttribute(name, value);
+  }
+  for (var name in style) {
+    var value = style[name];
+    if (value == this.implicit.css[name]) value = null;
+    if (value == null) e.style.removeProperty(name);
+    else e.style[name] = value;
+  }
+  return e;
+};
+
+/** TODO */
+pv.SvgScene.append = function(e, scenes, index) {
+  e.$scene = {scenes:scenes, index:index};
+  e = this.title(e, scenes[index]);
+  if (!e.parentNode) scenes.$g.appendChild(e);
+  return e.nextSibling;
+};
+
+/**
+ * Applies a title tooltip to the specified element <tt>e</tt>, using the
+ * <tt>title</tt> property of the specified scene node <tt>s</tt>. Note that
+ * this implementation does not create an SVG <tt>title</tt> element as a child
+ * of <tt>e</tt>; although this is the recommended standard, it is only
+ * supported in Opera. Instead, an anchor element is created around the element
+ * <tt>e</tt>, and the <tt>xlink:title</tt> attribute is set accordingly.
+ *
+ * @param e an SVG element.
+ * @param s a scene node.
+ */
+pv.SvgScene.title = function(e, s) {
+  var a = e.parentNode;
+  if (a && (a.tagName != "a")) a = null;
+  if (s.title) {
+    if (!a) {
+      a = this.create("a");
+      if (e.parentNode) e.parentNode.replaceChild(a, e);
+      a.appendChild(e);
+    }
+    a.setAttributeNS(this.xlink, "title", s.title);
+    return a;
+  }
+  if (a) a.parentNode.replaceChild(e, a);
+  return e;
+};
+
+/** TODO */
+pv.SvgScene.dispatch = pv.listener(function(e) {
+  var t = e.target.$scene;
+  if (t) {
+    var type = e.type;
+
+    /* Fixes for mousewheel support on Firefox & Opera. */
+    switch (type) {
+      case "DOMMouseScroll": {
+        type = "mousewheel";
+        e.wheel = -480 * e.detail;
+        break;
+      }
+      case "mousewheel": {
+        e.wheel = (window.opera ? 12 : 1) * e.wheelDelta;
+        break;
+      }
+    }
+
+    if (pv.Mark.dispatch(type, t.scenes, t.index)) e.preventDefault();
+  }
+});
+
+/** @private Remove siblings following element <i>e</i>. */
+pv.SvgScene.removeSiblings = function(e) {
+  while (e) {
+    var n = e.nextSibling;
+    e.parentNode.removeChild(e);
+    e = n;
+  }
+};
+
+/** @private Do nothing when rendering undefined mark types. */
+pv.SvgScene.undefined = function() {};
+/**
+ * @private Converts the specified b-spline curve segment to a bezier curve
+ * compatible with SVG "C".
+ *
+ * @param p0 the first control point.
+ * @param p1 the second control point.
+ * @param p2 the third control point.
+ * @param p3 the fourth control point.
+ */
+pv.SvgScene.pathBasis = (function() {
+
+  /**
+   * Matrix to transform basis (b-spline) control points to bezier control
+   * points. Derived from FvD 11.2.8.
+   */
+  var basis = [
+    [ 1/6, 2/3, 1/6,   0 ],
+    [   0, 2/3, 1/3,   0 ],
+    [   0, 1/3, 2/3,   0 ],
+    [   0, 1/6, 2/3, 1/6 ]
+  ];
+
+  /**
+   * Returns the point that is the weighted sum of the specified control points,
+   * using the specified weights. This method requires that there are four
+   * weights and four control points.
+   */
+  function weight(w, p0, p1, p2, p3) {
+    return {
+      x: w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left,
+      y: w[0] * p0.top  + w[1] * p1.top  + w[2] * p2.top  + w[3] * p3.top
+    };
+  }
+
+  var convert = function(p0, p1, p2, p3) {
+    var b1 = weight(basis[1], p0, p1, p2, p3),
+        b2 = weight(basis[2], p0, p1, p2, p3),
+        b3 = weight(basis[3], p0, p1, p2, p3);
+    return "C" + b1.x + "," + b1.y
+         + "," + b2.x + "," + b2.y
+         + "," + b3.x + "," + b3.y;
+  };
+
+  convert.segment = function(p0, p1, p2, p3) {
+    var b0 = weight(basis[0], p0, p1, p2, p3),
+        b1 = weight(basis[1], p0, p1, p2, p3),
+        b2 = weight(basis[2], p0, p1, p2, p3),
+        b3 = weight(basis[3], p0, p1, p2, p3);
+    return "M" + b0.x + "," + b0.y
+         + "C" + b1.x + "," + b1.y
+         + "," + b2.x + "," + b2.y
+         + "," + b3.x + "," + b3.y;
+  };
+
+  return convert;
+})();
+
+/**
+ * @private Interpolates the given points using the basis spline interpolation.
+ * Returns an SVG path without the leading M instruction to allow path
+ * appending.
+ *
+ * @param points the array of points.
+ */
+pv.SvgScene.curveBasis = function(points) {
+  if (points.length <= 2) return "";
+  var path = "",
+      p0 = points[0],
+      p1 = p0,
+      p2 = p0,
+      p3 = points[1];
+  path += this.pathBasis(p0, p1, p2, p3);
+  for (var i = 2; i < points.length; i++) {
+    p0 = p1;
+    p1 = p2;
+    p2 = p3;
+    p3 = points[i];
+    path += this.pathBasis(p0, p1, p2, p3);
+  }
+  /* Cycle through to get the last point. */
+  path += this.pathBasis(p1, p2, p3, p3);
+  path += this.pathBasis(p2, p3, p3, p3);
+  return path;
+};
+
+/**
+ * @private Interpolates the given points using the basis spline interpolation.
+ * If points.length == tangents.length then a regular Hermite interpolation is
+ * performed, if points.length == tangents.length + 2 then the first and last
+ * segments are filled in with cubic bazier segments.  Returns an array of path
+ * strings.
+ *
+ * @param points the array of points.
+ */
+pv.SvgScene.curveBasisSegments = function(points) {
+  if (points.length <= 2) return "";
+  var paths = [],
+      p0 = points[0],
+      p1 = p0,
+      p2 = p0,
+      p3 = points[1],
+      firstPath = this.pathBasis.segment(p0, p1, p2, p3);
+
+  p0 = p1;
+  p1 = p2;
+  p2 = p3;
+  p3 = points[2];
+  paths.push(firstPath + this.pathBasis(p0, p1, p2, p3)); // merge first & second path
+  for (var i = 3; i < points.length; i++) {
+    p0 = p1;
+    p1 = p2;
+    p2 = p3;
+    p3 = points[i];
+    paths.push(this.pathBasis.segment(p0, p1, p2, p3));
+  }
+
+  // merge last & second-to-last path
+  paths.push(this.pathBasis.segment(p1, p2, p3, p3) + this.pathBasis(p2, p3, p3, p3));
+  return paths;
+};
+
+/**
+ * @private Interpolates the given points with respective tangents using the cubic
+ * Hermite spline interpolation. If points.length == tangents.length then a regular
+ * Hermite interpolation is performed, if points.length == tangents.length + 2 then
+ * the first and last segments are filled in with cubic bazier segments.
+ * Returns an SVG path without the leading M instruction to allow path appending.
+ *
+ * @param points the array of points.
+ * @param tangents the array of tangent vectors.
+ */
+pv.SvgScene.curveHermite = function(points, tangents) {
+  if (tangents.length < 1
+      || (points.length != tangents.length
+      && points.length != tangents.length + 2)) return "";
+  var quad = points.length != tangents.length,
+      path = "",
+      p0 = points[0],
+      p = points[1],
+      t0 = tangents[0],
+      t = t0,
+      pi = 1;
+
+  if (quad) {
+    path += "Q" + (p.left - t0.x * 2 / 3) + ","  + (p.top - t0.y * 2 / 3)
+        + "," + p.left + "," + p.top;
+    p0 = points[1];
+    pi = 2;
+  }
+
+  if (tangents.length > 1) {
+    t = tangents[1];
+    p = points[pi];
+    pi++;
+    path += "C" + (p0.left + t0.x) + "," + (p0.top + t0.y)
+        + "," + (p.left - t.x) + "," + (p.top - t.y)
+        + "," + p.left + "," + p.top;
+    for (var i = 2; i < tangents.length; i++, pi++) {
+      p = points[pi];
+      t = tangents[i];
+      path += "S" + (p.left - t.x) + "," + (p.top - t.y)
+          + "," + p.left + "," + p.top;
+    }
+  }
+
+  if (quad) {
+    var lp = points[pi];
+    path += "Q" + (p.left + t.x * 2 / 3) + ","  + (p.top + t.y * 2 / 3) + ","
+        + lp.left + "," + lp.top;
+  }
+
+  return path;
+};
+
+/**
+ * @private Interpolates the given points with respective tangents using the
+ * cubic Hermite spline interpolation. Returns an array of path strings.
+ *
+ * @param points the array of points.
+ * @param tangents the array of tangent vectors.
+ */
+pv.SvgScene.curveHermiteSegments = function(points, tangents) {
+  if (tangents.length < 1
+      || (points.length != tangents.length
+      && points.length != tangents.length + 2)) return [];
+  var quad = points.length != tangents.length,
+      paths = [],
+      p0 = points[0],
+      p = p0,
+      t0 = tangents[0],
+      t = t0,
+      pi = 1;
+
+  if (quad) {
+    p = points[1];
+    paths.push("M" + p0.left + "," + p0.top
+        + "Q" + (p.left - t.x * 2 / 3) + "," + (p.top - t.y * 2 / 3)
+        + "," + p.left + "," + p.top);
+    pi = 2;
+  }
+
+  for (var i = 1; i < tangents.length; i++, pi++) {
+    p0 = p;
+    t0 = t;
+    p = points[pi];
+    t = tangents[i];
+    paths.push("M" + p0.left + "," + p0.top
+        + "C" + (p0.left + t0.x) + "," + (p0.top + t0.y)
+        + "," + (p.left - t.x) + "," + (p.top - t.y)
+        + "," + p.left + "," + p.top);
+  }
+
+  if (quad) {
+    var lp = points[pi];
+    paths.push("M" + p.left + "," + p.top
+        + "Q" + (p.left + t.x * 2 / 3) + ","  + (p.top + t.y * 2 / 3) + ","
+        + lp.left + "," + lp.top);
+  }
+
+  return paths;
+};
+
+/**
+ * @private Computes the tangents for the given points needed for cardinal
+ * spline interpolation. Returns an array of tangent vectors. Note: that for n
+ * points only the n-2 well defined tangents are returned.
+ *
+ * @param points the array of points.
+ * @param tension the tension of hte cardinal spline.
+ */
+pv.SvgScene.cardinalTangents = function(points, tension) {
+  var tangents = [],
+      a = (1 - tension) / 2,
+      p0 = points[0],
+      p1 = points[1],
+      p2 = points[2];
+
+  for (var i = 3; i < points.length; i++) {
+    tangents.push({x: a * (p2.left - p0.left), y: a * (p2.top - p0.top)});
+    p0 = p1;
+    p1 = p2;
+    p2 = points[i];
+  }
+
+  tangents.push({x: a * (p2.left - p0.left), y: a * (p2.top - p0.top)});
+  return tangents;
+};
+
+/**
+ * @private Interpolates the given points using cardinal spline interpolation.
+ * Returns an SVG path without the leading M instruction to allow path
+ * appending.
+ *
+ * @param points the array of points.
+ * @param tension the tension of hte cardinal spline.
+ */
+pv.SvgScene.curveCardinal = function(points, tension) {
+  if (points.length <= 2) return "";
+  return this.curveHermite(points, this.cardinalTangents(points, tension));
+};
+
+/**
+ * @private Interpolates the given points using cardinal spline interpolation.
+ * Returns an array of path strings.
+ *
+ * @param points the array of points.
+ * @param tension the tension of hte cardinal spline.
+ */
+pv.SvgScene.curveCardinalSegments = function(points, tension) {
+  if (points.length <= 2) return "";
+  return this.curveHermiteSegments(points, this.cardinalTangents(points, tension));
+};
+
+/**
+ * @private Interpolates the given points using Fritsch-Carlson Monotone cubic
+ * Hermite interpolation. Returns an array of tangent vectors.
+ *
+ * @param points the array of points.
+ */
+pv.SvgScene.monotoneTangents = function(points) {
+  var tangents = [],
+      d = [],
+      m = [],
+      dx = [],
+      k = 0;
+
+  /* Compute the slopes of the secant lines between successive points. */
+  for (k = 0; k < points.length-1; k++) {
+    d[k] = (points[k+1].top - points[k].top)/(points[k+1].left - points[k].left);
+  }
+
+  /* Initialize the tangents at every point as the average of the secants. */
+  m[0] = d[0];
+  dx[0] = points[1].left - points[0].left;
+  for (k = 1; k < points.length - 1; k++) {
+    m[k] = (d[k-1]+d[k])/2;
+    dx[k] = (points[k+1].left - points[k-1].left)/2;
+  }
+  m[k] = d[k-1];
+  dx[k] = (points[k].left - points[k-1].left);
+
+  /* Step 3. Very important, step 3. Yep. Wouldn't miss it. */
+  for (k = 0; k < points.length - 1; k++) {
+    if (d[k] == 0) {
+      m[ k ] = 0;
+      m[k+1] = 0;
+    }
+  }
+
+  /* Step 4 + 5. Out of 5 or more steps. */
+  for (k = 0; k < points.length - 1; k++) {
+    if ((Math.abs(m[k]) < 1e-5) || (Math.abs(m[k+1]) < 1e-5)) continue;
+    var ak = m[k] / d[k],
+        bk = m[k + 1] / d[k],
+        s = ak * ak + bk * bk; // monotone constant (?)
+    if (s > 9) {
+      var tk = 3 / Math.sqrt(s);
+      m[k] = tk * ak * d[k];
+      m[k + 1] = tk * bk * d[k];
+    }
+  }
+
+  var len;
+  for (var i = 0; i < points.length; i++) {
+    len = 1 + m[i] * m[i]; // pv.vector(1, m[i]).norm().times(dx[i]/3)
+    tangents.push({x: dx[i] / 3 / len, y: m[i] * dx[i] / 3 / len});
+  }
+
+  return tangents;
+};
+
+/**
+ * @private Interpolates the given points using Fritsch-Carlson Monotone cubic
+ * Hermite interpolation. Returns an SVG path without the leading M instruction
+ * to allow path appending.
+ *
+ * @param points the array of points.
+ */
+pv.SvgScene.curveMonotone = function(points) {
+  if (points.length <= 2) return "";
+  return this.curveHermite(points, this.monotoneTangents(points));
+}
+
+/**
+ * @private Interpolates the given points using Fritsch-Carlson Monotone cubic
+ * Hermite interpolation.
+ * Returns an array of path strings.
+ *
+ * @param points the array of points.
+ */
+pv.SvgScene.curveMonotoneSegments = function(points) {
+  if (points.length <= 2) return "";
+  return this.curveHermiteSegments(points, this.monotoneTangents(points));
+};
+pv.SvgScene.area = function(scenes) {
+  var e = scenes.$g.firstChild;
+  if (!scenes.length) return e;
+  var s = scenes[0];
+
+  /* segmented */
+  if (s.segmented) return this.areaSegment(scenes);
+
+  /* visible */
+  if (!s.visible) return e;
+  var fill = s.fillStyle, stroke = s.strokeStyle;
+  if (!fill.opacity && !stroke.opacity) return e;
+
+  /** @private Computes the straight path for the range [i, j]. */
+  function path(i, j) {
+    var p1 = [], p2 = [];
+    for (var k = j; i <= k; i++, j--) {
+      var si = scenes[i],
+          sj = scenes[j],
+          pi = si.left + "," + si.top,
+          pj = (sj.left + sj.width) + "," + (sj.top + sj.height);
+
+      /* interpolate */
+      if (i < k) {
+        var sk = scenes[i + 1], sl = scenes[j - 1];
+        switch (s.interpolate) {
+          case "step-before": {
+            pi += "V" + sk.top;
+            pj += "H" + (sl.left + sl.width);
+            break;
+          }
+          case "step-after": {
+            pi += "H" + sk.left;
+            pj += "V" + (sl.top + sl.height);
+            break;
+          }
+        }
+      }
+
+      p1.push(pi);
+      p2.push(pj);
+    }
+    return p1.concat(p2).join("L");
+  }
+
+  /** @private Computes the curved path for the range [i, j]. */
+  function pathCurve(i, j) {
+    var pointsT = [], pointsB = [], pathT, pathB;
+
+    for (var k = j; i <= k; i++, j--) {
+      var sj = scenes[j];
+      pointsT.push(scenes[i]);
+      pointsB.push({left: sj.left + sj.width, top: sj.top + sj.height});
+    }
+
+    if (s.interpolate == "basis") {
+      pathT = pv.SvgScene.curveBasis(pointsT);
+      pathB = pv.SvgScene.curveBasis(pointsB);
+    } else if (s.interpolate == "cardinal") {
+      pathT = pv.SvgScene.curveCardinal(pointsT, s.tension);
+      pathB = pv.SvgScene.curveCardinal(pointsB, s.tension);
+    } else { // monotone
+      pathT = pv.SvgScene.curveMonotone(pointsT);
+      pathB = pv.SvgScene.curveMonotone(pointsB);
+    }
+
+    return pointsT[0].left + "," + pointsT[0].top + pathT
+         + "L" + pointsB[0].left + "," + pointsB[0].top + pathB;
+  }
+
+  /* points */
+  var d = [], si, sj;
+  for (var i = 0; i < scenes.length; i++) {
+    si = scenes[i]; if (!si.width && !si.height) continue;
+    for (var j = i + 1; j < scenes.length; j++) {
+      sj = scenes[j]; if (!sj.width && !sj.height) break;
+    }
+    if (i && (s.interpolate != "step-after")) i--;
+    if ((j < scenes.length) && (s.interpolate != "step-before")) j++;
+    d.push(((j - i > 2
+        && (s.interpolate == "basis"
+        || s.interpolate == "cardinal"
+        || s.interpolate == "monotone"))
+        ? pathCurve : path)(i, j - 1));
+    i = j - 1;
+  }
+  if (!d.length) return e;
+
+  e = this.expect(e, "path", {
+      "shape-rendering": s.antialias ? null : "crispEdges",
+      "pointer-events": s.events,
+      "cursor": s.cursor,
+      "d": "M" + d.join("ZM") + "Z",
+      "fill": fill.color,
+      "fill-opacity": fill.opacity || null,
+      "stroke": stroke.color,
+      "stroke-opacity": stroke.opacity || null,
+      "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
+    });
+  return this.append(e, scenes, 0);
+};
+
+pv.SvgScene.areaSegment = function(scenes) {
+  var e = scenes.$g.firstChild, s = scenes[0], pathsT, pathsB;
+  if (s.interpolate == "basis"
+      || s.interpolate == "cardinal"
+      || s.interpolate == "monotone") {
+    var pointsT = [], pointsB = [];
+
+    for (var i = 0, n = scenes.length; i < n; i++) {
+      var sj = scenes[n - i - 1];
+      pointsT.push(scenes[i]);
+      pointsB.push({left: sj.left + sj.width, top: sj.top + sj.height});
+    }
+
+    if (s.interpolate == "basis") {
+      pathsT = this.curveBasisSegments(pointsT);
+      pathsB = this.curveBasisSegments(pointsB);
+    } else if (s.interpolate == "cardinal") {
+      pathsT = this.curveCardinalSegments(pointsT, s.tension);
+      pathsB = this.curveCardinalSegments(pointsB, s.tension);
+    } else { // monotone
+      pathsT = this.curveMonotoneSegments(pointsT);
+      pathsB = this.curveMonotoneSegments(pointsB);
+    }
+  }
+
+  for (var i = 0, n = scenes.length - 1; i < n; i++) {
+    var s1 = scenes[i], s2 = scenes[i + 1];
+
+    /* visible */
+    if (!s1.visible || !s2.visible) continue;
+    var fill = s1.fillStyle, stroke = s1.strokeStyle;
+    if (!fill.opacity && !stroke.opacity) continue;
+
+    var d;
+    if (pathsT) {
+      var pathT = pathsT[i],
+          pathB = "L" + pathsB[n - i - 1].substr(1);
+
+      d = pathT + pathB + "Z";
+    } else {
+      /* interpolate */
+      var si = s1, sj = s2;
+      switch (s1.interpolate) {
+        case "step-before": si = s2; break;
+        case "step-after": sj = s1; break;
+      }
+
+      /* path */
+      d = "M" + s1.left + "," + si.top
+        + "L" + s2.left + "," + sj.top
+        + "L" + (s2.left + s2.width) + "," + (sj.top + sj.height)
+        + "L" + (s1.left + s1.width) + "," + (si.top + si.height)
+        + "Z";
+    }
+
+    e = this.expect(e, "path", {
+        "shape-rendering": s1.antialias ? null : "crispEdges",
+        "pointer-events": s1.events,
+        "cursor": s1.cursor,
+        "d": d,
+        "fill": fill.color,
+        "fill-opacity": fill.opacity || null,
+        "stroke": stroke.color,
+        "stroke-opacity": stroke.opacity || null,
+        "stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.bar = function(scenes) {
+  var e = scenes.$g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+    var fill = s.fillStyle, stroke = s.strokeStyle;
+    if (!fill.opacity && !stroke.opacity) continue;
+
+    e = this.expect(e, "rect", {
+        "shape-rendering": s.antialias ? null : "crispEdges",
+        "pointer-events": s.events,
+        "cursor": s.cursor,
+        "x": s.left,
+        "y": s.top,
+        "width": Math.max(1E-10, s.width),
+        "height": Math.max(1E-10, s.height),
+        "fill": fill.color,
+        "fill-opacity": fill.opacity || null,
+        "stroke": stroke.color,
+        "stroke-opacity": stroke.opacity || null,
+        "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.dot = function(scenes) {
+  var e = scenes.$g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+    var fill = s.fillStyle, stroke = s.strokeStyle;
+    if (!fill.opacity && !stroke.opacity) continue;
+
+    /* points */
+    var radius = s.radius, path = null;
+    switch (s.shape) {
+      case "cross": {
+        path = "M" + -radius + "," + -radius
+            + "L" + radius + "," + radius
+            + "M" + radius + "," + -radius
+            + "L" + -radius + "," + radius;
+        break;
+      }
+      case "triangle": {
+        var h = radius, w = radius * 1.1547; // 2 / Math.sqrt(3)
+        path = "M0," + h
+            + "L" + w +"," + -h
+            + " " + -w + "," + -h
+            + "Z";
+        break;
+      }
+      case "diamond": {
+        radius *= Math.SQRT2;
+        path = "M0," + -radius
+            + "L" + radius + ",0"
+            + " 0," + radius
+            + " " + -radius + ",0"
+            + "Z";
+        break;
+      }
+      case "square": {
+        path = "M" + -radius + "," + -radius
+            + "L" + radius + "," + -radius
+            + " " + radius + "," + radius
+            + " " + -radius + "," + radius
+            + "Z";
+        break;
+      }
+      case "tick": {
+        path = "M0,0L0," + -s.size;
+        break;
+      }
+      case "bar": {
+        path = "M0," + (s.size / 2) + "L0," + -(s.size / 2);
+        break;
+      }
+    }
+
+    /* Use <circle> for circles, <path> for everything else. */
+    var svg = {
+      "shape-rendering": s.antialias ? null : "crispEdges",
+      "pointer-events": s.events,
+      "cursor": s.cursor,
+      "fill": fill.color,
+      "fill-opacity": fill.opacity || null,
+      "stroke": stroke.color,
+      "stroke-opacity": stroke.opacity || null,
+      "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
+    };
+    if (path) {
+      svg.transform = "translate(" + s.left + "," + s.top + ")";
+      if (s.angle) svg.transform += " rotate(" + 180 * s.angle / Math.PI + ")";
+      svg.d = path;
+      e = this.expect(e, "path", svg);
+    } else {
+      svg.cx = s.left;
+      svg.cy = s.top;
+      svg.r = radius;
+      e = this.expect(e, "circle", svg);
+    }
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.image = function(scenes) {
+  var e = scenes.$g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+
+    /* fill */
+    e = this.fill(e, scenes, i);
+
+    /* image */
+    if (s.image) {
+      e = this.expect(e, "foreignObject", {
+          "cursor": s.cursor,
+          "x": s.left,
+          "y": s.top,
+          "width": s.width,
+          "height": s.height
+        });
+      var c = e.firstChild || e.appendChild(document.createElementNS(this.xhtml, "canvas"));
+      c.$scene = {scenes:scenes, index:i};
+      c.style.width = s.width;
+      c.style.height = s.height;
+      c.width = s.imageWidth;
+      c.height = s.imageHeight;
+      c.getContext("2d").putImageData(s.image, 0, 0);
+    } else {
+      e = this.expect(e, "image", {
+          "preserveAspectRatio": "none",
+          "cursor": s.cursor,
+          "x": s.left,
+          "y": s.top,
+          "width": s.width,
+          "height": s.height
+        });
+      e.setAttributeNS(this.xlink, "href", s.url);
+    }
+    e = this.append(e, scenes, i);
+
+    /* stroke */
+    e = this.stroke(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.label = function(scenes) {
+  var e = scenes.$g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+    var fill = s.textStyle;
+    if (!fill.opacity || !s.text) continue;
+
+    /* text-baseline, text-align */
+    var x = 0, y = 0, dy = 0, anchor = "start";
+    switch (s.textBaseline) {
+      case "middle": dy = ".35em"; break;
+      case "top": dy = ".71em"; y = s.textMargin; break;
+      case "bottom": y = "-" + s.textMargin; break;
+    }
+    switch (s.textAlign) {
+      case "right": anchor = "end"; x = "-" + s.textMargin; break;
+      case "center": anchor = "middle"; break;
+      case "left": x = s.textMargin; break;
+    }
+
+    e = this.expect(e, "text", {
+        "pointer-events": s.events,
+        "cursor": s.cursor,
+        "x": x,
+        "y": y,
+        "dy": dy,
+        "transform": "translate(" + s.left + "," + s.top + ")"
+            + (s.textAngle ? " rotate(" + 180 * s.textAngle / Math.PI + ")" : "")
+            + (this.scale != 1 ? " scale(" + 1 / this.scale + ")" : ""),
+        "fill": fill.color,
+        "fill-opacity": fill.opacity || null,
+        "text-anchor": anchor
+      }, {
+        "font": s.font,
+        "text-shadow": s.textShadow,
+        "text-decoration": s.textDecoration
+      });
+    if (e.firstChild) e.firstChild.nodeValue = s.text;
+    else e.appendChild(document.createTextNode(s.text));
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.line = function(scenes) {
+  var e = scenes.$g.firstChild;
+  if (scenes.length < 2) return e;
+  var s = scenes[0];
+
+  /* segmented */
+  if (s.segmented) return this.lineSegment(scenes);
+
+  /* visible */
+  if (!s.visible) return e;
+  var fill = s.fillStyle, stroke = s.strokeStyle;
+  if (!fill.opacity && !stroke.opacity) return e;
+
+  /* points */
+  var d = "M" + s.left + "," + s.top;
+
+  if (scenes.length > 2 && (s.interpolate == "basis" || s.interpolate == "cardinal" || s.interpolate == "monotone")) {
+    switch (s.interpolate) {
+      case "basis": d += this.curveBasis(scenes); break;
+      case "cardinal": d += this.curveCardinal(scenes, s.tension); break;
+      case "monotone": d += this.curveMonotone(scenes); break;
+    }
+  } else {
+    for (var i = 1; i < scenes.length; i++) {
+      d += this.pathSegment(scenes[i - 1], scenes[i]);
+    }
+  }
+
+  e = this.expect(e, "path", {
+      "shape-rendering": s.antialias ? null : "crispEdges",
+      "pointer-events": s.events,
+      "cursor": s.cursor,
+      "d": d,
+      "fill": fill.color,
+      "fill-opacity": fill.opacity || null,
+      "stroke": stroke.color,
+      "stroke-opacity": stroke.opacity || null,
+      "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null,
+      "stroke-linejoin": s.lineJoin
+    });
+  return this.append(e, scenes, 0);
+};
+
+pv.SvgScene.lineSegment = function(scenes) {
+  var e = scenes.$g.firstChild;
+
+  var s = scenes[0];
+  var paths;
+  switch (s.interpolate) {
+    case "basis": paths = this.curveBasisSegments(scenes); break;
+    case "cardinal": paths = this.curveCardinalSegments(scenes, s.tension); break;
+    case "monotone": paths = this.curveMonotoneSegments(scenes); break;
+  }
+
+  for (var i = 0, n = scenes.length - 1; i < n; i++) {
+    var s1 = scenes[i], s2 = scenes[i + 1];
+
+    /* visible */
+    if (!s1.visible || !s2.visible) continue;
+    var stroke = s1.strokeStyle, fill = pv.Color.transparent;
+    if (!stroke.opacity) continue;
+
+    /* interpolate */
+    var d;
+    if ((s1.interpolate == "linear") && (s1.lineJoin == "miter")) {
+      fill = stroke;
+      stroke = pv.Color.transparent;
+      d = this.pathJoin(scenes[i - 1], s1, s2, scenes[i + 2]);
+    } else if(paths) {
+      d = paths[i];
+    } else {
+      d = "M" + s1.left + "," + s1.top + this.pathSegment(s1, s2);
+    }
+
+    e = this.expect(e, "path", {
+        "shape-rendering": s1.antialias ? null : "crispEdges",
+        "pointer-events": s1.events,
+        "cursor": s1.cursor,
+        "d": d,
+        "fill": fill.color,
+        "fill-opacity": fill.opacity || null,
+        "stroke": stroke.color,
+        "stroke-opacity": stroke.opacity || null,
+        "stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null,
+        "stroke-linejoin": s1.lineJoin
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+
+/** @private Returns the path segment for the specified points. */
+pv.SvgScene.pathSegment = function(s1, s2) {
+  var l = 1; // sweep-flag
+  switch (s1.interpolate) {
+    case "polar-reverse":
+      l = 0;
+    case "polar": {
+      var dx = s2.left - s1.left,
+          dy = s2.top - s1.top,
+          e = 1 - s1.eccentricity,
+          r = Math.sqrt(dx * dx + dy * dy) / (2 * e);
+      if ((e <= 0) || (e > 1)) break; // draw a straight line
+      return "A" + r + "," + r + " 0 0," + l + " " + s2.left + "," + s2.top;
+    }
+    case "step-before": return "V" + s2.top + "H" + s2.left;
+    case "step-after": return "H" + s2.left + "V" + s2.top;
+  }
+  return "L" + s2.left + "," + s2.top;
+};
+
+/** @private Line-line intersection, per Akenine-Moller 16.16.1. */
+pv.SvgScene.lineIntersect = function(o1, d1, o2, d2) {
+  return o1.plus(d1.times(o2.minus(o1).dot(d2.perp()) / d1.dot(d2.perp())));
+}
+
+/** @private Returns the miter join path for the specified points. */
+pv.SvgScene.pathJoin = function(s0, s1, s2, s3) {
+  /*
+   * P1-P2 is the current line segment. V is a vector that is perpendicular to
+   * the line segment, and has length lineWidth / 2. ABCD forms the initial
+   * bounding box of the line segment (i.e., the line segment if we were to do
+   * no joins).
+   */
+  var p1 = pv.vector(s1.left, s1.top),
+      p2 = pv.vector(s2.left, s2.top),
+      p = p2.minus(p1),
+      v = p.perp().norm(),
+      w = v.times(s1.lineWidth / (2 * this.scale)),
+      a = p1.plus(w),
+      b = p2.plus(w),
+      c = p2.minus(w),
+      d = p1.minus(w);
+
+  /*
+   * Start join. P0 is the previous line segment's start point. We define the
+   * cutting plane as the average of the vector perpendicular to P0-P1, and
+   * the vector perpendicular to P1-P2. This insures that the cross-section of
+   * the line on the cutting plane is equal if the line-width is unchanged.
+   * Note that we don't implement miter limits, so these can get wild.
+   */
+  if (s0 && s0.visible) {
+    var v1 = p1.minus(s0.left, s0.top).perp().norm().plus(v);
+    d = this.lineIntersect(p1, v1, d, p);
+    a = this.lineIntersect(p1, v1, a, p);
+  }
+
+  /* Similarly, for end join. */
+  if (s3 && s3.visible) {
+    var v2 = pv.vector(s3.left, s3.top).minus(p2).perp().norm().plus(v);
+    c = this.lineIntersect(p2, v2, c, p);
+    b = this.lineIntersect(p2, v2, b, p);
+  }
+
+  return "M" + a.x + "," + a.y
+       + "L" + b.x + "," + b.y
+       + " " + c.x + "," + c.y
+       + " " + d.x + "," + d.y;
+};
+pv.SvgScene.panel = function(scenes) {
+  var g = scenes.$g, e = g && g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+
+    /* svg */
+    if (!scenes.parent) {
+      s.canvas.style.display = "inline-block";
+      if (g && (g.parentNode != s.canvas)) {
+        g = s.canvas.firstChild;
+        e = g && g.firstChild;
+      }
+      if (!g) {
+        g = s.canvas.appendChild(this.create("svg"));
+        g.setAttribute("font-size", "10px");
+        g.setAttribute("font-family", "sans-serif");
+        g.setAttribute("fill", "none");
+        g.setAttribute("stroke", "none");
+        g.setAttribute("stroke-width", 1.5);
+        for (var j = 0; j < this.events.length; j++) {
+          g.addEventListener(this.events[j], this.dispatch, false);
+        }
+        e = g.firstChild;
+      }
+      scenes.$g = g;
+      g.setAttribute("width", s.width + s.left + s.right);
+      g.setAttribute("height", s.height + s.top + s.bottom);
+    }
+
+    /* clip (nest children) */
+    if (s.overflow == "hidden") {
+      var id = pv.id().toString(36),
+          c = this.expect(e, "g", {"clip-path": "url(#" + id + ")"});
+      if (!c.parentNode) g.appendChild(c);
+      scenes.$g = g = c;
+      e = c.firstChild;
+
+      e = this.expect(e, "clipPath", {"id": id});
+      var r = e.firstChild || e.appendChild(this.create("rect"));
+      r.setAttribute("x", s.left);
+      r.setAttribute("y", s.top);
+      r.setAttribute("width", s.width);
+      r.setAttribute("height", s.height);
+      if (!e.parentNode) g.appendChild(e);
+      e = e.nextSibling;
+    }
+
+    /* fill */
+    e = this.fill(e, scenes, i);
+
+    /* transform (push) */
+    var k = this.scale,
+        t = s.transform,
+        x = s.left + t.x,
+        y = s.top + t.y;
+    this.scale *= t.k;
+
+    /* children */
+    for (var j = 0; j < s.children.length; j++) {
+      s.children[j].$g = e = this.expect(e, "g", {
+          "transform": "translate(" + x + "," + y + ")"
+              + (t.k != 1 ? " scale(" + t.k + ")" : "")
+        });
+      this.updateAll(s.children[j]);
+      if (!e.parentNode) g.appendChild(e);
+      e = e.nextSibling;
+    }
+
+    /* transform (pop) */
+    this.scale = k;
+
+    /* stroke */
+    e = this.stroke(e, scenes, i);
+
+    /* clip (restore group) */
+    if (s.overflow == "hidden") {
+      scenes.$g = g = c.parentNode;
+      e = c.nextSibling;
+    }
+  }
+  return e;
+};
+
+pv.SvgScene.fill = function(e, scenes, i) {
+  var s = scenes[i], fill = s.fillStyle;
+  if (fill.opacity || s.events == "all") {
+    e = this.expect(e, "rect", {
+        "shape-rendering": s.antialias ? null : "crispEdges",
+        "pointer-events": s.events,
+        "cursor": s.cursor,
+        "x": s.left,
+        "y": s.top,
+        "width": s.width,
+        "height": s.height,
+        "fill": fill.color,
+        "fill-opacity": fill.opacity,
+        "stroke": null
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+
+pv.SvgScene.stroke = function(e, scenes, i) {
+  var s = scenes[i], stroke = s.strokeStyle;
+  if (stroke.opacity || s.events == "all") {
+    e = this.expect(e, "rect", {
+        "shape-rendering": s.antialias ? null : "crispEdges",
+        "pointer-events": s.events == "all" ? "stroke" : s.events,
+        "cursor": s.cursor,
+        "x": s.left,
+        "y": s.top,
+        "width": Math.max(1E-10, s.width),
+        "height": Math.max(1E-10, s.height),
+        "fill": null,
+        "stroke": stroke.color,
+        "stroke-opacity": stroke.opacity,
+        "stroke-width": s.lineWidth / this.scale
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.rule = function(scenes) {
+  var e = scenes.$g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+    var stroke = s.strokeStyle;
+    if (!stroke.opacity) continue;
+
+    e = this.expect(e, "line", {
+        "shape-rendering": s.antialias ? null : "crispEdges",
+        "pointer-events": s.events,
+        "cursor": s.cursor,
+        "x1": s.left,
+        "y1": s.top,
+        "x2": s.left + s.width,
+        "y2": s.top + s.height,
+        "stroke": stroke.color,
+        "stroke-opacity": stroke.opacity,
+        "stroke-width": s.lineWidth / this.scale
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+pv.SvgScene.wedge = function(scenes) {
+  var e = scenes.$g.firstChild;
+  for (var i = 0; i < scenes.length; i++) {
+    var s = scenes[i];
+
+    /* visible */
+    if (!s.visible) continue;
+    var fill = s.fillStyle, stroke = s.strokeStyle;
+    if (!fill.opacity && !stroke.opacity) continue;
+
+    /* points */
+    var r1 = s.innerRadius, r2 = s.outerRadius, a = Math.abs(s.angle), p;
+    if (a >= 2 * Math.PI) {
+      if (r1) {
+        p = "M0," + r2
+            + "A" + r2 + "," + r2 + " 0 1,1 0," + (-r2)
+            + "A" + r2 + "," + r2 + " 0 1,1 0," + r2
+            + "M0," + r1
+            + "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
+            + "A" + r1 + "," + r1 + " 0 1,1 0," + r1
+            + "Z";
+      } else {
+        p = "M0," + r2
+            + "A" + r2 + "," + r2 + " 0 1,1 0," + (-r2)
+            + "A" + r2 + "," + r2 + " 0 1,1 0," + r2
+            + "Z";
+      }
+    } else {
+      var sa = Math.min(s.startAngle, s.endAngle),
+          ea = Math.max(s.startAngle, s.endAngle),
+          c1 = Math.cos(sa), c2 = Math.cos(ea),
+          s1 = Math.sin(sa), s2 = Math.sin(ea);
+      if (r1) {
+        p = "M" + r2 * c1 + "," + r2 * s1
+            + "A" + r2 + "," + r2 + " 0 "
+            + ((a < Math.PI) ? "0" : "1") + ",1 "
+            + r2 * c2 + "," + r2 * s2
+            + "L" + r1 * c2 + "," + r1 * s2
+            + "A" + r1 + "," + r1 + " 0 "
+            + ((a < Math.PI) ? "0" : "1") + ",0 "
+            + r1 * c1 + "," + r1 * s1 + "Z";
+      } else {
+        p = "M" + r2 * c1 + "," + r2 * s1
+            + "A" + r2 + "," + r2 + " 0 "
+            + ((a < Math.PI) ? "0" : "1") + ",1 "
+            + r2 * c2 + "," + r2 * s2 + "L0,0Z";
+      }
+    }
+
+    e = this.expect(e, "path", {
+        "shape-rendering": s.antialias ? null : "crispEdges",
+        "pointer-events": s.events,
+        "cursor": s.cursor,
+        "transform": "translate(" + s.left + "," + s.top + ")",
+        "d": p,
+        "fill": fill.color,
+        "fill-rule": "evenodd",
+        "fill-opacity": fill.opacity || null,
+        "stroke": stroke.color,
+        "stroke-opacity": stroke.opacity || null,
+        "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
+      });
+    e = this.append(e, scenes, i);
+  }
+  return e;
+};
+/**
+ * Constructs a new mark with default properties. Marks, with the exception of
+ * the root panel, are not typically constructed directly; instead, they are
+ * added to a panel or an existing mark via {@link pv.Mark#add}.
+ *
+ * @class Represents a data-driven graphical mark. The <tt>Mark</tt> class is
+ * the base class for all graphical marks in Protovis; it does not provide any
+ * specific rendering functionality, but together with {@link Panel} establishes
+ * the core framework.
+ *
+ * <p>Concrete mark types include familiar visual elements such as bars, lines
+ * and labels. Although a bar mark may be used to construct a bar chart, marks
+ * know nothing about charts; it is only through their specification and
+ * composition that charts are produced. These building blocks permit many
+ * combinatorial possibilities.
+ *
+ * <p>Marks are associated with <b>data</b>: a mark is generated once per
+ * associated datum, mapping the datum to visual <b>properties</b> such as
+ * position and color. Thus, a single mark specification represents a set of
+ * visual elements that share the same data and visual encoding. The type of
+ * mark defines the names of properties and their meaning. A property may be
+ * static, ignoring the associated datum and returning a constant; or, it may be
+ * dynamic, derived from the associated datum or index. Such dynamic encodings
+ * can be specified succinctly using anonymous functions. Special properties
+ * called event handlers can be registered to add interactivity.
+ *
+ * <p>Protovis uses <b>inheritance</b> to simplify the specification of related
+ * marks: a new mark can be derived from an existing mark, inheriting its
+ * properties. The new mark can then override properties to specify new
+ * behavior, potentially in terms of the old behavior. In this way, the old mark
+ * serves as the <b>prototype</b> for the new mark. Most mark types share the
+ * same basic properties for consistency and to facilitate inheritance.
+ *
+ * <p>The prioritization of redundant properties is as follows:<ol>
+ *
+ * <li>If the <tt>width</tt> property is not specified (i.e., null), its value
+ * is the width of the parent panel, minus this mark's left and right margins;
+ * the left and right margins are zero if not specified.
+ *
+ * <li>Otherwise, if the <tt>right</tt> margin is not specified, its value is
+ * the width of the parent panel, minus this mark's width and left margin; the
+ * left margin is zero if not specified.
+ *
+ * <li>Otherwise, if the <tt>left</tt> property is not specified, its value is
+ * the width of the parent panel, minus this mark's width and the right margin.
+ *
+ * </ol>This prioritization is then duplicated for the <tt>height</tt>,
+ * <tt>bottom</tt> and <tt>top</tt> properties, respectively.
+ *
+ * <p>While most properties are <i>variable</i>, some mark types, such as lines
+ * and areas, generate a single visual element rather than a distinct visual
+ * element per datum. With these marks, some properties may be <b>fixed</b>.
+ * Fixed properties can vary per mark, but not <i>per datum</i>! These
+ * properties are evaluated solely for the first (0-index) datum, and typically
+ * are specified as a constant. However, it is valid to use a function if the
+ * property varies between panels or is dynamically generated.
+ *
+ * <p>See also the <a href="../../api/">Protovis guide</a>.
+ */
+pv.Mark = function() {
+  /*
+   * TYPE 0 constant defs
+   * TYPE 1 function defs
+   * TYPE 2 constant properties
+   * TYPE 3 function properties
+   * in order of evaluation!
+   */
+  this.$properties = [];
+  this.$handlers = {};
+};
+
+/** @private Records which properties are defined on this mark type. */
+pv.Mark.prototype.properties = {};
+
+/** @private Records the cast function for each property. */
+pv.Mark.cast = {};
+
+/**
+ * @private Defines and registers a property method for the property with the
+ * given name.  This method should be called on a mark class prototype to define
+ * each exposed property. (Note this refers to the JavaScript
+ * <tt>prototype</tt>, not the Protovis mark prototype, which is the {@link
+ * #proto} field.)
+ *
+ * <p>The created property method supports several modes of invocation: <ol>
+ *
+ * <li>If invoked with a <tt>Function</tt> argument, this function is evaluated
+ * for each associated datum. The return value of the function is used as the
+ * computed property value. The context of the function (<tt>this</tt>) is this
+ * mark. The arguments to the function are the associated data of this mark and
+ * any enclosing panels. For example, a linear encoding of numerical data to
+ * height is specified as
+ *
+ * <pre>m.height(function(d) d * 100);</pre>
+ *
+ * The expression <tt>d * 100</tt> will be evaluated for the height property of
+ * each mark instance. The return value of the property method (e.g.,
+ * <tt>m.height</tt>) is this mark (<tt>m</tt>)).<p>
+ *
+ * <li>If invoked with a non-function argument, the property is treated as a
+ * constant. The return value of the property method (e.g., <tt>m.height</tt>)
+ * is this mark.<p>
+ *
+ * <li>If invoked with no arguments, the computed property value for the current
+ * mark instance in the scene graph is returned. This facilitates <i>property
+ * chaining</i>, where one mark's properties are defined in terms of another's.
+ * For example, to offset a mark's location from its prototype, you might say
+ *
+ * <pre>m.top(function() this.proto.top() + 10);</pre>
+ *
+ * Note that the index of the mark being evaluated (in the above example,
+ * <tt>this.proto</tt>) is inherited from the <tt>Mark</tt> class and set by
+ * this mark. So, if the fifth element's top property is being evaluated, the
+ * fifth instance of <tt>this.proto</tt> will similarly be queried for the value
+ * of its top property. If the mark being evaluated has a different number of
+ * instances, or its data is unrelated, the behavior of this method is
+ * undefined. In these cases it may be better to index the <tt>scene</tt>
+ * explicitly to specify the exact instance.
+ *
+ * </ol><p>Property names should follow standard JavaScript method naming
+ * conventions, using lowerCamel-style capitalization.
+ *
+ * <p>In addition to creating the property method, every property is registered
+ * in the {@link #properties} map on the <tt>prototype</tt>. Although this is an
+ * instance field, it is considered immutable and shared by all instances of a
+ * given mark type. The <tt>properties</tt> map can be queried to see if a mark
+ * type defines a particular property, such as width or height.
+ *
+ * @param {string} name the property name.
+ * @param {function} [cast] the cast function for this property.
+ */
+pv.Mark.prototype.property = function(name, cast) {
+  if (!this.hasOwnProperty("properties")) {
+    this.properties = pv.extend(this.properties);
+  }
+  this.properties[name] = true;
+
+  /*
+   * Define the setter-getter globally, since the default behavior should be the
+   * same for all properties, and since the Protovis inheritance chain is
+   * independent of the JavaScript inheritance chain. For example, anchors
+   * define a "name" property that is evaluated on derived marks, even though
+   * those marks don't normally have a name.
+   */
+  pv.Mark.prototype.propertyMethod(name, false, pv.Mark.cast[name] = cast);
+  return this;
+};
+
+/**
+ * @private Defines a setter-getter for the specified property.
+ *
+ * <p>If a cast function has been assigned to the specified property name, the
+ * property function is wrapped by the cast function, or, if a constant is
+ * specified, the constant is immediately cast. Note, however, that if the
+ * property value is null, the cast function is not invoked.
+ *
+ * @param {string} name the property name.
+ * @param {boolean} [def] whether is a property or a def.
+ * @param {function} [cast] the cast function for this property.
+ */
+pv.Mark.prototype.propertyMethod = function(name, def, cast) {
+  if (!cast) cast = pv.Mark.cast[name];
+  this[name] = function(v) {
+
+      /* If this is a def, use it rather than property. */
+      if (def && this.scene) {
+        var defs = this.scene.defs;
+        if (arguments.length) {
+          defs[name] = {
+            id: (v == null) ? 0 : pv.id(),
+            value: ((v != null) && cast) ? cast(v) : v
+          };
+          return this;
+        }
+        return defs[name] ? defs[name].value : null;
+      }
+
+      /* If arguments are specified, set the property value. */
+      if (arguments.length) {
+        var type = !def << 1 | (typeof v == "function");
+        this.propertyValue(name, (type & 1 && cast) ? function() {
+            var x = v.apply(this, arguments);
+            return (x != null) ? cast(x) : null;
+          } : (((v != null) && cast) ? cast(v) : v)).type = type;
+        return this;
+      }
+
+      return this.instance()[name];
+    };
+};
+
+/** @private Sets the value of the property <i>name</i> to <i>v</i>. */
+pv.Mark.prototype.propertyValue = function(name, v) {
+  var properties = this.$properties, p = {name: name, id: pv.id(), value: v};
+  for (var i = 0; i < properties.length; i++) {
+    if (properties[i].name == name) {
+      properties.splice(i, 1);
+      break;
+    }
+  }
+  properties.push(p);
+  return p;
+};
+
+/* Define all global properties. */
+pv.Mark.prototype
+    .property("data")
+    .property("visible", Boolean)
+    .property("left", Number)
+    .property("right", Number)
+    .property("top", Number)
+    .property("bottom", Number)
+    .property("cursor", String)
+    .property("title", String)
+    .property("reverse", Boolean)
+    .property("antialias", Boolean)
+    .property("events", String);
+
+/**
+ * The mark type; a lower camelCase name. The type name controls rendering
+ * behavior, and unless the rendering engine is extended, must be one of the
+ * built-in concrete mark types: area, bar, dot, image, label, line, panel,
+ * rule, or wedge.
+ *
+ * @type string
+ * @name pv.Mark.prototype.type
+ */
+
+/**
+ * The mark prototype, possibly undefined, from which to inherit property
+ * functions. The mark prototype is not necessarily of the same type as this
+ * mark. Any properties defined on this mark will override properties inherited
+ * either from the prototype or from the type-specific defaults.
+ *
+ * @type pv.Mark
+ * @name pv.Mark.prototype.proto
+ */
+
+/**
+ * The enclosing parent panel. The parent panel is generally undefined only for
+ * the root panel; however, it is possible to create "offscreen" marks that are
+ * used only for inheritance purposes.
+ *
+ * @type pv.Panel
+ * @name pv.Mark.prototype.parent
+ */
+
+/**
+ * The child index. -1 if the enclosing parent panel is null; otherwise, the
+ * zero-based index of this mark into the parent panel's <tt>children</tt> array.
+ *
+ * @type number
+ */
+pv.Mark.prototype.childIndex = -1;
+
+/**
+ * The mark index. The value of this field depends on which instance (i.e.,
+ * which element of the data array) is currently being evaluated. During the
+ * build phase, the index is incremented over each datum; when handling events,
+ * the index is set to the instance that triggered the event.
+ *
+ * @type number
+ */
+pv.Mark.prototype.index = -1;
+
+/**
+ * The current scale factor, based on any enclosing transforms. The current
+ * scale can be used to create scale-independent graphics. For example, to
+ * define a dot that has a radius of 10 irrespective of any zooming, say:
+ *
+ * <pre>dot.radius(function() 10 / this.scale)</pre>
+ *
+ * Note that the stroke width and font size are defined irrespective of scale
+ * (i.e., in screen space) already. Also note that when a transform is applied
+ * to a panel, the scale affects only the child marks, not the panel itself.
+ *
+ * @type number
+ * @see pv.Panel#transform
+ */
+pv.Mark.prototype.scale = 1;
+
+/**
+ * @private The scene graph. The scene graph is an array of objects; each object
+ * (or "node") corresponds to an instance of this mark and an element in the
+ * data array. The scene graph can be traversed to lookup previously-evaluated
+ * properties.
+ *
+ * @name pv.Mark.prototype.scene
+ */
+
+/**
+ * The root parent panel. This may be undefined for "offscreen" marks that are
+ * created for inheritance purposes only.
+ *
+ * @type pv.Panel
+ * @name pv.Mark.prototype.root
+ */
+
+/**
+ * The data property; an array of objects. The size of the array determines the
+ * number of marks that will be instantiated; each element in the array will be
+ * passed to property functions to compute the property values. Typically, the
+ * data property is specified as a constant array, such as
+ *
+ * <pre>m.data([1, 2, 3, 4, 5]);</pre>
+ *
+ * However, it is perfectly acceptable to define the data property as a
+ * function. This function might compute the data dynamically, allowing
+ * different data to be used per enclosing panel. For instance, in the stacked
+ * area graph example (see {@link #scene}), the data function on the area mark
+ * dereferences each series.
+ *
+ * @type array
+ * @name pv.Mark.prototype.data
+ */
+
+/**
+ * The visible property; a boolean determining whether or not the mark instance
+ * is visible. If a mark instance is not visible, its other properties will not
+ * be evaluated. Similarly, for panels no child marks will be rendered.
+ *
+ * @type boolean
+ * @name pv.Mark.prototype.visible
+ */
+
+/**
+ * The left margin; the distance, in pixels, between the left edge of the
+ * enclosing panel and the left edge of this mark. Note that in some cases this
+ * property may be redundant with the right property, or with the conjunction of
+ * right and width.
+ *
+ * @type number
+ * @name pv.Mark.prototype.left
+ */
+
+/**
+ * The right margin; the distance, in pixels, between the right edge of the
+ * enclosing panel and the right edge of this mark. Note that in some cases this
+ * property may be redundant with the left property, or with the conjunction of
+ * left and width.
+ *
+ * @type number
+ * @name pv.Mark.prototype.right
+ */
+
+/**
+ * The top margin; the distance, in pixels, between the top edge of the
+ * enclosing panel and the top edge of this mark. Note that in some cases this
+ * property may be redundant with the bottom property, or with the conjunction
+ * of bottom and height.
+ *
+ * @type number
+ * @name pv.Mark.prototype.top
+ */
+
+/**
+ * The bottom margin; the distance, in pixels, between the bottom edge of the
+ * enclosing panel and the bottom edge of this mark. Note that in some cases
+ * this property may be redundant with the top property, or with the conjunction
+ * of top and height.
+ *
+ * @type number
+ * @name pv.Mark.prototype.bottom
+ */
+
+/**
+ * The cursor property; corresponds to the CSS cursor property. This is
+ * typically used in conjunction with event handlers to indicate interactivity.
+ *
+ * @type string
+ * @name pv.Mark.prototype.cursor
+ * @see <a href="http://www.w3.org/TR/CSS2/ui.html#propdef-cursor">CSS2 cursor</a>
+ */
+
+/**
+ * The title property; corresponds to the HTML/SVG title property, allowing the
+ * general of simple plain text tooltips.
+ *
+ * @type string
+ * @name pv.Mark.prototype.title
+ */
+
+/**
+ * The events property; corresponds to the SVG pointer-events property,
+ * specifying how the mark should participate in mouse events. The default value
+ * is "painted". Supported values are:
+ *
+ * <p>"painted": The given mark may receive events when the mouse is over a
+ * "painted" area. The painted areas are the interior (i.e., fill) of the mark
+ * if a 'fillStyle' is specified, and the perimeter (i.e., stroke) of the mark
+ * if a 'strokeStyle' is specified.
+ *
+ * <p>"all": The given mark may receive events when the mouse is over either the
+ * interior (i.e., fill) or the perimeter (i.e., stroke) of the mark, regardless
+ * of the specified fillStyle and strokeStyle.
+ *
+ * <p>"none": The given mark may not receive events.
+ *
+ * @type string
+ * @name pv.Mark.prototype.events
+ */
+
+/**
+ * The reverse property; a boolean determining whether marks are ordered from
+ * front-to-back or back-to-front. SVG does not support explicit z-ordering;
+ * shapes are rendered in the order they appear. Thus, by default, marks are
+ * rendered in data order. Setting the reverse property to false reverses the
+ * order in which they are rendered; however, the properties are still evaluated
+ * (i.e., built) in forward order.
+ *
+ * @type boolean
+ * @name pv.Mark.prototype.reverse
+ */
+
+/**
+ * Default properties for all mark types. By default, the data array is the
+ * parent data as a single-element array; if the data property is not specified,
+ * this causes each mark to be instantiated as a singleton with the parents
+ * datum. The visible property is true by default, and the reverse property is
+ * false.
+ *
+ * @type pv.Mark
+ */
+pv.Mark.prototype.defaults = new pv.Mark()
+    .data(function(d) { return [d]; })
+    .visible(true)
+    .antialias(true)
+    .events("painted");
+
+/**
+ * Sets the prototype of this mark to the specified mark. Any properties not
+ * defined on this mark may be inherited from the specified prototype mark, or
+ * its prototype, and so on. The prototype mark need not be the same type of
+ * mark as this mark. (Note that for inheritance to be useful, properties with
+ * the same name on different mark types should have equivalent meaning.)
+ *
+ * @param {pv.Mark} proto the new prototype.
+ * @returns {pv.Mark} this mark.
+ * @see #add
+ */
+pv.Mark.prototype.extend = function(proto) {
+  this.proto = proto;
+  return this;
+};
+
+/**
+ * Adds a new mark of the specified type to the enclosing parent panel, whilst
+ * simultaneously setting the prototype of the new mark to be this mark.
+ *
+ * @param {function} type the type of mark to add; a constructor, such as
+ * <tt>pv.Bar</tt>.
+ * @returns {pv.Mark} the new mark.
+ * @see #extend
+ */
+pv.Mark.prototype.add = function(type) {
+  return this.parent.add(type).extend(this);
+};
+
+/**
+ * Defines a custom property on this mark. Custom properties are currently
+ * fixed, in that they are initialized once per mark set (i.e., per parent panel
+ * instance). Custom properties can be used to store local state for the mark,
+ * such as data needed by other properties (e.g., a custom scale) or interaction
+ * state.
+ *
+ * <p>WARNING We plan on changing this feature in a future release to define
+ * standard properties, as opposed to <i>fixed</i> properties that behave
+ * idiosyncratically within event handlers. Furthermore, we recommend storing
+ * state in an external data structure, rather than tying it to the
+ * visualization specification as with defs.
+ *
+ * @param {string} name the name of the local variable.
+ * @param {function} [v] an optional initializer; may be a constant or a
+ * function.
+ */
+pv.Mark.prototype.def = function(name, v) {
+  this.propertyMethod(name, true);
+  return this[name](arguments.length > 1 ? v : null);
+};
+
+/**
+ * Returns an anchor with the specified name. All marks support the five
+ * standard anchor names:<ul>
+ *
+ * <li>top
+ * <li>left
+ * <li>center
+ * <li>bottom
+ * <li>right
+ *
+ * </ul>In addition to positioning properties (left, right, top bottom), the
+ * anchors support text rendering properties (text-align, text-baseline). Text is
+ * rendered to appear inside the mark by default.
+ *
+ * <p>To facilitate stacking, anchors are defined in terms of their opposite
+ * edge. For example, the top anchor defines the bottom property, such that the
+ * mark extends upwards; the bottom anchor instead defines the top property,
+ * such that the mark extends downwards. See also {@link pv.Layout.Stack}.
+ *
+ * <p>While anchor names are typically constants, the anchor name is a true
+ * property, which means you can specify a function to compute the anchor name
+ * dynamically. See the {@link pv.Anchor#name} property for details.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor} the new anchor.
+ */
+pv.Mark.prototype.anchor = function(name) {
+  var target = this, scene;
+
+  /* Default anchor name. */
+  if (!name) name = "center";
+
+  /** @private Find the instances of target that match source. */
+  function instances(source) {
+    var mark = target, index = [];
+
+    /* Mirrored descent. */
+    while (!(scene = mark.scene)) {
+      source = source.parent;
+      index.push({index: source.index, childIndex: mark.childIndex});
+      mark = mark.parent;
+    }
+    while (index.length) {
+      var i = index.pop();
+      scene = scene[i.index].children[i.childIndex];
+    }
+
+    /*
+     * When the anchor target is also an ancestor, as in the case of adding
+     * to a panel anchor, only generate one instance per panel. Also, set
+     * the margins to zero, since they are offset by the enclosing panel.
+     */
+    if (target.hasOwnProperty("index")) {
+      var s = pv.extend(scene[target.index]);
+      s.right = s.top = s.left = s.bottom = 0;
+      return [s];
+    }
+    return scene;
+  }
+
+  return new pv.Anchor(this)
+    .name(name)
+    .def("$mark.anchor", function() {
+        scene = this.scene.target = instances(this);
+      })
+    .data(function() {
+        return scene.map(function(s) { return s.data; });
+      })
+    .visible(function() {
+        return scene[this.index].visible;
+      })
+    .left(function() {
+        var s = scene[this.index], w = s.width || 0;
+        switch (this.name()) {
+          case "bottom":
+          case "top":
+          case "center": return s.left + w / 2;
+          case "left": return null;
+        }
+        return s.left + w;
+      })
+    .top(function() {
+        var s = scene[this.index], h = s.height || 0;
+        switch (this.name()) {
+          case "left":
+          case "right":
+          case "center": return s.top + h / 2;
+          case "top": return null;
+        }
+        return s.top + h;
+      })
+    .right(function() {
+        var s = scene[this.index];
+        return this.name() == "left" ? s.right + (s.width || 0) : null;
+      })
+    .bottom(function() {
+        var s = scene[this.index];
+        return this.name() == "top" ? s.bottom + (s.height || 0) : null;
+      })
+    .textAlign(function() {
+        switch (this.name()) {
+          case "bottom":
+          case "top":
+          case "center": return "center";
+          case "right": return "right";
+        }
+        return "left";
+      })
+    .textBaseline(function() {
+        switch (this.name()) {
+          case "right":
+          case "left":
+          case "center": return "middle";
+          case "top": return "top";
+        }
+        return "bottom";
+      });
+};
+
+/**
+ * Returns the anchor target of this mark, if it is derived from an anchor;
+ * otherwise returns null. For example, if a label is derived from a bar anchor,
+ *
+ * <pre>bar.anchor("top").add(pv.Label);</pre>
+ *
+ * then property functions on the label can refer to the bar via the
+ * <tt>anchorTarget</tt> method. This method is also useful for mark types
+ * defining properties on custom anchors.
+ *
+ * @returns {pv.Mark} the anchor target of this mark; possibly null.
+ */
+pv.Mark.prototype.anchorTarget = function() {
+  return this.proto.anchorTarget();
+};
+
+/**
+ * Alias for setting the left, right, top and bottom properties simultaneously.
+ *
+ * @see #left
+ * @see #right
+ * @see #top
+ * @see #bottom
+ * @returns {pv.Mark} this.
+ */
+pv.Mark.prototype.margin = function(n) {
+  return this.left(n).right(n).top(n).bottom(n);
+};
+
+/**
+ * @private Returns the current instance of this mark in the scene graph. This
+ * is typically equivalent to <tt>this.scene[this.index]</tt>, however if the
+ * scene or index is unset, the default instance of the mark is returned. If no
+ * default is set, the default is the last instance. Similarly, if the scene or
+ * index of the parent panel is unset, the default instance of this mark in the
+ * last instance of the enclosing panel is returned, and so on.
+ *
+ * @returns a node in the scene graph.
+ */
+pv.Mark.prototype.instance = function(defaultIndex) {
+  var scene = this.scene || this.parent.instance(-1).children[this.childIndex],
+      index = !arguments.length || this.hasOwnProperty("index") ? this.index : defaultIndex;
+  return scene[index < 0 ? scene.length - 1 : index];
+};
+
+/**
+ * @private Returns the first instance of this mark in the scene graph. This
+ * method can only be called when the mark is bound to the scene graph (for
+ * example, from an event handler, or within a property function).
+ *
+ * @returns a node in the scene graph.
+ */
+pv.Mark.prototype.first = function() {
+  return this.scene[0];
+};
+
+/**
+ * @private Returns the last instance of this mark in the scene graph. This
+ * method can only be called when the mark is bound to the scene graph (for
+ * example, from an event handler, or within a property function). In addition,
+ * note that mark instances are built sequentially, so the last instance of this
+ * mark may not yet be constructed.
+ *
+ * @returns a node in the scene graph.
+ */
+pv.Mark.prototype.last = function() {
+  return this.scene[this.scene.length - 1];
+};
+
+/**
+ * @private Returns the previous instance of this mark in the scene graph, or
+ * null if this is the first instance.
+ *
+ * @returns a node in the scene graph, or null.
+ */
+pv.Mark.prototype.sibling = function() {
+  return (this.index == 0) ? null : this.scene[this.index - 1];
+};
+
+/**
+ * @private Returns the current instance in the scene graph of this mark, in the
+ * previous instance of the enclosing parent panel. May return null if this
+ * instance could not be found.
+ *
+ * @returns a node in the scene graph, or null.
+ */
+pv.Mark.prototype.cousin = function() {
+  var p = this.parent, s = p && p.sibling();
+  return (s && s.children) ? s.children[this.childIndex][this.index] : null;
+};
+
+/**
+ * Renders this mark, including recursively rendering all child marks if this is
+ * a panel. This method finds all instances of this mark and renders them. This
+ * method descends recursively to the level of the mark to be rendered, finding
+ * all visible instances of the mark. After the marks are rendered, the scene
+ * and index attributes are removed from the mark to restore them to a clean
+ * state.
+ *
+ * <p>If an enclosing panel has an index property set (as is the case inside in
+ * an event handler), then only instances of this mark inside the given instance
+ * of the panel will be rendered; otherwise, all visible instances of the mark
+ * will be rendered.
+ */
+pv.Mark.prototype.render = function() {
+  var parent = this.parent,
+      stack = pv.Mark.stack;
+
+  /* For the first render, take it from the top. */
+  if (parent && !this.root.scene) {
+    this.root.render();
+    return;
+  }
+
+  /* Record the path to this mark. */
+  var indexes = [];
+  for (var mark = this; mark.parent; mark = mark.parent) {
+    indexes.unshift(mark.childIndex);
+  }
+
+  /** @private */
+  function render(mark, depth, scale) {
+    mark.scale = scale;
+    if (depth < indexes.length) {
+      stack.unshift(null);
+      if (mark.hasOwnProperty("index")) {
+        renderInstance(mark, depth, scale);
+      } else {
+        for (var i = 0, n = mark.scene.length; i < n; i++) {
+          mark.index = i;
+          renderInstance(mark, depth, scale);
+        }
+        delete mark.index;
+      }
+      stack.shift();
+    } else {
+      mark.build();
+
+      /*
+       * In the update phase, the scene is rendered by creating and updating
+       * elements and attributes in the SVG image. No properties are evaluated
+       * during the update phase; instead the values computed previously in the
+       * build phase are simply translated into SVG. The update phase is
+       * decoupled (see pv.Scene) to allow different rendering engines.
+       */
+      pv.Scene.scale = scale;
+      pv.Scene.updateAll(mark.scene);
+    }
+    delete mark.scale;
+  }
+
+  /**
+   * @private Recursively renders the current instance of the specified mark.
+   * This is slightly tricky because `index` and `scene` properties may or may
+   * not already be set; if they are set, it means we are rendering only a
+   * specific instance; if they are unset, we are rendering all instances.
+   * Furthermore, we must preserve the original context of these properties when
+   * rendering completes.
+   *
+   * <p>Another tricky aspect is that the `scene` attribute should be set for
+   * any preceding children, so as to allow property chaining. This is
+   * consistent with first-pass rendering.
+   */
+  function renderInstance(mark, depth, scale) {
+    var s = mark.scene[mark.index], i;
+    if (s.visible) {
+      var childIndex = indexes[depth],
+          child = mark.children[childIndex];
+
+      /* Set preceding child scenes. */
+      for (i = 0; i < childIndex; i++) {
+        mark.children[i].scene = s.children[i];
+      }
+
+      /* Set current child scene, if necessary. */
+      stack[0] = s.data;
+      if (child.scene) {
+        render(child, depth + 1, scale * s.transform.k);
+      } else {
+        child.scene = s.children[childIndex];
+        render(child, depth + 1, scale * s.transform.k);
+        delete child.scene;
+      }
+
+      /* Clear preceding child scenes. */
+      for (i = 0; i < childIndex; i++) {
+        delete mark.children[i].scene;
+      }
+    }
+  }
+
+  /* Bind this mark's property definitions. */
+  this.bind();
+
+  /* The render context is the first ancestor with an explicit index. */
+  while (parent && !parent.hasOwnProperty("index")) parent = parent.parent;
+
+  /* Recursively render all instances of this mark. */
+  this.context(
+      parent ? parent.scene : undefined,
+      parent ? parent.index : -1,
+      function() { render(this.root, 0, 1); });
+};
+
+/** @private Stores the current data stack. */
+pv.Mark.stack = [];
+
+/**
+ * @private In the bind phase, inherited property definitions are cached so they
+ * do not need to be queried during build.
+ */
+pv.Mark.prototype.bind = function() {
+  var seen = {}, types = [[], [], [], []], data, visible;
+
+  /** Scans the proto chain for the specified mark. */
+  function bind(mark) {
+    do {
+      var properties = mark.$properties;
+      for (var i = properties.length - 1; i >= 0 ; i--) {
+        var p = properties[i];
+        if (!(p.name in seen)) {
+          seen[p.name] = p;
+          switch (p.name) {
+            case "data": data = p; break;
+            case "visible": visible = p; break;
+            default: types[p.type].push(p); break;
+          }
+        }
+      }
+    } while (mark = mark.proto);
+  }
+
+  /* Scan the proto chain for all defined properties. */
+  bind(this);
+  bind(this.defaults);
+  types[1].reverse();
+  types[3].reverse();
+
+  /* Any undefined properties are null. */
+  var mark = this;
+  do for (var name in mark.properties) {
+    if (!(name in seen)) {
+      types[2].push(seen[name] = {name: name, type: 2, value: null});
+    }
+  } while (mark = mark.proto);
+
+  /* Define setter-getter for inherited defs. */
+  var defs = types[0].concat(types[1]);
+  for (var i = 0; i < defs.length; i++) {
+    this.propertyMethod(defs[i].name, true);
+  }
+
+  /* Setup binds to evaluate constants before functions. */
+  this.binds = {
+    properties: seen,
+    data: data,
+    defs: defs,
+    required: [visible],
+    optional: pv.blend(types)
+  };
+};
+
+/**
+ * @private Evaluates properties and computes implied properties. Properties are
+ * stored in the {@link #scene} array for each instance of this mark.
+ *
+ * <p>As marks are built recursively, the {@link #index} property is updated to
+ * match the current index into the data array for each mark. Note that the
+ * index property is only set for the mark currently being built and its
+ * enclosing parent panels. The index property for other marks is unset, but is
+ * inherited from the global <tt>Mark</tt> class prototype. This allows mark
+ * properties to refer to properties on other marks <i>in the same panel</i>
+ * conveniently; however, in general it is better to reference mark instances
+ * specifically through the scene graph rather than depending on the magical
+ * behavior of {@link #index}.
+ *
+ * <p>The root scene array has a special property, <tt>data</tt>, which stores
+ * the current data stack. The first element in this stack is the current datum,
+ * followed by the datum of the enclosing parent panel, and so on. The data
+ * stack should not be accessed directly; instead, property functions are passed
+ * the current data stack as arguments.
+ *
+ * <p>The evaluation of the <tt>data</tt> and <tt>visible</tt> properties is
+ * special. The <tt>data</tt> property is evaluated first; unlike the other
+ * properties, the data stack is from the parent panel, rather than the current
+ * mark, since the data is not defined until the data property is evaluated.
+ * The <tt>visisble</tt> property is subsequently evaluated for each instance;
+ * only if true will the {@link #buildInstance} method be called, evaluating
+ * other properties and recursively building the scene graph.
+ *
+ * <p>If this mark is being re-built, any old instances of this mark that no
+ * longer exist (because the new data array contains fewer elements) will be
+ * cleared using {@link #clearInstance}.
+ *
+ * @param parent the instance of the parent panel from the scene graph.
+ */
+pv.Mark.prototype.build = function() {
+  var scene = this.scene, stack = pv.Mark.stack;
+  if (!scene) {
+    scene = this.scene = [];
+    scene.mark = this;
+    scene.type = this.type;
+    scene.childIndex = this.childIndex;
+    if (this.parent) {
+      scene.parent = this.parent.scene;
+      scene.parentIndex = this.parent.index;
+    }
+  }
+
+  /* Evaluate defs. */
+  if (this.binds.defs.length) {
+    var defs = scene.defs;
+    if (!defs) scene.defs = defs = {};
+    for (var i = 0; i < this.binds.defs.length; i++) {
+      var p = this.binds.defs[i], d = defs[p.name];
+      if (!d || (p.id > d.id)) {
+        defs[p.name] = {
+          id: 0, // this def will be re-evaluated on next build
+          value: (p.type & 1) ? p.value.apply(this, stack) : p.value
+        };
+      }
+    }
+  }
+
+  /* Evaluate special data property. */
+  var data = this.binds.data;
+  data = data.type & 1 ? data.value.apply(this, stack) : data.value;
+
+  /* Create, update and delete scene nodes. */
+  stack.unshift(null);
+  scene.length = data.length;
+  for (var i = 0; i < data.length; i++) {
+    pv.Mark.prototype.index = this.index = i;
+    var s = scene[i];
+    if (!s) scene[i] = s = {};
+    s.data = stack[0] = data[i];
+    this.buildInstance(s);
+  }
+  pv.Mark.prototype.index = -1;
+  delete this.index;
+  stack.shift();
+
+  return this;
+};
+
+/**
+ * @private Evaluates the specified array of properties for the specified
+ * instance <tt>s</tt> in the scene graph.
+ *
+ * @param s a node in the scene graph; the instance of the mark to build.
+ * @param properties an array of properties.
+ */
+pv.Mark.prototype.buildProperties = function(s, properties) {
+  for (var i = 0, n = properties.length; i < n; i++) {
+    var p = properties[i], v = p.value; // assume case 2 (constant)
+    switch (p.type) {
+      case 0:
+      case 1: v = this.scene.defs[p.name].value; break;
+      case 3: v = v.apply(this, pv.Mark.stack); break;
+    }
+    s[p.name] = v;
+  }
+};
+
+/**
+ * @private Evaluates all of the properties for this mark for the specified
+ * instance <tt>s</tt> in the scene graph. The set of properties to evaluate is
+ * retrieved from the {@link #properties} array for this mark type (see {@link
+ * #type}).  After these properties are evaluated, any <b>implied</b> properties
+ * may be computed by the mark and set on the scene graph; see
+ * {@link #buildImplied}.
+ *
+ * <p>For panels, this method recursively builds the scene graph for all child
+ * marks as well. In general, this method should not need to be overridden by
+ * concrete mark types.
+ *
+ * @param s a node in the scene graph; the instance of the mark to build.
+ */
+pv.Mark.prototype.buildInstance = function(s) {
+  this.buildProperties(s, this.binds.required);
+  if (s.visible) {
+    this.buildProperties(s, this.binds.optional);
+    this.buildImplied(s);
+  }
+};
+
+/**
+ * @private Computes the implied properties for this mark for the specified
+ * instance <tt>s</tt> in the scene graph. Implied properties are those with
+ * dependencies on multiple other properties; for example, the width property
+ * may be implied if the left and right properties are set. This method can be
+ * overridden by concrete mark types to define new implied properties, if
+ * necessary.
+ *
+ * @param s a node in the scene graph; the instance of the mark to build.
+ */
+pv.Mark.prototype.buildImplied = function(s) {
+  var l = s.left;
+  var r = s.right;
+  var t = s.top;
+  var b = s.bottom;
+
+  /* Assume width and height are zero if not supported by this mark type. */
+  var p = this.properties;
+  var w = p.width ? s.width : 0;
+  var h = p.height ? s.height : 0;
+
+  /* Compute implied width, right and left. */
+  var width = this.parent ? this.parent.width() : (w + l + r);
+  if (w == null) {
+    w = width - (r = r || 0) - (l = l || 0);
+  } else if (r == null) {
+    r = width - w - (l = l || 0);
+  } else if (l == null) {
+    l = width - w - (r = r || 0);
+  }
+
+  /* Compute implied height, bottom and top. */
+  var height = this.parent ? this.parent.height() : (h + t + b);
+  if (h == null) {
+    h = height - (t = t || 0) - (b = b || 0);
+  } else if (b == null) {
+    b = height - h - (t = t || 0);
+  } else if (t == null) {
+    t = height - h - (b = b || 0);
+  }
+
+  s.left = l;
+  s.right = r;
+  s.top = t;
+  s.bottom = b;
+
+  /* Only set width and height if they are supported by this mark type. */
+  if (p.width) s.width = w;
+  if (p.height) s.height = h;
+
+  /* Set any null colors to pv.Color.transparent. */
+  if (p.textStyle && !s.textStyle) s.textStyle = pv.Color.transparent;
+  if (p.fillStyle && !s.fillStyle) s.fillStyle = pv.Color.transparent;
+  if (p.strokeStyle && !s.strokeStyle) s.strokeStyle = pv.Color.transparent;
+};
+
+/**
+ * Returns the current location of the mouse (cursor) relative to this mark's
+ * parent. The <i>x</i> coordinate corresponds to the left margin, while the
+ * <i>y</i> coordinate corresponds to the top margin.
+ *
+ * @returns {pv.Vector} the mouse location.
+ */
+pv.Mark.prototype.mouse = function() {
+
+  /* Compute xy-coordinates relative to the panel. */
+  var x = pv.event.pageX || 0,
+      y = pv.event.pageY || 0,
+      n = this.root.canvas();
+  do {
+    x -= n.offsetLeft;
+    y -= n.offsetTop;
+  } while (n = n.offsetParent);
+
+  /* Compute the inverse transform of all enclosing panels. */
+  var t = pv.Transform.identity,
+      p = this.properties.transform ? this : this.parent,
+      pz = [];
+  do { pz.push(p); } while (p = p.parent);
+  while (p = pz.pop()) t = t.translate(p.left(), p.top()).times(p.transform());
+  t = t.invert();
+
+  return pv.vector(x * t.k + t.x, y * t.k + t.y);
+};
+
+/**
+ * Registers an event handler for the specified event type with this mark. When
+ * an event of the specified type is triggered, the specified handler will be
+ * invoked. The handler is invoked in a similar method to property functions:
+ * the context is <tt>this</tt> mark instance, and the arguments are the full
+ * data stack. Event handlers can use property methods to manipulate the display
+ * properties of the mark:
+ *
+ * <pre>m.event("click", function() this.fillStyle("red"));</pre>
+ *
+ * Alternatively, the external data can be manipulated and the visualization
+ * redrawn:
+ *
+ * <pre>m.event("click", function(d) {
+ *     data = all.filter(function(k) k.name == d);
+ *     vis.render();
+ *   });</pre>
+ *
+ * The return value of the event handler determines which mark gets re-rendered.
+ * Use defs ({@link #def}) to set temporary state from event handlers.
+ *
+ * <p>The complete set of event types is defined by SVG; see the reference
+ * below. The set of supported event types is:<ul>
+ *
+ * <li>click
+ * <li>mousedown
+ * <li>mouseup
+ * <li>mouseover
+ * <li>mousemove
+ * <li>mouseout
+ *
+ * </ul>Since Protovis does not specify any concept of focus, it does not
+ * support key events; these should be handled outside the visualization using
+ * standard JavaScript. In the future, support for interaction may be extended
+ * to support additional event types, particularly those most relevant to
+ * interactive visualization, such as selection.
+ *
+ * <p>TODO In the current implementation, event handlers are not inherited from
+ * prototype marks. They must be defined explicitly on each interactive mark. In
+ * addition, only one event handler for a given event type can be defined; when
+ * specifying multiple event handlers for the same type, only the last one will
+ * be used.
+ *
+ * @see <a href="http://www.w3.org/TR/SVGTiny12/interact.html#SVGEvents">SVG events</a>
+ * @param {string} type the event type.
+ * @param {function} handler the event handler.
+ * @returns {pv.Mark} this.
+ */
+pv.Mark.prototype.event = function(type, handler) {
+  this.$handlers[type] = pv.functor(handler);
+  return this;
+};
+
+/** @private Evaluates the function <i>f</i> with the specified context. */
+pv.Mark.prototype.context = function(scene, index, f) {
+  var proto = pv.Mark.prototype,
+      stack = pv.Mark.stack,
+      oscene = pv.Mark.scene,
+      oindex = proto.index;
+
+  /** @private Sets the context. */
+  function apply(scene, index) {
+    pv.Mark.scene = scene;
+    proto.index = index;
+    if (!scene) return;
+
+    var that = scene.mark,
+        mark = that,
+        ancestors = [];
+
+    /* Set ancestors' scene and index; populate data stack. */
+    do {
+      ancestors.push(mark);
+      stack.push(scene[index].data);
+      mark.index = index;
+      mark.scene = scene;
+      index = scene.parentIndex;
+      scene = scene.parent;
+    } while (mark = mark.parent);
+
+    /* Set ancestors' scale; requires top-down. */
+    for (var i = ancestors.length - 1, k = 1; i > 0; i--) {
+      mark = ancestors[i];
+      mark.scale = k;
+      k *= mark.scene[mark.index].transform.k;
+    }
+
+    /* Set children's scene and scale. */
+    if (that.children) for (var i = 0, n = that.children.length; i < n; i++) {
+      mark = that.children[i];
+      mark.scene = that.scene[that.index].children[i];
+      mark.scale = k;
+    }
+  }
+
+  /** @private Clears the context. */
+  function clear(scene, index) {
+    if (!scene) return;
+    var that = scene.mark,
+        mark;
+
+    /* Reset children. */
+    if (that.children) for (var i = 0, n = that.children.length; i < n; i++) {
+      mark = that.children[i];
+      delete mark.scene;
+      delete mark.scale;
+    }
+
+    /* Reset ancestors. */
+    mark = that;
+    do {
+      stack.pop();
+      if (mark.parent) {
+        delete mark.scene;
+        delete mark.scale;
+      }
+      delete mark.index;
+    } while (mark = mark.parent);
+  }
+
+  /* Context switch, invoke the function, then switch back. */
+  clear(oscene, oindex);
+  apply(scene, index);
+  try {
+    f.apply(this, stack);
+  } finally {
+    clear(scene, index);
+    apply(oscene, oindex);
+  }
+};
+
+/** @private Execute the event listener, then re-render. */
+pv.Mark.dispatch = function(type, scene, index) {
+  var m = scene.mark, p = scene.parent, l = m.$handlers[type];
+  if (!l) return p && pv.Mark.dispatch(type, p, scene.parentIndex);
+  m.context(scene, index, function() {
+      m = l.apply(m, pv.Mark.stack);
+      if (m && m.render) m.render();
+    });
+  return true;
+};
+/**
+ * Constructs a new mark anchor with default properties.
+ *
+ * @class Represents an anchor on a given mark. An anchor is itself a mark, but
+ * without a visual representation. It serves only to provide useful default
+ * properties that can be inherited by other marks. Each type of mark can define
+ * any number of named anchors for convenience. If the concrete mark type does
+ * not define an anchor implementation specifically, one will be inherited from
+ * the mark's parent class.
+ *
+ * <p>For example, the bar mark provides anchors for its four sides: left,
+ * right, top and bottom. Adding a label to the top anchor of a bar,
+ *
+ * <pre>bar.anchor("top").add(pv.Label);</pre>
+ *
+ * will render a text label on the top edge of the bar; the top anchor defines
+ * the appropriate position properties (top and left), as well as text-rendering
+ * properties for convenience (textAlign and textBaseline).
+ *
+ * <p>Note that anchors do not <i>inherit</i> from their targets; the positional
+ * properties are copied from the scene graph, which guarantees that the anchors
+ * are positioned correctly, even if the positional properties are not defined
+ * deterministically. (In addition, it also improves performance by avoiding
+ * re-evaluating expensive properties.) If you want the anchor to inherit from
+ * the target, use {@link pv.Mark#extend} before adding. For example:
+ *
+ * <pre>bar.anchor("top").extend(bar).add(pv.Label);</pre>
+ *
+ * The anchor defines it's own positional properties, but other properties (such
+ * as the title property, say) can be inherited using the above idiom. Also note
+ * that you can override positional properties in the anchor for custom
+ * behavior.
+ *
+ * @extends pv.Mark
+ * @param {pv.Mark} target the anchor target.
+ */
+pv.Anchor = function(target) {
+  pv.Mark.call(this);
+  this.target = target;
+  this.parent = target.parent;
+};
+
+pv.Anchor.prototype = pv.extend(pv.Mark)
+    .property("name", String);
+
+/**
+ * The anchor name. The set of supported anchor names is dependent on the
+ * concrete mark type; see the mark type for details. For example, bars support
+ * left, right, top and bottom anchors.
+ *
+ * <p>While anchor names are typically constants, the anchor name is a true
+ * property, which means you can specify a function to compute the anchor name
+ * dynamically. For instance, if you wanted to alternate top and bottom anchors,
+ * saying
+ *
+ * <pre>m.anchor(function() (this.index % 2) ? "top" : "bottom").add(pv.Dot);</pre>
+ *
+ * would have the desired effect.
+ *
+ * @type string
+ * @name pv.Anchor.prototype.name
+ */
+
+/**
+ * Returns the anchor target of this mark, if it is derived from an anchor;
+ * otherwise returns null. For example, if a label is derived from a bar anchor,
+ *
+ * <pre>bar.anchor("top").add(pv.Label);</pre>
+ *
+ * then property functions on the label can refer to the bar via the
+ * <tt>anchorTarget</tt> method. This method is also useful for mark types
+ * defining properties on custom anchors.
+ *
+ * @returns {pv.Mark} the anchor target of this mark; possibly null.
+ */
+pv.Anchor.prototype.anchorTarget = function() {
+  return this.target;
+};
+/**
+ * Constructs a new area mark with default properties. Areas are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents an area mark: the solid area between two series of
+ * connected line segments. Unsurprisingly, areas are used most frequently for
+ * area charts.
+ *
+ * <p>Just as a line represents a polyline, the <tt>Area</tt> mark type
+ * represents a <i>polygon</i>. However, an area is not an arbitrary polygon;
+ * vertices are paired either horizontally or vertically into parallel
+ * <i>spans</i>, and each span corresponds to an associated datum. Either the
+ * width or the height must be specified, but not both; this determines whether
+ * the area is horizontally-oriented or vertically-oriented.  Like lines, areas
+ * can be stroked and filled with arbitrary colors.
+ *
+ * <p>See also the <a href="../../api/Area.html">Area guide</a>.
+ *
+ * @extends pv.Mark
+ */
+pv.Area = function() {
+  pv.Mark.call(this);
+};
+
+pv.Area.prototype = pv.extend(pv.Mark)
+    .property("width", Number)
+    .property("height", Number)
+    .property("lineWidth", Number)
+    .property("strokeStyle", pv.color)
+    .property("fillStyle", pv.color)
+    .property("segmented", Boolean)
+    .property("interpolate", String)
+    .property("tension", Number);
+
+pv.Area.prototype.type = "area";
+
+/**
+ * The width of a given span, in pixels; used for horizontal spans. If the width
+ * is specified, the height property should be 0 (the default). Either the top
+ * or bottom property should be used to space the spans vertically, typically as
+ * a multiple of the index.
+ *
+ * @type number
+ * @name pv.Area.prototype.width
+ */
+
+/**
+ * The height of a given span, in pixels; used for vertical spans. If the height
+ * is specified, the width property should be 0 (the default). Either the left
+ * or right property should be used to space the spans horizontally, typically
+ * as a multiple of the index.
+ *
+ * @type number
+ * @name pv.Area.prototype.height
+ */
+
+/**
+ * The width of stroked lines, in pixels; used in conjunction with
+ * <tt>strokeStyle</tt> to stroke the perimeter of the area. Unlike the
+ * {@link Line} mark type, the entire perimeter is stroked, rather than just one
+ * edge. The default value of this property is 1.5, but since the default stroke
+ * style is null, area marks are not stroked by default.
+ *
+ * <p>This property is <i>fixed</i> for non-segmented areas. See
+ * {@link pv.Mark}.
+ *
+ * @type number
+ * @name pv.Area.prototype.lineWidth
+ */
+
+/**
+ * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
+ * stroke the perimeter of the area. Unlike the {@link Line} mark type, the
+ * entire perimeter is stroked, rather than just one edge. The default value of
+ * this property is null, meaning areas are not stroked by default.
+ *
+ * <p>This property is <i>fixed</i> for non-segmented areas. See
+ * {@link pv.Mark}.
+ *
+ * @type string
+ * @name pv.Area.prototype.strokeStyle
+ * @see pv.color
+ */
+
+/**
+ * The area fill style; if non-null, the interior of the polygon forming the
+ * area is filled with the specified color. The default value of this property
+ * is a categorical color.
+ *
+ * <p>This property is <i>fixed</i> for non-segmented areas. See
+ * {@link pv.Mark}.
+ *
+ * @type string
+ * @name pv.Area.prototype.fillStyle
+ * @see pv.color
+ */
+
+/**
+ * Whether the area is segmented; whether variations in fill style, stroke
+ * style, and the other properties are treated as fixed. Rendering segmented
+ * areas is noticeably slower than non-segmented areas.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type boolean
+ * @name pv.Area.prototype.segmented
+ */
+
+/**
+ * How to interpolate between values. Linear interpolation ("linear") is the
+ * default, producing a straight line between points. For piecewise constant
+ * functions (i.e., step functions), either "step-before" or "step-after" can be
+ * specified. To draw open uniform b-splines, specify "basis". To draw cardinal
+ * splines, specify "cardinal"; see also {@link #tension}.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type string
+ * @name pv.Area.prototype.interpolate
+ */
+
+/**
+ * The tension of cardinal splines; used in conjunction with
+ * interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
+ * the given tension. In some sense, the tension can be interpreted as the
+ * "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
+ * linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
+ * default value is 0.7.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type number
+ * @name pv.Area.prototype.tension
+ */
+
+/**
+ * Default properties for areas. By default, there is no stroke and the fill
+ * style is a categorical color.
+ *
+ * @type pv.Area
+ */
+pv.Area.prototype.defaults = new pv.Area()
+    .extend(pv.Mark.prototype.defaults)
+    .lineWidth(1.5)
+    .fillStyle(pv.Colors.category20().by(pv.parent))
+    .interpolate("linear")
+    .tension(.7);
+
+/** @private Sets width and height to zero if null. */
+pv.Area.prototype.buildImplied = function(s) {
+  if (s.height == null) s.height = 0;
+  if (s.width == null) s.width = 0;
+  pv.Mark.prototype.buildImplied.call(this, s);
+};
+
+/** @private Records which properties may be fixed. */
+pv.Area.fixed = {
+  lineWidth: 1,
+  lineJoin: 1,
+  strokeStyle: 1,
+  fillStyle: 1,
+  segmented: 1,
+  interpolate: 1,
+  tension: 1
+};
+
+/**
+ * @private Make segmented required, such that this fixed property is always
+ * evaluated, even if the first segment is not visible. Also cache which
+ * properties are normally fixed.
+ */
+pv.Area.prototype.bind = function() {
+  pv.Mark.prototype.bind.call(this);
+  var binds = this.binds,
+      required = binds.required,
+      optional = binds.optional;
+  for (var i = 0, n = optional.length; i < n; i++) {
+    var p = optional[i];
+    p.fixed = p.name in pv.Area.fixed;
+    if (p.name == "segmented") {
+      required.push(p);
+      optional.splice(i, 1);
+      i--;
+      n--;
+    }
+  }
+
+  /* Cache the original arrays so they can be restored on build. */
+  this.binds.$required = required;
+  this.binds.$optional = optional;
+};
+
+/**
+ * @private Override the default build behavior such that fixed properties are
+ * determined dynamically, based on the value of the (always) fixed segmented
+ * property. Any fixed properties are only evaluated on the first instance,
+ * although their values are propagated to subsequent instances, so that they
+ * are available for property chaining and the like.
+ */
+pv.Area.prototype.buildInstance = function(s) {
+  var binds = this.binds;
+
+  /* Handle fixed properties on secondary instances. */
+  if (this.index) {
+    var fixed = binds.fixed;
+
+    /* Determine which properties are fixed. */
+    if (!fixed) {
+      fixed = binds.fixed = [];
+      function f(p) { return !p.fixed || (fixed.push(p), false); }
+      binds.required = binds.required.filter(f);
+      if (!this.scene[0].segmented) binds.optional = binds.optional.filter(f);
+    }
+
+    /* Copy fixed property values from the first instance. */
+    for (var i = 0, n = fixed.length; i < n; i++) {
+      var p = fixed[i].name;
+      s[p] = this.scene[0][p];
+    }
+  }
+
+  /* Evaluate all properties on the first instance. */
+  else {
+    binds.required = binds.$required;
+    binds.optional = binds.$optional;
+    binds.fixed = null;
+  }
+
+  pv.Mark.prototype.buildInstance.call(this, s);
+};
+
+/**
+ * Constructs a new area anchor with default properties. Areas support five
+ * different anchors:<ul>
+ *
+ * <li>top
+ * <li>left
+ * <li>center
+ * <li>bottom
+ * <li>right
+ *
+ * </ul>In addition to positioning properties (left, right, top bottom), the
+ * anchors support text rendering properties (text-align, text-baseline). Text
+ * is rendered to appear inside the area. The area anchor also propagates the
+ * interpolate, eccentricity, and tension properties such that an anchored area
+ * or line will match positions between control points.
+ *
+ * <p>For consistency with the other mark types, the anchor positions are
+ * defined in terms of their opposite edge. For example, the top anchor defines
+ * the bottom property, such that an area added to the top anchor grows upward.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor}
+ */
+pv.Area.prototype.anchor = function(name) {
+  var scene;
+  return pv.Mark.prototype.anchor.call(this, name)
+    .def("$area.anchor", function() {
+        scene = this.scene.target;
+      })
+    .interpolate(function() {
+       return scene[this.index].interpolate;
+      })
+    .eccentricity(function() {
+       return scene[this.index].eccentricity;
+      })
+    .tension(function() {
+        return scene[this.index].tension;
+      });
+};
+/**
+ * Constructs a new bar mark with default properties. Bars are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents a bar: an axis-aligned rectangle that can be stroked and
+ * filled. Bars are used for many chart types, including bar charts, histograms
+ * and Gantt charts. Bars can also be used as decorations, for example to draw a
+ * frame border around a panel; in fact, a panel is a special type (a subclass)
+ * of bar.
+ *
+ * <p>Bars can be positioned in several ways. Most commonly, one of the four
+ * corners is fixed using two margins, and then the width and height properties
+ * determine the extent of the bar relative to this fixed location. For example,
+ * using the bottom and left properties fixes the bottom-left corner; the width
+ * then extends to the right, while the height extends to the top. As an
+ * alternative to the four corners, a bar can be positioned exclusively using
+ * margins; this is convenient as an inset from the containing panel, for
+ * example. See {@link pv.Mark} for details on the prioritization of redundant
+ * positioning properties.
+ *
+ * <p>See also the <a href="../../api/Bar.html">Bar guide</a>.
+ *
+ * @extends pv.Mark
+ */
+pv.Bar = function() {
+  pv.Mark.call(this);
+};
+
+pv.Bar.prototype = pv.extend(pv.Mark)
+    .property("width", Number)
+    .property("height", Number)
+    .property("lineWidth", Number)
+    .property("strokeStyle", pv.color)
+    .property("fillStyle", pv.color);
+
+pv.Bar.prototype.type = "bar";
+
+/**
+ * The width of the bar, in pixels. If the left position is specified, the bar
+ * extends rightward from the left edge; if the right position is specified, the
+ * bar extends leftward from the right edge.
+ *
+ * @type number
+ * @name pv.Bar.prototype.width
+ */
+
+/**
+ * The height of the bar, in pixels. If the bottom position is specified, the
+ * bar extends upward from the bottom edge; if the top position is specified,
+ * the bar extends downward from the top edge.
+ *
+ * @type number
+ * @name pv.Bar.prototype.height
+ */
+
+/**
+ * The width of stroked lines, in pixels; used in conjunction with
+ * <tt>strokeStyle</tt> to stroke the bar's border.
+ *
+ * @type number
+ * @name pv.Bar.prototype.lineWidth
+ */
+
+/**
+ * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
+ * stroke the bar's border. The default value of this property is null, meaning
+ * bars are not stroked by default.
+ *
+ * @type string
+ * @name pv.Bar.prototype.strokeStyle
+ * @see pv.color
+ */
+
+/**
+ * The bar fill style; if non-null, the interior of the bar is filled with the
+ * specified color. The default value of this property is a categorical color.
+ *
+ * @type string
+ * @name pv.Bar.prototype.fillStyle
+ * @see pv.color
+ */
+
+/**
+ * Default properties for bars. By default, there is no stroke and the fill
+ * style is a categorical color.
+ *
+ * @type pv.Bar
+ */
+pv.Bar.prototype.defaults = new pv.Bar()
+    .extend(pv.Mark.prototype.defaults)
+    .lineWidth(1.5)
+    .fillStyle(pv.Colors.category20().by(pv.parent));
+/**
+ * Constructs a new dot mark with default properties. Dots are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents a dot; a dot is simply a sized glyph centered at a given
+ * point that can also be stroked and filled. The <tt>size</tt> property is
+ * proportional to the area of the rendered glyph to encourage meaningful visual
+ * encodings. Dots can visually encode up to eight dimensions of data, though
+ * this may be unwise due to integrality. See {@link pv.Mark} for details on the
+ * prioritization of redundant positioning properties.
+ *
+ * <p>See also the <a href="../../api/Dot.html">Dot guide</a>.
+ *
+ * @extends pv.Mark
+ */
+pv.Dot = function() {
+  pv.Mark.call(this);
+};
+
+pv.Dot.prototype = pv.extend(pv.Mark)
+    .property("size", Number)
+    .property("radius", Number)
+    .property("shape", String)
+    .property("angle", Number)
+    .property("lineWidth", Number)
+    .property("strokeStyle", pv.color)
+    .property("fillStyle", pv.color);
+
+pv.Dot.prototype.type = "dot";
+
+/**
+ * The size of the dot, in square pixels. Square pixels are used such that the
+ * area of the dot is linearly proportional to the value of the size property,
+ * facilitating representative encodings.
+ *
+ * @see #radius
+ * @type number
+ * @name pv.Dot.prototype.size
+ */
+
+/**
+ * The radius of the dot, in pixels. This is an alternative to using
+ * {@link #size}.
+ *
+ * @see #size
+ * @type number
+ * @name pv.Dot.prototype.radius
+ */
+
+/**
+ * The shape name. Several shapes are supported:<ul>
+ *
+ * <li>cross
+ * <li>triangle
+ * <li>diamond
+ * <li>square
+ * <li>circle
+ * <li>tick
+ * <li>bar
+ *
+ * </ul>These shapes can be further changed using the {@link #angle} property;
+ * for instance, a cross can be turned into a plus by rotating. Similarly, the
+ * tick, which is vertical by default, can be rotated horizontally. Note that
+ * some shapes (cross and tick) do not have interior areas, and thus do not
+ * support fill style meaningfully.
+ *
+ * <p>Note: it may be more natural to use the {@link pv.Rule} mark for
+ * horizontal and vertical ticks. The tick shape is only necessary if angled
+ * ticks are needed.
+ *
+ * @type string
+ * @name pv.Dot.prototype.shape
+ */
+
+/**
+ * The rotation angle, in radians. Used to rotate shapes, such as to turn a
+ * cross into a plus.
+ *
+ * @type number
+ * @name pv.Dot.prototype.angle
+ */
+
+/**
+ * The width of stroked lines, in pixels; used in conjunction with
+ * <tt>strokeStyle</tt> to stroke the dot's shape.
+ *
+ * @type number
+ * @name pv.Dot.prototype.lineWidth
+ */
+
+/**
+ * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
+ * stroke the dot's shape. The default value of this property is a categorical
+ * color.
+ *
+ * @type string
+ * @name pv.Dot.prototype.strokeStyle
+ * @see pv.color
+ */
+
+/**
+ * The fill style; if non-null, the interior of the dot is filled with the
+ * specified color. The default value of this property is null, meaning dots are
+ * not filled by default.
+ *
+ * @type string
+ * @name pv.Dot.prototype.fillStyle
+ * @see pv.color
+ */
+
+/**
+ * Default properties for dots. By default, there is no fill and the stroke
+ * style is a categorical color. The default shape is "circle" with size 20.
+ *
+ * @type pv.Dot
+ */
+pv.Dot.prototype.defaults = new pv.Dot()
+    .extend(pv.Mark.prototype.defaults)
+    .size(20)
+    .shape("circle")
+    .lineWidth(1.5)
+    .strokeStyle(pv.Colors.category10().by(pv.parent));
+
+/**
+ * Constructs a new dot anchor with default properties. Dots support five
+ * different anchors:<ul>
+ *
+ * <li>top
+ * <li>left
+ * <li>center
+ * <li>bottom
+ * <li>right
+ *
+ * </ul>In addition to positioning properties (left, right, top bottom), the
+ * anchors support text rendering properties (text-align, text-baseline). Text is
+ * rendered to appear outside the dot. Note that this behavior is different from
+ * other mark anchors, which default to rendering text <i>inside</i> the mark.
+ *
+ * <p>For consistency with the other mark types, the anchor positions are
+ * defined in terms of their opposite edge. For example, the top anchor defines
+ * the bottom property, such that a bar added to the top anchor grows upward.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor}
+ */
+pv.Dot.prototype.anchor = function(name) {
+  var scene;
+  return pv.Mark.prototype.anchor.call(this, name)
+    .def("$wedge.anchor", function() {
+        scene = this.scene.target;
+      })
+    .left(function() {
+        var s = scene[this.index];
+        switch (this.name()) {
+          case "bottom":
+          case "top":
+          case "center": return s.left;
+          case "left": return null;
+        }
+        return s.left + s.radius;
+      })
+    .right(function() {
+        var s = scene[this.index];
+        return this.name() == "left" ? s.right + s.radius : null;
+      })
+    .top(function() {
+        var s = scene[this.index];
+        switch (this.name()) {
+          case "left":
+          case "right":
+          case "center": return s.top;
+          case "top": return null;
+        }
+        return s.top + s.radius;
+      })
+    .bottom(function() {
+        var s = scene[this.index];
+        return this.name() == "top" ? s.bottom + s.radius : null;
+      })
+    .textAlign(function() {
+        switch (this.name()) {
+          case "left": return "right";
+          case "bottom":
+          case "top":
+          case "center": return "center";
+        }
+        return "left";
+      })
+    .textBaseline(function() {
+        switch (this.name()) {
+          case "right":
+          case "left":
+          case "center": return "middle";
+          case "bottom": return "top";
+        }
+        return "bottom";
+      });
+};
+
+/** @private Sets radius based on size or vice versa. */
+pv.Dot.prototype.buildImplied = function(s) {
+  if (s.radius == null) s.radius = Math.sqrt(s.size);
+  else if (s.size == null) s.size = s.radius * s.radius;
+  pv.Mark.prototype.buildImplied.call(this, s);
+};
+/**
+ * Constructs a new label mark with default properties. Labels are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents a text label, allowing textual annotation of other marks or
+ * arbitrary text within the visualization. The character data must be plain
+ * text (unicode), though the text can be styled using the {@link #font}
+ * property. If rich text is needed, external HTML elements can be overlaid on
+ * the canvas by hand.
+ *
+ * <p>Labels are positioned using the box model, similarly to {@link Dot}. Thus,
+ * a label has no width or height, but merely a text anchor location. The text
+ * is positioned relative to this anchor location based on the
+ * {@link #textAlign}, {@link #textBaseline} and {@link #textMargin} properties.
+ * Furthermore, the text may be rotated using {@link #textAngle}.
+ *
+ * <p>Labels ignore events, so as to not interfere with event handlers on
+ * underlying marks, such as bars. In the future, we may support event handlers
+ * on labels.
+ *
+ * <p>See also the <a href="../../api/Label.html">Label guide</a>.
+ *
+ * @extends pv.Mark
+ */
+pv.Label = function() {
+  pv.Mark.call(this);
+};
+
+pv.Label.prototype = pv.extend(pv.Mark)
+    .property("text", String)
+    .property("font", String)
+    .property("textAngle", Number)
+    .property("textStyle", pv.color)
+    .property("textAlign", String)
+    .property("textBaseline", String)
+    .property("textMargin", Number)
+    .property("textDecoration", String)
+    .property("textShadow", String);
+
+pv.Label.prototype.type = "label";
+
+/**
+ * The character data to render; a string. The default value of the text
+ * property is the identity function, meaning the label's associated datum will
+ * be rendered using its <tt>toString</tt>.
+ *
+ * @type string
+ * @name pv.Label.prototype.text
+ */
+
+/**
+ * The font format, per the CSS Level 2 specification. The default font is "10px
+ * sans-serif", for consistency with the HTML 5 canvas element specification.
+ * Note that since text is not wrapped, any line-height property will be
+ * ignored. The other font-style, font-variant, font-weight, font-size and
+ * font-family properties are supported.
+ *
+ * @see <a href="http://www.w3.org/TR/CSS2/fonts.html#font-shorthand">CSS2 fonts</a>
+ * @type string
+ * @name pv.Label.prototype.font
+ */
+
+/**
+ * The rotation angle, in radians. Text is rotated clockwise relative to the
+ * anchor location. For example, with the default left alignment, an angle of
+ * Math.PI / 2 causes text to proceed downwards. The default angle is zero.
+ *
+ * @type number
+ * @name pv.Label.prototype.textAngle
+ */
+
+/**
+ * The text color. The name "textStyle" is used for consistency with "fillStyle"
+ * and "strokeStyle", although it might be better to rename this property (and
+ * perhaps use the same name as "strokeStyle"). The default color is black.
+ *
+ * @type string
+ * @name pv.Label.prototype.textStyle
+ * @see pv.color
+ */
+
+/**
+ * The horizontal text alignment. One of:<ul>
+ *
+ * <li>left
+ * <li>center
+ * <li>right
+ *
+ * </ul>The default horizontal alignment is left.
+ *
+ * @type string
+ * @name pv.Label.prototype.textAlign
+ */
+
+/**
+ * The vertical text alignment. One of:<ul>
+ *
+ * <li>top
+ * <li>middle
+ * <li>bottom
+ *
+ * </ul>The default vertical alignment is bottom.
+ *
+ * @type string
+ * @name pv.Label.prototype.textBaseline
+ */
+
+/**
+ * The text margin; may be specified in pixels, or in font-dependent units (such
+ * as ".1ex"). The margin can be used to pad text away from its anchor location,
+ * in a direction dependent on the horizontal and vertical alignment
+ * properties. For example, if the text is left- and middle-aligned, the margin
+ * shifts the text to the right. The default margin is 3 pixels.
+ *
+ * @type number
+ * @name pv.Label.prototype.textMargin
+ */
+
+/**
+ * A list of shadow effects to be applied to text, per the CSS Text Level 3
+ * text-shadow property. An example specification is "0.1em 0.1em 0.1em
+ * rgba(0,0,0,.5)"; the first length is the horizontal offset, the second the
+ * vertical offset, and the third the blur radius.
+ *
+ * @see <a href="http://www.w3.org/TR/css3-text/#text-shadow">CSS3 text</a>
+ * @type string
+ * @name pv.Label.prototype.textShadow
+ */
+
+/**
+ * A list of decoration to be applied to text, per the CSS Text Level 3
+ * text-decoration property. An example specification is "underline".
+ *
+ * @see <a href="http://www.w3.org/TR/css3-text/#text-decoration">CSS3 text</a>
+ * @type string
+ * @name pv.Label.prototype.textDecoration
+ */
+
+/**
+ * Default properties for labels. See the individual properties for the default
+ * values.
+ *
+ * @type pv.Label
+ */
+pv.Label.prototype.defaults = new pv.Label()
+    .extend(pv.Mark.prototype.defaults)
+    .events("none")
+    .text(pv.identity)
+    .font("10px sans-serif")
+    .textAngle(0)
+    .textStyle("black")
+    .textAlign("left")
+    .textBaseline("bottom")
+    .textMargin(3);
+/**
+ * Constructs a new line mark with default properties. Lines are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents a series of connected line segments, or <i>polyline</i>,
+ * that can be stroked with a configurable color and thickness. Each
+ * articulation point in the line corresponds to a datum; for <i>n</i> points,
+ * <i>n</i>-1 connected line segments are drawn. The point is positioned using
+ * the box model. Arbitrary paths are also possible, allowing radar plots and
+ * other custom visualizations.
+ *
+ * <p>Like areas, lines can be stroked and filled with arbitrary colors. In most
+ * cases, lines are only stroked, but the fill style can be used to construct
+ * arbitrary polygons.
+ *
+ * <p>See also the <a href="../../api/Line.html">Line guide</a>.
+ *
+ * @extends pv.Mark
+ */
+pv.Line = function() {
+  pv.Mark.call(this);
+};
+
+pv.Line.prototype = pv.extend(pv.Mark)
+    .property("lineWidth", Number)
+    .property("lineJoin", String)
+    .property("strokeStyle", pv.color)
+    .property("fillStyle", pv.color)
+    .property("segmented", Boolean)
+    .property("interpolate", String)
+    .property("eccentricity", Number)
+    .property("tension", Number);
+
+pv.Line.prototype.type = "line";
+
+/**
+ * The width of stroked lines, in pixels; used in conjunction with
+ * <tt>strokeStyle</tt> to stroke the line.
+ *
+ * @type number
+ * @name pv.Line.prototype.lineWidth
+ */
+
+/**
+ * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
+ * stroke the line. The default value of this property is a categorical color.
+ *
+ * @type string
+ * @name pv.Line.prototype.strokeStyle
+ * @see pv.color
+ */
+
+/**
+ * The type of corners where two lines meet. Accepted values are "bevel",
+ * "round" and "miter". The default value is "miter".
+ *
+ * <p>For segmented lines, only "miter" joins and "linear" interpolation are
+ * currently supported. Any other value, including null, will disable joins,
+ * producing disjoint line segments. Note that the miter joins must be computed
+ * manually (at least in the current SVG renderer); since this calculation may
+ * be expensive and unnecessary for small lines, specifying null can improve
+ * performance significantly.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type string
+ * @name pv.Line.prototype.lineJoin
+ */
+
+/**
+ * The line fill style; if non-null, the interior of the line is closed and
+ * filled with the specified color. The default value of this property is a
+ * null, meaning that lines are not filled by default.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type string
+ * @name pv.Line.prototype.fillStyle
+ * @see pv.color
+ */
+
+/**
+ * Whether the line is segmented; whether variations in stroke style, line width
+ * and the other properties are treated as fixed. Rendering segmented lines is
+ * noticeably slower than non-segmented lines.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type boolean
+ * @name pv.Line.prototype.segmented
+ */
+
+/**
+ * How to interpolate between values. Linear interpolation ("linear") is the
+ * default, producing a straight line between points. For piecewise constant
+ * functions (i.e., step functions), either "step-before" or "step-after" can be
+ * specified. To draw a clockwise circular arc between points, specify "polar";
+ * to draw a counterclockwise circular arc between points, specify
+ * "polar-reverse". To draw open uniform b-splines, specify "basis". To draw
+ * cardinal splines, specify "cardinal"; see also {@link #tension}.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type string
+ * @name pv.Line.prototype.interpolate
+ */
+
+/**
+ * The eccentricity of polar line segments; used in conjunction with
+ * interpolate("polar"). The default value of 0 means that line segments are
+ * drawn as circular arcs. A value of 1 draws a straight line. A value between 0
+ * and 1 draws an elliptical arc with the given eccentricity.
+ *
+ * @type number
+ * @name pv.Line.prototype.eccentricity
+ */
+
+/**
+ * The tension of cardinal splines; used in conjunction with
+ * interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
+ * the given tension. In some sense, the tension can be interpreted as the
+ * "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
+ * linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
+ * default value is 0.7.
+ *
+ * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
+ *
+ * @type number
+ * @name pv.Line.prototype.tension
+ */
+
+/**
+ * Default properties for lines. By default, there is no fill and the stroke
+ * style is a categorical color. The default interpolation is linear.
+ *
+ * @type pv.Line
+ */
+pv.Line.prototype.defaults = new pv.Line()
+    .extend(pv.Mark.prototype.defaults)
+    .lineJoin("miter")
+    .lineWidth(1.5)
+    .strokeStyle(pv.Colors.category10().by(pv.parent))
+    .interpolate("linear")
+    .eccentricity(0)
+    .tension(.7);
+
+/** @private Reuse Area's implementation for segmented bind & build. */
+pv.Line.prototype.bind = pv.Area.prototype.bind;
+pv.Line.prototype.buildInstance = pv.Area.prototype.buildInstance;
+
+/**
+ * Constructs a new line anchor with default properties. Lines support five
+ * different anchors:<ul>
+ *
+ * <li>top
+ * <li>left
+ * <li>center
+ * <li>bottom
+ * <li>right
+ *
+ * </ul>In addition to positioning properties (left, right, top bottom), the
+ * anchors support text rendering properties (text-align, text-baseline). Text is
+ * rendered to appear outside the line. Note that this behavior is different
+ * from other mark anchors, which default to rendering text <i>inside</i> the
+ * mark.
+ *
+ * <p>For consistency with the other mark types, the anchor positions are
+ * defined in terms of their opposite edge. For example, the top anchor defines
+ * the bottom property, such that a bar added to the top anchor grows upward.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor}
+ */
+pv.Line.prototype.anchor = function(name) {
+  return pv.Area.prototype.anchor.call(this, name)
+    .textAlign(function(d) {
+        switch (this.name()) {
+          case "left": return "right";
+          case "bottom":
+          case "top":
+          case "center": return "center";
+          case "right": return "left";
+        }
+      })
+    .textBaseline(function(d) {
+        switch (this.name()) {
+          case "right":
+          case "left":
+          case "center": return "middle";
+          case "top": return "bottom";
+          case "bottom": return "top";
+        }
+      });
+};
+/**
+ * Constructs a new rule with default properties. Rules are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents a horizontal or vertical rule. Rules are frequently used
+ * for axes and grid lines. For example, specifying only the bottom property
+ * draws horizontal rules, while specifying only the left draws vertical
+ * rules. Rules can also be used as thin bars. The visual style is controlled in
+ * the same manner as lines.
+ *
+ * <p>Rules are positioned exclusively the standard box model properties. The
+ * following combinations of properties are supported:
+ *
+ * <table>
+ * <thead><th style="width:12em;">Properties</th><th>Orientation</th></thead>
+ * <tbody>
+ * <tr><td>left</td><td>vertical</td></tr>
+ * <tr><td>right</td><td>vertical</td></tr>
+ * <tr><td>left, bottom, top</td><td>vertical</td></tr>
+ * <tr><td>right, bottom, top</td><td>vertical</td></tr>
+ * <tr><td>top</td><td>horizontal</td></tr>
+ * <tr><td>bottom</td><td>horizontal</td></tr>
+ * <tr><td>top, left, right</td><td>horizontal</td></tr>
+ * <tr><td>bottom, left, right</td><td>horizontal</td></tr>
+ * <tr><td>left, top, height</td><td>vertical</td></tr>
+ * <tr><td>left, bottom, height</td><td>vertical</td></tr>
+ * <tr><td>right, top, height</td><td>vertical</td></tr>
+ * <tr><td>right, bottom, height</td><td>vertical</td></tr>
+ * <tr><td>left, top, width</td><td>horizontal</td></tr>
+ * <tr><td>left, bottom, width</td><td>horizontal</td></tr>
+ * <tr><td>right, top, width</td><td>horizontal</td></tr>
+ * <tr><td>right, bottom, width</td><td>horizontal</td></tr>
+ * </tbody>
+ * </table>
+ *
+ * <p>Small rules can be used as tick marks; alternatively, a {@link Dot} with
+ * the "tick" shape can be used.
+ *
+ * <p>See also the <a href="../../api/Rule.html">Rule guide</a>.
+ *
+ * @see pv.Line
+ * @extends pv.Mark
+ */
+pv.Rule = function() {
+  pv.Mark.call(this);
+};
+
+pv.Rule.prototype = pv.extend(pv.Mark)
+    .property("width", Number)
+    .property("height", Number)
+    .property("lineWidth", Number)
+    .property("strokeStyle", pv.color);
+
+pv.Rule.prototype.type = "rule";
+
+/**
+ * The width of the rule, in pixels. If the left position is specified, the rule
+ * extends rightward from the left edge; if the right position is specified, the
+ * rule extends leftward from the right edge.
+ *
+ * @type number
+ * @name pv.Rule.prototype.width
+ */
+
+/**
+ * The height of the rule, in pixels. If the bottom position is specified, the
+ * rule extends upward from the bottom edge; if the top position is specified,
+ * the rule extends downward from the top edge.
+ *
+ * @type number
+ * @name pv.Rule.prototype.height
+ */
+
+/**
+ * The width of stroked lines, in pixels; used in conjunction with
+ * <tt>strokeStyle</tt> to stroke the rule. The default value is 1 pixel.
+ *
+ * @type number
+ * @name pv.Rule.prototype.lineWidth
+ */
+
+/**
+ * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
+ * stroke the rule. The default value of this property is black.
+ *
+ * @type string
+ * @name pv.Rule.prototype.strokeStyle
+ * @see pv.color
+ */
+
+/**
+ * Default properties for rules. By default, a single-pixel black line is
+ * stroked.
+ *
+ * @type pv.Rule
+ */
+pv.Rule.prototype.defaults = new pv.Rule()
+    .extend(pv.Mark.prototype.defaults)
+    .lineWidth(1)
+    .strokeStyle("black")
+    .antialias(false);
+
+/**
+ * Constructs a new rule anchor with default properties. Rules support five
+ * different anchors:<ul>
+ *
+ * <li>top
+ * <li>left
+ * <li>center
+ * <li>bottom
+ * <li>right
+ *
+ * </ul>In addition to positioning properties (left, right, top bottom), the
+ * anchors support text rendering properties (text-align, text-baseline). Text is
+ * rendered to appear outside the rule. Note that this behavior is different
+ * from other mark anchors, which default to rendering text <i>inside</i> the
+ * mark.
+ *
+ * <p>For consistency with the other mark types, the anchor positions are
+ * defined in terms of their opposite edge. For example, the top anchor defines
+ * the bottom property, such that a bar added to the top anchor grows upward.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor}
+ */
+pv.Rule.prototype.anchor = pv.Line.prototype.anchor;
+
+/** @private Sets width or height based on orientation. */
+pv.Rule.prototype.buildImplied = function(s) {
+  var l = s.left, r = s.right, t = s.top, b = s.bottom;
+
+  /* Determine horizontal or vertical orientation. */
+  if ((s.width != null)
+      || ((l == null) && (r == null))
+      || ((r != null) && (l != null))) {
+    s.height = 0;
+  } else {
+    s.width = 0;
+  }
+
+  pv.Mark.prototype.buildImplied.call(this, s);
+};
+/**
+ * Constructs a new, empty panel with default properties. Panels, with the
+ * exception of the root panel, are not typically constructed directly; instead,
+ * they are added to an existing panel or mark via {@link pv.Mark#add}.
+ *
+ * @class Represents a container mark. Panels allow repeated or nested
+ * structures, commonly used in small multiple displays where a small
+ * visualization is tiled to facilitate comparison across one or more
+ * dimensions. Other types of visualizations may benefit from repeated and
+ * possibly overlapping structure as well, such as stacked area charts. Panels
+ * can also offset the position of marks to provide padding from surrounding
+ * content.
+ *
+ * <p>All Protovis displays have at least one panel; this is the root panel to
+ * which marks are rendered. The box model properties (four margins, width and
+ * height) are used to offset the positions of contained marks. The data
+ * property determines the panel count: a panel is generated once per associated
+ * datum. When nested panels are used, property functions can declare additional
+ * arguments to access the data associated with enclosing panels.
+ *
+ * <p>Panels can be rendered inline, facilitating the creation of sparklines.
+ * This allows designers to reuse browser layout features, such as text flow and
+ * tables; designers can also overlay HTML elements such as rich text and
+ * images.
+ *
+ * <p>All panels have a <tt>children</tt> array (possibly empty) containing the
+ * child marks in the order they were added. Panels also have a <tt>root</tt>
+ * field which points to the root (outermost) panel; the root panel's root field
+ * points to itself.
+ *
+ * <p>See also the <a href="../../api/">Protovis guide</a>.
+ *
+ * @extends pv.Bar
+ */
+pv.Panel = function() {
+  pv.Bar.call(this);
+
+  /**
+   * The child marks; zero or more {@link pv.Mark}s in the order they were
+   * added.
+   *
+   * @see #add
+   * @type pv.Mark[]
+   */
+  this.children = [];
+  this.root = this;
+
+  /**
+   * The internal $dom field is set by the Protovis loader; see lang/init.js. It
+   * refers to the script element that contains the Protovis specification, so
+   * that the panel knows where in the DOM to insert the generated SVG element.
+   *
+   * @private
+   */
+  this.$dom = pv.$ && pv.$.s;
+};
+
+pv.Panel.prototype = pv.extend(pv.Bar)
+    .property("transform")
+    .property("overflow", String)
+    .property("canvas", function(c) {
+        return (typeof c == "string")
+            ? document.getElementById(c)
+            : c; // assume that c is the passed-in element
+      });
+
+pv.Panel.prototype.type = "panel";
+
+/**
+ * The canvas element; either the string ID of the canvas element in the current
+ * document, or a reference to the canvas element itself. If null, a canvas
+ * element will be created and inserted into the document at the location of the
+ * script element containing the current Protovis specification. This property
+ * only applies to root panels and is ignored on nested panels.
+ *
+ * <p>Note: the "canvas" element here refers to a <tt>div</tt> (or other suitable
+ * HTML container element), <i>not</i> a <tt>canvas</tt> element. The name of
+ * this property is a historical anachronism from the first implementation that
+ * used HTML 5 canvas, rather than SVG.
+ *
+ * @type string
+ * @name pv.Panel.prototype.canvas
+ */
+
+/**
+ * Specifies whether child marks are clipped when they overflow this panel.
+ * This affects the clipping of all this panel's descendant marks.
+ *
+ * @type string
+ * @name pv.Panel.prototype.overflow
+ * @see <a href="http://www.w3.org/TR/CSS2/visufx.html#overflow">CSS2</a>
+ */
+
+/**
+ * The transform to be applied to child marks. The default transform is
+ * identity, which has no effect. Note that the panel's own fill and stroke are
+ * not affected by the transform, and panel's transform only affects the
+ * <tt>scale</tt> of child marks, not the panel itself.
+ *
+ * @type pv.Transform
+ * @name pv.Panel.prototype.transform
+ * @see pv.Mark#scale
+ */
+
+/**
+ * Default properties for panels. By default, the margins are zero, the fill
+ * style is transparent.
+ *
+ * @type pv.Panel
+ */
+pv.Panel.prototype.defaults = new pv.Panel()
+    .extend(pv.Bar.prototype.defaults)
+    .fillStyle(null) // override Bar default
+    .overflow("visible");
+
+/**
+ * Returns an anchor with the specified name. This method is overridden such
+ * that adding to a panel's anchor adds to the panel, rather than to the panel's
+ * parent.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor} the new anchor.
+ */
+pv.Panel.prototype.anchor = function(name) {
+  var anchor = pv.Bar.prototype.anchor.call(this, name);
+  anchor.parent = this;
+  return anchor;
+};
+
+/**
+ * Adds a new mark of the specified type to this panel. Unlike the normal
+ * {@link Mark#add} behavior, adding a mark to a panel does not cause the mark
+ * to inherit from the panel. Since the contained marks are offset by the panel
+ * margins already, inheriting properties is generally undesirable; of course,
+ * it is always possible to change this behavior by calling {@link Mark#extend}
+ * explicitly.
+ *
+ * @param {function} type the type of the new mark to add.
+ * @returns {pv.Mark} the new mark.
+ */
+pv.Panel.prototype.add = function(type) {
+  var child = new type();
+  child.parent = this;
+  child.root = this.root;
+  child.childIndex = this.children.length;
+  this.children.push(child);
+  return child;
+};
+
+/** @private Bind this panel, then any child marks recursively. */
+pv.Panel.prototype.bind = function() {
+  pv.Mark.prototype.bind.call(this);
+  for (var i = 0; i < this.children.length; i++) {
+    this.children[i].bind();
+  }
+};
+
+/**
+ * @private Evaluates all of the properties for this panel for the specified
+ * instance <tt>s</tt> in the scene graph, including recursively building the
+ * scene graph for child marks.
+ *
+ * @param s a node in the scene graph; the instance of the panel to build.
+ * @see Mark#scene
+ */
+pv.Panel.prototype.buildInstance = function(s) {
+  pv.Bar.prototype.buildInstance.call(this, s);
+  if (!s.visible) return;
+  if (!s.children) s.children = [];
+
+  /*
+   * Multiply the current scale factor by this panel's transform. Also clear the
+   * default index as we recurse into child marks; it will be reset to the
+   * current index when the next panel instance is built.
+   */
+  var scale = this.scale * s.transform.k, child, n = this.children.length;
+  pv.Mark.prototype.index = -1;
+
+  /*
+   * Build each child, passing in the parent (this panel) scene graph node. The
+   * child mark's scene is initialized from the corresponding entry in the
+   * existing scene graph, such that properties from the previous build can be
+   * reused; this is largely to facilitate the recycling of SVG elements.
+   */
+  for (var i = 0; i < n; i++) {
+    child = this.children[i];
+    child.scene = s.children[i]; // possibly undefined
+    child.scale = scale;
+    child.build();
+  }
+
+  /*
+   * Once the child marks have been built, the new scene graph nodes are removed
+   * from the child marks and placed into the scene graph. The nodes cannot
+   * remain on the child nodes because this panel (or a parent panel) may be
+   * instantiated multiple times!
+   */
+  for (var i = 0; i < n; i++) {
+    child = this.children[i];
+    s.children[i] = child.scene;
+    delete child.scene;
+    delete child.scale;
+  }
+
+  /* Delete any expired child scenes. */
+  s.children.length = n;
+};
+
+/**
+ * @private Computes the implied properties for this panel for the specified
+ * instance <tt>s</tt> in the scene graph. Panels have two implied
+ * properties:<ul>
+ *
+ * <li>The <tt>canvas</tt> property references the DOM element, typically a DIV,
+ * that contains the SVG element that is used to display the visualization. This
+ * property may be specified as a string, referring to the unique ID of the
+ * element in the DOM. The string is converted to a reference to the DOM
+ * element. The width and height of the SVG element is inferred from this DOM
+ * element. If no canvas property is specified, a new SVG element is created and
+ * inserted into the document, using the panel dimensions; see
+ * {@link #createCanvas}.
+ *
+ * <li>The <tt>children</tt> array, while not a property per se, contains the
+ * scene graph for each child mark. This array is initialized to be empty, and
+ * is populated above in {@link #buildInstance}.
+ *
+ * </ul>The current implementation creates the SVG element, if necessary, during
+ * the build phase; in the future, it may be preferrable to move this to the
+ * update phase, although then the canvas property would be undefined. In
+ * addition, DOM inspection is necessary to define the implied width and height
+ * properties that may be inferred from the DOM.
+ *
+ * @param s a node in the scene graph; the instance of the panel to build.
+ */
+pv.Panel.prototype.buildImplied = function(s) {
+  if (!this.parent) {
+    var c = s.canvas;
+    if (c) {
+      /* Clear the container if it's not associated with this panel. */
+      if (c.$panel != this) {
+        c.$panel = this;
+        while (c.lastChild) c.removeChild(c.lastChild);
+      }
+
+      /* If width and height weren't specified, inspect the container. */
+      var w, h;
+      if (s.width == null) {
+        w = parseFloat(pv.css(c, "width"));
+        s.width = w - s.left - s.right;
+      }
+      if (s.height == null) {
+        h = parseFloat(pv.css(c, "height"));
+        s.height = h - s.top - s.bottom;
+      }
+    } else {
+      var cache = this.$canvas || (this.$canvas = []);
+      if (!(c = cache[this.index])) {
+        c = cache[this.index] = document.createElement("span");
+        if (this.$dom) { // script element for text/javascript+protovis
+          this.$dom.parentNode.insertBefore(c, this.$dom);
+        } else { // find the last element in the body
+          var n = document.body;
+          while (n.lastChild && n.lastChild.tagName) n = n.lastChild;
+          if (n != document.body) n = n.parentNode;
+          n.appendChild(c);
+        }
+      }
+    }
+    s.canvas = c;
+  }
+  if (!s.transform) s.transform = pv.Transform.identity;
+  pv.Mark.prototype.buildImplied.call(this, s);
+};
+/**
+ * Constructs a new image with default properties. Images are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents an image, either a static resource or a dynamically-
+ * generated pixel buffer. Images share the same layout and style properties as
+ * bars. The external image resource is specified via the {@link #url}
+ * property. The optional fill, if specified, appears beneath the image, while
+ * the optional stroke appears above the image.
+ *
+ * <p>Dynamic images such as heatmaps are supported using the {@link #image}
+ * psuedo-property. This function is passed the <i>x</i> and <i>y</i> index, in
+ * addition to the current data stack. The return value is a {@link pv.Color},
+ * or null for transparent. A string can also be returned, which will be parsed
+ * into a color; however, it is typically much faster to return an object with
+ * <tt>r</tt>, <tt>g</tt>, <tt>b</tt> and <tt>a</tt> attributes, to avoid the
+ * cost of parsing and object instantiation.
+ *
+ * <p>See {@link pv.Bar} for details on positioning properties.
+ *
+ * @extends pv.Bar
+ */
+pv.Image = function() {
+  pv.Bar.call(this);
+};
+
+pv.Image.prototype = pv.extend(pv.Bar)
+    .property("url", String)
+    .property("imageWidth", Number)
+    .property("imageHeight", Number);
+
+pv.Image.prototype.type = "image";
+
+/**
+ * The URL of the image to display. The set of supported image types is
+ * browser-dependent; PNG and JPEG are recommended.
+ *
+ * @type string
+ * @name pv.Image.prototype.url
+ */
+
+/**
+ * The width of the image in pixels. For static images, this property is
+ * computed implicitly from the loaded image resources. For dynamic images, this
+ * property can be used to specify the width of the pixel buffer; otherwise, the
+ * value is derived from the <tt>width</tt> property.
+ *
+ * @type number
+ * @name pv.Image.prototype.imageWidth
+ */
+
+/**
+ * The height of the image in pixels. For static images, this property is
+ * computed implicitly from the loaded image resources. For dynamic images, this
+ * property can be used to specify the height of the pixel buffer; otherwise, the
+ * value is derived from the <tt>height</tt> property.
+ *
+ * @type number
+ * @name pv.Image.prototype.imageHeight
+ */
+
+/**
+ * Default properties for images. By default, there is no stroke or fill style.
+ *
+ * @type pv.Image
+ */
+pv.Image.prototype.defaults = new pv.Image()
+    .extend(pv.Bar.prototype.defaults)
+    .fillStyle(null);
+
+/**
+ * Specifies the dynamic image function. By default, no image function is
+ * specified and the <tt>url</tt> property is used to load a static image
+ * resource. If an image function is specified, it will be invoked for each
+ * pixel in the image, based on the related <tt>imageWidth</tt> and
+ * <tt>imageHeight</tt> properties.
+ *
+ * <p>For example, given a two-dimensional array <tt>heatmap</tt>, containing
+ * numbers in the range [0, 1] in row-major order, a simple monochrome heatmap
+ * image can be specified as:
+ *
+ * <pre>vis.add(pv.Image)
+ *     .imageWidth(heatmap[0].length)
+ *     .imageHeight(heatmap.length)
+ *     .image(pv.ramp("white", "black").by(function(x, y) heatmap[y][x]));</pre>
+ *
+ * For fastest performance, use an ordinal scale which caches the fixed color
+ * palette, or return an object literal with <tt>r</tt>, <tt>g</tt>, <tt>b</tt>
+ * and <tt>a</tt> attributes. A {@link pv.Color} or string can also be returned,
+ * though this typically results in slower performance.
+ *
+ * @param {function} f the new sizing function.
+ * @returns {pv.Layout.Pack} this.
+ */
+pv.Image.prototype.image = function(f) {
+  /** @private */
+  this.$image = function() {
+      var c = f.apply(this, arguments);
+      return c == null ? pv.Color.transparent
+          : typeof c == "string" ? pv.color(c)
+          : c;
+    };
+  return this;
+};
+
+/** @private Scan the proto chain for an image function. */
+pv.Image.prototype.bind = function() {
+  pv.Bar.prototype.bind.call(this);
+  var binds = this.binds, mark = this;
+  do {
+    binds.image = mark.$image;
+  } while (!binds.image && (mark = mark.proto));
+};
+
+/** @private */
+pv.Image.prototype.buildImplied = function(s) {
+  pv.Bar.prototype.buildImplied.call(this, s);
+  if (!s.visible) return;
+
+  /* Compute the implied image dimensions. */
+  if (s.imageWidth == null) s.imageWidth = s.width;
+  if (s.imageHeight == null) s.imageHeight = s.height;
+
+  /* Compute the pixel values. */
+  if ((s.url == null) && this.binds.image) {
+
+    /* Cache the canvas element to reuse across renders. */
+    var canvas = this.$canvas || (this.$canvas = document.createElement("canvas")),
+        context = canvas.getContext("2d"),
+        w = s.imageWidth,
+        h = s.imageHeight,
+        stack = pv.Mark.stack,
+        data;
+
+    /* Evaluate the image function, storing into a CanvasPixelArray. */
+    canvas.width = w;
+    canvas.height = h;
+    data = (s.image = context.createImageData(w, h)).data;
+    stack.unshift(null, null);
+    for (var y = 0, p = 0; y < h; y++) {
+      stack[1] = y;
+      for (var x = 0; x < w; x++) {
+        stack[0] = x;
+        var color = this.binds.image.apply(this, stack);
+        data[p++] = color.r;
+        data[p++] = color.g;
+        data[p++] = color.b;
+        data[p++] = 255 * color.a;
+      }
+    }
+    stack.splice(0, 2);
+  }
+};
+/**
+ * Constructs a new wedge with default properties. Wedges are not typically
+ * constructed directly, but by adding to a panel or an existing mark via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents a wedge, or pie slice. Specified in terms of start and end
+ * angle, inner and outer radius, wedges can be used to construct donut charts
+ * and polar bar charts as well. If the {@link #angle} property is used, the end
+ * angle is implied by adding this value to start angle. By default, the start
+ * angle is the previously-generated wedge's end angle. This design allows
+ * explicit control over the wedge placement if desired, while offering
+ * convenient defaults for the construction of radial graphs.
+ *
+ * <p>The center point of the circle is positioned using the standard box model.
+ * The wedge can be stroked and filled, similar to {@link pv.Bar}.
+ *
+ * <p>See also the <a href="../../api/Wedge.html">Wedge guide</a>.
+ *
+ * @extends pv.Mark
+ */
+pv.Wedge = function() {
+  pv.Mark.call(this);
+};
+
+pv.Wedge.prototype = pv.extend(pv.Mark)
+    .property("startAngle", Number)
+    .property("endAngle", Number)
+    .property("angle", Number)
+    .property("innerRadius", Number)
+    .property("outerRadius", Number)
+    .property("lineWidth", Number)
+    .property("strokeStyle", pv.color)
+    .property("fillStyle", pv.color);
+
+pv.Wedge.prototype.type = "wedge";
+
+/**
+ * The start angle of the wedge, in radians. The start angle is measured
+ * clockwise from the 3 o'clock position. The default value of this property is
+ * the end angle of the previous instance (the {@link Mark#sibling}), or -PI / 2
+ * for the first wedge; for pie and donut charts, typically only the
+ * {@link #angle} property needs to be specified.
+ *
+ * @type number
+ * @name pv.Wedge.prototype.startAngle
+ */
+
+/**
+ * The end angle of the wedge, in radians. If not specified, the end angle is
+ * implied as the start angle plus the {@link #angle}.
+ *
+ * @type number
+ * @name pv.Wedge.prototype.endAngle
+ */
+
+/**
+ * The angular span of the wedge, in radians. This property is used if end angle
+ * is not specified.
+ *
+ * @type number
+ * @name pv.Wedge.prototype.angle
+ */
+
+/**
+ * The inner radius of the wedge, in pixels. The default value of this property
+ * is zero; a positive value will produce a donut slice rather than a pie slice.
+ * The inner radius can vary per-wedge.
+ *
+ * @type number
+ * @name pv.Wedge.prototype.innerRadius
+ */
+
+/**
+ * The outer radius of the wedge, in pixels. This property is required. For
+ * pies, only this radius is required; for donuts, the inner radius must be
+ * specified as well. The outer radius can vary per-wedge.
+ *
+ * @type number
+ * @name pv.Wedge.prototype.outerRadius
+ */
+
+/**
+ * The width of stroked lines, in pixels; used in conjunction with
+ * <tt>strokeStyle</tt> to stroke the wedge's border.
+ *
+ * @type number
+ * @name pv.Wedge.prototype.lineWidth
+ */
+
+/**
+ * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
+ * stroke the wedge's border. The default value of this property is null,
+ * meaning wedges are not stroked by default.
+ *
+ * @type string
+ * @name pv.Wedge.prototype.strokeStyle
+ * @see pv.color
+ */
+
+/**
+ * The wedge fill style; if non-null, the interior of the wedge is filled with
+ * the specified color. The default value of this property is a categorical
+ * color.
+ *
+ * @type string
+ * @name pv.Wedge.prototype.fillStyle
+ * @see pv.color
+ */
+
+/**
+ * Default properties for wedges. By default, there is no stroke and the fill
+ * style is a categorical color.
+ *
+ * @type pv.Wedge
+ */
+pv.Wedge.prototype.defaults = new pv.Wedge()
+    .extend(pv.Mark.prototype.defaults)
+    .startAngle(function() {
+        var s = this.sibling();
+        return s ? s.endAngle : -Math.PI / 2;
+      })
+    .innerRadius(0)
+    .lineWidth(1.5)
+    .strokeStyle(null)
+    .fillStyle(pv.Colors.category20().by(pv.index));
+
+/**
+ * Returns the mid-radius of the wedge, which is defined as half-way between the
+ * inner and outer radii.
+ *
+ * @see #innerRadius
+ * @see #outerRadius
+ * @returns {number} the mid-radius, in pixels.
+ */
+pv.Wedge.prototype.midRadius = function() {
+  return (this.innerRadius() + this.outerRadius()) / 2;
+};
+
+/**
+ * Returns the mid-angle of the wedge, which is defined as half-way between the
+ * start and end angles.
+ *
+ * @see #startAngle
+ * @see #endAngle
+ * @returns {number} the mid-angle, in radians.
+ */
+pv.Wedge.prototype.midAngle = function() {
+  return (this.startAngle() + this.endAngle()) / 2;
+};
+
+/**
+ * Constructs a new wedge anchor with default properties. Wedges support five
+ * different anchors:<ul>
+ *
+ * <li>outer
+ * <li>inner
+ * <li>center
+ * <li>start
+ * <li>end
+ *
+ * </ul>In addition to positioning properties (left, right, top bottom), the
+ * anchors support text rendering properties (text-align, text-baseline,
+ * textAngle). Text is rendered to appear inside the wedge.
+ *
+ * @param {string} name the anchor name; either a string or a property function.
+ * @returns {pv.Anchor}
+ */
+pv.Wedge.prototype.anchor = function(name) {
+  function partial(s) { return s.innerRadius || s.angle < 2 * Math.PI; }
+  function midRadius(s) { return (s.innerRadius + s.outerRadius) / 2; }
+  function midAngle(s) { return (s.startAngle + s.endAngle) / 2; }
+  var scene;
+  return pv.Mark.prototype.anchor.call(this, name)
+    .def("$wedge.anchor", function() {
+        scene = this.scene.target;
+      })
+    .left(function() {
+        var s = scene[this.index];
+        if (partial(s)) switch (this.name()) {
+          case "outer": return s.left + s.outerRadius * Math.cos(midAngle(s));
+          case "inner": return s.left + s.innerRadius * Math.cos(midAngle(s));
+          case "start": return s.left + midRadius(s) * Math.cos(s.startAngle);
+          case "center": return s.left + midRadius(s) * Math.cos(midAngle(s));
+          case "end": return s.left + midRadius(s) * Math.cos(s.endAngle);
+        }
+        return s.left;
+      })
+    .top(function() {
+        var s = scene[this.index];
+        if (partial(s)) switch (this.name()) {
+          case "outer": return s.top + s.outerRadius * Math.sin(midAngle(s));
+          case "inner": return s.top + s.innerRadius * Math.sin(midAngle(s));
+          case "start": return s.top + midRadius(s) * Math.sin(s.startAngle);
+          case "center": return s.top + midRadius(s) * Math.sin(midAngle(s));
+          case "end": return s.top + midRadius(s) * Math.sin(s.endAngle);
+        }
+        return s.top;
+      })
+    .textAlign(function() {
+        var s = scene[this.index];
+        if (partial(s)) switch (this.name()) {
+          case "outer": return pv.Wedge.upright(midAngle(s)) ? "right" : "left";
+          case "inner": return pv.Wedge.upright(midAngle(s)) ? "left" : "right";
+        }
+        return "center";
+      })
+    .textBaseline(function() {
+        var s = scene[this.index];
+        if (partial(s)) switch (this.name()) {
+          case "start": return pv.Wedge.upright(s.startAngle) ? "top" : "bottom";
+          case "end": return pv.Wedge.upright(s.endAngle) ? "bottom" : "top";
+        }
+        return "middle";
+      })
+    .textAngle(function() {
+        var s = scene[this.index], a = 0;
+        if (partial(s)) switch (this.name()) {
+          case "center":
+          case "inner":
+          case "outer": a = midAngle(s); break;
+          case "start": a = s.startAngle; break;
+          case "end": a = s.endAngle; break;
+        }
+        return pv.Wedge.upright(a) ? a : (a + Math.PI);
+      });
+};
+
+/**
+ * Returns true if the specified angle is considered "upright", as in, text
+ * rendered at that angle would appear upright. If the angle is not upright,
+ * text is rotated 180 degrees to be upright, and the text alignment properties
+ * are correspondingly changed.
+ *
+ * @param {number} angle an angle, in radius.
+ * @returns {boolean} true if the specified angle is upright.
+ */
+pv.Wedge.upright = function(angle) {
+  angle = angle % (2 * Math.PI);
+  angle = (angle < 0) ? (2 * Math.PI + angle) : angle;
+  return (angle < Math.PI / 2) || (angle >= 3 * Math.PI / 2);
+};
+
+/** @private Sets angle based on endAngle or vice versa. */
+pv.Wedge.prototype.buildImplied = function(s) {
+  if (s.angle == null) s.angle = s.endAngle - s.startAngle;
+  else if (s.endAngle == null) s.endAngle = s.startAngle + s.angle;
+  pv.Mark.prototype.buildImplied.call(this, s);
+};
+/**
+ * Abstract; not implemented. There is no explicit constructor; this class
+ * merely serves to document the attributes that are used on particles in
+ * physics simulations.
+ *
+ * @class A weighted particle that can participate in a force simulation.
+ *
+ * @name pv.Particle
+ */
+
+/**
+ * The next particle in the simulation. Particles form a singly-linked list.
+ *
+ * @field
+ * @type pv.Particle
+ * @name pv.Particle.prototype.next
+ */
+
+/**
+ * The <i>x</i>-position of the particle.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.x
+ */
+
+/**
+ * The <i>y</i>-position of the particle.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.y
+ */
+
+/**
+ * The <i>x</i>-velocity of the particle.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.vx
+ */
+
+/**
+ * The <i>y</i>-velocity of the particle.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.vy
+ */
+
+/**
+ * The <i>x</i>-position of the particle at -dt.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.px
+ */
+
+/**
+ * The <i>y</i>-position of the particle at -dt.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.py
+ */
+
+/**
+ * The <i>x</i>-force on the particle.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.fx
+ */
+
+/**
+ * The <i>y</i>-force on the particle.
+ *
+ * @field
+ * @type number
+ * @name pv.Particle.prototype.fy
+ */
+/**
+ * Constructs a new empty simulation.
+ *
+ * @param {array} particles
+ * @returns {pv.Simulation} a new simulation for the specified particles.
+ * @see pv.Simulation
+ */
+pv.simulation = function(particles) {
+  return new pv.Simulation(particles);
+};
+
+/**
+ * Constructs a new simulation for the specified particles.
+ *
+ * @class Represents a particle simulation. Particles are massive points in
+ * two-dimensional space. Forces can be applied to these particles, causing them
+ * to move. Constraints can also be applied to restrict particle movement, for
+ * example, constraining particles to a fixed position, or simulating collision
+ * between circular particles with area.
+ *
+ * <p>The simulation uses <a
+ * href="http://en.wikipedia.org/wiki/Verlet_integration">Position Verlet</a>
+ * integration, due to the ease with which <a
+ * href="http://www.teknikus.dk/tj/gdc2001.htm">geometric constraints</a> can be
+ * implemented. For each time step, Verlet integration is performed, new forces
+ * are accumulated, and then constraints are applied.
+ *
+ * <p>The simulation makes two simplifying assumptions: all particles are
+ * equal-mass, and the time step of the simulation is fixed. It would be easy to
+ * incorporate variable-mass particles as a future enhancement. Variable time
+ * steps are also possible, but are likely to introduce instability in the
+ * simulation.
+ *
+ * <p>This class can be used directly to simulate particle interaction.
+ * Alternatively, for network diagrams, see {@link pv.Layout.Force}.
+ *
+ * @param {array} particles an array of {@link pv.Particle}s to simulate.
+ * @see pv.Layout.Force
+ * @see pv.Force
+ * @see pv.Constraint
+ */
+pv.Simulation = function(particles) {
+  for (var i = 0; i < particles.length; i++) this.particle(particles[i]);
+};
+
+/**
+ * The particles in the simulation. Particles are stored as a linked list; this
+ * field represents the first particle in the simulation.
+ *
+ * @field
+ * @type pv.Particle
+ * @name pv.Simulation.prototype.particles
+ */
+
+/**
+ * The forces in the simulation. Forces are stored as a linked list; this field
+ * represents the first force in the simulation.
+ *
+ * @field
+ * @type pv.Force
+ * @name pv.Simulation.prototype.forces
+ */
+
+/**
+ * The constraints in the simulation. Constraints are stored as a linked list;
+ * this field represents the first constraint in the simulation.
+ *
+ * @field
+ * @type pv.Constraint
+ * @name pv.Simulation.prototype.constraints
+ */
+
+/**
+ * Adds the specified particle to the simulation.
+ *
+ * @param {pv.Particle} p the new particle.
+ * @returns {pv.Simulation} this.
+ */
+pv.Simulation.prototype.particle = function(p) {
+  p.next = this.particles;
+  /* Default velocities and forces to zero if unset. */
+  if (isNaN(p.px)) p.px = p.x;
+  if (isNaN(p.py)) p.py = p.y;
+  if (isNaN(p.fx)) p.fx = 0;
+  if (isNaN(p.fy)) p.fy = 0;
+  this.particles = p;
+  return this;
+};
+
+/**
+ * Adds the specified force to the simulation.
+ *
+ * @param {pv.Force} f the new force.
+ * @returns {pv.Simulation} this.
+ */
+pv.Simulation.prototype.force = function(f) {
+  f.next = this.forces;
+  this.forces = f;
+  return this;
+};
+
+/**
+ * Adds the specified constraint to the simulation.
+ *
+ * @param {pv.Constraint} c the new constraint.
+ * @returns {pv.Simulation} this.
+ */
+pv.Simulation.prototype.constraint = function(c) {
+  c.next = this.constraints;
+  this.constraints = c;
+  return this;
+};
+
+/**
+ * Apply constraints, and then set the velocities to zero.
+ *
+ * @returns {pv.Simulation} this.
+ */
+pv.Simulation.prototype.stabilize = function(n) {
+  var c;
+  if (!arguments.length) n = 3; // TODO use cooling schedule
+  for (var i = 0; i < n; i++) {
+    var q = new pv.Quadtree(this.particles);
+    for (c = this.constraints; c; c = c.next) c.apply(this.particles, q);
+  }
+  for (var p = this.particles; p; p = p.next) {
+    p.px = p.x;
+    p.py = p.y;
+  }
+  return this;
+};
+
+/**
+ * Advances the simulation one time-step.
+ */
+pv.Simulation.prototype.step = function() {
+  var p, f, c;
+
+  /*
+   * Assumptions:
+   * - The mass (m) of every particles is 1.
+   * - The time step (dt) is 1.
+   */
+
+  /* Position Verlet integration. */
+  for (p = this.particles; p; p = p.next) {
+    var px = p.px, py = p.py;
+    p.px = p.x;
+    p.py = p.y;
+    p.x += p.vx = ((p.x - px) + p.fx);
+    p.y += p.vy = ((p.y - py) + p.fy);
+  }
+
+  /* Apply constraints, then accumulate new forces. */
+  var q = new pv.Quadtree(this.particles);
+  for (c = this.constraints; c; c = c.next) c.apply(this.particles, q);
+  for (p = this.particles; p; p = p.next) p.fx = p.fy = 0;
+  for (f = this.forces; f; f = f.next) f.apply(this.particles, q);
+};
+/**
+ * Constructs a new quadtree for the specified array of particles.
+ *
+ * @class Represents a quadtree: a two-dimensional recursive spatial
+ * subdivision. This particular implementation uses square partitions, dividing
+ * each square into four equally-sized squares. Each particle exists in a unique
+ * node; if multiple particles are in the same position, some particles may be
+ * stored on internal nodes rather than leaf nodes.
+ *
+ * <p>This quadtree can be used to accelerate various spatial operations, such
+ * as the Barnes-Hut approximation for computing n-body forces, or collision
+ * detection.
+ *
+ * @see pv.Force.charge
+ * @see pv.Constraint.collision
+ * @param {pv.Particle} particles the linked list of particles.
+ */
+pv.Quadtree = function(particles) {
+  var p;
+
+  /* Compute bounds. */
+  var x1 = Number.POSITIVE_INFINITY, y1 = x1,
+      x2 = Number.NEGATIVE_INFINITY, y2 = x2;
+  for (p = particles; p; p = p.next) {
+    if (p.x < x1) x1 = p.x;
+    if (p.y < y1) y1 = p.y;
+    if (p.x > x2) x2 = p.x;
+    if (p.y > y2) y2 = p.y;
+  }
+
+  /* Squarify the bounds. */
+  var dx = x2 - x1, dy = y2 - y1;
+  if (dx > dy) y2 = y1 + dx;
+  else x2 = x1 + dy;
+  this.xMin = x1;
+  this.yMin = y1;
+  this.xMax = x2;
+  this.yMax = y2;
+
+  /**
+   * @ignore Recursively inserts the specified particle <i>p</i> at the node
+   * <i>n</i> or one of its descendants. The bounds are defined by [<i>x1</i>,
+   * <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
+   */
+  function insert(n, p, x1, y1, x2, y2) {
+    if (isNaN(p.x) || isNaN(p.y)) return; // ignore invalid particles
+    if (n.leaf) {
+      if (n.p) {
+        /*
+         * If the particle at this leaf node is at the same position as the new
+         * particle we are adding, we leave the particle associated with the
+         * internal node while adding the new particle to a child node. This
+         * avoids infinite recursion.
+         */
+        if ((Math.abs(n.p.x - p.x) + Math.abs(n.p.y - p.y)) < .01) {
+          insertChild(n, p, x1, y1, x2, y2);
+        } else {
+          var v = n.p;
+          n.p = null;
+          insertChild(n, v, x1, y1, x2, y2);
+          insertChild(n, p, x1, y1, x2, y2);
+        }
+      } else {
+        n.p = p;
+      }
+    } else {
+      insertChild(n, p, x1, y1, x2, y2);
+    }
+  }
+
+  /**
+   * @ignore Recursively inserts the specified particle <i>p</i> into a
+   * descendant of node <i>n</i>. The bounds are defined by [<i>x1</i>,
+   * <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
+   */
+  function insertChild(n, p, x1, y1, x2, y2) {
+    /* Compute the split point, and the quadrant in which to insert p. */
+    var sx = (x1 + x2) * .5,
+        sy = (y1 + y2) * .5,
+        right = p.x >= sx,
+        bottom = p.y >= sy;
+
+    /* Recursively insert into the child node. */
+    n.leaf = false;
+    switch ((bottom << 1) + right) {
+      case 0: n = n.c1 || (n.c1 = new pv.Quadtree.Node()); break;
+      case 1: n = n.c2 || (n.c2 = new pv.Quadtree.Node()); break;
+      case 2: n = n.c3 || (n.c3 = new pv.Quadtree.Node()); break;
+      case 3: n = n.c4 || (n.c4 = new pv.Quadtree.Node()); break;
+    }
+
+    /* Update the bounds as we recurse. */
+    if (right) x1 = sx; else x2 = sx;
+    if (bottom) y1 = sy; else y2 = sy;
+    insert(n, p, x1, y1, x2, y2);
+  }
+
+  /* Insert all particles. */
+  this.root = new pv.Quadtree.Node();
+  for (p = particles; p; p = p.next) insert(this.root, p, x1, y1, x2, y2);
+};
+
+/**
+ * The root node of the quadtree.
+ *
+ * @type pv.Quadtree.Node
+ * @name pv.Quadtree.prototype.root
+ */
+
+/**
+ * The minimum x-coordinate value of all contained particles.
+ *
+ * @type number
+ * @name pv.Quadtree.prototype.xMin
+ */
+
+/**
+ * The maximum x-coordinate value of all contained particles.
+ *
+ * @type number
+ * @name pv.Quadtree.prototype.xMax
+ */
+
+/**
+ * The minimum y-coordinate value of all contained particles.
+ *
+ * @type number
+ * @name pv.Quadtree.prototype.yMin
+ */
+
+/**
+ * The maximum y-coordinate value of all contained particles.
+ *
+ * @type number
+ * @name pv.Quadtree.prototype.yMax
+ */
+
+/**
+ * Constructs a new node.
+ *
+ * @class A node in a quadtree.
+ *
+ * @see pv.Quadtree
+ */
+pv.Quadtree.Node = function() {
+  /*
+   * Prepopulating all attributes significantly increases performance! Also,
+   * letting the language interpreter manage garbage collection was moderately
+   * faster than creating a cache pool.
+   */
+  this.leaf = true;
+  this.c1 = null;
+  this.c2 = null;
+  this.c3 = null;
+  this.c4 = null;
+  this.p = null;
+};
+
+/**
+ * True if this node is a leaf node; i.e., it has no children. Note that both
+ * leaf nodes and non-leaf (internal) nodes may have associated particles. If
+ * this is a non-leaf node, then at least one of {@link #c1}, {@link #c2},
+ * {@link #c3} or {@link #c4} is guaranteed to be non-null.
+ *
+ * @type boolean
+ * @name pv.Quadtree.Node.prototype.leaf
+ */
+
+/**
+ * The particle associated with this node, if any.
+ *
+ * @type pv.Particle
+ * @name pv.Quadtree.Node.prototype.p
+ */
+
+/**
+ * The child node for the second quadrant, if any.
+ *
+ * @type pv.Quadtree.Node
+ * @name pv.Quadtree.Node.prototype.c2
+ */
+
+/**
+ * The child node for the third quadrant, if any.
+ *
+ * @type pv.Quadtree.Node
+ * @name pv.Quadtree.Node.prototype.c3
+ */
+
+/**
+ * The child node for the fourth quadrant, if any.
+ *
+ * @type pv.Quadtree.Node
+ * @name pv.Quadtree.Node.prototype.c4
+ */
+/**
+ * Abstract; see an implementing class.
+ *
+ * @class Represents a force that acts on particles. Note that this interface
+ * does not specify how to bind a force to specific particles; in general,
+ * forces are applied globally to all particles. However, some forces may be
+ * applied to specific particles or between particles, such as spring forces,
+ * through additional specialization.
+ *
+ * @see pv.Simulation
+ * @see pv.Particle
+ * @see pv.Force.charge
+ * @see pv.Force.drag
+ * @see pv.Force.spring
+ */
+pv.Force = {};
+
+/**
+ * Applies this force to the specified particles.
+ *
+ * @function
+ * @name pv.Force.prototype.apply
+ * @param {pv.Particle} particles particles to which to apply this force.
+ * @param {pv.Quadtree} q a quadtree for spatial acceleration.
+ */
+/**
+ * Constructs a new charge force, with an optional charge constant. The charge
+ * constant can be negative for repulsion (e.g., particles with electrical
+ * charge of equal sign), or positive for attraction (e.g., massive particles
+ * with mutual gravity). The default charge constant is -40.
+ *
+ * @class An n-body force, as defined by Coulomb's law or Newton's law of
+ * gravitation, inversely proportional to the square of the distance between
+ * particles. Note that the force is independent of the <i>mass</i> of the
+ * associated particles, and that the particles do not have charges of varying
+ * magnitude; instead, the attraction or repulsion of all particles is globally
+ * specified as the charge {@link #constant}.
+ *
+ * <p>This particular implementation uses the Barnes-Hut algorithm. For details,
+ * see <a
+ * href="http://www.nature.com/nature/journal/v324/n6096/abs/324446a0.html">"A
+ * hierarchical O(N log N) force-calculation algorithm"</a>, J. Barnes &amp;
+ * P. Hut, <i>Nature</i> 1986.
+ *
+ * @name pv.Force.charge
+ * @param {number} [k] the charge constant.
+ */
+pv.Force.charge = function(k) {
+  var min = 2, // minimum distance at which to observe forces
+      min1 = 1 / min,
+      max = 500, // maximum distance at which to observe forces
+      max1 = 1 / max,
+      theta = .9, // Barnes-Hut theta approximation constant
+      force = {};
+
+  if (!arguments.length) k = -40; // default charge constant (repulsion)
+
+  /**
+   * Sets or gets the charge constant. If an argument is specified, it is the
+   * new charge constant. The charge constant can be negative for repulsion
+   * (e.g., particles with electrical charge of equal sign), or positive for
+   * attraction (e.g., massive particles with mutual gravity). The default
+   * charge constant is -40.
+   *
+   * @function
+   * @name pv.Force.charge.prototype.constant
+   * @param {number} x the charge constant.
+   * @returns {pv.Force.charge} this.
+   */
+  force.constant = function(x) {
+    if (arguments.length) {
+      k = Number(x);
+      return force;
+    }
+    return k;
+  };
+
+  /**
+   * Sets or gets the domain; specifies the minimum and maximum domain within
+   * which charge forces are applied. A minimum distance threshold avoids
+   * applying forces that are two strong (due to granularity of the simulation's
+   * numeric integration). A maximum distance threshold improves performance by
+   * skipping force calculations for particles that are far apart.
+   *
+   * <p>The default domain is [2, 500].
+   *
+   * @function
+   * @name pv.Force.charge.prototype.domain
+   * @param {number} a
+   * @param {number} b
+   * @returns {pv.Force.charge} this.
+   */
+  force.domain = function(a, b) {
+    if (arguments.length) {
+      min = Number(a);
+      min1 = 1 / min;
+      max = Number(b);
+      max1 = 1 / max;
+      return force;
+    }
+    return [min, max];
+  };
+
+  /**
+   * Sets or gets the Barnes-Hut approximation factor. The Barnes-Hut
+   * approximation criterion is the ratio of the size of the quadtree node to
+   * the distance from the point to the node's center of mass is beneath some
+   * threshold.
+   *
+   * @function
+   * @name pv.Force.charge.prototype.theta
+   * @param {number} x the new Barnes-Hut approximation factor.
+   * @returns {pv.Force.charge} this.
+   */
+  force.theta = function(x) {
+    if (arguments.length) {
+      theta = Number(x);
+      return force;
+    }
+    return theta;
+  };
+
+  /**
+   * @ignore Recursively computes the center of charge for each node in the
+   * quadtree. This is equivalent to the center of mass, assuming that all
+   * particles have unit weight.
+   */
+  function accumulate(n) {
+    var cx = 0, cy = 0;
+    n.cn = 0;
+    function accumulateChild(c) {
+      accumulate(c);
+      n.cn += c.cn;
+      cx += c.cn * c.cx;
+      cy += c.cn * c.cy;
+    }
+    if (!n.leaf) {
+      if (n.c1) accumulateChild(n.c1);
+      if (n.c2) accumulateChild(n.c2);
+      if (n.c3) accumulateChild(n.c3);
+      if (n.c4) accumulateChild(n.c4);
+    }
+    if (n.p) {
+      n.cn += k;
+      cx += k * n.p.x;
+      cy += k * n.p.y;
+    }
+    n.cx = cx / n.cn;
+    n.cy = cy / n.cn;
+  }
+
+  /**
+   * @ignore Recursively computes forces on the given particle using the given
+   * quadtree node. The Barnes-Hut approximation criterion is the ratio of the
+   * size of the quadtree node to the distance from the point to the node's
+   * center of mass is beneath some threshold.
+   */
+  function forces(n, p, x1, y1, x2, y2) {
+    var dx = n.cx - p.x,
+        dy = n.cy - p.y,
+        dn = 1 / Math.sqrt(dx * dx + dy * dy);
+
+    /* Barnes-Hut criterion. */
+    if ((n.leaf && (n.p != p)) || ((x2 - x1) * dn < theta)) {
+      if (dn < max1) return;
+      if (dn > min1) dn = min1;
+      var kc = n.cn * dn * dn * dn,
+          fx = dx * kc,
+          fy = dy * kc;
+      p.fx += fx;
+      p.fy += fy;
+    } else if (!n.leaf) {
+      var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5;
+      if (n.c1) forces(n.c1, p, x1, y1, sx, sy);
+      if (n.c2) forces(n.c2, p, sx, y1, x2, sy);
+      if (n.c3) forces(n.c3, p, x1, sy, sx, y2);
+      if (n.c4) forces(n.c4, p, sx, sy, x2, y2);
+      if (dn < max1) return;
+      if (dn > min1) dn = min1;
+      if (n.p && (n.p != p)) {
+        var kc = k * dn * dn * dn,
+            fx = dx * kc,
+            fy = dy * kc;
+        p.fx += fx;
+        p.fy += fy;
+      }
+    }
+  }
+
+  /**
+   * Applies this force to the specified particles. The force is applied between
+   * all pairs of particles within the domain, using the specified quadtree to
+   * accelerate n-body force calculation using the Barnes-Hut approximation
+   * criterion.
+   *
+   * @function
+   * @name pv.Force.charge.prototype.apply
+   * @param {pv.Particle} particles particles to which to apply this force.
+   * @param {pv.Quadtree} q a quadtree for spatial acceleration.
+   */
+  force.apply = function(particles, q) {
+    accumulate(q.root);
+    for (var p = particles; p; p = p.next) {
+      forces(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
+    }
+  };
+
+  return force;
+};
+/**
+ * Constructs a new drag force with the specified constant.
+ *
+ * @class Implements a drag force, simulating friction. The drag force is
+ * applied in the opposite direction of the particle's velocity. Since Position
+ * Verlet integration does not track velocities explicitly, the error term with
+ * this estimate of velocity is fairly high, so the drag force may be
+ * inaccurate.
+ *
+ * @extends pv.Force
+ * @param {number} k the drag constant.
+ * @see #constant
+ */
+pv.Force.drag = function(k) {
+  var force = {};
+
+  if (!arguments.length) k = .1; // default drag constant
+
+  /**
+   * Sets or gets the drag constant, in the range [0,1]. The default drag
+   * constant is 0.1. The drag forces scales linearly with the particle's
+   * velocity based on the given drag constant.
+   *
+   * @function
+   * @name pv.Force.drag.prototype.constant
+   * @param {number} x the new drag constant.
+   * @returns {pv.Force.drag} this, or the current drag constant.
+   */
+  force.constant = function(x) {
+    if (arguments.length) { k = x; return force; }
+    return k;
+  };
+
+  /**
+   * Applies this force to the specified particles.
+   *
+   * @function
+   * @name pv.Force.drag.prototype.apply
+   * @param {pv.Particle} particles particles to which to apply this force.
+   */
+  force.apply = function(particles) {
+    if (k) for (var p = particles; p; p = p.next) {
+      p.fx -= k * p.vx;
+      p.fy -= k * p.vy;
+    }
+  };
+
+  return force;
+};
+/**
+ * Constructs a new spring force with the specified constant. The links
+ * associated with this spring force must be specified before the spring force
+ * can be applied.
+ *
+ * @class Implements a spring force, per Hooke's law. The spring force can be
+ * configured with a tension constant, rest length, and damping factor. The
+ * tension and damping will automatically be normalized using the inverse square
+ * root of the maximum link degree of attached nodes; this makes springs weaker
+ * between nodes of high link degree.
+ *
+ * <p>Unlike other forces (such as charge and drag forces) which may be applied
+ * globally, spring forces are only applied between linked particles. Therefore,
+ * an array of links must be specified before this force can be applied; the
+ * links should be an array of {@link pv.Layout.Network.Link}s. See also
+ * {@link pv.Layout.Force} for an example of using spring and charge forces for
+ * network layout.
+ *
+ * @extends pv.Force
+ * @param {number} k the spring constant.
+ * @see #constant
+ * @see #links
+ */
+pv.Force.spring = function(k) {
+  var d = .1, // default damping factor
+      l = 20, // default rest length
+      links, // links on which to apply spring forces
+      kl, // per-spring normalization
+      force = {};
+
+  if (!arguments.length) k = .1; // default spring constant (tension)
+
+  /**
+   * Sets or gets the links associated with this spring force. Unlike other
+   * forces (such as charge and drag forces) which may be applied globally,
+   * spring forces are only applied between linked particles. Therefore, an
+   * array of links must be specified before this force can be applied; the
+   * links should be an array of {@link pv.Layout.Network.Link}s.
+   *
+   * @function
+   * @name pv.Force.spring.prototype.links
+   * @param {array} x the new array of links.
+   * @returns {pv.Force.spring} this, or the current array of links.
+   */
+  force.links = function(x) {
+    if (arguments.length) {
+      links = x;
+      kl = x.map(function(l) {
+          return 1 / Math.sqrt(Math.max(
+              l.sourceNode.linkDegree,
+              l.targetNode.linkDegree));
+        });
+      return force;
+    }
+    return links;
+  };
+
+  /**
+   * Sets or gets the spring constant. The default value is 0.1; greater values
+   * will result in stronger tension. The spring tension is automatically
+   * normalized using the inverse square root of the maximum link degree of
+   * attached nodes.
+   *
+   * @function
+   * @name pv.Force.spring.prototype.constant
+   * @param {number} x the new spring constant.
+   * @returns {pv.Force.spring} this, or the current spring constant.
+   */
+  force.constant = function(x) {
+    if (arguments.length) {
+      k = Number(x);
+      return force;
+    }
+    return k;
+  };
+
+  /**
+   * The spring damping factor, in the range [0,1]. Damping functions
+   * identically to drag forces, damping spring bounciness by applying a force
+   * in the opposite direction of attached nodes' velocities. The default value
+   * is 0.1. The spring damping is automatically normalized using the inverse
+   * square root of the maximum link degree of attached nodes.
+   *
+   * @function
+   * @name pv.Force.spring.prototype.damping
+   * @param {number} x the new spring damping factor.
+   * @returns {pv.Force.spring} this, or the current spring damping factor.
+   */
+  force.damping = function(x) {
+    if (arguments.length) {
+      d = Number(x);
+      return force;
+    }
+    return d;
+  };
+
+  /**
+   * The spring rest length. The default value is 20 pixels.
+   *
+   * @function
+   * @name pv.Force.spring.prototype.length
+   * @param {number} x the new spring rest length.
+   * @returns {pv.Force.spring} this, or the current spring rest length.
+   */
+  force.length = function(x) {
+    if (arguments.length) {
+      l = Number(x);
+      return force;
+    }
+    return l;
+  };
+
+  /**
+   * Applies this force to the specified particles.
+   *
+   * @function
+   * @name pv.Force.spring.prototype.apply
+   * @param {pv.Particle} particles particles to which to apply this force.
+   */
+  force.apply = function(particles) {
+    for (var i = 0; i < links.length; i++) {
+      var a = links[i].sourceNode,
+          b = links[i].targetNode,
+          dx = a.x - b.x,
+          dy = a.y - b.y,
+          dn = Math.sqrt(dx * dx + dy * dy),
+          dd = dn ? (1 / dn) : 1,
+          ks = k * kl[i], // normalized tension
+          kd = d * kl[i], // normalized damping
+          kk = (ks * (dn - l) + kd * (dx * (a.vx - b.vx) + dy * (a.vy - b.vy)) * dd) * dd,
+          fx = -kk * (dn ? dx : (.01 * (.5 - Math.random()))),
+          fy = -kk * (dn ? dy : (.01 * (.5 - Math.random())));
+      a.fx += fx;
+      a.fy += fy;
+      b.fx -= fx;
+      b.fy -= fy;
+    }
+  };
+
+  return force;
+};
+/**
+ * Abstract; see an implementing class.
+ *
+ * @class Represents a constraint that acts on particles. Note that this
+ * interface does not specify how to bind a constraint to specific particles; in
+ * general, constraints are applied globally to all particles. However, some
+ * constraints may be applied to specific particles or between particles, such
+ * as position constraints, through additional specialization.
+ *
+ * @see pv.Simulation
+ * @see pv.Particle
+ * @see pv.Constraint.bound
+ * @see pv.Constraint.collision
+ * @see pv.Constraint.position
+ */
+pv.Constraint = {};
+
+/**
+ * Applies this constraint to the specified particles.
+ *
+ * @function
+ * @name pv.Constraint.prototype.apply
+ * @param {pv.Particle} particles particles to which to apply this constraint.
+ * @param {pv.Quadtree} q a quadtree for spatial acceleration.
+ * @returns {pv.Constraint} this.
+ */
+/**
+ * Constructs a new collision constraint. The default search radius is 10, and
+ * the default repeat count is 1. A radius function must be specified to compute
+ * the radius of particles.
+ *
+ * @class Constraints circles to avoid overlap. Each particle is treated as a
+ * circle, with the radius of the particle computed using a specified function.
+ * For example, if the particle has an <tt>r</tt> attribute storing the radius,
+ * the radius <tt>function(d) d.r</tt> specifies a collision constraint using
+ * this radius. The radius function is passed each {@link pv.Particle} as the
+ * first argument.
+ *
+ * <p>To accelerate collision detection, this implementation uses a quadtree and
+ * a search radius. The search radius is computed as the maximum radius of all
+ * particles in the simulation.
+ *
+ * @see pv.Constraint
+ * @param {function} radius the radius function.
+ */
+pv.Constraint.collision = function(radius) {
+  var n = 1, // number of times to repeat the constraint
+      r1,
+      px1,
+      py1,
+      px2,
+      py2,
+      constraint = {};
+
+  if (!arguments.length) r1 = 10; // default search radius
+
+  /**
+   * Sets or gets the repeat count. If the repeat count is greater than 1, the
+   * constraint will be applied repeatedly; this is a form of the Gauss-Seidel
+   * method for constraints relaxation. Repeating the collision constraint makes
+   * the constraint have more of an effect when there is a potential for many
+   * co-occurring collisions.
+   *
+   * @function
+   * @name pv.Constraint.collision.prototype.repeat
+   * @param {number} x the number of times to repeat this constraint.
+   * @returns {pv.Constraint.collision} this.
+   */
+  constraint.repeat = function(x) {
+    if (arguments.length) {
+      n = Number(x);
+      return constraint;
+    }
+    return n;
+  };
+
+  /** @private */
+  function constrain(n, p, x1, y1, x2, y2) {
+    if (!n.leaf) {
+      var sx = (x1 + x2) * .5,
+          sy = (y1 + y2) * .5,
+          top = sy > py1,
+          bottom = sy < py2,
+          left = sx > px1,
+          right = sx < px2;
+      if (top) {
+        if (n.c1 && left) constrain(n.c1, p, x1, y1, sx, sy);
+        if (n.c2 && right) constrain(n.c2, p, sx, y1, x2, sy);
+      }
+      if (bottom) {
+        if (n.c3 && left) constrain(n.c3, p, x1, sy, sx, y2);
+        if (n.c4 && right) constrain(n.c4, p, sx, sy, x2, y2);
+      }
+    }
+    if (n.p && (n.p != p)) {
+      var dx = p.x - n.p.x,
+          dy = p.y - n.p.y,
+          l = Math.sqrt(dx * dx + dy * dy),
+          d = r1 + radius(n.p);
+      if (l < d) {
+        var k = (l - d) / l * .5;
+        dx *= k;
+        dy *= k;
+        p.x -= dx;
+        p.y -= dy;
+        n.p.x += dx;
+        n.p.y += dy;
+      }
+    }
+  }
+
+  /**
+   * Applies this constraint to the specified particles.
+   *
+   * @function
+   * @name pv.Constraint.collision.prototype.apply
+   * @param {pv.Particle} particles particles to which to apply this constraint.
+   * @param {pv.Quadtree} q a quadtree for spatial acceleration.
+   */
+  constraint.apply = function(particles, q) {
+    var p, r, max = -Infinity;
+    for (p = particles; p; p = p.next) {
+      r = radius(p);
+      if (r > max) max = r;
+    }
+    for (var i = 0; i < n; i++) {
+      for (p = particles; p; p = p.next) {
+        r = (r1 = radius(p)) + max;
+        px1 = p.x - r;
+        px2 = p.x + r;
+        py1 = p.y - r;
+        py2 = p.y + r;
+        constrain(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
+      }
+    }
+  };
+
+  return constraint;
+};
+/**
+ * Constructs a default position constraint using the <tt>fix</tt> attribute.
+ * An optional position function can be specified to determine how the fixed
+ * position per-particle is determined.
+ *
+ * @class Constraints particles to a fixed position. The fixed position per
+ * particle is determined using a given position function, which defaults to
+ * <tt>function(d) d.fix</tt>.
+ *
+ * <p>If the position function returns null, then no position constraint is
+ * applied to the given particle. Otherwise, the particle's position is set to
+ * the returned position, as expressed by a {@link pv.Vector}. (Note: the
+ * position does not need to be an instance of <tt>pv.Vector</tt>, but simply an
+ * object with <tt>x</tt> and <tt>y</tt> attributes.)
+ *
+ * <p>This constraint also supports a configurable alpha parameter, which
+ * defaults to 1. If the alpha parameter is in the range [0,1], then rather than
+ * setting the particle's new position directly to the position returned by the
+ * supplied position function, the particle's position is interpolated towards
+ * the fixed position. This results is a smooth (exponential) drift towards the
+ * fixed position, which can increase the stability of the physics simulation.
+ * In addition, the alpha parameter can be decayed over time, relaxing the
+ * position constraint, which helps to stabilize on an optimal solution.
+ *
+ * @param {function} [f] the position function.
+ */
+pv.Constraint.position = function(f) {
+  var a = 1, // default alpha
+      constraint = {};
+
+  if (!arguments.length) /** @ignore */ f = function(p) { return p.fix; };
+
+  /**
+   * Sets or gets the alpha parameter for position interpolation. If the alpha
+   * parameter is in the range [0,1], then rather than setting the particle's
+   * new position directly to the position returned by the supplied position
+   * function, the particle's position is interpolated towards the fixed
+   * position.
+   *
+   * @function
+   * @name pv.Constraint.position.prototype.alpha
+   * @param {number} x the new alpha parameter, in the range [0,1].
+   * @returns {pv.Constraint.position} this.
+   */
+  constraint.alpha = function(x) {
+    if (arguments.length) {
+      a = Number(x);
+      return constraint;
+    }
+    return a;
+  };
+
+  /**
+   * Applies this constraint to the specified particles.
+   *
+   * @function
+   * @name pv.Constraint.position.prototype.apply
+   * @param {pv.Particle} particles particles to which to apply this constraint.
+   */
+  constraint.apply = function(particles) {
+    for (var p = particles; p; p = p.next) {
+      var v = f(p);
+      if (v) {
+        p.x += (v.x - p.x) * a;
+        p.y += (v.y - p.y) * a;
+        p.fx = p.fy = p.vx = p.vy = 0;
+      }
+    }
+  };
+
+  return constraint;
+};
+/**
+ * Constructs a new bound constraint. Before the constraint can be used, the
+ * {@link #x} and {@link #y} methods must be call to specify the bounds.
+ *
+ * @class Constrains particles to within fixed rectangular bounds. For example,
+ * this constraint can be used to constrain particles in a physics simulation
+ * within the bounds of an enclosing panel.
+ *
+ * <p>Note that the current implementation treats particles as points, with no
+ * area. If the particles are rendered as dots, be sure to include some
+ * additional padding to inset the bounds such that the edges of the dots do not
+ * get clipped by the panel bounds. If the particles have different radii, this
+ * constraint would need to be extended using a radius function, similar to
+ * {@link pv.Constraint.collision}.
+ *
+ * @see pv.Layout.Force
+ * @extends pv.Constraint
+ */
+pv.Constraint.bound = function() {
+  var constraint = {},
+      x,
+      y;
+
+  /**
+   * Sets or gets the bounds on the x-coordinate.
+   *
+   * @function
+   * @name pv.Constraint.bound.prototype.x
+   * @param {number} min the minimum allowed x-coordinate.
+   * @param {number} max the maximum allowed x-coordinate.
+   * @returns {pv.Constraint.bound} this.
+   */
+  constraint.x = function(min, max) {
+    if (arguments.length) {
+      x = {min: Math.min(min, max), max: Math.max(min, max)};
+      return this;
+    }
+    return x;
+  };
+
+  /**
+   * Sets or gets the bounds on the y-coordinate.
+   *
+   * @function
+   * @name pv.Constraint.bound.prototype.y
+   * @param {number} min the minimum allowed y-coordinate.
+   * @param {number} max the maximum allowed y-coordinate.
+   * @returns {pv.Constraint.bound} this.
+   */
+  constraint.y = function(min, max) {
+    if (arguments.length) {
+      y = {min: Math.min(min, max), max: Math.max(min, max)};
+      return this;
+    }
+    return y;
+  };
+
+  /**
+   * Applies this constraint to the specified particles.
+   *
+   * @function
+   * @name pv.Constraint.bound.prototype.apply
+   * @param {pv.Particle} particles particles to which to apply this constraint.
+   */
+  constraint.apply = function(particles) {
+    if (x) for (var p = particles; p; p = p.next) {
+      p.x = p.x < x.min ? x.min : (p.x > x.max ? x.max : p.x);
+    }
+    if (y) for (var p = particles; p; p = p.next) {
+      p.y = p.y < y.min ? y.min : (p.y > y.max ? y.max : p.y);
+    }
+  };
+
+  return constraint;
+};
+/**
+ * Constructs a new, empty layout with default properties. Layouts are not
+ * typically constructed directly; instead, a concrete subclass is added to an
+ * existing panel via {@link pv.Mark#add}.
+ *
+ * @class Represents an abstract layout, encapsulating a visualization technique
+ * such as a streamgraph or treemap. Layouts are themselves containers,
+ * extending from {@link pv.Panel}, and defining a set of mark prototypes as
+ * children. These mark prototypes provide default properties that together
+ * implement the given visualization technique.
+ *
+ * <p>Layouts do not initially contain any marks; any exported marks (such as a
+ * network layout's <tt>link</tt> and <tt>node</tt>) are intended to be used as
+ * prototypes. By adding a concrete mark, such as a {@link pv.Bar}, to the
+ * appropriate mark prototype, the mark is added to the layout and inherits the
+ * given properties. This approach allows further customization of the layout,
+ * either by choosing a different mark type to add, or more simply by overriding
+ * some of the layout's defined properties.
+ *
+ * <p>Each concrete layout, such as treemap or circle-packing, has different
+ * behavior and may export different mark prototypes, depending on what marks
+ * are typically needed to render the desired visualization. Therefore it is
+ * important to understand how each layout is structured, such that the provided
+ * mark prototypes are used appropriately.
+ *
+ * <p>In addition to the mark prototypes, layouts may define custom properties
+ * that affect the overall behavior of the layout. For example, a treemap layout
+ * might use a property to specify which layout algorithm to use. These
+ * properties are just like other mark properties, and can be defined as
+ * constants or as functions. As with panels, the data property can be used to
+ * replicate layouts, and properties can be defined to in terms of layout data.
+ *
+ * @extends pv.Panel
+ */
+pv.Layout = function() {
+  pv.Panel.call(this);
+};
+
+pv.Layout.prototype = pv.extend(pv.Panel);
+
+/**
+ * @private Defines a local property with the specified name and cast. Note that
+ * although the property method is only defined locally, the cast function is
+ * global, which is necessary since properties are inherited!
+ *
+ * @param {string} name the property name.
+ * @param {function} [cast] the cast function for this property.
+ */
+pv.Layout.prototype.property = function(name, cast) {
+  if (!this.hasOwnProperty("properties")) {
+    this.properties = pv.extend(this.properties);
+  }
+  this.properties[name] = true;
+  this.propertyMethod(name, false, pv.Mark.cast[name] = cast);
+  return this;
+};
+/**
+ * Constructs a new, empty network layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents an abstract layout for network diagrams. This class
+ * provides the basic structure for both node-link diagrams (such as
+ * force-directed graph layout) and space-filling network diagrams (such as
+ * sunbursts and treemaps). Note that "network" here is a general term that
+ * includes hierarchical structures; a tree is represented using links from
+ * child to parent.
+ *
+ * <p>Network layouts require the graph data structure to be defined using two
+ * properties:<ul>
+ *
+ * <li><tt>nodes</tt> - an array of objects representing nodes. Objects in this
+ * array must conform to the {@link pv.Layout.Network.Node} interface; which is
+ * to say, be careful to avoid naming collisions with automatic attributes such
+ * as <tt>index</tt> and <tt>linkDegree</tt>. If the nodes property is defined
+ * as an array of primitives, such as numbers or strings, these primitives are
+ * automatically wrapped in an object; the resulting object's <tt>nodeValue</tt>
+ * attribute points to the original primitive value.
+ *
+ * <p><li><tt>links</tt> - an array of objects representing links. Objects in
+ * this array must conform to the {@link pv.Layout.Network.Link} interface; at a
+ * minimum, either <tt>source</tt> and <tt>target</tt> indexes or
+ * <tt>sourceNode</tt> and <tt>targetNode</tt> references must be set. Note that
+ * if the links property is defined after the nodes property, the links can be
+ * defined in terms of <tt>this.nodes()</tt>.
+ *
+ * </ul>
+ *
+ * <p>Three standard mark prototypes are provided:<ul>
+ *
+ * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}. The node
+ * mark is added directly to the layout, with the data property defined via the
+ * layout's <tt>nodes</tt> property. Properties such as <tt>strokeStyle</tt> and
+ * <tt>fillStyle</tt> can be overridden to compute properties from node data
+ * dynamically.
+ *
+ * <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Line}. The
+ * link mark is added to a child panel, whose data property is defined as
+ * layout's <tt>links</tt> property. The link's data property is then a
+ * two-element array of the source node and target node. Thus, poperties such as
+ * <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to compute
+ * properties from either the node data (the first argument) or the link data
+ * (the second argument; the parent panel data) dynamically.
+ *
+ * <p><li><tt>label</tt> - for rendering node labels; typically a
+ * {@link pv.Label}. The label mark is added directly to the layout, with the
+ * data property defined via the layout's <tt>nodes</tt> property. Properties
+ * such as <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to
+ * compute properties from node data dynamically.
+ *
+ * </ul>Note that some network implementations may not support all three
+ * standard mark prototypes; for example, space-filling hierarchical layouts
+ * typically do not use a <tt>link</tt> prototype, as the parent-child links are
+ * implied by the structure of the space-filling <tt>node</tt> marks.  Check the
+ * specific network layout for implementation details.
+ *
+ * <p>Network layout properties, including <tt>nodes</tt> and <tt>links</tt>,
+ * are typically cached rather than re-evaluated with every call to render. This
+ * is a performance optimization, as network layout algorithms can be
+ * expensive. If the network structure changes, call {@link #reset} to clear the
+ * cache before rendering. Note that although the network layout properties are
+ * cached, child mark properties, such as the marks used to render the nodes and
+ * links, <i>are not</i>. Therefore, non-structural changes to the network
+ * layout, such as changing the color of a mark on mouseover, do not need to
+ * reset the layout.
+ *
+ * @see pv.Layout.Hierarchy
+ * @see pv.Layout.Force
+ * @see pv.Layout.Matrix
+ * @see pv.Layout.Arc
+ * @see pv.Layout.Rollup
+ * @extends pv.Layout
+ */
+pv.Layout.Network = function() {
+  pv.Layout.call(this);
+  var that = this;
+
+  /* @private Version tracking to cache layout state, improving performance. */
+  this.$id = pv.id();
+
+  /**
+   * The node prototype. This prototype is intended to be used with a Dot mark
+   * in conjunction with the link prototype.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Network.prototype.node
+   */
+  (this.node = new pv.Mark()
+      .data(function() { return that.nodes(); })
+      .strokeStyle("#1f77b4")
+      .fillStyle("#fff")
+      .left(function(n) { return n.x; })
+      .top(function(n) { return n.y; })).parent = this;
+
+  /**
+   * The link prototype, which renders edges between source nodes and target
+   * nodes. This prototype is intended to be used with a Line mark in
+   * conjunction with the node prototype.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Network.prototype.link
+   */
+  this.link = new pv.Mark()
+      .extend(this.node)
+      .data(function(p) { return [p.sourceNode, p.targetNode]; })
+      .fillStyle(null)
+      .lineWidth(function(d, p) { return p.linkValue * 1.5; })
+      .strokeStyle("rgba(0,0,0,.2)");
+
+  this.link.add = function(type) {
+    return that.add(pv.Panel)
+        .data(function() { return that.links(); })
+      .add(type)
+        .extend(this);
+  };
+
+  /**
+   * The node label prototype, which renders the node name adjacent to the node.
+   * This prototype is provided as an alternative to using the anchor on the
+   * node mark; it is primarily intended to be used with radial node-link
+   * layouts, since it provides a convenient mechanism to set the text angle.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Network.prototype.label
+   */
+  (this.label = new pv.Mark()
+      .extend(this.node)
+      .textMargin(7)
+      .textBaseline("middle")
+      .text(function(n) { return n.nodeName || n.nodeValue; })
+      .textAngle(function(n) {
+          var a = n.midAngle;
+          return pv.Wedge.upright(a) ? a : (a + Math.PI);
+        })
+      .textAlign(function(n) {
+          return pv.Wedge.upright(n.midAngle) ? "left" : "right";
+        })).parent = this;
+};
+
+/**
+ * @class Represents a node in a network layout. There is no explicit
+ * constructor; this class merely serves to document the attributes that are
+ * used on nodes in network layouts. (Note that hierarchical nodes place
+ * additional requirements on node representation, vis {@link pv.Dom.Node}.)
+ *
+ * @see pv.Layout.Network
+ * @name pv.Layout.Network.Node
+ */
+
+/**
+ * The node index, zero-based. This attribute is populated automatically based
+ * on the index in the array returned by the <tt>nodes</tt> property.
+ *
+ * @type number
+ * @name pv.Layout.Network.Node.prototype.index
+ */
+
+/**
+ * The link degree; the sum of link values for all incoming and outgoing links.
+ * This attribute is populated automatically.
+ *
+ * @type number
+ * @name pv.Layout.Network.Node.prototype.linkDegree
+ */
+
+/**
+ * The node name; optional. If present, this attribute will be used to provide
+ * the text for node labels. If not present, the label text will fallback to the
+ * <tt>nodeValue</tt> attribute.
+ *
+ * @type string
+ * @name pv.Layout.Network.Node.prototype.nodeName
+ */
+
+/**
+ * The node value; optional. If present, and no <tt>nodeName</tt> attribute is
+ * present, the node value will be used as the label text. This attribute is
+ * also automatically populated if the nodes are specified as an array of
+ * primitives, such as strings or numbers.
+ *
+ * @type object
+ * @name pv.Layout.Network.Node.prototype.nodeValue
+ */
+
+/**
+ * @class Represents a link in a network layout. There is no explicit
+ * constructor; this class merely serves to document the attributes that are
+ * used on links in network layouts. For hierarchical layouts, this class is
+ * used to represent the parent-child links.
+ *
+ * @see pv.Layout.Network
+ * @name pv.Layout.Network.Link
+ */
+
+/**
+ * The link value, or weight; optional. If not specified (or not a number), the
+ * default value of 1 is used.
+ *
+ * @type number
+ * @name pv.Layout.Network.Link.prototype.linkValue
+ */
+
+/**
+ * The link's source node. If not set, this value will be derived from the
+ * <tt>source</tt> attribute index.
+ *
+ * @type pv.Layout.Network.Node
+ * @name pv.Layout.Network.Link.prototype.sourceNode
+ */
+
+/**
+ * The link's target node. If not set, this value will be derived from the
+ * <tt>target</tt> attribute index.
+ *
+ * @type pv.Layout.Network.Node
+ * @name pv.Layout.Network.Link.prototype.targetNode
+ */
+
+/**
+ * Alias for <tt>sourceNode</tt>, as expressed by the index of the source node.
+ * This attribute is not populated automatically, but may be used as a more
+ * convenient identification of the link's source, for example in a static JSON
+ * representation.
+ *
+ * @type number
+ * @name pv.Layout.Network.Link.prototype.source
+ */
+
+/**
+ * Alias for <tt>targetNode</tt>, as expressed by the index of the target node.
+ * This attribute is not populated automatically, but may be used as a more
+ * convenient identification of the link's target, for example in a static JSON
+ * representation.
+ *
+ * @type number
+ * @name pv.Layout.Network.Link.prototype.target
+ */
+
+/**
+ * Alias for <tt>linkValue</tt>. This attribute is not populated automatically,
+ * but may be used instead of the <tt>linkValue</tt> attribute when specifying
+ * links.
+ *
+ * @type number
+ * @name pv.Layout.Network.Link.prototype.value
+ */
+
+/** @private Transform nodes and links on cast. */
+pv.Layout.Network.prototype = pv.extend(pv.Layout)
+    .property("nodes", function(v) {
+        return v.map(function(d, i) {
+            if (typeof d != "object") d = {nodeValue: d};
+            d.index = i;
+            d.linkDegree = 0;
+            return d;
+          });
+      })
+    .property("links", function(v) {
+        return v.map(function(d) {
+            if (isNaN(d.linkValue)) d.linkValue = isNaN(d.value) ? 1 : d.value;
+            return d;
+          });
+      });
+
+/**
+ * Resets the cache, such that changes to layout property definitions will be
+ * visible on subsequent render. Unlike normal marks (and normal layouts),
+ * properties associated with network layouts are not automatically re-evaluated
+ * on render; the properties are cached, and any expensive layout algorithms are
+ * only run after the layout is explicitly reset.
+ *
+ * @returns {pv.Layout.Network} this.
+ */
+pv.Layout.Network.prototype.reset = function() {
+  this.$id = pv.id();
+  return this;
+};
+
+/** @private Skip evaluating properties if cached. */
+pv.Layout.Network.prototype.buildProperties = function(s, properties) {
+  if ((s.$id || 0) < this.$id) {
+    pv.Layout.prototype.buildProperties.call(this, s, properties);
+  }
+};
+
+/** @private Compute link degrees; map source and target indexes to nodes. */
+pv.Layout.Network.prototype.buildImplied = function(s) {
+  pv.Layout.prototype.buildImplied.call(this, s);
+  if (s.$id >= this.$id) return true;
+  s.$id = this.$id;
+  s.links.forEach(function(d) {
+      var v = d.linkValue;
+      (d.sourceNode || (d.sourceNode = s.nodes[d.source])).linkDegree += v;
+      (d.targetNode || (d.targetNode = s.nodes[d.target])).linkDegree += v;
+    });
+};
+/**
+ * Constructs a new, empty hierarchy layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Represents an abstract layout for hierarchy diagrams. This class is a
+ * specialization of {@link pv.Layout.Network}, providing the basic structure
+ * for both hierarchical node-link diagrams (such as Reingold-Tilford trees) and
+ * space-filling hierarchy diagrams (such as sunbursts and treemaps).
+ *
+ * <p>Unlike general network layouts, the <tt>links</tt> property need not be
+ * defined explicitly. Instead, the links are computed implicitly from the
+ * <tt>parentNode</tt> attribute of the node objects, as defined by the
+ * <tt>nodes</tt> property. This implementation is also available as
+ * {@link #links}, for reuse with non-hierarchical layouts; for example, to
+ * render a tree using force-directed layout.
+ *
+ * <p>Correspondingly, the <tt>nodes</tt> property is represented as a union of
+ * {@link pv.Layout.Network.Node} and {@link pv.Dom.Node}. To construct a node
+ * hierarchy from a simple JSON map, use the {@link pv.Dom} operator; this
+ * operator also provides an easy way to sort nodes before passing them to the
+ * layout.
+ *
+ * <p>For more details on how to use this layout, see
+ * {@link pv.Layout.Network}.
+ *
+ * @see pv.Layout.Cluster
+ * @see pv.Layout.Partition
+ * @see pv.Layout.Tree
+ * @see pv.Layout.Treemap
+ * @see pv.Layout.Indent
+ * @see pv.Layout.Pack
+ * @extends pv.Layout.Network
+ */
+pv.Layout.Hierarchy = function() {
+  pv.Layout.Network.call(this);
+  this.link.strokeStyle("#ccc");
+};
+
+pv.Layout.Hierarchy.prototype = pv.extend(pv.Layout.Network);
+
+/** @private Compute the implied links. (Links are null by default.) */
+pv.Layout.Hierarchy.prototype.buildImplied = function(s) {
+  if (!s.links) s.links = pv.Layout.Hierarchy.links.call(this);
+  pv.Layout.Network.prototype.buildImplied.call(this, s);
+};
+
+/** The implied links; computes links using the <tt>parentNode</tt> attribute. */
+pv.Layout.Hierarchy.links = function() {
+  return this.nodes()
+      .filter(function(n) { return n.parentNode; })
+      .map(function(n) {
+          return {
+              sourceNode: n,
+              targetNode: n.parentNode,
+              linkValue: 1
+            };
+      });
+};
+
+/** @private Provides standard node-link layout based on breadth & depth. */
+pv.Layout.Hierarchy.NodeLink = {
+
+  /** @private */
+  buildImplied: function(s) {
+    var nodes = s.nodes,
+        orient = s.orient,
+        horizontal = /^(top|bottom)$/.test(orient),
+        w = s.width,
+        h = s.height;
+
+    /* Compute default inner and outer radius. */
+    if (orient == "radial") {
+      var ir = s.innerRadius, or = s.outerRadius;
+      if (ir == null) ir = 0;
+      if (or == null) or = Math.min(w, h) / 2;
+    }
+
+    /** @private Returns the radius of the given node. */
+    function radius(n) {
+      return n.parentNode ? (n.depth * (or - ir) + ir) : 0;
+    }
+
+    /** @private Returns the angle of the given node. */
+    function midAngle(n) {
+      return (n.parentNode ? (n.breadth - .25) * 2 * Math.PI : 0);
+    }
+
+    /** @private */
+    function x(n) {
+      switch (orient) {
+        case "left": return n.depth * w;
+        case "right": return w - n.depth * w;
+        case "top": return n.breadth * w;
+        case "bottom": return w - n.breadth * w;
+        case "radial": return w / 2 + radius(n) * Math.cos(n.midAngle);
+      }
+    }
+
+    /** @private */
+    function y(n) {
+      switch (orient) {
+        case "left": return n.breadth * h;
+        case "right": return h - n.breadth * h;
+        case "top": return n.depth * h;
+        case "bottom": return h - n.depth * h;
+        case "radial": return h / 2 + radius(n) * Math.sin(n.midAngle);
+      }
+    }
+
+    for (var i = 0; i < nodes.length; i++) {
+      var n = nodes[i];
+      n.midAngle = orient == "radial" ? midAngle(n)
+          : horizontal ? Math.PI / 2 : 0;
+      n.x = x(n);
+      n.y = y(n);
+      if (n.firstChild) n.midAngle += Math.PI;
+    }
+  }
+};
+
+/** @private Provides standard space-filling layout based on breadth & depth. */
+pv.Layout.Hierarchy.Fill = {
+
+  /** @private */
+  constructor: function() {
+    this.node
+        .strokeStyle("#fff")
+        .fillStyle("#ccc")
+        .width(function(n) { return n.dx; })
+        .height(function(n) { return n.dy; })
+        .innerRadius(function(n) { return n.innerRadius; })
+        .outerRadius(function(n) { return n.outerRadius; })
+        .startAngle(function(n) { return n.startAngle; })
+        .angle(function(n) { return n.angle; });
+
+    this.label
+        .textAlign("center")
+        .left(function(n) { return n.x + (n.dx / 2); })
+        .top(function(n) { return n.y + (n.dy / 2); });
+
+    /* Hide unsupported link. */
+    delete this.link;
+  },
+
+  /** @private */
+  buildImplied: function(s) {
+    var nodes = s.nodes,
+        orient = s.orient,
+        horizontal = /^(top|bottom)$/.test(orient),
+        w = s.width,
+        h = s.height,
+        depth = -nodes[0].minDepth;
+
+    /* Compute default inner and outer radius. */
+    if (orient == "radial") {
+      var ir = s.innerRadius, or = s.outerRadius;
+      if (ir == null) ir = 0;
+      if (ir) depth *= 2; // use full depth step for root
+      if (or == null) or = Math.min(w, h) / 2;
+    }
+
+    /** @private Scales the specified depth for a space-filling layout. */
+    function scale(d, depth) {
+      return (d + depth) / (1 + depth);
+    }
+
+    /** @private */
+    function x(n) {
+      switch (orient) {
+        case "left": return scale(n.minDepth, depth) * w;
+        case "right": return (1 - scale(n.maxDepth, depth)) * w;
+        case "top": return n.minBreadth * w;
+        case "bottom": return (1 - n.maxBreadth) * w;
+        case "radial": return w / 2;
+      }
+    }
+
+    /** @private */
+    function y(n) {
+      switch (orient) {
+        case "left": return n.minBreadth * h;
+        case "right": return (1 - n.maxBreadth) * h;
+        case "top": return scale(n.minDepth, depth) * h;
+        case "bottom": return (1 - scale(n.maxDepth, depth)) * h;
+        case "radial": return h / 2;
+      }
+    }
+
+    /** @private */
+    function dx(n) {
+      switch (orient) {
+        case "left":
+        case "right": return (n.maxDepth - n.minDepth) / (1 + depth) * w;
+        case "top":
+        case "bottom": return (n.maxBreadth - n.minBreadth) * w;
+        case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.cos(n.midAngle) : 0;
+      }
+    }
+
+    /** @private */
+    function dy(n) {
+      switch (orient) {
+        case "left":
+        case "right": return (n.maxBreadth - n.minBreadth) * h;
+        case "top":
+        case "bottom": return (n.maxDepth - n.minDepth) / (1 + depth) * h;
+        case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.sin(n.midAngle) : 0;
+      }
+    }
+
+    /** @private */
+    function innerRadius(n) {
+      return Math.max(0, scale(n.minDepth, depth / 2)) * (or - ir) + ir;
+    }
+
+    /** @private */
+    function outerRadius(n) {
+      return scale(n.maxDepth, depth / 2) * (or - ir) + ir;
+    }
+
+    /** @private */
+    function startAngle(n) {
+      return (n.parentNode ? n.minBreadth - .25 : 0) * 2 * Math.PI;
+    }
+
+    /** @private */
+    function angle(n) {
+      return (n.parentNode ? n.maxBreadth - n.minBreadth : 1) * 2 * Math.PI;
+    }
+
+    for (var i = 0; i < nodes.length; i++) {
+      var n = nodes[i];
+      n.x = x(n);
+      n.y = y(n);
+      if (orient == "radial") {
+        n.innerRadius = innerRadius(n);
+        n.outerRadius = outerRadius(n);
+        n.startAngle = startAngle(n);
+        n.angle = angle(n);
+        n.midAngle = n.startAngle + n.angle / 2;
+      } else {
+        n.midAngle = horizontal ? -Math.PI / 2 : 0;
+      }
+      n.dx = dx(n);
+      n.dy = dy(n);
+    }
+  }
+};
+/**
+ * Constructs a new, empty grid layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a grid layout with regularly-sized rows and columns. The
+ * number of rows and columns are determined from their respective
+ * properties. For example, the 2&times;3 array:
+ *
+ * <pre>1 2 3
+ * 4 5 6</pre>
+ *
+ * can be represented using the <tt>rows</tt> property as:
+ *
+ * <pre>[[1, 2, 3], [4, 5, 6]]</pre>
+ *
+ * If your data is in column-major order, you can equivalently use the
+ * <tt>columns</tt> property. If the <tt>rows</tt> property is an array, it
+ * takes priority over the <tt>columns</tt> property. The data is implicitly
+ * transposed, as if the {@link pv.transpose} operator were applied.
+ *
+ * <p>This layout exports a single <tt>cell</tt> mark prototype, which is
+ * intended to be used with a bar, panel, layout, or subclass thereof. The data
+ * property of the cell prototype is defined as the elements in the array. For
+ * example, if the array is a two-dimensional array of values in the range
+ * [0,1], a simple heatmap can be generated as:
+ *
+ * <pre>vis.add(pv.Layout.Grid)
+ *     .rows(arrays)
+ *   .cell.add(pv.Bar)
+ *     .fillStyle(pv.ramp("white", "black"))</pre>
+ *
+ * The grid subdivides the full width and height of the parent panel into equal
+ * rectangles. Note, however, that for large, interactive, or animated heatmaps,
+ * you may see significantly better performance through dynamic {@link pv.Image}
+ * generation.
+ *
+ * <p>For irregular grids using value-based spatial partitioning, see {@link
+ * pv.Layout.Treemap}.
+ *
+ * @extends pv.Layout
+ */
+pv.Layout.Grid = function() {
+  pv.Layout.call(this);
+  var that = this;
+
+  /**
+   * The cell prototype. This prototype is intended to be used with a bar,
+   * panel, or layout (or subclass thereof) to render the grid cells.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Grid.prototype.cell
+   */
+  (this.cell = new pv.Mark()
+      .data(function() {
+          return that.scene[that.index].$grid;
+        })
+      .width(function() {
+          return that.width() / that.cols();
+        })
+      .height(function() {
+          return that.height() / that.rows();
+        })
+      .left(function() {
+          return this.width() * (this.index % that.cols());
+        })
+      .top(function() {
+          return this.height() * Math.floor(this.index / that.cols());
+        })).parent = this;
+};
+
+pv.Layout.Grid.prototype = pv.extend(pv.Layout)
+    .property("rows")
+    .property("cols");
+
+/**
+ * Default properties for grid layouts. By default, there is one row and one
+ * column, and the data is the propagated to the child cell.
+ *
+ * @type pv.Layout.Grid
+ */
+pv.Layout.Grid.prototype.defaults = new pv.Layout.Grid()
+    .extend(pv.Layout.prototype.defaults)
+    .rows(1)
+    .cols(1);
+
+/** @private */
+pv.Layout.Grid.prototype.buildImplied = function(s) {
+  pv.Layout.prototype.buildImplied.call(this, s);
+  var r = s.rows, c = s.cols;
+  if (typeof c == "object") r = pv.transpose(c);
+  if (typeof r == "object") {
+    s.$grid = pv.blend(r);
+    s.rows = r.length;
+    s.cols = r[0] ? r[0].length : 0;
+  } else {
+    s.$grid = pv.repeat([s.data], r * c);
+  }
+};
+
+/**
+ * The number of rows. This property can also be specified as the data in
+ * row-major order; in this case, the rows property is implicitly set to the
+ * length of the array, and the cols property is set to the length of the first
+ * element in the array.
+ *
+ * @type number
+ * @name pv.Layout.Grid.prototype.rows
+ */
+
+/**
+ * The number of columns. This property can also be specified as the data in
+ * column-major order; in this case, the cols property is implicitly set to the
+ * length of the array, and the rows property is set to the length of the first
+ * element in the array.
+ *
+ * @type number
+ * @name pv.Layout.Grid.prototype.cols
+ */
+/**
+ * Constructs a new, empty stack layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a layout for stacked visualizations, ranging from simple
+ * stacked bar charts to more elaborate "streamgraphs" composed of stacked
+ * areas. Stack layouts uses length as a visual encoding, as opposed to
+ * position, as the layers do not share an aligned axis.
+ *
+ * <p>Marks can be stacked vertically or horizontally. For example,
+ *
+ * <pre>vis.add(pv.Layout.Stack)
+ *     .layers([[1, 1.2, 1.7, 1.5, 1.7],
+ *              [.5, 1, .8, 1.1, 1.3],
+ *              [.2, .5, .8, .9, 1]])
+ *     .x(function() this.index * 35)
+ *     .y(function(d) d * 40)
+ *   .layer.add(pv.Area);</pre>
+ *
+ * specifies a vertically-stacked area chart, using the default "bottom-left"
+ * orientation with "zero" offset. This visualization can be easily changed into
+ * a streamgraph using the "wiggle" offset, which attempts to minimize change in
+ * slope weighted by layer thickness. See the {@link #offset} property for more
+ * supported streamgraph algorithms.
+ *
+ * <p>In the simplest case, the layer data can be specified as a two-dimensional
+ * array of numbers. The <tt>x</tt> and <tt>y</tt> psuedo-properties are used to
+ * define the thickness of each layer at the given position, respectively; in
+ * the above example of the "bottom-left" orientation, the <tt>x</tt> and
+ * <tt>y</tt> psuedo-properties are equivalent to the <tt>left</tt> and
+ * <tt>height</tt> properties that you might use if you implemented a stacked
+ * area by hand.
+ *
+ * <p>The advantage of using the stack layout is that the baseline, i.e., the
+ * <tt>bottom</tt> property is computed automatically using the specified offset
+ * algorithm. In addition, the order of layers can be computed using a built-in
+ * algorithm via the <tt>order</tt> property.
+ *
+ * <p>With the exception of the "expand" <tt>offset</tt>, the stack layout does
+ * not perform any automatic scaling of data; the values returned from
+ * <tt>x</tt> and <tt>y</tt> specify pixel sizes. To simplify scaling math, use
+ * this layout in conjunction with {@link pv.Scale.linear} or similar.
+ *
+ * <p>In other cases, the <tt>values</tt> psuedo-property can be used to define
+ * the data more flexibly. As with a typical panel &amp; area, the
+ * <tt>layers</tt> property corresponds to the data in the enclosing panel,
+ * while the <tt>values</tt> psuedo-property corresponds to the data for the
+ * area within the panel. For example, given an array of data values:
+ *
+ * <pre>var crimea = [
+ *  { date: "4/1854", wounds: 0, other: 110, disease: 110 },
+ *  { date: "5/1854", wounds: 0, other: 95, disease: 105 },
+ *  { date: "6/1854", wounds: 0, other: 40, disease: 95 },
+ *  ...</pre>
+ *
+ * and a corresponding array of series names:
+ *
+ * <pre>var causes = ["wounds", "other", "disease"];</pre>
+ *
+ * Separate layers can be defined for each cause like so:
+ *
+ * <pre>vis.add(pv.Layout.Stack)
+ *     .layers(causes)
+ *     .values(crimea)
+ *     .x(function(d) x(d.date))
+ *     .y(function(d, p) y(d[p]))
+ *   .layer.add(pv.Area)
+ *     ...</pre>
+ *
+ * As with the panel &amp; area case, the datum that is passed to the
+ * psuedo-properties <tt>x</tt> and <tt>y</tt> are the values (an element in
+ * <tt>crimea</tt>); the second argument is the layer data (a string in
+ * <tt>causes</tt>). Additional arguments specify the data of enclosing panels,
+ * if any.
+ *
+ * @extends pv.Layout
+ */
+pv.Layout.Stack = function() {
+  pv.Layout.call(this);
+  var that = this,
+      /** @ignore */ none = function() { return null; },
+      prop = {t: none, l: none, r: none, b: none, w: none, h: none},
+      values,
+      buildImplied = that.buildImplied;
+
+  /** @private Proxy the given property on the layer. */
+  function proxy(name) {
+    return function() {
+        return prop[name](this.parent.index, this.index);
+      };
+  }
+
+  /** @private Compute the layout! */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, s);
+
+    var data = s.layers,
+        n = data.length,
+        m,
+        orient = s.orient,
+        horizontal = /^(top|bottom)\b/.test(orient),
+        h = this.parent[horizontal ? "height" : "width"](),
+        x = [],
+        y = [],
+        dy = [];
+
+    /*
+     * Iterate over the data, evaluating the values, x and y functions. The
+     * context in which the x and y psuedo-properties are evaluated is a
+     * pseudo-mark that is a grandchild of this layout.
+     */
+    var stack = pv.Mark.stack, o = {parent: {parent: this}};
+    stack.unshift(null);
+    values = [];
+    for (var i = 0; i < n; i++) {
+      dy[i] = [];
+      y[i] = [];
+      o.parent.index = i;
+      stack[0] = data[i];
+      values[i] = this.$values.apply(o.parent, stack);
+      if (!i) m = values[i].length;
+      stack.unshift(null);
+      for (var j = 0; j < m; j++) {
+        stack[0] = values[i][j];
+        o.index = j;
+        if (!i) x[j] = this.$x.apply(o, stack);
+        dy[i][j] = this.$y.apply(o, stack);
+      }
+      stack.shift();
+    }
+    stack.shift();
+
+    /* order */
+    var index;
+    switch (s.order) {
+      case "inside-out": {
+        var max = dy.map(function(v) { return pv.max.index(v); }),
+            map = pv.range(n).sort(function(a, b) { return max[a] - max[b]; }),
+            sums = dy.map(function(v) { return pv.sum(v); }),
+            top = 0,
+            bottom = 0,
+            tops = [],
+            bottoms = [];
+        for (var i = 0; i < n; i++) {
+          var j = map[i];
+          if (top < bottom) {
+            top += sums[j];
+            tops.push(j);
+          } else {
+            bottom += sums[j];
+            bottoms.push(j);
+          }
+        }
+        index = bottoms.reverse().concat(tops);
+        break;
+      }
+      case "reverse": index = pv.range(n - 1, -1, -1); break;
+      default: index = pv.range(n); break;
+    }
+
+    /* offset */
+    switch (s.offset) {
+      case "silohouette": {
+        for (var j = 0; j < m; j++) {
+          var o = 0;
+          for (var i = 0; i < n; i++) o += dy[i][j];
+          y[index[0]][j] = (h - o) / 2;
+        }
+        break;
+      }
+      case "wiggle": {
+        var o = 0;
+        for (var i = 0; i < n; i++) o += dy[i][0];
+        y[index[0]][0] = o = (h - o) / 2;
+        for (var j = 1; j < m; j++) {
+          var s1 = 0, s2 = 0, dx = x[j] - x[j - 1];
+          for (var i = 0; i < n; i++) s1 += dy[i][j];
+          for (var i = 0; i < n; i++) {
+            var s3 = (dy[index[i]][j] - dy[index[i]][j - 1]) / (2 * dx);
+            for (var k = 0; k < i; k++) {
+              s3 += (dy[index[k]][j] - dy[index[k]][j - 1]) / dx;
+            }
+            s2 += s3 * dy[index[i]][j];
+          }
+          y[index[0]][j] = o -= s1 ? s2 / s1 * dx : 0;
+        }
+        break;
+      }
+      case "expand": {
+        for (var j = 0; j < m; j++) {
+          y[index[0]][j] = 0;
+          var k = 0;
+          for (var i = 0; i < n; i++) k += dy[i][j];
+          if (k) {
+            k = h / k;
+            for (var i = 0; i < n; i++) dy[i][j] *= k;
+          } else {
+            k = h / n;
+            for (var i = 0; i < n; i++) dy[i][j] = k;
+          }
+        }
+        break;
+      }
+      default: {
+        for (var j = 0; j < m; j++) y[index[0]][j] = 0;
+        break;
+      }
+    }
+
+    /* Propagate the offset to the other series. */
+    for (var j = 0; j < m; j++) {
+      var o = y[index[0]][j];
+      for (var i = 1; i < n; i++) {
+        o += dy[index[i - 1]][j];
+        y[index[i]][j] = o;
+      }
+    }
+
+    /* Find the property definitions for dynamic substitution. */
+    var i = orient.indexOf("-"),
+        pdy = horizontal ? "h" : "w",
+        px = i < 0 ? (horizontal ? "l" : "b") : orient.charAt(i + 1),
+        py = orient.charAt(0);
+    for (var p in prop) prop[p] = none;
+    prop[px] = function(i, j) { return x[j]; };
+    prop[py] = function(i, j) { return y[i][j]; };
+    prop[pdy] = function(i, j) { return dy[i][j]; };
+  };
+
+  /**
+   * The layer prototype. This prototype is intended to be used with an area,
+   * bar or panel mark (or subclass thereof). Other mark types may be possible,
+   * though note that the stack layout is not currently designed to support
+   * radial stacked visualizations using wedges.
+   *
+   * <p>The layer is not a direct child of the stack layout; a hidden panel is
+   * used to replicate layers.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Stack.prototype.layer
+   */
+  this.layer = new pv.Mark()
+      .data(function() { return values[this.parent.index]; })
+      .top(proxy("t"))
+      .left(proxy("l"))
+      .right(proxy("r"))
+      .bottom(proxy("b"))
+      .width(proxy("w"))
+      .height(proxy("h"));
+
+  this.layer.add = function(type) {
+    return that.add(pv.Panel)
+        .data(function() { return that.layers(); })
+      .add(type)
+        .extend(this);
+  };
+};
+
+pv.Layout.Stack.prototype = pv.extend(pv.Layout)
+    .property("orient", String)
+    .property("offset", String)
+    .property("order", String)
+    .property("layers");
+
+/**
+ * Default properties for stack layouts. The default orientation is
+ * "bottom-left", the default offset is "zero", and the default layers is
+ * <tt>[[]]</tt>.
+ *
+ * @type pv.Layout.Stack
+ */
+pv.Layout.Stack.prototype.defaults = new pv.Layout.Stack()
+    .extend(pv.Layout.prototype.defaults)
+    .orient("bottom-left")
+    .offset("zero")
+    .layers([[]]);
+
+/** @private */
+pv.Layout.Stack.prototype.$x
+    = /** @private */ pv.Layout.Stack.prototype.$y
+    = function() { return 0; };
+
+/**
+ * The x psuedo-property; determines the position of the value within the layer.
+ * This typically corresponds to the independent variable. For example, with the
+ * default "bottom-left" orientation, this function defines the "left" property.
+ *
+ * @param {function} f the x function.
+ * @returns {pv.Layout.Stack} this.
+ */
+pv.Layout.Stack.prototype.x = function(f) {
+  /** @private */ this.$x = pv.functor(f);
+  return this;
+};
+
+/**
+ * The y psuedo-property; determines the thickness of the layer at the given
+ * value.  This typically corresponds to the dependent variable. For example,
+ * with the default "bottom-left" orientation, this function defines the
+ * "height" property.
+ *
+ * @param {function} f the y function.
+ * @returns {pv.Layout.Stack} this.
+ */
+pv.Layout.Stack.prototype.y = function(f) {
+  /** @private */ this.$y = pv.functor(f);
+  return this;
+};
+
+/** @private The default value function; identity. */
+pv.Layout.Stack.prototype.$values = pv.identity;
+
+/**
+ * The values function; determines the values for a given layer. The default
+ * value is the identity function, which assumes that the layers property is
+ * specified as a two-dimensional (i.e., nested) array.
+ *
+ * @param {function} f the values function.
+ * @returns {pv.Layout.Stack} this.
+ */
+pv.Layout.Stack.prototype.values = function(f) {
+  this.$values = pv.functor(f);
+  return this;
+};
+
+/**
+ * The layer data in row-major order. The value of this property is typically a
+ * two-dimensional (i.e., nested) array, but any array can be used, provided the
+ * values psuedo-property is defined accordingly.
+ *
+ * @type array[]
+ * @name pv.Layout.Stack.prototype.layers
+ */
+
+/**
+ * The layer orientation. The following values are supported:<ul>
+ *
+ * <li>bottom-left == bottom
+ * <li>bottom-right
+ * <li>top-left == top
+ * <li>top-right
+ * <li>left-top
+ * <li>left-bottom == left
+ * <li>right-top
+ * <li>right-bottom == right
+ *
+ * </ul>. The default value is "bottom-left", which means that the layers will
+ * be built from the bottom-up, and the values within layers will be laid out
+ * from left-to-right.
+ *
+ * <p>Note that with non-zero baselines, some orientations may give similar
+ * results. For example, offset("silohouette") centers the layers, resulting in
+ * a streamgraph. Thus, the orientations "bottom-left" and "top-left" will
+ * produce similar results, differing only in the layer order.
+ *
+ * @type string
+ * @name pv.Layout.Stack.prototype.orient
+ */
+
+/**
+ * The layer order. The following values are supported:<ul>
+ *
+ * <li><i>null</i> - use given layer order.
+ * <li>inside-out - sort by maximum value, with balanced order.
+ * <li>reverse - use reverse of given layer order.
+ *
+ * </ul>For details on the inside-out order algorithm, refer to "Stacked Graphs
+ * -- Geometry &amp; Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
+ * November/December 2008.
+ *
+ * @type string
+ * @name pv.Layout.Stack.prototype.order
+ */
+
+/**
+ * The layer offset; the y-position of the bottom of the lowest layer. The
+ * following values are supported:<ul>
+ *
+ * <li>zero - use a zero baseline, i.e., the y-axis.
+ * <li>silohouette - center the stream, i.e., ThemeRiver.
+ * <li>wiggle - minimize weighted change in slope.
+ * <li>expand - expand layers to fill the enclosing layout dimensions.
+ *
+ * </ul>For details on these offset algorithms, refer to "Stacked Graphs --
+ * Geometry &amp; Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
+ * November/December 2008.
+ *
+ * @type string
+ * @name pv.Layout.Stack.prototype.offset
+ */
+/**
+ * Constructs a new, empty treemap layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a space-filling rectangular layout, with the hierarchy
+ * represented via containment. Treemaps represent nodes as boxes, with child
+ * nodes placed within parent boxes. The size of each box is proportional to the
+ * size of the node in the tree. This particular algorithm is taken from Bruls,
+ * D.M., C. Huizing, and J.J. van Wijk, <a
+ * href="http://www.win.tue.nl/~vanwijk/stm.pdf">"Squarified Treemaps"</a> in
+ * <i>Data Visualization 2000, Proceedings of the Joint Eurographics and IEEE
+ * TCVG Sumposium on Visualization</i>, 2000, pp. 33-42.
+ *
+ * <p>The meaning of the exported mark prototypes changes slightly in the
+ * space-filling implementation:<ul>
+ *
+ * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar}. The node
+ * data is populated with <tt>dx</tt> and <tt>dy</tt> attributes, in addition to
+ * the standard <tt>x</tt> and <tt>y</tt> position attributes.
+ *
+ * <p><li><tt>leaf</tt> - for rendering leaf nodes only, with no fill or stroke
+ * style by default; typically a {@link pv.Panel} or another layout!
+ *
+ * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
+ * in the arrangement of the space-filling nodes.
+ *
+ * <p><li><tt>label</tt> - for rendering node labels; typically a
+ * {@link pv.Label}.
+ *
+ * </ul>For more details on how to use this layout, see
+ * {@link pv.Layout.Hierarchy}.
+ *
+ * @extends pv.Layout.Hierarchy
+ */
+pv.Layout.Treemap = function() {
+  pv.Layout.Hierarchy.call(this);
+
+  this.node
+      .strokeStyle("#fff")
+      .fillStyle("rgba(31, 119, 180, .25)")
+      .width(function(n) { return n.dx; })
+      .height(function(n) { return n.dy; });
+
+  this.label
+      .visible(function(n) { return !n.firstChild; })
+      .left(function(n) { return n.x + (n.dx / 2); })
+      .top(function(n) { return n.y + (n.dy / 2); })
+      .textAlign("center")
+      .textAngle(function(n) { return n.dx > n.dy ? 0 : -Math.PI / 2; });
+
+  (this.leaf = new pv.Mark()
+      .extend(this.node)
+      .fillStyle(null)
+      .strokeStyle(null)
+      .visible(function(n) { return !n.firstChild; })).parent = this;
+
+  /* Hide unsupported link. */
+  delete this.link;
+};
+
+pv.Layout.Treemap.prototype = pv.extend(pv.Layout.Hierarchy)
+    .property("round", Boolean)
+    .property("paddingLeft", Number)
+    .property("paddingRight", Number)
+    .property("paddingTop", Number)
+    .property("paddingBottom", Number)
+    .property("mode", String)
+    .property("order", String);
+
+/**
+ * Default propertiess for treemap layouts. The default mode is "squarify" and
+ * the default order is "ascending".
+ *
+ * @type pv.Layout.Treemap
+ */
+pv.Layout.Treemap.prototype.defaults = new pv.Layout.Treemap()
+    .extend(pv.Layout.Hierarchy.prototype.defaults)
+    .mode("squarify") // squarify, slice-and-dice, slice, dice
+    .order("ascending"); // ascending, descending, reverse, null
+
+/**
+ * Whether node sizes should be rounded to integer values. This has a similar
+ * effect to setting <tt>antialias(false)</tt> for node values, but allows the
+ * treemap algorithm to accumulate error related to pixel rounding.
+ *
+ * @type boolean
+ * @name pv.Layout.Treemap.prototype.round
+ */
+
+/**
+ * The left inset between parent add child in pixels. Defaults to 0.
+ *
+ * @type number
+ * @name pv.Layout.Treemap.prototype.paddingLeft
+ * @see #padding
+ */
+
+/**
+ * The right inset between parent add child in pixels. Defaults to 0.
+ *
+ * @type number
+ * @name pv.Layout.Treemap.prototype.paddingRight
+ * @see #padding
+ */
+
+/**
+ * The top inset between parent and child in pixels. Defaults to 0.
+ *
+ * @type number
+ * @name pv.Layout.Treemap.prototype.paddingTop
+ * @see #padding
+ */
+
+/**
+ * The bottom inset between parent and child in pixels. Defaults to 0.
+ *
+ * @type number
+ * @name pv.Layout.Treemap.prototype.paddingBottom
+ * @see #padding
+ */
+
+/**
+ * The treemap algorithm. The default value is "squarify". The "slice-and-dice"
+ * algorithm may also be used, which alternates between horizontal and vertical
+ * slices for different depths. In addition, the "slice" and "dice" algorithms
+ * may be specified explicitly to control whether horizontal or vertical slices
+ * are used, which may be useful for nested treemap layouts.
+ *
+ * @type string
+ * @name pv.Layout.Treemap.prototype.mode
+ * @see <a
+ * href="ftp://ftp.cs.umd.edu/pub/hcil/Reports-Abstracts-Bibliography/2001-06html/2001-06.pdf"
+ * >"Ordered Treemap Layouts"</a> by B. Shneiderman &amp; M. Wattenberg, IEEE
+ * InfoVis 2001.
+ */
+
+/**
+ * The sibling node order. A <tt>null</tt> value means to use the sibling order
+ * specified by the nodes property as-is; "reverse" will reverse the given
+ * order. The default value "ascending" will sort siblings in ascending order of
+ * size, while "descending" will do the reverse. For sorting based on data
+ * attributes other than size, use the default <tt>null</tt> for the order
+ * property, and sort the nodes beforehand using the {@link pv.Dom} operator.
+ *
+ * @type string
+ * @name pv.Layout.Treemap.prototype.order
+ */
+
+/**
+ * Alias for setting the left, right, top and bottom padding properties
+ * simultaneously.
+ *
+ * @see #paddingLeft
+ * @see #paddingRight
+ * @see #paddingTop
+ * @see #paddingBottom
+ * @returns {pv.Layout.Treemap} this.
+ */
+pv.Layout.Treemap.prototype.padding = function(n) {
+  return this.paddingLeft(n).paddingRight(n).paddingTop(n).paddingBottom(n);
+};
+
+/** @private The default size function. */
+pv.Layout.Treemap.prototype.$size = function(d) {
+  return Number(d.nodeValue);
+};
+
+/**
+ * Specifies the sizing function. By default, the size function uses the
+ * <tt>nodeValue</tt> attribute of nodes as a numeric value: <tt>function(d)
+ * Number(d.nodeValue)</tt>.
+ *
+ * <p>The sizing function is invoked for each leaf node in the tree, per the
+ * <tt>nodes</tt> property. For example, if the tree data structure represents a
+ * file system, with files as leaf nodes, and each file has a <tt>bytes</tt>
+ * attribute, you can specify a size function as:
+ *
+ * <pre>    .size(function(d) d.bytes)</pre>
+ *
+ * @param {function} f the new sizing function.
+ * @returns {pv.Layout.Treemap} this.
+ */
+pv.Layout.Treemap.prototype.size = function(f) {
+  this.$size = pv.functor(f);
+  return this;
+};
+
+/** @private */
+pv.Layout.Treemap.prototype.buildImplied = function(s) {
+  if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
+
+  var that = this,
+      nodes = s.nodes,
+      root = nodes[0],
+      stack = pv.Mark.stack,
+      left = s.paddingLeft,
+      right = s.paddingRight,
+      top = s.paddingTop,
+      bottom = s.paddingBottom,
+      /** @ignore */ size = function(n) { return n.size; },
+      round = s.round ? Math.round : Number,
+      mode = s.mode;
+
+  /** @private */
+  function slice(row, sum, horizontal, x, y, w, h) {
+    for (var i = 0, d = 0; i < row.length; i++) {
+      var n = row[i];
+      if (horizontal) {
+        n.x = x + d;
+        n.y = y;
+        d += n.dx = round(w * n.size / sum);
+        n.dy = h;
+      } else {
+        n.x = x;
+        n.y = y + d;
+        n.dx = w;
+        d += n.dy = round(h * n.size / sum);
+      }
+    }
+    if (n) { // correct on-axis rounding error
+      if (horizontal) {
+        n.dx += w - d;
+      } else {
+        n.dy += h - d;
+      }
+    }
+  }
+
+  /** @private */
+  function ratio(row, l) {
+    var rmax = -Infinity, rmin = Infinity, s = 0;
+    for (var i = 0; i < row.length; i++) {
+      var r = row[i].size;
+      if (r < rmin) rmin = r;
+      if (r > rmax) rmax = r;
+      s += r;
+    }
+    s = s * s;
+    l = l * l;
+    return Math.max(l * rmax / s, s / (l * rmin));
+  }
+
+  /** @private */
+  function layout(n, i) {
+    var x = n.x + left,
+        y = n.y + top,
+        w = n.dx - left - right,
+        h = n.dy - top - bottom;
+
+    /* Assume squarify by default. */
+    if (mode != "squarify") {
+      slice(n.childNodes, n.size,
+          mode == "slice" ? true
+          : mode == "dice" ? false
+          : i & 1, x, y, w, h);
+      return;
+    }
+
+    var row = [],
+        mink = Infinity,
+        l = Math.min(w, h),
+        k = w * h / n.size;
+
+    /* Abort if the size is nonpositive. */
+    if (n.size <= 0) return;
+
+    /* Scale the sizes to fill the current subregion. */
+    n.visitBefore(function(n) { n.size *= k; });
+
+    /** @private Position the specified nodes along one dimension. */
+    function position(row) {
+      var horizontal = w == l,
+          sum = pv.sum(row, size),
+          r = l ? round(sum / l) : 0;
+      slice(row, sum, horizontal, x, y, horizontal ? w : r, horizontal ? r : h);
+      if (horizontal) {
+        y += r;
+        h -= r;
+      } else {
+        x += r;
+        w -= r;
+      }
+      l = Math.min(w, h);
+      return horizontal;
+    }
+
+    var children = n.childNodes.slice(); // copy
+    while (children.length) {
+      var child = children[children.length - 1];
+      if (!child.size) {
+        children.pop();
+        continue;
+      }
+      row.push(child);
+
+      var k = ratio(row, l);
+      if (k <= mink) {
+        children.pop();
+        mink = k;
+      } else {
+        row.pop();
+        position(row);
+        row.length = 0;
+        mink = Infinity;
+      }
+    }
+
+    /* correct off-axis rounding error */
+    if (position(row)) for (var i = 0; i < row.length; i++) {
+      row[i].dy += h;
+    } else for (var i = 0; i < row.length; i++) {
+      row[i].dx += w;
+    }
+  }
+
+  /* Recursively compute the node depth and size. */
+  stack.unshift(null);
+  root.visitAfter(function(n, i) {
+      n.depth = i;
+      n.x = n.y = n.dx = n.dy = 0;
+      n.size = n.firstChild
+          ? pv.sum(n.childNodes, function(n) { return n.size; })
+          : that.$size.apply(that, (stack[0] = n, stack));
+    });
+  stack.shift();
+
+  /* Sort. */
+  switch (s.order) {
+    case "ascending": {
+      root.sort(function(a, b) { return a.size - b.size; });
+      break;
+    }
+    case "descending": {
+      root.sort(function(a, b) { return b.size - a.size; });
+      break;
+    }
+    case "reverse": root.reverse(); break;
+  }
+
+  /* Recursively compute the layout. */
+  root.x = 0;
+  root.y = 0;
+  root.dx = s.width;
+  root.dy = s.height;
+  root.visitBefore(layout);
+};
+/**
+ * Constructs a new, empty tree layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a node-link tree diagram using the Reingold-Tilford "tidy"
+ * tree layout algorithm. The specific algorithm used by this layout is based on
+ * <a href="http://citeseer.ist.psu.edu/buchheim02improving.html">"Improving
+ * Walker's Algorithm to Run in Linear Time"</A> by C. Buchheim, M. J&uuml;nger
+ * &amp; S. Leipert, Graph Drawing 2002. This layout supports both cartesian and
+ * radial orientations orientations for node-link diagrams.
+ *
+ * <p>The tree layout supports a "group" property, which if true causes siblings
+ * to be positioned closer together than unrelated nodes at the same depth. The
+ * layout can be configured using the <tt>depth</tt> and <tt>breadth</tt>
+ * properties, which control the increments in pixel space between nodes in both
+ * dimensions, similar to the indent layout.
+ *
+ * <p>For more details on how to use this layout, see
+ * {@link pv.Layout.Hierarchy}.
+ *
+ * @extends pv.Layout.Hierarchy
+ */
+pv.Layout.Tree = function() {
+  pv.Layout.Hierarchy.call(this);
+};
+
+pv.Layout.Tree.prototype = pv.extend(pv.Layout.Hierarchy)
+    .property("group", Number)
+    .property("breadth", Number)
+    .property("depth", Number)
+    .property("orient", String);
+
+/**
+ * Default properties for tree layouts. The default orientation is "top", the
+ * default group parameter is 1, and the default breadth and depth offsets are
+ * 15 and 60 respectively.
+ *
+ * @type pv.Layout.Tree
+ */
+pv.Layout.Tree.prototype.defaults = new pv.Layout.Tree()
+    .extend(pv.Layout.Hierarchy.prototype.defaults)
+    .group(1)
+    .breadth(15)
+    .depth(60)
+    .orient("top");
+
+/** @private */
+pv.Layout.Tree.prototype.buildImplied = function(s) {
+  if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
+
+  var nodes = s.nodes,
+      orient = s.orient,
+      depth = s.depth,
+      breadth = s.breadth,
+      group = s.group,
+      w = s.width,
+      h = s.height;
+
+  /** @private */
+  function firstWalk(v) {
+    var l, r, a;
+    if (!v.firstChild) {
+      if (l = v.previousSibling) {
+        v.prelim = l.prelim + distance(v.depth, true);
+      }
+    } else {
+      l = v.firstChild;
+      r = v.lastChild;
+      a = l; // default ancestor
+      for (var c = l; c; c = c.nextSibling) {
+        firstWalk(c);
+        a = apportion(c, a);
+      }
+      executeShifts(v);
+      var midpoint = .5 * (l.prelim + r.prelim);
+      if (l = v.previousSibling) {
+        v.prelim = l.prelim + distance(v.depth, true);
+        v.mod = v.prelim - midpoint;
+      } else {
+        v.prelim = midpoint;
+      }
+    }
+  }
+
+  /** @private */
+  function secondWalk(v, m, depth) {
+    v.breadth = v.prelim + m;
+    m += v.mod;
+    for (var c = v.firstChild; c; c = c.nextSibling) {
+      secondWalk(c, m, depth);
+    }
+  }
+
+  /** @private */
+  function apportion(v, a) {
+    var w = v.previousSibling;
+    if (w) {
+      var vip = v,
+          vop = v,
+          vim = w,
+          vom = v.parentNode.firstChild,
+          sip = vip.mod,
+          sop = vop.mod,
+          sim = vim.mod,
+          som = vom.mod,
+          nr = nextRight(vim),
+          nl = nextLeft(vip);
+      while (nr && nl) {
+        vim = nr;
+        vip = nl;
+        vom = nextLeft(vom);
+        vop = nextRight(vop);
+        vop.ancestor = v;
+        var shift = (vim.prelim + sim) - (vip.prelim + sip) + distance(vim.depth, false);
+        if (shift > 0) {
+          moveSubtree(ancestor(vim, v, a), v, shift);
+          sip += shift;
+          sop += shift;
+        }
+        sim += vim.mod;
+        sip += vip.mod;
+        som += vom.mod;
+        sop += vop.mod;
+        nr = nextRight(vim);
+        nl = nextLeft(vip);
+      }
+      if (nr && !nextRight(vop)) {
+        vop.thread = nr;
+        vop.mod += sim - sop;
+      }
+      if (nl && !nextLeft(vom)) {
+        vom.thread = nl;
+        vom.mod += sip - som;
+        a = v;
+      }
+    }
+    return a;
+  }
+
+  /** @private */
+  function nextLeft(v) {
+    return v.firstChild || v.thread;
+  }
+
+  /** @private */
+  function nextRight(v) {
+    return v.lastChild || v.thread;
+  }
+
+  /** @private */
+  function moveSubtree(wm, wp, shift) {
+    var subtrees = wp.number - wm.number;
+    wp.change -= shift / subtrees;
+    wp.shift += shift;
+    wm.change += shift / subtrees;
+    wp.prelim += shift;
+    wp.mod += shift;
+  }
+
+  /** @private */
+  function executeShifts(v) {
+    var shift = 0, change = 0;
+    for (var c = v.lastChild; c; c = c.previousSibling) {
+      c.prelim += shift;
+      c.mod += shift;
+      change += c.change;
+      shift += c.shift + change;
+    }
+  }
+
+  /** @private */
+  function ancestor(vim, v, a) {
+    return (vim.ancestor.parentNode == v.parentNode) ? vim.ancestor : a;
+  }
+
+  /** @private */
+  function distance(depth, siblings) {
+    return (siblings ? 1 : (group + 1)) / ((orient == "radial") ? depth : 1);
+  }
+
+  /* Initialize temporary layout variables. TODO: store separately. */
+  var root = nodes[0];
+  root.visitAfter(function(v, i) {
+      v.ancestor = v;
+      v.prelim = 0;
+      v.mod = 0;
+      v.change = 0;
+      v.shift = 0;
+      v.number = v.previousSibling ? (v.previousSibling.number + 1) : 0;
+      v.depth = i;
+    });
+
+  /* Compute the layout using Buchheim et al.'s algorithm. */
+  firstWalk(root);
+  secondWalk(root, -root.prelim, 0);
+
+  /** @private Returns the angle of the given node. */
+  function midAngle(n) {
+    return (orient == "radial") ? n.breadth / depth : 0;
+  }
+
+  /** @private */
+  function x(n) {
+    switch (orient) {
+      case "left": return n.depth;
+      case "right": return w - n.depth;
+      case "top":
+      case "bottom": return n.breadth + w / 2;
+      case "radial": return w / 2 + n.depth * Math.cos(midAngle(n));
+    }
+  }
+
+  /** @private */
+  function y(n) {
+    switch (orient) {
+      case "left":
+      case "right": return n.breadth + h / 2;
+      case "top": return n.depth;
+      case "bottom": return h - n.depth;
+      case "radial": return h / 2 + n.depth * Math.sin(midAngle(n));
+    }
+  }
+
+  /* Clear temporary layout variables; transform depth and breadth. */
+  root.visitAfter(function(v) {
+      v.breadth *= breadth;
+      v.depth *= depth;
+      v.midAngle = midAngle(v);
+      v.x = x(v);
+      v.y = y(v);
+      if (v.firstChild) v.midAngle += Math.PI;
+      delete v.breadth;
+      delete v.depth;
+      delete v.ancestor;
+      delete v.prelim;
+      delete v.mod;
+      delete v.change;
+      delete v.shift;
+      delete v.number;
+      delete v.thread;
+    });
+};
+
+/**
+ * The offset between siblings nodes; defaults to 15.
+ *
+ * @type number
+ * @name pv.Layout.Tree.prototype.breadth
+ */
+
+/**
+ * The offset between parent and child nodes; defaults to 60.
+ *
+ * @type number
+ * @name pv.Layout.Tree.prototype.depth
+ */
+
+/**
+ * The orientation. The default orientation is "top", which means that the root
+ * node is placed on the top edge, leaf nodes appear at the bottom, and internal
+ * nodes are in-between. The following orientations are supported:<ul>
+ *
+ * <li>left - left-to-right.
+ * <li>right - right-to-left.
+ * <li>top - top-to-bottom.
+ * <li>bottom - bottom-to-top.
+ * <li>radial - radially, with the root at the center.</ul>
+ *
+ * @type string
+ * @name pv.Layout.Tree.prototype.orient
+ */
+
+/**
+ * The sibling grouping, i.e., whether differentiating space is placed between
+ * sibling groups. The default is 1 (or true), causing sibling leaves to be
+ * separated by one breadth offset. Setting this to false (or 0) causes
+ * non-siblings to be adjacent.
+ *
+ * @type number
+ * @name pv.Layout.Tree.prototype.group
+ */
+/**
+ * Constructs a new, empty indent layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a hierarchical layout using the indent algorithm. This
+ * layout implements a node-link diagram where the nodes are presented in
+ * preorder traversal, and nodes are indented based on their depth from the
+ * root. This technique is used ubiquitously by operating systems to represent
+ * file directories; although it requires much vertical space, indented trees
+ * allow efficient <i>interactive</i> exploration of trees to find a specific
+ * node. In addition they allow rapid scanning of node labels, and multivariate
+ * data such as file sizes can be displayed adjacent to the hierarchy.
+ *
+ * <p>The indent layout can be configured using the <tt>depth</tt> and
+ * <tt>breadth</tt> properties, which control the increments in pixel space for
+ * each indent and row in the layout. This layout does not support multiple
+ * orientations; the root node is rendered in the top-left, while
+ * <tt>breadth</tt> is a vertical offset from the top, and <tt>depth</tt> is a
+ * horizontal offset from the left.
+ *
+ * <p>For more details on how to use this layout, see
+ * {@link pv.Layout.Hierarchy}.
+ *
+ * @extends pv.Layout.Hierarchy
+ */
+pv.Layout.Indent = function() {
+  pv.Layout.Hierarchy.call(this);
+  this.link.interpolate("step-after");
+};
+
+pv.Layout.Indent.prototype = pv.extend(pv.Layout.Hierarchy)
+    .property("depth", Number)
+    .property("breadth", Number);
+
+/**
+ * The horizontal offset between different levels of the tree; defaults to 15.
+ *
+ * @type number
+ * @name pv.Layout.Indent.prototype.depth
+ */
+
+/**
+ * The vertical offset between nodes; defaults to 15.
+ *
+ * @type number
+ * @name pv.Layout.Indent.prototype.breadth
+ */
+
+/**
+ * Default properties for indent layouts. By default the depth and breadth
+ * offsets are 15 pixels.
+ *
+ * @type pv.Layout.Indent
+ */
+pv.Layout.Indent.prototype.defaults = new pv.Layout.Indent()
+    .extend(pv.Layout.Hierarchy.prototype.defaults)
+    .depth(15)
+    .breadth(15);
+
+/** @private */
+pv.Layout.Indent.prototype.buildImplied = function(s) {
+  if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
+
+  var nodes = s.nodes,
+      bspace = s.breadth,
+      dspace = s.depth,
+      ax = 0,
+      ay = 0;
+
+  /** @private */
+  function position(n, breadth, depth) {
+    n.x = ax + depth++ * dspace;
+    n.y = ay + breadth++ * bspace;
+    n.midAngle = 0;
+    for (var c = n.firstChild; c; c = c.nextSibling) {
+      breadth = position(c, breadth, depth);
+    }
+    return breadth;
+  }
+
+  position(nodes[0], 1, 1);
+};
+/**
+ * Constructs a new, empty circle-packing layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a hierarchical layout using circle-packing. The meaning of
+ * the exported mark prototypes changes slightly in the space-filling
+ * implementation:<ul>
+ *
+ * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
+ *
+ * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
+ * in the arrangement of the space-filling nodes.
+ *
+ * <p><li><tt>label</tt> - for rendering node labels; typically a
+ * {@link pv.Label}.
+ *
+ * </ul>The pack layout support dynamic sizing for leaf nodes, if a
+ * {@link #size} psuedo-property is specified. The default size function returns
+ * 1, causing all leaf nodes to be sized equally, and all internal nodes to be
+ * sized by the number of leaf nodes they have as descendants.
+ *
+ * <p>The size function can be used in conjunction with the order property,
+ * which allows the nodes to the sorted by the computed size. Note: for sorting
+ * based on other data attributes, simply use the default <tt>null</tt> for the
+ * order property, and sort the nodes beforehand using the {@link pv.Dom}
+ * operator.
+ *
+ * <p>For more details on how to use this layout, see
+ * {@link pv.Layout.Hierarchy}.
+ *
+ * @extends pv.Layout.Hierarchy
+ * @see <a href="http://portal.acm.org/citation.cfm?id=1124772.1124851"
+ * >"Visualization of large hierarchical data by circle packing"</a> by W. Wang,
+ * H. Wang, G. Dai, and H. Wang, ACM CHI 2006.
+ */
+pv.Layout.Pack = function() {
+  pv.Layout.Hierarchy.call(this);
+
+  this.node
+      .radius(function(n) { return n.radius; })
+      .strokeStyle("rgb(31, 119, 180)")
+      .fillStyle("rgba(31, 119, 180, .25)");
+
+  this.label
+      .textAlign("center");
+
+  /* Hide unsupported link. */
+  delete this.link;
+};
+
+pv.Layout.Pack.prototype = pv.extend(pv.Layout.Hierarchy)
+    .property("spacing", Number)
+    .property("order", String); // ascending, descending, reverse, null
+
+/**
+ * Default properties for circle-packing layouts. The default spacing parameter
+ * is 1 and the default order is "ascending".
+ *
+ * @type pv.Layout.Pack
+ */
+pv.Layout.Pack.prototype.defaults = new pv.Layout.Pack()
+    .extend(pv.Layout.Hierarchy.prototype.defaults)
+    .spacing(1)
+    .order("ascending");
+
+/**
+ * The spacing parameter; defaults to 1, which provides a little bit of padding
+ * between sibling nodes and the enclosing circle. Larger values increase the
+ * spacing, by making the sibling nodes smaller; a value of zero makes the leaf
+ * nodes as large as possible, with no padding on enclosing circles.
+ *
+ * @type number
+ * @name pv.Layout.Pack.prototype.spacing
+ */
+
+/**
+ * The sibling node order. The default order is <tt>null</tt>, which means to
+ * use the sibling order specified by the nodes property as-is. A value of
+ * "ascending" will sort siblings in ascending order of size, while "descending"
+ * will do the reverse. For sorting based on data attributes other than size,
+ * use the default <tt>null</tt> for the order property, and sort the nodes
+ * beforehand using the {@link pv.Dom} operator.
+ *
+ * @see pv.Dom.Node#sort
+ * @type string
+ * @name pv.Layout.Pack.prototype.order
+ */
+
+/** @private The default size function. */
+pv.Layout.Pack.prototype.$radius = function() { return 1; };
+
+// TODO is it possible for spacing to operate in pixel space?
+// Right now it appears to be multiples of the smallest radius.
+
+/**
+ * Specifies the sizing function. By default, a sizing function is disabled and
+ * all nodes are given constant size. The sizing function is invoked for each
+ * leaf node in the tree (passed to the constructor).
+ *
+ * <p>For example, if the tree data structure represents a file system, with
+ * files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
+ * specify a size function as:
+ *
+ * <pre>    .size(function(d) d.bytes)</pre>
+ *
+ * As with other properties, a size function may specify additional arguments to
+ * access the data associated with the layout and any enclosing panels.
+ *
+ * @param {function} f the new sizing function.
+ * @returns {pv.Layout.Pack} this.
+ */
+pv.Layout.Pack.prototype.size = function(f) {
+  this.$radius = typeof f == "function"
+      ? function() { return Math.sqrt(f.apply(this, arguments)); }
+      : (f = Math.sqrt(f), function() { return f; });
+  return this;
+};
+
+/** @private */
+pv.Layout.Pack.prototype.buildImplied = function(s) {
+  if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
+
+  var that = this,
+      nodes = s.nodes,
+      root = nodes[0];
+
+  /** @private Compute the radii of the leaf nodes. */
+  function radii(nodes) {
+    var stack = pv.Mark.stack;
+    stack.unshift(null);
+    for (var i = 0, n = nodes.length; i < n; i++) {
+      var c = nodes[i];
+      if (!c.firstChild) {
+        c.radius = that.$radius.apply(that, (stack[0] = c, stack));
+      }
+    }
+    stack.shift();
+  }
+
+  /** @private */
+  function packTree(n) {
+    var nodes = [];
+    for (var c = n.firstChild; c; c = c.nextSibling) {
+      if (c.firstChild) c.radius = packTree(c);
+      c.n = c.p = c;
+      nodes.push(c);
+    }
+
+    /* Sort. */
+    switch (s.order) {
+      case "ascending": {
+        nodes.sort(function(a, b) { return a.radius - b.radius; });
+        break;
+      }
+      case "descending": {
+        nodes.sort(function(a, b) { return b.radius - a.radius; });
+        break;
+      }
+      case "reverse": nodes.reverse(); break;
+    }
+
+    return packCircle(nodes);
+  }
+
+  /** @private */
+  function packCircle(nodes) {
+    var xMin = Infinity,
+        xMax = -Infinity,
+        yMin = Infinity,
+        yMax = -Infinity,
+        a, b, c, j, k;
+
+    /** @private */
+    function bound(n) {
+      xMin = Math.min(n.x - n.radius, xMin);
+      xMax = Math.max(n.x + n.radius, xMax);
+      yMin = Math.min(n.y - n.radius, yMin);
+      yMax = Math.max(n.y + n.radius, yMax);
+    }
+
+    /** @private */
+    function insert(a, b) {
+      var c = a.n;
+      a.n = b;
+      b.p = a;
+      b.n = c;
+      c.p = b;
+    }
+
+    /** @private */
+    function splice(a, b) {
+      a.n = b;
+      b.p = a;
+    }
+
+    /** @private */
+    function intersects(a, b) {
+      var dx = b.x - a.x,
+          dy = b.y - a.y,
+          dr = a.radius + b.radius;
+      return (dr * dr - dx * dx - dy * dy) > .001; // within epsilon
+    }
+
+    /* Create first node. */
+    a = nodes[0];
+    a.x = -a.radius;
+    a.y = 0;
+    bound(a);
+
+    /* Create second node. */
+    if (nodes.length > 1) {
+      b = nodes[1];
+      b.x = b.radius;
+      b.y = 0;
+      bound(b);
+
+      /* Create third node and build chain. */
+      if (nodes.length > 2) {
+        c = nodes[2];
+        place(a, b, c);
+        bound(c);
+        insert(a, c);
+        a.p = c;
+        insert(c, b);
+        b = a.n;
+
+        /* Now iterate through the rest. */
+        for (var i = 3; i < nodes.length; i++) {
+          place(a, b, c = nodes[i]);
+
+          /* Search for the closest intersection. */
+          var isect = 0, s1 = 1, s2 = 1;
+          for (j = b.n; j != b; j = j.n, s1++) {
+            if (intersects(j, c)) {
+              isect = 1;
+              break;
+            }
+          }
+          if (isect == 1) {
+            for (k = a.p; k != j.p; k = k.p, s2++) {
+              if (intersects(k, c)) {
+                if (s2 < s1) {
+                  isect = -1;
+                  j = k;
+                }
+                break;
+              }
+            }
+          }
+
+          /* Update node chain. */
+          if (isect == 0) {
+            insert(a, c);
+            b = c;
+            bound(c);
+          } else if (isect > 0) {
+            splice(a, j);
+            b = j;
+            i--;
+          } else if (isect < 0) {
+            splice(j, b);
+            a = j;
+            i--;
+          }
+        }
+      }
+    }
+
+    /* Re-center the circles and return the encompassing radius. */
+    var cx = (xMin + xMax) / 2,
+        cy = (yMin + yMax) / 2,
+        cr = 0;
+    for (var i = 0; i < nodes.length; i++) {
+      var n = nodes[i];
+      n.x -= cx;
+      n.y -= cy;
+      cr = Math.max(cr, n.radius + Math.sqrt(n.x * n.x + n.y * n.y));
+    }
+    return cr + s.spacing;
+  }
+
+  /** @private */
+  function place(a, b, c) {
+    var da = b.radius + c.radius,
+        db = a.radius + c.radius,
+        dx = b.x - a.x,
+        dy = b.y - a.y,
+        dc = Math.sqrt(dx * dx + dy * dy),
+        cos = (db * db + dc * dc - da * da) / (2 * db * dc),
+        theta = Math.acos(cos),
+        x = cos * db,
+        h = Math.sin(theta) * db;
+    dx /= dc;
+    dy /= dc;
+    c.x = a.x + x * dx + h * dy;
+    c.y = a.y + x * dy - h * dx;
+  }
+
+  /** @private */
+  function transform(n, x, y, k) {
+    for (var c = n.firstChild; c; c = c.nextSibling) {
+      c.x += n.x;
+      c.y += n.y;
+      transform(c, x, y, k);
+    }
+    n.x = x + k * n.x;
+    n.y = y + k * n.y;
+    n.radius *= k;
+  }
+
+  radii(nodes);
+
+  /* Recursively compute the layout. */
+  root.x = 0;
+  root.y = 0;
+  root.radius = packTree(root);
+
+  var w = this.width(),
+      h = this.height(),
+      k = 1 / Math.max(2 * root.radius / w, 2 * root.radius / h);
+  transform(root, w / 2, h / 2, k);
+};
+/**
+ * Constructs a new, empty force-directed layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements force-directed network layout as a node-link diagram. This
+ * layout uses the Fruchterman-Reingold algorithm, which applies an attractive
+ * spring force between neighboring nodes, and a repulsive electrical charge
+ * force between all nodes. An additional drag force improves stability of the
+ * simulation. See {@link pv.Force.spring}, {@link pv.Force.drag} and {@link
+ * pv.Force.charge} for more details; note that the n-body charge force is
+ * approximated using the Barnes-Hut algorithm.
+ *
+ * <p>This layout is implemented on top of {@link pv.Simulation}, which can be
+ * used directly for more control over simulation parameters. The simulation
+ * uses Position Verlet integration, which does not compute velocities
+ * explicitly, but allows for easy geometric constraints, such as bounding the
+ * nodes within the layout panel. Many of the configuration properties supported
+ * by this layout are simply passed through to the underlying forces and
+ * constraints of the simulation.
+ *
+ * <p>Force layouts are typically interactive. The gradual movement of the nodes
+ * as they stabilize to a local stress minimum can help reveal the structure of
+ * the network, as can {@link pv.Behavior.drag}, which allows the user to pick
+ * up nodes and reposition them while the physics simulation continues. This
+ * layout can also be used with pan &amp; zoom behaviors for interaction.
+ *
+ * <p>To facilitate interaction, this layout by default automatically re-renders
+ * using a <tt>setInterval</tt> every 42 milliseconds. This can be disabled via
+ * the <tt>iterations</tt> property, which if non-null specifies the number of
+ * simulation iterations to run before the force-directed layout is finalized.
+ * Be careful not to use too high an iteration count, as this can lead to an
+ * annoying delay on page load.
+ *
+ * <p>As with other network layouts, the network data can be updated
+ * dynamically, provided the property cache is reset. See
+ * {@link pv.Layout.Network} for details. New nodes are initialized with random
+ * positions near the center. Alternatively, positions can be specified manually
+ * by setting the <tt>x</tt> and <tt>y</tt> attributes on nodes.
+ *
+ * @extends pv.Layout.Network
+ * @see <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.13.8444&rep=rep1&type=pdf"
+ * >"Graph Drawing by Force-directed Placement"</a> by T. Fruchterman &amp;
+ * E. Reingold, Software--Practice &amp; Experience, November 1991.
+ */
+pv.Layout.Force = function() {
+  pv.Layout.Network.call(this);
+
+  /* Force-directed graphs can be messy, so reduce the link width. */
+  this.link.lineWidth(function(d, p) { return Math.sqrt(p.linkValue) * 1.5; });
+  this.label.textAlign("center");
+};
+
+pv.Layout.Force.prototype = pv.extend(pv.Layout.Network)
+    .property("bound", Boolean)
+    .property("iterations", Number)
+    .property("dragConstant", Number)
+    .property("chargeConstant", Number)
+    .property("chargeMinDistance", Number)
+    .property("chargeMaxDistance", Number)
+    .property("chargeTheta", Number)
+    .property("springConstant", Number)
+    .property("springDamping", Number)
+    .property("springLength", Number);
+
+/**
+ * The bound parameter; true if nodes should be constrained within the layout
+ * panel. Bounding is disabled by default. Currently the layout does not observe
+ * the radius of the nodes; strictly speaking, only the center of the node is
+ * constrained to be within the panel, with an additional 6-pixel offset for
+ * padding. A future enhancement could extend the bound constraint to observe
+ * the node's radius, which would also support bounding for variable-size nodes.
+ *
+ * <p>Note that if this layout is used in conjunction with pan &amp; zoom
+ * behaviors, those behaviors should have their bound parameter set to the same
+ * value.
+ *
+ * @type boolean
+ * @name pv.Layout.Force.prototype.bound
+ */
+
+/**
+ * The number of simulation iterations to run, or null if this layout is
+ * interactive. Force-directed layouts are interactive by default, using a
+ * <tt>setInterval</tt> to advance the physics simulation and re-render
+ * automatically.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.iterations
+ */
+
+/**
+ * The drag constant, in the range [0,1]. A value of 0 means no drag (a
+ * perfectly frictionless environment), while a value of 1 means friction
+ * immediately cancels all momentum. The default value is 0.1, which provides a
+ * minimum amount of drag that helps stabilize bouncy springs; lower values may
+ * result in excessive bounciness, while higher values cause the simulation to
+ * take longer to converge.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.dragConstant
+ * @see pv.Force.drag#constant
+ */
+
+/**
+ * The charge constant, which should be a negative number. The default value is
+ * -40; more negative values will result in a stronger repulsive force, which
+ * may lead to faster convergence at the risk of instability. Too strong
+ * repulsive charge forces can cause comparatively weak springs to be stretched
+ * well beyond their rest length, emphasizing global structure over local
+ * structure. A nonnegative value will break the Fruchterman-Reingold algorithm,
+ * and is for entertainment purposes only.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.chargeConstant
+ * @see pv.Force.charge#constant
+ */
+
+/**
+ * The minimum distance at which charge forces are applied. The default minimum
+ * distance of 2 avoids applying forces that are two strong; because the physics
+ * simulation is run at discrete time intervals, it is possible for two same-
+ * charged particles to become very close or even a singularity! Since the
+ * charge force is inversely proportional to the square of the distance, very
+ * small distances can break the simulation.
+ *
+ * <p>In rare cases, two particles can become stuck on top of each other, as a
+ * minimum distance threshold will prevent the charge force from repelling them.
+ * However, this occurs very rarely because other forces and momentum typically
+ * cause the particles to become separated again, at which point the repulsive
+ * charge force kicks in.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.chargeMinDistance
+ * @see pv.Force.charge#domain
+ */
+
+/**
+ * The maximum distance at which charge forces are applied. This improves
+ * performance by ignoring weak charge forces at great distances. Note that this
+ * parameter is partly redundant, as the Barnes-Hut algorithm for n-body forces
+ * already improves performance for far-away particles through approximation.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.chargeMaxDistance
+ * @see pv.Force.charge#domain
+ */
+
+/**
+ * The Barnes-Hut approximation factor. The Barnes-Hut approximation criterion
+ * is the ratio of the size of the quadtree node to the distance from the point
+ * to the node's center of mass is beneath some threshold. The default value is
+ * 0.9.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.chargeTheta
+ * @see pv.Force.charge#theta
+ */
+
+/**
+ * The spring constant, which should be a positive number. The default value is
+ * 0.1; greater values will result in a stronger attractive force, which may
+ * lead to faster convergence at the risk of instability. Too strong spring
+ * forces can cause comparatively weak charge forces to be ignored, emphasizing
+ * local structure over global structure. A nonpositive value will break the
+ * Fruchterman-Reingold algorithm, and is for entertainment purposes only.
+ *
+ * <p>The spring tension is automatically normalized using the inverse square
+ * root of the maximum link degree of attached nodes.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.springConstant
+ * @see pv.Force.spring#constant
+ */
+
+/**
+ * The spring damping factor, in the range [0,1]. Damping functions identically
+ * to drag forces, damping spring bounciness by applying a force in the opposite
+ * direction of attached nodes' velocities. The default value is 0.3.
+ *
+ * <p>The spring damping is automatically normalized using the inverse square
+ * root of the maximum link degree of attached nodes.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.springDamping
+ * @see pv.Force.spring#damping
+ */
+
+/**
+ * The spring rest length. The default value is 20 pixels. Larger values may be
+ * appropriate if the layout panel is larger, or if the nodes are rendered
+ * larger than the default dot size of 20.
+ *
+ * @type number
+ * @name pv.Layout.Force.prototype.springLength
+ * @see pv.Force.spring#length
+ */
+
+/**
+ * Default properties for force-directed layouts. The default drag constant is
+ * 0.1, the default charge constant is -40 (with a domain of [2, 500] and theta
+ * of 0.9), and the default spring constant is 0.1 (with a damping of 0.3 and a
+ * rest length of 20).
+ *
+ * @type pv.Layout.Force
+ */
+pv.Layout.Force.prototype.defaults = new pv.Layout.Force()
+    .extend(pv.Layout.Network.prototype.defaults)
+    .dragConstant(.1)
+    .chargeConstant(-40)
+    .chargeMinDistance(2)
+    .chargeMaxDistance(500)
+    .chargeTheta(.9)
+    .springConstant(.1)
+    .springDamping(.3)
+    .springLength(20);
+
+/** @private Initialize the physics simulation. */
+pv.Layout.Force.prototype.buildImplied = function(s) {
+
+  /* Any cached interactive layouts need to be rebound for the timer. */
+  if (pv.Layout.Network.prototype.buildImplied.call(this, s)) {
+    var f = s.$force;
+    if (f) {
+      f.next = this.binds.$force;
+      this.binds.$force = f;
+    }
+    return;
+  }
+
+  var that = this,
+      nodes = s.nodes,
+      links = s.links,
+      k = s.iterations,
+      w = s.width,
+      h = s.height;
+
+  /* Initialize positions randomly near the center. */
+  for (var i = 0, n; i < nodes.length; i++) {
+    n = nodes[i];
+    if (isNaN(n.x)) n.x = w / 2 + 40 * Math.random() - 20;
+    if (isNaN(n.y)) n.y = h / 2 + 40 * Math.random() - 20;
+  }
+
+  /* Initialize the simulation. */
+  var sim = pv.simulation(nodes);
+
+  /* Drag force. */
+  sim.force(pv.Force.drag(s.dragConstant));
+
+  /* Charge (repelling) force. */
+  sim.force(pv.Force.charge(s.chargeConstant)
+      .domain(s.chargeMinDistance, s.chargeMaxDistance)
+      .theta(s.chargeTheta));
+
+  /* Spring (attracting) force. */
+  sim.force(pv.Force.spring(s.springConstant)
+      .damping(s.springDamping)
+      .length(s.springLength)
+      .links(links));
+
+  /* Position constraint (for interactive dragging). */
+  sim.constraint(pv.Constraint.position());
+
+  /* Optionally add bound constraint. TODO: better padding. */
+  if (s.bound) {
+    sim.constraint(pv.Constraint.bound().x(6, w - 6).y(6, h - 6));
+  }
+
+  /** @private Returns the speed of the given node, to determine cooling. */
+  function speed(n) {
+    return n.fix ? 1 : n.vx * n.vx + n.vy * n.vy;
+  }
+
+  /*
+   * If the iterations property is null (the default), the layout is
+   * interactive. The simulation is run until the fastest particle drops below
+   * an arbitrary minimum speed. Although the timer keeps firing, this speed
+   * calculation is fast so there is minimal CPU overhead. Note: if a particle
+   * is fixed for interactivity, treat this as a high speed and resume
+   * simulation.
+   */
+  if (k == null) {
+    sim.step(); // compute initial previous velocities
+    sim.step(); // compute initial velocities
+
+    /* Add the simulation state to the bound list. */
+    var force = s.$force = this.binds.$force = {
+      next: this.binds.$force,
+      nodes: nodes,
+      min: 1e-4 * (links.length + 1),
+      sim: sim
+    };
+
+    /* Start the timer, if not already started. */
+    if (!this.$timer) this.$timer = setInterval(function() {
+      var render = false;
+      for (var f = that.binds.$force; f; f = f.next) {
+        if (pv.max(f.nodes, speed) > f.min) {
+          f.sim.step();
+          render = true;
+        }
+      }
+      if (render) that.render();
+    }, 42);
+  } else for (var i = 0; i < k; i++) {
+    sim.step();
+  }
+};
+/**
+ * Constructs a new, empty cluster layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a hierarchical layout using the cluster (or dendrogram)
+ * algorithm. This layout provides both node-link and space-filling
+ * implementations of cluster diagrams. In many ways it is similar to
+ * {@link pv.Layout.Partition}, except that leaf nodes are positioned at maximum
+ * depth, and the depth of internal nodes is based on their distance from their
+ * deepest descendant, rather than their distance from the root.
+ *
+ * <p>The cluster layout supports a "group" property, which if true causes
+ * siblings to be positioned closer together than unrelated nodes at the same
+ * depth. Unlike the partition layout, this layout does not support dynamic
+ * sizing for leaf nodes; all leaf nodes are the same size.
+ *
+ * <p>For more details on how to use this layout, see
+ * {@link pv.Layout.Hierarchy}.
+ *
+ * @see pv.Layout.Cluster.Fill
+ * @extends pv.Layout.Hierarchy
+ */
+pv.Layout.Cluster = function() {
+  pv.Layout.Hierarchy.call(this);
+  var interpolate, // cached interpolate
+      buildImplied = this.buildImplied;
+
+  /** @private Cache layout state to optimize properties. */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, s);
+    interpolate
+        = /^(top|bottom)$/.test(s.orient) ? "step-before"
+        : /^(left|right)$/.test(s.orient) ? "step-after"
+        : "linear";
+  };
+
+  this.link.interpolate(function() { return interpolate; });
+};
+
+pv.Layout.Cluster.prototype = pv.extend(pv.Layout.Hierarchy)
+    .property("group", Number)
+    .property("orient", String)
+    .property("innerRadius", Number)
+    .property("outerRadius", Number);
+
+/**
+ * The group parameter; defaults to 0, disabling grouping of siblings. If this
+ * parameter is set to a positive number (or true, which is equivalent to 1),
+ * then additional space will be allotted between sibling groups. In other
+ * words, siblings (nodes that share the same parent) will be positioned more
+ * closely than nodes at the same depth that do not share a parent.
+ *
+ * @type number
+ * @name pv.Layout.Cluster.prototype.group
+ */
+
+/**
+ * The orientation. The default orientation is "top", which means that the root
+ * node is placed on the top edge, leaf nodes appear on the bottom edge, and
+ * internal nodes are in-between. The following orientations are supported:<ul>
+ *
+ * <li>left - left-to-right.
+ * <li>right - right-to-left.
+ * <li>top - top-to-bottom.
+ * <li>bottom - bottom-to-top.
+ * <li>radial - radially, with the root at the center.</ul>
+ *
+ * @type string
+ * @name pv.Layout.Cluster.prototype.orient
+ */
+
+/**
+ * The inner radius; defaults to 0. This property applies only to radial
+ * orientations, and can be used to compress the layout radially. Note that for
+ * the node-link implementation, the root node is always at the center,
+ * regardless of the value of this property; this property only affects internal
+ * and leaf nodes. For the space-filling implementation, a non-zero value of
+ * this property will result in the root node represented as a ring rather than
+ * a circle.
+ *
+ * @type number
+ * @name pv.Layout.Cluster.prototype.innerRadius
+ */
+
+/**
+ * The outer radius; defaults to fill the containing panel, based on the height
+ * and width of the layout. If the layout has no height and width specified, it
+ * will extend to fill the enclosing panel.
+ *
+ * @type number
+ * @name pv.Layout.Cluster.prototype.outerRadius
+ */
+
+/**
+ * Defaults for cluster layouts. The default group parameter is 0 and the
+ * default orientation is "top".
+ *
+ * @type pv.Layout.Cluster
+ */
+pv.Layout.Cluster.prototype.defaults = new pv.Layout.Cluster()
+    .extend(pv.Layout.Hierarchy.prototype.defaults)
+    .group(0)
+    .orient("top");
+
+/** @private */
+pv.Layout.Cluster.prototype.buildImplied = function(s) {
+  if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
+
+  var root = s.nodes[0],
+      group = s.group,
+      breadth,
+      depth,
+      leafCount = 0,
+      leafIndex = .5 - group / 2;
+
+  /* Count the leaf nodes and compute the depth of descendants. */
+  var p = undefined;
+  root.visitAfter(function(n) {
+      if (n.firstChild) {
+        n.depth = 1 + pv.max(n.childNodes, function(n) { return n.depth; });
+      } else {
+        if (group && (p != n.parentNode)) {
+          p = n.parentNode;
+          leafCount += group;
+        }
+        leafCount++;
+        n.depth = 0;
+      }
+    });
+  breadth = 1 / leafCount;
+  depth = 1 / root.depth;
+
+  /* Compute the unit breadth and depth of each node. */
+  var p = undefined;
+  root.visitAfter(function(n) {
+      if (n.firstChild) {
+        n.breadth = pv.mean(n.childNodes, function(n) { return n.breadth; });
+      } else {
+        if (group && (p != n.parentNode)) {
+          p = n.parentNode;
+          leafIndex += group;
+        }
+        n.breadth = breadth * leafIndex++;
+      }
+      n.depth = 1 - n.depth * depth;
+    });
+
+  /* Compute breadth and depth ranges for space-filling layouts. */
+  root.visitAfter(function(n) {
+      n.minBreadth = n.firstChild
+          ? n.firstChild.minBreadth
+          : (n.breadth - breadth / 2);
+      n.maxBreadth = n.firstChild
+          ? n.lastChild.maxBreadth
+          : (n.breadth + breadth / 2);
+    });
+  root.visitBefore(function(n) {
+      n.minDepth = n.parentNode
+          ? n.parentNode.maxDepth
+          : 0;
+      n.maxDepth = n.parentNode
+          ? (n.depth + root.depth)
+          : (n.minDepth + 2 * root.depth);
+    });
+  root.minDepth = -depth;
+
+  pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
+};
+
+/**
+ * Constructs a new, empty space-filling cluster layout. Layouts are not
+ * typically constructed directly; instead, they are added to an existing panel
+ * via {@link pv.Mark#add}.
+ *
+ * @class A variant of cluster layout that is space-filling. The meaning of the
+ * exported mark prototypes changes slightly in the space-filling
+ * implementation:<ul>
+ *
+ * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
+ * non-radial orientations, and a {@link pv.Wedge} for radial orientations.
+ *
+ * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
+ * in the arrangement of the space-filling nodes.
+ *
+ * <p><li><tt>label</tt> - for rendering node labels; typically a
+ * {@link pv.Label}.
+ *
+ * </ul>For more details on how to use this layout, see
+ * {@link pv.Layout.Cluster}.
+ *
+ * @extends pv.Layout.Cluster
+ */
+pv.Layout.Cluster.Fill = function() {
+  pv.Layout.Cluster.call(this);
+  pv.Layout.Hierarchy.Fill.constructor.call(this);
+};
+
+pv.Layout.Cluster.Fill.prototype = pv.extend(pv.Layout.Cluster);
+
+/** @private */
+pv.Layout.Cluster.Fill.prototype.buildImplied = function(s) {
+  if (pv.Layout.Cluster.prototype.buildImplied.call(this, s)) return;
+  pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
+};
+/**
+ * Constructs a new, empty partition layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implemeents a hierarchical layout using the partition (or sunburst,
+ * icicle) algorithm. This layout provides both node-link and space-filling
+ * implementations of partition diagrams. In many ways it is similar to
+ * {@link pv.Layout.Cluster}, except that leaf nodes are positioned based on
+ * their distance from the root.
+ *
+ * <p>The partition layout support dynamic sizing for leaf nodes, if a
+ * {@link #size} psuedo-property is specified. The default size function returns
+ * 1, causing all leaf nodes to be sized equally, and all internal nodes to be
+ * sized by the number of leaf nodes they have as descendants.
+ *
+ * <p>The size function can be used in conjunction with the order property,
+ * which allows the nodes to the sorted by the computed size. Note: for sorting
+ * based on other data attributes, simply use the default <tt>null</tt> for the
+ * order property, and sort the nodes beforehand using the {@link pv.Dom}
+ * operator.
+ *
+ * <p>For more details on how to use this layout, see
+ * {@link pv.Layout.Hierarchy}.
+ *
+ * @see pv.Layout.Partition.Fill
+ * @extends pv.Layout.Hierarchy
+ */
+pv.Layout.Partition = function() {
+  pv.Layout.Hierarchy.call(this);
+};
+
+pv.Layout.Partition.prototype = pv.extend(pv.Layout.Hierarchy)
+    .property("order", String) // null, ascending, descending?
+    .property("orient", String) // top, left, right, bottom, radial
+    .property("innerRadius", Number)
+    .property("outerRadius", Number);
+
+/**
+ * The sibling node order. The default order is <tt>null</tt>, which means to
+ * use the sibling order specified by the nodes property as-is. A value of
+ * "ascending" will sort siblings in ascending order of size, while "descending"
+ * will do the reverse. For sorting based on data attributes other than size,
+ * use the default <tt>null</tt> for the order property, and sort the nodes
+ * beforehand using the {@link pv.Dom} operator.
+ *
+ * @see pv.Dom.Node#sort
+ * @type string
+ * @name pv.Layout.Partition.prototype.order
+ */
+
+/**
+ * The orientation. The default orientation is "top", which means that the root
+ * node is placed on the top edge, leaf nodes appear at the bottom, and internal
+ * nodes are in-between. The following orientations are supported:<ul>
+ *
+ * <li>left - left-to-right.
+ * <li>right - right-to-left.
+ * <li>top - top-to-bottom.
+ * <li>bottom - bottom-to-top.
+ * <li>radial - radially, with the root at the center.</ul>
+ *
+ * @type string
+ * @name pv.Layout.Partition.prototype.orient
+ */
+
+/**
+ * The inner radius; defaults to 0. This property applies only to radial
+ * orientations, and can be used to compress the layout radially. Note that for
+ * the node-link implementation, the root node is always at the center,
+ * regardless of the value of this property; this property only affects internal
+ * and leaf nodes. For the space-filling implementation, a non-zero value of
+ * this property will result in the root node represented as a ring rather than
+ * a circle.
+ *
+ * @type number
+ * @name pv.Layout.Partition.prototype.innerRadius
+ */
+
+/**
+ * The outer radius; defaults to fill the containing panel, based on the height
+ * and width of the layout. If the layout has no height and width specified, it
+ * will extend to fill the enclosing panel.
+ *
+ * @type number
+ * @name pv.Layout.Partition.prototype.outerRadius
+ */
+
+/**
+ * Default properties for partition layouts. The default orientation is "top".
+ *
+ * @type pv.Layout.Partition
+ */
+pv.Layout.Partition.prototype.defaults = new pv.Layout.Partition()
+    .extend(pv.Layout.Hierarchy.prototype.defaults)
+    .orient("top");
+
+/** @private */
+pv.Layout.Partition.prototype.$size = function() { return 1; };
+
+/**
+ * Specifies the sizing function. By default, a sizing function is disabled and
+ * all nodes are given constant size. The sizing function is invoked for each
+ * leaf node in the tree (passed to the constructor).
+ *
+ * <p>For example, if the tree data structure represents a file system, with
+ * files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
+ * specify a size function as:
+ *
+ * <pre>    .size(function(d) d.bytes)</pre>
+ *
+ * As with other properties, a size function may specify additional arguments to
+ * access the data associated with the layout and any enclosing panels.
+ *
+ * @param {function} f the new sizing function.
+ * @returns {pv.Layout.Partition} this.
+ */
+pv.Layout.Partition.prototype.size = function(f) {
+  this.$size = f;
+  return this;
+};
+
+/** @private */
+pv.Layout.Partition.prototype.buildImplied = function(s) {
+  if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
+
+  var that = this,
+      root = s.nodes[0],
+      stack = pv.Mark.stack,
+      maxDepth = 0;
+
+  /* Recursively compute the tree depth and node size. */
+  stack.unshift(null);
+  root.visitAfter(function(n, i) {
+      if (i > maxDepth) maxDepth = i;
+      n.size = n.firstChild
+          ? pv.sum(n.childNodes, function(n) { return n.size; })
+          : that.$size.apply(that, (stack[0] = n, stack));
+    });
+  stack.shift();
+
+  /* Order */
+  switch (s.order) {
+    case "ascending": root.sort(function(a, b) { return a.size - b.size; }); break;
+    case "descending": root.sort(function(b, a) { return a.size - b.size; }); break;
+  }
+
+  /* Compute the unit breadth and depth of each node. */
+  var ds = 1 / maxDepth;
+  root.minBreadth = 0;
+  root.breadth = .5;
+  root.maxBreadth = 1;
+  root.visitBefore(function(n) {
+    var b = n.minBreadth, s = n.maxBreadth - b;
+      for (var c = n.firstChild; c; c = c.nextSibling) {
+        c.minBreadth = b;
+        c.maxBreadth = b += (c.size / n.size) * s;
+        c.breadth = (b + c.minBreadth) / 2;
+      }
+    });
+  root.visitAfter(function(n, i) {
+      n.minDepth = (i - 1) * ds;
+      n.maxDepth = n.depth = i * ds;
+    });
+
+  pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
+};
+
+/**
+ * Constructs a new, empty space-filling partition layout. Layouts are not
+ * typically constructed directly; instead, they are added to an existing panel
+ * via {@link pv.Mark#add}.
+ *
+ * @class A variant of partition layout that is space-filling. The meaning of
+ * the exported mark prototypes changes slightly in the space-filling
+ * implementation:<ul>
+ *
+ * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
+ * non-radial orientations, and a {@link pv.Wedge} for radial orientations.
+ *
+ * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
+ * in the arrangement of the space-filling nodes.
+ *
+ * <p><li><tt>label</tt> - for rendering node labels; typically a
+ * {@link pv.Label}.
+ *
+ * </ul>For more details on how to use this layout, see
+ * {@link pv.Layout.Partition}.
+ *
+ * @extends pv.Layout.Partition
+ */
+pv.Layout.Partition.Fill = function() {
+  pv.Layout.Partition.call(this);
+  pv.Layout.Hierarchy.Fill.constructor.call(this);
+};
+
+pv.Layout.Partition.Fill.prototype = pv.extend(pv.Layout.Partition);
+
+/** @private */
+pv.Layout.Partition.Fill.prototype.buildImplied = function(s) {
+  if (pv.Layout.Partition.prototype.buildImplied.call(this, s)) return;
+  pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
+};
+/**
+ * Constructs a new, empty arc layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a layout for arc diagrams. An arc diagram is a network
+ * visualization with a one-dimensional layout of nodes, using circular arcs to
+ * render links between nodes. For undirected networks, arcs are rendering on a
+ * single side; this makes arc diagrams useful as annotations to other
+ * two-dimensional network layouts, such as rollup, matrix or table layouts. For
+ * directed networks, links in opposite directions can be rendered on opposite
+ * sides using <tt>directed(true)</tt>.
+ *
+ * <p>Arc layouts are particularly sensitive to node ordering; for best results,
+ * order the nodes such that related nodes are close to each other. A poor
+ * (e.g., random) order may result in large arcs with crossovers that impede
+ * visual processing. A future improvement to this layout may include automatic
+ * reordering using, e.g., spectral graph layout or simulated annealing.
+ *
+ * <p>This visualization technique is related to that developed by
+ * M. Wattenberg, <a
+ * href="http://www.research.ibm.com/visual/papers/arc-diagrams.pdf">"Arc
+ * Diagrams: Visualizing Structure in Strings"</a> in <i>IEEE InfoVis</i>, 2002.
+ * However, this implementation is limited to simple node-link networks, as
+ * opposed to structures with hierarchical self-similarity (such as strings).
+ *
+ * <p>As with other network layouts, three mark prototypes are provided:<ul>
+ *
+ * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
+ * <li><tt>link</tt> - for rendering links; typically a {@link pv.Line}.
+ * <li><tt>label</tt> - for rendering node labels; typically a {@link pv.Label}.
+ *
+ * </ul>For more details on how this layout is structured and can be customized,
+ * see {@link pv.Layout.Network}.
+ *
+ * @extends pv.Layout.Network
+ **/
+pv.Layout.Arc = function() {
+  pv.Layout.Network.call(this);
+  var interpolate, // cached interpolate
+      directed, // cached directed
+      reverse, // cached reverse
+      buildImplied = this.buildImplied;
+
+  /** @private Cache layout state to optimize properties. */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, s);
+    directed = s.directed;
+    interpolate = s.orient == "radial" ? "linear" : "polar";
+    reverse = s.orient == "right" || s.orient == "top";
+  };
+
+  /* Override link properties to handle directedness and orientation. */
+  this.link
+      .data(function(p) {
+          var s = p.sourceNode, t = p.targetNode;
+          return reverse != (directed || (s.breadth < t.breadth)) ? [s, t] : [t, s];
+        })
+      .interpolate(function() { return interpolate; });
+};
+
+pv.Layout.Arc.prototype = pv.extend(pv.Layout.Network)
+    .property("orient", String)
+    .property("directed", Boolean);
+
+/**
+ * Default properties for arc layouts. By default, the orientation is "bottom".
+ *
+ * @type pv.Layout.Arc
+ */
+pv.Layout.Arc.prototype.defaults = new pv.Layout.Arc()
+    .extend(pv.Layout.Network.prototype.defaults)
+    .orient("bottom");
+
+/**
+ * Specifies an optional sort function. The sort function follows the same
+ * comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
+ * function provides an alternative to sort the nodes as they are specified by
+ * the <tt>nodes</tt> property; the main advantage of doing this is that the
+ * comparator function can access implicit fields populated by the network
+ * layout, such as the <tt>linkDegree</tt>.
+ *
+ * <p>Note that arc diagrams are particularly sensitive to order. This is
+ * referred to as the seriation problem, and many different techniques exist to
+ * find good node orders that emphasize clusters, such as spectral layout and
+ * simulated annealing.
+ *
+ * @param {function} f comparator function for nodes.
+ * @returns {pv.Layout.Arc} this.
+ */
+pv.Layout.Arc.prototype.sort = function(f) {
+  this.$sort = f;
+  return this;
+};
+
+/** @private Populates the x, y and angle attributes on the nodes. */
+pv.Layout.Arc.prototype.buildImplied = function(s) {
+  if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
+
+  var nodes = s.nodes,
+      orient = s.orient,
+      sort = this.$sort,
+      index = pv.range(nodes.length),
+      w = s.width,
+      h = s.height,
+      r = Math.min(w, h) / 2;
+
+  /* Sort the nodes. */
+  if (sort) index.sort(function(a, b) { return sort(nodes[a], nodes[b]); });
+
+  /** @private Returns the mid-angle, given the breadth. */
+  function midAngle(b) {
+    switch (orient) {
+      case "top": return -Math.PI / 2;
+      case "bottom": return Math.PI / 2;
+      case "left": return Math.PI;
+      case "right": return 0;
+      case "radial": return (b - .25) * 2 * Math.PI;
+    }
+  }
+
+  /** @private Returns the x-position, given the breadth. */
+  function x(b) {
+    switch (orient) {
+      case "top":
+      case "bottom": return b * w;
+      case "left": return 0;
+      case "right": return w;
+      case "radial": return w / 2 + r * Math.cos(midAngle(b));
+    }
+  }
+
+  /** @private Returns the y-position, given the breadth. */
+  function y(b) {
+    switch (orient) {
+      case "top": return 0;
+      case "bottom": return h;
+      case "left":
+      case "right": return b * h;
+      case "radial": return h / 2 + r * Math.sin(midAngle(b));
+    }
+  }
+
+  /* Populate the x, y and mid-angle attributes. */
+  for (var i = 0; i < nodes.length; i++) {
+    var n = nodes[index[i]], b = n.breadth = (i + .5) / nodes.length;
+    n.x = x(b);
+    n.y = y(b);
+    n.midAngle = midAngle(b);
+  }
+};
+
+/**
+ * The orientation. The default orientation is "left", which means that nodes
+ * will be positioned from left-to-right in the order they are specified in the
+ * <tt>nodes</tt> property. The following orientations are supported:<ul>
+ *
+ * <li>left - left-to-right.
+ * <li>right - right-to-left.
+ * <li>top - top-to-bottom.
+ * <li>bottom - bottom-to-top.
+ * <li>radial - radially, starting at 12 o'clock and proceeding clockwise.</ul>
+ *
+ * @type string
+ * @name pv.Layout.Arc.prototype.orient
+ */
+
+/**
+ * Whether this arc digram is directed (bidirectional); only applies to
+ * non-radial orientations. By default, arc digrams are undirected, such that
+ * all arcs appear on one side. If the arc digram is directed, then forward
+ * links are drawn on the conventional side (the same as as undirected
+ * links--right, left, bottom and top for left, right, top and bottom,
+ * respectively), while reverse links are drawn on the opposite side.
+ *
+ * @type boolean
+ * @name pv.Layout.Arc.prototype.directed
+ */
+/**
+ * Constructs a new, empty horizon layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a horizon layout, which is a variation of a single-series
+ * area chart where the area is folded into multiple bands. Color is used to
+ * encode band, allowing the size of the chart to be reduced significantly
+ * without impeding readability. This layout algorithm is based on the work of
+ * J. Heer, N. Kong and M. Agrawala in <a
+ * href="http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf">"Sizing
+ * the Horizon: The Effects of Chart Size and Layering on the Graphical
+ * Perception of Time Series Visualizations"</a>, CHI 2009.
+ *
+ * <p>This layout exports a single <tt>band</tt> mark prototype, which is
+ * intended to be used with an area mark. The band mark is contained in a panel
+ * which is replicated per band (and for negative/positive bands). For example,
+ * to create a simple horizon graph given an array of numbers:
+ *
+ * <pre>vis.add(pv.Layout.Horizon)
+ *     .bands(n)
+ *   .band.add(pv.Area)
+ *     .data(data)
+ *     .left(function() this.index * 35)
+ *     .height(function(d) d * 40);</pre>
+ *
+ * The layout can be further customized by changing the number of bands, and
+ * toggling whether the negative bands are mirrored or offset. (See the
+ * above-referenced paper for guidance.)
+ *
+ * <p>The <tt>fillStyle</tt> of the area can be overridden, though typically it
+ * is easier to customize the layout's behavior through the custom
+ * <tt>backgroundStyle</tt>, <tt>positiveStyle</tt> and <tt>negativeStyle</tt>
+ * properties. By default, the background is white, positive bands are blue, and
+ * negative bands are red. For the most accurate presentation, use fully-opaque
+ * colors of equal intensity for the negative and positive bands.
+ *
+ * @extends pv.Layout
+ */
+pv.Layout.Horizon = function() {
+  pv.Layout.call(this);
+  var that = this,
+      bands, // cached bands
+      mode, // cached mode
+      size, // cached height
+      fill, // cached background style
+      red, // cached negative color (ramp)
+      blue, // cached positive color (ramp)
+      buildImplied = this.buildImplied;
+
+  /** @private Cache the layout state to optimize properties. */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, s);
+    bands = s.bands;
+    mode = s.mode;
+    size = Math.round((mode == "color" ? .5 : 1) * s.height);
+    fill = s.backgroundStyle;
+    red = pv.ramp(fill, s.negativeStyle).domain(0, bands);
+    blue = pv.ramp(fill, s.positiveStyle).domain(0, bands);
+  };
+
+  var bands = new pv.Panel()
+      .data(function() { return pv.range(bands * 2); })
+      .overflow("hidden")
+      .height(function() { return size; })
+      .top(function(i) { return mode == "color" ? (i & 1) * size : 0; })
+      .fillStyle(function(i) { return i ? null : fill; });
+
+  /**
+   * The band prototype. This prototype is intended to be used with an Area
+   * mark to render the horizon bands.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Horizon.prototype.band
+   */
+  this.band = new pv.Mark()
+      .top(function(d, i) {
+          return mode == "mirror" && i & 1
+              ? (i + 1 >> 1) * size
+              : null;
+        })
+      .bottom(function(d, i) {
+          return mode == "mirror"
+              ? (i & 1 ? null : (i + 1 >> 1) * -size)
+              : ((i & 1 || -1) * (i + 1 >> 1) * size);
+        })
+      .fillStyle(function(d, i) {
+          return (i & 1 ? red : blue)((i >> 1) + 1);
+        });
+
+  this.band.add = function(type) {
+    return that.add(pv.Panel).extend(bands).add(type).extend(this);
+  };
+};
+
+pv.Layout.Horizon.prototype = pv.extend(pv.Layout)
+    .property("bands", Number)
+    .property("mode", String)
+    .property("backgroundStyle", pv.color)
+    .property("positiveStyle", pv.color)
+    .property("negativeStyle", pv.color);
+
+/**
+ * Default properties for horizon layouts. By default, there are two bands, the
+ * mode is "offset", the background style is "white", the positive style is
+ * blue, negative style is red.
+ *
+ * @type pv.Layout.Horizon
+ */
+pv.Layout.Horizon.prototype.defaults = new pv.Layout.Horizon()
+    .extend(pv.Layout.prototype.defaults)
+    .bands(2)
+    .mode("offset")
+    .backgroundStyle("white")
+    .positiveStyle("#1f77b4")
+    .negativeStyle("#d62728");
+
+/**
+ * The horizon mode: offset, mirror, or color. The default is "offset".
+ *
+ * @type string
+ * @name pv.Layout.Horizon.prototype.mode
+ */
+
+/**
+ * The number of bands. Must be at least one. The default value is two.
+ *
+ * @type number
+ * @name pv.Layout.Horizon.prototype.bands
+ */
+
+/**
+ * The positive band color; if non-null, the interior of positive bands are
+ * filled with the specified color. The default value of this property is blue.
+ * For accurate blending, this color should be fully opaque.
+ *
+ * @type pv.Color
+ * @name pv.Layout.Horizon.prototype.positiveStyle
+ */
+
+/**
+ * The negative band color; if non-null, the interior of negative bands are
+ * filled with the specified color. The default value of this property is red.
+ * For accurate blending, this color should be fully opaque.
+ *
+ * @type pv.Color
+ * @name pv.Layout.Horizon.prototype.negativeStyle
+ */
+
+/**
+ * The background color. The panel background is filled with the specified
+ * color, and the negative and positive bands are filled with an interpolated
+ * color between this color and the respective band color. The default value of
+ * this property is white. For accurate blending, this color should be fully
+ * opaque.
+ *
+ * @type pv.Color
+ * @name pv.Layout.Horizon.prototype.backgroundStyle
+ */
+/**
+ * Constructs a new, empty rollup network layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a network visualization using a node-link diagram where
+ * nodes are rolled up along two dimensions. This implementation is based on the
+ * "PivotGraph" designed by Martin Wattenberg:
+ *
+ * <blockquote>The method is designed for graphs that are "multivariate", i.e.,
+ * where each node is associated with several attributes. Unlike visualizations
+ * which emphasize global graph topology, PivotGraph uses a simple grid-based
+ * approach to focus on the relationship between node attributes &amp;
+ * connections.</blockquote>
+ *
+ * This layout requires two psuedo-properties to be specified, which assign node
+ * positions along the two dimensions {@link #x} and {@link #y}, corresponding
+ * to the left and top properties, respectively. Typically, these functions are
+ * specified using an {@link pv.Scale.ordinal}. Nodes that share the same
+ * position in <i>x</i> and <i>y</i> are "rolled up" into a meta-node, and
+ * similarly links are aggregated between meta-nodes. For example, to construct
+ * a rollup to analyze links by gender and affiliation, first define two ordinal
+ * scales:
+ *
+ * <pre>var x = pv.Scale.ordinal(nodes, function(d) d.gender).split(0, w),
+ *     y = pv.Scale.ordinal(nodes, function(d) d.aff).split(0, h);</pre>
+ *
+ * Next, define the position psuedo-properties:
+ *
+ * <pre>    .x(function(d) x(d.gender))
+ *     .y(function(d) y(d.aff))</pre>
+ *
+ * Linear and other quantitative scales can alternatively be used to position
+ * the nodes along either dimension. Note, however, that the rollup requires
+ * that the positions match exactly, and thus ordinal scales are recommended to
+ * avoid precision errors.
+ *
+ * <p>Note that because this layout provides a visualization of the rolled up
+ * graph, the data properties for the mark prototypes (<tt>node</tt>,
+ * <tt>link</tt> and <tt>label</tt>) are different from most other network
+ * layouts: they reference the rolled-up nodes and links, rather than the nodes
+ * and links of the full network. The underlying nodes and links for each
+ * rolled-up node and link can be accessed via the <tt>nodes</tt> and
+ * <tt>links</tt> attributes, respectively. The aggregated link values for
+ * rolled-up links can similarly be accessed via the <tt>linkValue</tt>
+ * attribute.
+ *
+ * <p>For undirected networks, links are duplicated in both directions. For
+ * directed networks, use <tt>directed(true)</tt>. The graph is assumed to be
+ * undirected by default.
+ *
+ * @extends pv.Layout.Network
+ * @see <a href="http://www.research.ibm.com/visual/papers/pivotgraph.pdf"
+ * >"Visual Exploration of Multivariate Graphs"</a> by M. Wattenberg, CHI 2006.
+ */
+pv.Layout.Rollup = function() {
+  pv.Layout.Network.call(this);
+  var that = this,
+      nodes, // cached rollup nodes
+      links, // cached rollup links
+      buildImplied = that.buildImplied;
+
+  /** @private Cache layout state to optimize properties. */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, s);
+    nodes = s.$rollup.nodes;
+    links = s.$rollup.links;
+  };
+
+  /* Render rollup nodes. */
+  this.node
+      .data(function() { return nodes; })
+      .size(function(d) { return d.nodes.length * 20; });
+
+  /* Render rollup links. */
+  this.link
+      .interpolate("polar")
+      .eccentricity(.8);
+
+  this.link.add = function(type) {
+    return that.add(pv.Panel)
+        .data(function() { return links; })
+      .add(type)
+        .extend(this);
+  };
+};
+
+pv.Layout.Rollup.prototype = pv.extend(pv.Layout.Network)
+    .property("directed", Boolean);
+
+/**
+ * Whether the underlying network is directed. By default, the graph is assumed
+ * to be undirected, and links are rendered in both directions. If the network
+ * is directed, then forward links are drawn above the diagonal, while reverse
+ * links are drawn below.
+ *
+ * @type boolean
+ * @name pv.Layout.Rollup.prototype.directed
+ */
+
+/**
+ * Specifies the <i>x</i>-position function used to rollup nodes. The rolled up
+ * nodes are positioned horizontally using the return values from the given
+ * function. Typically the function is specified as an ordinal scale. For
+ * single-dimension rollups, a constant value can be specified.
+ *
+ * @param {function} f the <i>x</i>-position function.
+ * @returns {pv.Layout.Rollup} this.
+ * @see pv.Scale.ordinal
+ */
+pv.Layout.Rollup.prototype.x = function(f) {
+  this.$x = pv.functor(f);
+  return this;
+};
+
+/**
+ * Specifies the <i>y</i>-position function used to rollup nodes. The rolled up
+ * nodes are positioned vertically using the return values from the given
+ * function. Typically the function is specified as an ordinal scale. For
+ * single-dimension rollups, a constant value can be specified.
+ *
+ * @param {function} f the <i>y</i>-position function.
+ * @returns {pv.Layout.Rollup} this.
+ * @see pv.Scale.ordinal
+ */
+pv.Layout.Rollup.prototype.y = function(f) {
+  this.$y = pv.functor(f);
+  return this;
+};
+
+/** @private */
+pv.Layout.Rollup.prototype.buildImplied = function(s) {
+  if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
+
+  var nodes = s.nodes,
+      links = s.links,
+      directed = s.directed,
+      n = nodes.length,
+      x = [],
+      y = [],
+      rnindex = 0,
+      rnodes = {},
+      rlinks = {};
+
+  /** @private */
+  function id(i) {
+    return x[i] + "," + y[i];
+  }
+
+  /* Iterate over the data, evaluating the x and y functions. */
+  var stack = pv.Mark.stack, o = {parent: this};
+  stack.unshift(null);
+  for (var i = 0; i < n; i++) {
+    o.index = i;
+    stack[0] = nodes[i];
+    x[i] = this.$x.apply(o, stack);
+    y[i] = this.$y.apply(o, stack);
+  }
+  stack.shift();
+
+  /* Compute rollup nodes. */
+  for (var i = 0; i < nodes.length; i++) {
+    var nodeId = id(i),
+        rn = rnodes[nodeId];
+    if (!rn) {
+      rn = rnodes[nodeId] = pv.extend(nodes[i]);
+      rn.index = rnindex++;
+      rn.x = x[i];
+      rn.y = y[i];
+      rn.nodes = [];
+    }
+    rn.nodes.push(nodes[i]);
+  }
+
+  /* Compute rollup links. */
+  for (var i = 0; i < links.length; i++) {
+    var source = links[i].sourceNode,
+        target = links[i].targetNode,
+        rsource = rnodes[id(source.index)],
+        rtarget = rnodes[id(target.index)],
+        reverse = !directed && rsource.index > rtarget.index,
+        linkId = reverse
+            ? rtarget.index + "," + rsource.index
+            : rsource.index + "," + rtarget.index,
+        rl = rlinks[linkId];
+    if (!rl) {
+      rl = rlinks[linkId] = {
+        sourceNode: rsource,
+        targetNode: rtarget,
+        linkValue: 0,
+        links: []
+      };
+    }
+    rl.links.push(links[i]);
+    rl.linkValue += links[i].linkValue;
+  }
+
+  /* Export the rolled up nodes and links to the scene. */
+  s.$rollup = {
+    nodes: pv.values(rnodes),
+    links: pv.values(rlinks)
+  };
+};
+/**
+ * Constructs a new, empty matrix network layout. Layouts are not typically
+ * constructed directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class Implements a network visualization using a matrix view. This is, in
+ * effect, a visualization of the graph's <i>adjacency matrix</i>: the cell at
+ * row <i>i</i>, column <i>j</i>, corresponds to the link from node <i>i</i> to
+ * node <i>j</i>. The fill color of each cell is binary by default, and
+ * corresponds to whether a link exists between the two nodes. If the underlying
+ * graph has links with variable values, the <tt>fillStyle</tt> property can be
+ * substited to use an appropriate color function, such as {@link pv.ramp}.
+ *
+ * <p>For undirected networks, the matrix is symmetric around the diagonal. For
+ * directed networks, links in opposite directions can be rendered on opposite
+ * sides of the diagonal using <tt>directed(true)</tt>. The graph is assumed to
+ * be undirected by default.
+ *
+ * <p>The mark prototypes for this network layout are slightly different than
+ * other implementations:<ul>
+ *
+ * <li><tt>node</tt> - unsupported; undefined. No mark is needed to visualize
+ * nodes directly, as the nodes are implicit in the location (rows and columns)
+ * of the links.
+ *
+ * <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Bar}. The
+ * link mark is added directly to the layout, with the data property defined as
+ * all possible pairs of nodes. Each pair is represented as a
+ * {@link pv.Network.Layout.Link}, though the <tt>linkValue</tt> attribute may
+ * be 0 if no link exists in the graph.
+ *
+ * <p><li><tt>label</tt> - for rendering node labels; typically a
+ * {@link pv.Label}. The label mark is added directly to the layout, with the
+ * data property defined via the layout's <tt>nodes</tt> property; note,
+ * however, that the nodes are duplicated so as to provide a label across the
+ * top and down the side. Properties such as <tt>strokeStyle</tt> and
+ * <tt>fillStyle</tt> can be overridden to compute properties from node data
+ * dynamically.
+ *
+ * </ul>For more details on how to use this layout, see
+ * {@link pv.Layout.Network}.
+ *
+ * @extends pv.Layout.Network
+ */
+pv.Layout.Matrix = function() {
+  pv.Layout.Network.call(this);
+  var that = this,
+      n, // cached matrix size
+      dx, // cached cell width
+      dy, // cached cell height
+      labels, // cached labels (array of strings)
+      pairs, // cached pairs (array of links)
+      buildImplied = that.buildImplied;
+
+  /** @private Cache layout state to optimize properties. */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, s);
+    n = s.nodes.length;
+    dx = s.width / n;
+    dy = s.height / n;
+    labels = s.$matrix.labels;
+    pairs = s.$matrix.pairs;
+  };
+
+  /* Links are all pairs of nodes. */
+  this.link
+      .data(function() { return pairs; })
+      .left(function() { return dx * (this.index % n); })
+      .top(function() { return dy * Math.floor(this.index / n); })
+      .width(function() { return dx; })
+      .height(function() { return dy; })
+      .lineWidth(1.5)
+      .strokeStyle("#fff")
+      .fillStyle(function(l) { return l.linkValue ? "#555" : "#eee"; })
+      .parent = this;
+
+  /* No special add for links! */
+  delete this.link.add;
+
+  /* Labels are duplicated for top & left. */
+  this.label
+      .data(function() { return labels; })
+      .left(function() { return this.index & 1 ? dx * ((this.index >> 1) + .5) : null; })
+      .top(function() { return this.index & 1 ? null : dy * ((this.index >> 1) + .5); })
+      .textMargin(4)
+      .textAlign(function() { return this.index & 1 ? "left" : "right"; })
+      .textAngle(function() { return this.index & 1 ? -Math.PI / 2 : 0; });
+
+  /* The node mark is unused. */
+  delete this.node;
+};
+
+pv.Layout.Matrix.prototype = pv.extend(pv.Layout.Network)
+    .property("directed", Boolean);
+
+/**
+ * Whether this matrix visualization is directed (bidirectional). By default,
+ * the graph is assumed to be undirected, such that the visualization is
+ * symmetric across the matrix diagonal. If the network is directed, then
+ * forward links are drawn above the diagonal, while reverse links are drawn
+ * below.
+ *
+ * @type boolean
+ * @name pv.Layout.Matrix.prototype.directed
+ */
+
+/**
+ * Specifies an optional sort function. The sort function follows the same
+ * comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
+ * function provides an alternative to sort the nodes as they are specified by
+ * the <tt>nodes</tt> property; the main advantage of doing this is that the
+ * comparator function can access implicit fields populated by the network
+ * layout, such as the <tt>linkDegree</tt>.
+ *
+ * <p>Note that matrix visualizations are particularly sensitive to order. This
+ * is referred to as the seriation problem, and many different techniques exist
+ * to find good node orders that emphasize clusters, such as spectral layout and
+ * simulated annealing.
+ *
+ * @param {function} f comparator function for nodes.
+ * @returns {pv.Layout.Matrix} this.
+ */
+pv.Layout.Matrix.prototype.sort = function(f) {
+  this.$sort = f;
+  return this;
+};
+
+/** @private */
+pv.Layout.Matrix.prototype.buildImplied = function(s) {
+  if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
+
+  var nodes = s.nodes,
+      links = s.links,
+      sort = this.$sort,
+      n = nodes.length,
+      index = pv.range(n),
+      labels = [],
+      pairs = [],
+      map = {};
+
+  s.$matrix = {labels: labels, pairs: pairs};
+
+  /* Sort the nodes. */
+  if (sort) index.sort(function(a, b) { return sort(nodes[a], nodes[b]); });
+
+  /* Create pairs. */
+  for (var i = 0; i < n; i++) {
+    for (var j = 0; j < n; j++) {
+      var a = index[i],
+          b = index[j],
+          p = {
+            row: i,
+            col: j,
+            sourceNode: nodes[a],
+            targetNode: nodes[b],
+            linkValue: 0
+          };
+      pairs.push(map[a + "." + b] = p);
+    }
+  }
+
+  /* Create labels. */
+  for (var i = 0; i < n; i++) {
+    var a = index[i];
+    labels.push(nodes[a], nodes[a]);
+  }
+
+  /* Accumulate link values. */
+  for (var i = 0; i < links.length; i++) {
+    var l = links[i],
+        source = l.sourceNode.index,
+        target = l.targetNode.index,
+        value = l.linkValue;
+    map[source + "." + target].linkValue += value;
+    if (!s.directed) map[target + "." + source].linkValue += value;
+  }
+};
+// ranges (bad, satisfactory, good)
+// measures (actual, forecast)
+// markers (previous, goal)
+
+/*
+ * Chart design based on the recommendations of Stephen Few. Implementation
+ * based on the work of Clint Ivy, Jamie Love, and Jason Davies.
+ * http://projects.instantcognition.com/protovis/bulletchart/
+ */
+
+/**
+ * Constructs a new, empty bullet layout. Layouts are not typically constructed
+ * directly; instead, they are added to an existing panel via
+ * {@link pv.Mark#add}.
+ *
+ * @class
+ * @extends pv.Layout
+ */
+pv.Layout.Bullet = function() {
+  pv.Layout.call(this);
+  var that = this,
+      buildImplied = that.buildImplied,
+      scale = that.x = pv.Scale.linear(),
+      orient,
+      horizontal,
+      rangeColor,
+      measureColor,
+      x;
+
+  /** @private Cache layout state to optimize properties. */
+  this.buildImplied = function(s) {
+    buildImplied.call(this, x = s);
+    orient = s.orient;
+    horizontal = /^left|right$/.test(orient);
+    rangeColor = pv.ramp("#bbb", "#eee")
+        .domain(0, Math.max(1, x.ranges.length - 1));
+    measureColor = pv.ramp("steelblue", "lightsteelblue")
+        .domain(0, Math.max(1, x.measures.length - 1));
+  };
+
+  /**
+   * The range prototype.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Bullet.prototype.range
+   */
+  (this.range = new pv.Mark())
+      .data(function() { return x.ranges; })
+      .reverse(true)
+      .left(function() { return orient == "left" ? 0 : null; })
+      .top(function() { return orient == "top" ? 0 : null; })
+      .right(function() { return orient == "right" ? 0 : null; })
+      .bottom(function() { return orient == "bottom" ? 0 : null; })
+      .width(function(d) { return horizontal ? scale(d) : null; })
+      .height(function(d) { return horizontal ? null : scale(d); })
+      .fillStyle(function() { return rangeColor(this.index); })
+      .antialias(false)
+      .parent = that;
+
+  /**
+   * The measure prototype.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Bullet.prototype.measure
+   */
+  (this.measure = new pv.Mark())
+      .extend(this.range)
+      .data(function() { return x.measures; })
+      .left(function() { return orient == "left" ? 0 : horizontal ? null : this.parent.width() / 3.25; })
+      .top(function() { return orient == "top" ? 0 : horizontal ? this.parent.height() / 3.25 : null; })
+      .right(function() { return orient == "right" ? 0 : horizontal ? null : this.parent.width() / 3.25; })
+      .bottom(function() { return orient == "bottom" ? 0 : horizontal ? this.parent.height() / 3.25 : null; })
+      .fillStyle(function() { return measureColor(this.index); })
+      .parent = that;
+
+  /**
+   * The marker prototype.
+   *
+   * @type pv.Mark
+   * @name pv.Layout.Bullet.prototype.marker
+   */
+  (this.marker = new pv.Mark())
+      .data(function() { return x.markers; })
+      .left(function(d) { return orient == "left" ? scale(d) : horizontal ? null : this.parent.width() / 2; })
+      .top(function(d) { return orient == "top" ? scale(d) : horizontal ? this.parent.height() / 2 : null; })
+      .right(function(d) { return orient == "right" ? scale(d) : null; })
+      .bottom(function(d) { return orient == "bottom" ? scale(d) : null; })
+      .strokeStyle("black")
+      .shape("bar")
+      .angle(function() { return horizontal ? 0 : Math.PI / 2; })
+      .parent = that;
+
+  (this.tick = new pv.Mark())
+      .data(function() { return scale.ticks(7); })
+      .left(function(d) { return orient == "left" ? scale(d) : null; })
+      .top(function(d) { return orient == "top" ? scale(d) : null; })
+      .right(function(d) { return orient == "right" ? scale(d) : horizontal ? null : -6; })
+      .bottom(function(d) { return orient == "bottom" ? scale(d) : horizontal ? -8 : null; })
+      .height(function() { return horizontal ? 6 : null; })
+      .width(function() { return horizontal ? null : 6; })
+      .parent = that;
+};
+
+pv.Layout.Bullet.prototype = pv.extend(pv.Layout)
+    .property("orient", String) // left, right, top, bottom
+    .property("ranges")
+    .property("markers")
+    .property("measures")
+    .property("maximum", Number);
+
+/**
+ * Default properties for bullet layouts.
+ *
+ * @type pv.Layout.Bullet
+ */
+pv.Layout.Bullet.prototype.defaults = new pv.Layout.Bullet()
+    .extend(pv.Layout.prototype.defaults)
+    .orient("left")
+    .ranges([])
+    .markers([])
+    .measures([]);
+
+/**
+ * The orientation.
+ *
+ * @type string
+ * @name pv.Layout.Bullet.prototype.orient
+ */
+
+/**
+ * The array of range values.
+ *
+ * @type array
+ * @name pv.Layout.Bullet.prototype.ranges
+ */
+
+/**
+ * The array of marker values.
+ *
+ * @type array
+ * @name pv.Layout.Bullet.prototype.markers
+ */
+
+/**
+ * The array of measure values.
+ *
+ * @type array
+ * @name pv.Layout.Bullet.prototype.measures
+ */
+
+/**
+ * Optional; the maximum range value.
+ *
+ * @type number
+ * @name pv.Layout.Bullet.prototype.maximum
+ */
+
+/** @private */
+pv.Layout.Bullet.prototype.buildImplied = function(s) {
+  pv.Layout.prototype.buildImplied.call(this, s);
+  var size = this.parent[/^left|right$/.test(s.orient) ? "width" : "height"]();
+  s.maximum = s.maximum || pv.max([].concat(s.ranges, s.markers, s.measures));
+  this.x.domain(0, s.maximum).range(0, size);
+};
+/**
+ * Abstract; see an implementing class for details.
+ *
+ * @class Represents a reusable interaction; applies an interactive behavior to
+ * a given mark. Behaviors are themselves functions designed to be used as event
+ * handlers. For example, to add pan and zoom support to any panel, say:
+ *
+ * <pre>    .event("mousedown", pv.Behavior.pan())
+ *     .event("mousewheel", pv.Behavior.zoom())</pre>
+ *
+ * The behavior should be registered on the event that triggers the start of the
+ * behavior. Typically, the behavior will take care of registering for any
+ * additional events that are necessary. For example, dragging starts on
+ * mousedown, while the drag behavior automatically listens for mousemove and
+ * mouseup events on the window. By listening to the window, the behavior can
+ * continue to receive mouse events even if the mouse briefly leaves the mark
+ * being dragged, or even the root panel.
+ *
+ * <p>Each behavior implementation has specific requirements as to which events
+ * it supports, and how it should be used. For example, the drag behavior
+ * requires that the data associated with the mark be an object with <tt>x</tt>
+ * and <tt>y</tt> attributes, such as a {@link pv.Vector}, storing the mark's
+ * position. See an implementing class for details.
+ *
+ * @see pv.Behavior.drag
+ * @see pv.Behavior.pan
+ * @see pv.Behavior.point
+ * @see pv.Behavior.select
+ * @see pv.Behavior.zoom
+ * @extends function
+ */
+pv.Behavior = {};
+/**
+ * Returns a new drag behavior to be registered on mousedown events.
+ *
+ * @class Implements interactive dragging starting with mousedown events.
+ * Register this behavior on marks that should be draggable by the user, such as
+ * the selected region for brushing and linking. This behavior can be used in
+ * tandom with {@link pv.Behavior.select} to allow the selected region to be
+ * dragged interactively.
+ *
+ * <p>After the initial mousedown event is triggered, this behavior listens for
+ * mousemove and mouseup events on the window. This allows dragging to continue
+ * even if the mouse temporarily leaves the mark that is being dragged, or even
+ * the root panel.
+ *
+ * <p>This behavior requires that the data associated with the mark being
+ * dragged have <tt>x</tt> and <tt>y</tt> attributes that correspond to the
+ * mark's location in pixels. The mark's positional properties are not set
+ * directly by this behavior; instead, the positional properties should be
+ * defined as:
+ *
+ * <pre>    .left(function(d) d.x)
+ *     .top(function(d) d.y)</pre>
+ *
+ * Thus, the behavior does not move the mark directly, but instead updates the
+ * mark position by updating the underlying data. Note that if the positional
+ * properties are defined with bottom and right (rather than top and left), the
+ * drag behavior will be inverted, which will confuse users!
+ *
+ * <p>The drag behavior is bounded by the parent panel; the <tt>x</tt> and
+ * <tt>y</tt> attributes are clamped such that the mark being dragged does not
+ * extend outside the enclosing panel's bounds. To facilitate this, the drag
+ * behavior also queries for <tt>dx</tt> and <tt>dy</tt> attributes on the
+ * underlying data, to determine the dimensions of the bar being dragged. For
+ * non-rectangular marks, the drag behavior simply treats the mark as a point,
+ * which means that only the mark's center is bounded.
+ *
+ * <p>The mark being dragged is automatically re-rendered for each mouse event
+ * as part of the drag operation. In addition, a <tt>fix</tt> attribute is
+ * populated on the mark, which allows visual feedback for dragging. For
+ * example, to change the mark fill color while dragging:
+ *
+ * <pre>    .fillStyle(function(d) d.fix ? "#ff7f0e" : "#aec7e8")</pre>
+ *
+ * In some cases, such as with network layouts, dragging the mark may cause
+ * related marks to change, in which case additional marks may also need to be
+ * rendered. This can be accomplished by listening for the drag
+ * psuedo-events:<ul>
+ *
+ * <li>dragstart (on mousedown)
+ * <li>drag (on mousemove)
+ * <li>dragend (on mouseup)
+ *
+ * </ul>For example, to render the parent panel while dragging, thus
+ * re-rendering all sibling marks:
+ *
+ * <pre>    .event("mousedown", pv.Behavior.drag())
+ *     .event("drag", function() this.parent)</pre>
+ *
+ * This behavior may be enhanced in the future to allow more flexible
+ * configuration of drag behavior.
+ *
+ * @extends pv.Behavior
+ * @see pv.Behavior
+ * @see pv.Behavior.select
+ * @see pv.Layout.force
+ */
+pv.Behavior.drag = function() {
+  var scene, // scene context
+      index, // scene context
+      p, // particle being dragged
+      v1, // initial mouse-particle offset
+      max;
+
+  /** @private */
+  function mousedown(d) {
+    index = this.index;
+    scene = this.scene;
+    var m = this.mouse();
+    v1 = ((p = d).fix = pv.vector(d.x, d.y)).minus(m);
+    max = {
+      x: this.parent.width() - (d.dx || 0),
+      y: this.parent.height() - (d.dy || 0)
+    };
+    scene.mark.context(scene, index, function() { this.render(); });
+    pv.Mark.dispatch("dragstart", scene, index);
+  }
+
+  /** @private */
+  function mousemove() {
+    if (!scene) return;
+    scene.mark.context(scene, index, function() {
+        var m = this.mouse();
+        p.x = p.fix.x = Math.max(0, Math.min(v1.x + m.x, max.x));
+        p.y = p.fix.y = Math.max(0, Math.min(v1.y + m.y, max.y));
+        this.render();
+      });
+    pv.Mark.dispatch("drag", scene, index);
+  }
+
+  /** @private */
+  function mouseup() {
+    if (!scene) return;
+    p.fix = null;
+    scene.mark.context(scene, index, function() { this.render(); });
+    pv.Mark.dispatch("dragend", scene, index);
+    scene = null;
+  }
+
+  pv.listen(window, "mousemove", mousemove);
+  pv.listen(window, "mouseup", mouseup);
+  return mousedown;
+};
+/**
+ * Returns a new point behavior to be registered on mousemove events.
+ *
+ * @class Implements interactive fuzzy pointing, identifying marks that are in
+ * close proximity to the mouse cursor. This behavior is an alternative to the
+ * native mouseover and mouseout events, improving usability. Rather than
+ * requiring the user to mouseover a mark exactly, the mouse simply needs to
+ * move near the given mark and a "point" event is triggered. In addition, if
+ * multiple marks overlap, the point behavior can be used to identify the mark
+ * instance closest to the cursor, as opposed to the one that is rendered on
+ * top.
+ *
+ * <p>The point behavior can also identify the closest mark instance for marks
+ * that produce a continuous graphic primitive. The point behavior can thus be
+ * used to provide details-on-demand for both discrete marks (such as dots and
+ * bars), as well as continuous marks (such as lines and areas).
+ *
+ * <p>This behavior is implemented by finding the closest mark instance to the
+ * mouse cursor on every mousemove event. If this closest mark is within the
+ * given radius threshold, which defaults to 30 pixels, a "point" psuedo-event
+ * is dispatched to the given mark instance. If any mark were previously
+ * pointed, it would receive a corresponding "unpoint" event. These two
+ * psuedo-event types correspond to the native "mouseover" and "mouseout"
+ * events, respectively. To increase the radius at which the point behavior can
+ * be applied, specify an appropriate threshold to the constructor, up to
+ * <tt>Infinity</tt>.
+ *
+ * <p>By default, the standard Cartesian distance is computed. However, with
+ * some visualizations it is desirable to consider only a single dimension, such
+ * as the <i>x</i>-dimension for an independent variable. In this case, the
+ * collapse parameter can be set to collapse the <i>y</i> dimension:
+ *
+ * <pre>    .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
+ *
+ * <p>This behavior only listens to mousemove events on the assigned panel,
+ * which is typically the root panel. The behavior will search recursively for
+ * descendant marks to point. If the mouse leaves the assigned panel, the
+ * behavior no longer receives mousemove events; an unpoint psuedo-event is
+ * automatically dispatched to unpoint any pointed mark. Marks may be re-pointed
+ * when the mouse reenters the panel.
+ *
+ * <p>Panels have transparent fill styles by default; this means that panels may
+ * not receive the initial mousemove event to start pointing. To fix this
+ * problem, either given the panel a visible fill style (such as "white"), or
+ * set the <tt>events</tt> property to "all" such that the panel receives events
+ * despite its transparent fill.
+ *
+ * <p>Note: this behavior does not currently wedge marks.
+ *
+ * @extends pv.Behavior
+ *
+ * @param {number} [r] the fuzzy radius threshold in pixels
+ * @see <a href="http://www.tovigrossman.com/papers/chi2005bubblecursor.pdf"
+ * >"The Bubble Cursor: Enhancing Target Acquisition by Dynamic Resizing of the
+ * Cursor's Activation Area"</a> by T. Grossman &amp; R. Balakrishnan, CHI 2005.
+ */
+pv.Behavior.point = function(r) {
+  var unpoint, // the current pointer target
+      collapse = null, // dimensions to collapse
+      kx = 1, // x-dimension cost scale
+      ky = 1, // y-dimension cost scale
+      r2 = arguments.length ? r * r : 900; // fuzzy radius
+
+  /** @private Search for the mark closest to the mouse. */
+  function search(scene, index) {
+    var s = scene[index],
+        point = {cost: Infinity};
+    for (var i = 0, n = s.visible && s.children.length; i < n; i++) {
+      var child = s.children[i], mark = child.mark, p;
+      if (mark.type == "panel") {
+        mark.scene = child;
+        for (var j = 0, m = child.length; j < m; j++) {
+          mark.index = j;
+          p = search(child, j);
+          if (p.cost < point.cost) point = p;
+        }
+        delete mark.scene;
+        delete mark.index;
+      } else if (mark.$handlers.point) {
+        var v = mark.mouse();
+        for (var j = 0, m = child.length; j < m; j++) {
+          var c = child[j],
+              dx = v.x - c.left - (c.width || 0) / 2,
+              dy = v.y - c.top - (c.height || 0) / 2,
+              dd = kx * dx * dx + ky * dy * dy;
+          if (dd < point.cost) {
+            point.distance = dx * dx + dy * dy;
+            point.cost = dd;
+            point.scene = child;
+            point.index = j;
+          }
+        }
+      }
+    }
+    return point;
+  }
+
+  /** @private */
+  function mousemove() {
+    /* If the closest mark is far away, clear the current target. */
+    var point = search(this.scene, this.index);
+    if ((point.cost == Infinity) || (point.distance > r2)) point = null;
+
+    /* Unpoint the old target, if it's not the new target. */
+    if (unpoint) {
+      if (point
+          && (unpoint.scene == point.scene)
+          && (unpoint.index == point.index)) return;
+      pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
+    }
+
+    /* Point the new target, if there is one. */
+    if (unpoint = point) {
+      pv.Mark.dispatch("point", point.scene, point.index);
+
+      /* Unpoint when the mouse leaves the root panel. */
+      pv.listen(this.root.canvas(), "mouseout", mouseout);
+    }
+  }
+
+  /** @private */
+  function mouseout(e) {
+    if (unpoint && !pv.ancestor(this, e.relatedTarget)) {
+      pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
+      unpoint = null;
+    }
+  }
+
+  /**
+   * Sets or gets the collapse parameter. By default, the standard Cartesian
+   * distance is computed. However, with some visualizations it is desirable to
+   * consider only a single dimension, such as the <i>x</i>-dimension for an
+   * independent variable. In this case, the collapse parameter can be set to
+   * collapse the <i>y</i> dimension:
+   *
+   * <pre>    .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
+   *
+   * @function
+   * @returns {pv.Behavior.point} this, or the current collapse parameter.
+   * @name pv.Behavior.point.prototype.collapse
+   * @param {string} [x] the new collapse parameter
+   */
+  mousemove.collapse = function(x) {
+    if (arguments.length) {
+      collapse = String(x);
+      switch (collapse) {
+        case "y": kx = 1; ky = 0; break;
+        case "x": kx = 0; ky = 1; break;
+        default: kx = 1; ky = 1; break;
+      }
+      return mousemove;
+    }
+    return collapse;
+  };
+
+  return mousemove;
+};
+/**
+ * Returns a new select behavior to be registered on mousedown events.
+ *
+ * @class Implements interactive selecting starting with mousedown events.
+ * Register this behavior on panels that should be selectable by the user, such
+ * for brushing and linking. This behavior can be used in tandom with
+ * {@link pv.Behavior.drag} to allow the selected region to be dragged
+ * interactively.
+ *
+ * <p>After the initial mousedown event is triggered, this behavior listens for
+ * mousemove and mouseup events on the window. This allows selecting to continue
+ * even if the mouse temporarily leaves the assigned panel, or even the root
+ * panel.
+ *
+ * <p>This behavior requires that the data associated with the mark being
+ * dragged have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
+ * that correspond to the mark's location and dimensions in pixels. The mark's
+ * positional properties are not set directly by this behavior; instead, the
+ * positional properties should be defined as:
+ *
+ * <pre>    .left(function(d) d.x)
+ *     .top(function(d) d.y)
+ *     .width(function(d) d.dx)
+ *     .height(function(d) d.dy)</pre>
+ *
+ * Thus, the behavior does not resize the mark directly, but instead updates the
+ * selection by updating the assigned panel's underlying data. Note that if the
+ * positional properties are defined with bottom and right (rather than top and
+ * left), the drag behavior will be inverted, which will confuse users!
+ *
+ * <p>The select behavior is bounded by the assigned panel; the positional
+ * attributes are clamped such that the selection does not extend outside the
+ * panel's bounds.
+ *
+ * <p>The panel being selected is automatically re-rendered for each mouse event
+ * as part of the drag operation. This behavior may be enhanced in the future to
+ * allow more flexible configuration of select behavior. In some cases, such as
+ * with parallel coordinates, making a selection may cause related marks to
+ * change, in which case additional marks may also need to be rendered. This can
+ * be accomplished by listening for the select psuedo-events:<ul>
+ *
+ * <li>selectstart (on mousedown)
+ * <li>select (on mousemove)
+ * <li>selectend (on mouseup)
+ *
+ * </ul>For example, to render the parent panel while selecting, thus
+ * re-rendering all sibling marks:
+ *
+ * <pre>    .event("mousedown", pv.Behavior.drag())
+ *     .event("select", function() this.parent)</pre>
+ *
+ * This behavior may be enhanced in the future to allow more flexible
+ * configuration of the selection behavior.
+ *
+ * @extends pv.Behavior
+ * @see pv.Behavior.drag
+ */
+pv.Behavior.select = function() {
+  var scene, // scene context
+      index, // scene context
+      r, // region being selected
+      m1; // initial mouse position
+
+  /** @private */
+  function mousedown(d) {
+    index = this.index;
+    scene = this.scene;
+    m1 = this.mouse();
+    r = d;
+    r.x = m1.x;
+    r.y = m1.y;
+    r.dx = r.dy = 0;
+    pv.Mark.dispatch("selectstart", scene, index);
+  }
+
+  /** @private */
+  function mousemove() {
+    if (!scene) return;
+    scene.mark.context(scene, index, function() {
+        var m2 = this.mouse();
+        r.x = Math.max(0, Math.min(m1.x, m2.x));
+        r.y = Math.max(0, Math.min(m1.y, m2.y));
+        r.dx = Math.min(this.width(), Math.max(m2.x, m1.x)) - r.x;
+        r.dy = Math.min(this.height(), Math.max(m2.y, m1.y)) - r.y;
+        this.render();
+      });
+    pv.Mark.dispatch("select", scene, index);
+  }
+
+  /** @private */
+  function mouseup() {
+    if (!scene) return;
+    pv.Mark.dispatch("selectend", scene, index);
+    scene = null;
+  }
+
+  pv.listen(window, "mousemove", mousemove);
+  pv.listen(window, "mouseup", mouseup);
+  return mousedown;
+};
+/**
+ * Returns a new resize behavior to be registered on mousedown events.
+ *
+ * @class Implements interactive resizing of a selection starting with mousedown
+ * events. Register this behavior on selection handles that should be resizeable
+ * by the user, such for brushing and linking. This behavior can be used in
+ * tandom with {@link pv.Behavior.select} and {@link pv.Behavior.drag} to allow
+ * the selected region to be selected and dragged interactively.
+ *
+ * <p>After the initial mousedown event is triggered, this behavior listens for
+ * mousemove and mouseup events on the window. This allows resizing to continue
+ * even if the mouse temporarily leaves the assigned panel, or even the root
+ * panel.
+ *
+ * <p>This behavior requires that the data associated with the mark being
+ * resized have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
+ * that correspond to the mark's location and dimensions in pixels. The mark's
+ * positional properties are not set directly by this behavior; instead, the
+ * positional properties should be defined as:
+ *
+ * <pre>    .left(function(d) d.x)
+ *     .top(function(d) d.y)
+ *     .width(function(d) d.dx)
+ *     .height(function(d) d.dy)</pre>
+ *
+ * Thus, the behavior does not resize the mark directly, but instead updates the
+ * size by updating the assigned panel's underlying data. Note that if the
+ * positional properties are defined with bottom and right (rather than top and
+ * left), the resize behavior will be inverted, which will confuse users!
+ *
+ * <p>The resize behavior is bounded by the assigned mark's enclosing panel; the
+ * positional attributes are clamped such that the selection does not extend
+ * outside the panel's bounds.
+ *
+ * <p>The mark being resized is automatically re-rendered for each mouse event
+ * as part of the resize operation. This behavior may be enhanced in the future
+ * to allow more flexible configuration. In some cases, such as with parallel
+ * coordinates, resizing the selection may cause related marks to change, in
+ * which case additional marks may also need to be rendered. This can be
+ * accomplished by listening for the select psuedo-events:<ul>
+ *
+ * <li>resizestart (on mousedown)
+ * <li>resize (on mousemove)
+ * <li>resizeend (on mouseup)
+ *
+ * </ul>For example, to render the parent panel while resizing, thus
+ * re-rendering all sibling marks:
+ *
+ * <pre>    .event("mousedown", pv.Behavior.resize("left"))
+ *     .event("resize", function() this.parent)</pre>
+ *
+ * This behavior may be enhanced in the future to allow more flexible
+ * configuration of the selection behavior.
+ *
+ * @extends pv.Behavior
+ * @see pv.Behavior.select
+ * @see pv.Behavior.drag
+ */
+pv.Behavior.resize = function(side) {
+  var scene, // scene context
+      index, // scene context
+      r, // region being selected
+      m1; // initial mouse position
+
+  /** @private */
+  function mousedown(d) {
+    index = this.index;
+    scene = this.scene;
+    m1 = this.mouse();
+    r = d;
+    switch (side) {
+      case "left": m1.x = r.x + r.dx; break;
+      case "right": m1.x = r.x; break;
+      case "top": m1.y = r.y + r.dy; break;
+      case "bottom": m1.y = r.y; break;
+    }
+    pv.Mark.dispatch("resizestart", scene, index);
+  }
+
+  /** @private */
+  function mousemove() {
+    if (!scene) return;
+    scene.mark.context(scene, index, function() {
+        var m2 = this.mouse();
+        r.x = Math.max(0, Math.min(m1.x, m2.x));
+        r.y = Math.max(0, Math.min(m1.y, m2.y));
+        r.dx = Math.min(this.parent.width(), Math.max(m2.x, m1.x)) - r.x;
+        r.dy = Math.min(this.parent.height(), Math.max(m2.y, m1.y)) - r.y;
+        this.render();
+      });
+    pv.Mark.dispatch("resize", scene, index);
+  }
+
+  /** @private */
+  function mouseup() {
+    if (!scene) return;
+    pv.Mark.dispatch("resizeend", scene, index);
+    scene = null;
+  }
+
+  pv.listen(window, "mousemove", mousemove);
+  pv.listen(window, "mouseup", mouseup);
+  return mousedown;
+};
+/**
+ * Returns a new pan behavior to be registered on mousedown events.
+ *
+ * @class Implements interactive panning starting with mousedown events.
+ * Register this behavior on panels to allow panning. This behavior can be used
+ * in tandem with {@link pv.Behavior.zoom} to allow both panning and zooming:
+ *
+ * <pre>    .event("mousedown", pv.Behavior.pan())
+ *     .event("mousewheel", pv.Behavior.zoom())</pre>
+ *
+ * The pan behavior currently supports only mouse events; support for keyboard
+ * shortcuts to improve accessibility may be added in the future.
+ *
+ * <p>After the initial mousedown event is triggered, this behavior listens for
+ * mousemove and mouseup events on the window. This allows panning to continue
+ * even if the mouse temporarily leaves the panel that is being panned, or even
+ * the root panel.
+ *
+ * <p>The implementation of this behavior relies on the panel's
+ * <tt>transform</tt> property, which specifies a matrix transformation that is
+ * applied to child marks. Note that the transform property only affects the
+ * panel's children, but not the panel itself; therefore the panel's fill and
+ * stroke will not change when the contents are panned.
+ *
+ * <p>Panels have transparent fill styles by default; this means that panels may
+ * not receive the initial mousedown event to start panning. To fix this
+ * problem, either given the panel a visible fill style (such as "white"), or
+ * set the <tt>events</tt> property to "all" such that the panel receives events
+ * despite its transparent fill.
+ *
+ * <p>The pan behavior has optional support for bounding. If enabled, the user
+ * will not be able to pan the panel outside of the initial bounds. This feature
+ * is designed to work in conjunction with the zoom behavior; otherwise,
+ * bounding the panel effectively disables all panning.
+ *
+ * @extends pv.Behavior
+ * @see pv.Behavior.zoom
+ * @see pv.Panel#transform
+ */
+pv.Behavior.pan = function() {
+  var scene, // scene context
+      index, // scene context
+      m1, // transformation matrix at the start of panning
+      v1, // mouse location at the start of panning
+      k, // inverse scale
+      bound; // whether to bound to the panel
+
+  /** @private */
+  function mousedown() {
+    index = this.index;
+    scene = this.scene;
+    v1 = pv.vector(pv.event.pageX, pv.event.pageY);
+    m1 = this.transform();
+    k = 1 / (m1.k * this.scale);
+    if (bound) {
+      bound = {
+        x: (1 - m1.k) * this.width(),
+        y: (1 - m1.k) * this.height()
+      };
+    }
+  }
+
+  /** @private */
+  function mousemove() {
+    if (!scene) return;
+    scene.mark.context(scene, index, function() {
+        var x = (pv.event.pageX - v1.x) * k,
+            y = (pv.event.pageY - v1.y) * k,
+            m = m1.translate(x, y);
+        if (bound) {
+          m.x = Math.max(bound.x, Math.min(0, m.x));
+          m.y = Math.max(bound.y, Math.min(0, m.y));
+        }
+        this.transform(m).render();
+      });
+    pv.Mark.dispatch("pan", scene, index);
+  }
+
+  /** @private */
+  function mouseup() {
+    scene = null;
+  }
+
+  /**
+   * Sets or gets the bound parameter. If bounding is enabled, the user will not
+   * be able to pan outside the initial panel bounds; this typically applies
+   * only when the pan behavior is used in tandem with the zoom behavior.
+   * Bounding is not enabled by default.
+   *
+   * <p>Note: enabling bounding after panning has already occurred will not
+   * immediately reset the transform. Bounding should be enabled before the
+   * panning behavior is applied.
+   *
+   * @function
+   * @returns {pv.Behavior.pan} this, or the current bound parameter.
+   * @name pv.Behavior.pan.prototype.bound
+   * @param {boolean} [x] the new bound parameter.
+   */
+  mousedown.bound = function(x) {
+    if (arguments.length) {
+      bound = Boolean(x);
+      return this;
+    }
+    return Boolean(bound);
+  };
+
+  pv.listen(window, "mousemove", mousemove);
+  pv.listen(window, "mouseup", mouseup);
+  return mousedown;
+};
+/**
+ * Returns a new zoom behavior to be registered on mousewheel events.
+ *
+ * @class Implements interactive zooming using mousewheel events. Register this
+ * behavior on panels to allow zooming. This behavior can be used in tandem with
+ * {@link pv.Behavior.pan} to allow both panning and zooming:
+ *
+ * <pre>    .event("mousedown", pv.Behavior.pan())
+ *     .event("mousewheel", pv.Behavior.zoom())</pre>
+ *
+ * The zoom behavior currently supports only mousewheel events; support for
+ * keyboard shortcuts and gesture events to improve accessibility may be added
+ * in the future.
+ *
+ * <p>The implementation of this behavior relies on the panel's
+ * <tt>transform</tt> property, which specifies a matrix transformation that is
+ * applied to child marks. Note that the transform property only affects the
+ * panel's children, but not the panel itself; therefore the panel's fill and
+ * stroke will not change when the contents are zoomed. The built-in support for
+ * transforms only supports uniform scaling and translates, which is sufficient
+ * for panning and zooming.  Note that this is not a strict geometric
+ * transformation, as the <tt>lineWidth</tt> property is scale-aware: strokes
+ * are drawn at constant size independent of scale.
+ *
+ * <p>Panels have transparent fill styles by default; this means that panels may
+ * not receive mousewheel events to zoom. To fix this problem, either given the
+ * panel a visible fill style (such as "white"), or set the <tt>events</tt>
+ * property to "all" such that the panel receives events despite its transparent
+ * fill.
+ *
+ * <p>The zoom behavior has optional support for bounding. If enabled, the user
+ * will not be able to zoom out farther than the initial bounds. This feature is
+ * designed to work in conjunction with the pan behavior.
+ *
+ * @extends pv.Behavior
+ * @see pv.Panel#transform
+ * @see pv.Mark#scale
+ * @param {number} speed
+ */
+pv.Behavior.zoom = function(speed) {
+  var bound; // whether to bound to the panel
+
+  if (!arguments.length) speed = 1 / 48;
+
+  /** @private */
+  function mousewheel() {
+    var v = this.mouse(),
+        k = pv.event.wheel * speed,
+        m = this.transform().translate(v.x, v.y)
+            .scale((k < 0) ? (1e3 / (1e3 - k)) : ((1e3 + k) / 1e3))
+            .translate(-v.x, -v.y);
+    if (bound) {
+      m.k = Math.max(1, m.k);
+      m.x = Math.max((1 - m.k) * this.width(), Math.min(0, m.x));
+      m.y = Math.max((1 - m.k) * this.height(), Math.min(0, m.y));
+    }
+    this.transform(m).render();
+    pv.Mark.dispatch("zoom", this.scene, this.index);
+  }
+
+  /**
+   * Sets or gets the bound parameter. If bounding is enabled, the user will not
+   * be able to zoom out farther than the initial panel bounds. Bounding is not
+   * enabled by default. If this behavior is used in tandem with the pan
+   * behavior, both should use the same bound parameter.
+   *
+   * <p>Note: enabling bounding after zooming has already occurred will not
+   * immediately reset the transform. Bounding should be enabled before the zoom
+   * behavior is applied.
+   *
+   * @function
+   * @returns {pv.Behavior.zoom} this, or the current bound parameter.
+   * @name pv.Behavior.zoom.prototype.bound
+   * @param {boolean} [x] the new bound parameter.
+   */
+  mousewheel.bound = function(x) {
+    if (arguments.length) {
+      bound = Boolean(x);
+      return this;
+    }
+    return Boolean(bound);
+  };
+
+  return mousewheel;
+};
+/**
+ * @ignore
+ * @namespace
+ */
+pv.Geo = function() {};
+/**
+ * Abstract; not implemented. There is no explicit constructor; this class
+ * merely serves to document the representation used by {@link pv.Geo.scale}.
+ *
+ * @class Represents a pair of geographic coordinates.
+ *
+ * @name pv.Geo.LatLng
+ * @see pv.Geo.scale
+ */
+
+/**
+ * The <i>latitude</i> coordinate in degrees; positive is North.
+ *
+ * @type number
+ * @name pv.Geo.LatLng.prototype.lat
+ */
+
+/**
+ * The <i>longitude</i> coordinate in degrees; positive is East.
+ *
+ * @type number
+ * @name pv.Geo.LatLng.prototype.lng
+ */
+/**
+ * Abstract; not implemented. There is no explicit constructor; this class
+ * merely serves to document the representation used by {@link pv.Geo.scale}.
+ *
+ * @class Represents a geographic projection. This class provides the core
+ * implementation for {@link pv.Geo.scale}s, mapping between geographic
+ * coordinates (latitude and longitude) and normalized screen space in the range
+ * [-1,1]. The remaining mapping between normalized screen space and actual
+ * pixels is performed by <tt>pv.Geo.scale</tt>.
+ *
+ * <p>Many geographic projections have a point around which the projection is
+ * centered. Rather than have each implementation add support for a
+ * user-specified center point, the <tt>pv.Geo.scale</tt> translates the
+ * geographic coordinates relative to the center point for both the forward and
+ * inverse projection.
+ *
+ * <p>In general, this class should not be used directly, unless the desire is
+ * to implement a new geographic projection. Instead, use <tt>pv.Geo.scale</tt>.
+ * Implementations are not required to implement inverse projections, but are
+ * needed for some forms of interactivity. Also note that some inverse
+ * projections are ambiguous, such as the connecting points in Dymaxian maps.
+ *
+ * @name pv.Geo.Projection
+ * @see pv.Geo.scale
+ */
+
+/**
+ * The <i>forward</i> projection.
+ *
+ * @function
+ * @name pv.Geo.Projection.prototype.project
+ * @param {pv.Geo.LatLng} latlng the latitude and longitude to project.
+ * @returns {pv.Vector} the xy-coordinates of the given point.
+ */
+
+/**
+ * The <i>inverse</i> projection; optional.
+ *
+ * @function
+ * @name pv.Geo.Projection.prototype.invert
+ * @param {pv.Vector} xy the x- and y-coordinates to invert.
+ * @returns {pv.Geo.LatLng} the latitude and longitude of the given point.
+ */
+/**
+ * The built-in projections.
+ *
+ * @see pv.Geo.Projection
+ * @namespace
+ */
+pv.Geo.projections = {
+
+  /** @see http://en.wikipedia.org/wiki/Mercator_projection */
+  mercator: {
+    project: function(latlng) {
+      return {
+          x: latlng.lng / 180,
+          y: latlng.lat > 85 ? 1 : latlng.lat < -85 ? -1
+              : Math.log(Math.tan(Math.PI / 4
+              + pv.radians(latlng.lat) / 2)) / Math.PI
+        };
+    },
+    invert: function(xy) {
+      return {
+          lng: xy.x * 180,
+          lat: pv.degrees(2 * Math.atan(Math.exp(xy.y * Math.PI)) - Math.PI / 2)
+        };
+    }
+  },
+
+  /** @see http://en.wikipedia.org/wiki/Gall-Peters_projection */
+  "gall-peters": {
+    project: function(latlng) {
+      return {
+          x: latlng.lng / 180,
+          y: Math.sin(pv.radians(latlng.lat))
+        };
+    },
+    invert: function(xy) {
+      return {
+          lng: xy.x * 180,
+          lat: pv.degrees(Math.asin(xy.y))
+        };
+    }
+  },
+
+  /** @see http://en.wikipedia.org/wiki/Sinusoidal_projection */
+  sinusoidal: {
+    project: function(latlng) {
+      return {
+          x: pv.radians(latlng.lng) * Math.cos(pv.radians(latlng.lat)) / Math.PI,
+          y: latlng.lat / 90
+        };
+    },
+    invert: function(xy) {
+      return {
+          lng: pv.degrees((xy.x * Math.PI) / Math.cos(xy.y * Math.PI / 2)),
+          lat: xy.y * 90
+        };
+    }
+  },
+
+  /** @see http://en.wikipedia.org/wiki/Aitoff_projection */
+  aitoff: {
+    project: function(latlng) {
+      var l = pv.radians(latlng.lng),
+          f = pv.radians(latlng.lat),
+          a = Math.acos(Math.cos(f) * Math.cos(l / 2));
+      return {
+          x: 2 * (a ? (Math.cos(f) * Math.sin(l / 2) * a / Math.sin(a)) : 0) / Math.PI,
+          y: 2 * (a ? (Math.sin(f) * a / Math.sin(a)) : 0) / Math.PI
+        };
+    },
+    invert: function(xy) {
+      var x = xy.x * Math.PI / 2,
+          y = xy.y * Math.PI / 2;
+      return {
+          lng: pv.degrees(x / Math.cos(y)),
+          lat: pv.degrees(y)
+        };
+    }
+  },
+
+  /** @see http://en.wikipedia.org/wiki/Hammer_projection */
+  hammer: {
+    project: function(latlng) {
+      var l = pv.radians(latlng.lng),
+          f = pv.radians(latlng.lat),
+          c = Math.sqrt(1 + Math.cos(f) * Math.cos(l / 2));
+      return {
+          x: 2 * Math.SQRT2 * Math.cos(f) * Math.sin(l / 2) / c / 3,
+          y: Math.SQRT2 * Math.sin(f) / c / 1.5
+        };
+    },
+    invert: function(xy) {
+      var x = xy.x * 3,
+          y = xy.y * 1.5,
+          z = Math.sqrt(1 - x * x / 16 - y * y / 4);
+      return {
+          lng: pv.degrees(2 * Math.atan2(z * x, 2 * (2 * z * z - 1))),
+          lat: pv.degrees(Math.asin(z * y))
+        };
+    }
+  },
+
+  /** The identity or "none" projection. */
+  identity: {
+    project: function(latlng) {
+      return {
+          x: latlng.lng / 180,
+          y: latlng.lat / 90
+        };
+    },
+    invert: function(xy) {
+      return {
+          lng: xy.x * 180,
+          lat: xy.y * 90
+        };
+    }
+  }
+};
+/**
+ * Returns a geographic scale. The arguments to this constructor are optional,
+ * and equivalent to calling {@link #projection}.
+ *
+ * @class Represents a geographic scale; a mapping between latitude-longitude
+ * coordinates and screen pixel coordinates. By default, the domain is inferred
+ * from the geographic coordinates, so that the domain fills the output range.
+ *
+ * <p>Note that geographic scales are two-dimensional transformations, rather
+ * than the one-dimensional bidrectional mapping typical of other scales.
+ * Rather than mapping (for example) between a numeric domain and a numeric
+ * range, geographic scales map between two coordinate objects: {@link
+ * pv.Geo.LatLng} and {@link pv.Vector}.
+ *
+ * @param {pv.Geo.Projection} [p] optional projection.
+ * @see pv.Geo.scale#ticks
+ */
+pv.Geo.scale = function(p) {
+  var rmin = {x: 0, y: 0}, // default range minimum
+      rmax = {x: 1, y: 1}, // default range maximum
+      d = [], // default domain
+      j = pv.Geo.projections.identity, // domain <-> normalized range
+      x = pv.Scale.linear(-1, 1).range(0, 1), // normalized <-> range
+      y = pv.Scale.linear(-1, 1).range(1, 0), // normalized <-> range
+      c = {lng: 0, lat: 0}, // Center Point
+      lastLatLng, // cached latlng
+      lastPoint; // cached point
+
+  /** @private */
+  function scale(latlng) {
+    if (!lastLatLng
+        || (latlng.lng != lastLatLng.lng)
+        || (latlng.lat != lastLatLng.lat)) {
+      lastLatLng = latlng;
+      var p = project(latlng);
+      lastPoint = {x: x(p.x), y: y(p.y)};
+    }
+    return lastPoint;
+  }
+
+  /** @private */
+  function project(latlng) {
+    var offset = {lng: latlng.lng - c.lng, lat: latlng.lat};
+    return j.project(offset);
+  }
+
+  /** @private */
+  function invert(xy) {
+    var latlng = j.invert(xy);
+    latlng.lng += c.lng;
+    return latlng;
+  }
+
+  /** Returns the projected x-coordinate. */
+  scale.x = function(latlng) {
+    return scale(latlng).x;
+  };
+
+  /** Returns the projected y-coordinate. */
+  scale.y = function(latlng) {
+    return scale(latlng).y;
+  };
+
+  /**
+   * Abstract; this is a local namespace on a given geographic scale.
+   *
+   * @namespace Tick functions for geographic scales. Because geographic scales
+   * represent two-dimensional transformations (as opposed to one-dimensional
+   * transformations typical of other scales), the tick values are similarly
+   * represented as two-dimensional coordinates in the input domain, i.e.,
+   * {@link pv.Geo.LatLng} objects.
+   *
+   * <p>Also, note that non-rectilinear projections, such as sinsuoidal and
+   * aitoff, may not produce straight lines for constant longitude or constant
+   * latitude. Therefore the returned array of ticks is a two-dimensional array,
+   * sampling various latitudes as constant longitude, and vice versa.
+   *
+   * <p>The tick lines can therefore be approximated as polylines, either with
+   * "linear" or "cardinal" interpolation. This is not as accurate as drawing
+   * the true curve through the projection space, but is usually sufficient.
+   *
+   * @name pv.Geo.scale.prototype.ticks
+   * @see pv.Geo.scale
+   * @see pv.Geo.LatLng
+   * @see pv.Line#interpolate
+   */
+  scale.ticks = {
+
+    /**
+     * Returns longitude ticks.
+     *
+     * @function
+     * @param {number} [m] the desired number of ticks.
+     * @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
+     * @name pv.Geo.scale.prototype.ticks.prototype.lng
+     */
+    lng: function(m) {
+      var lat, lng;
+      if (d.length > 1) {
+        var s = pv.Scale.linear();
+        if (m == undefined) m = 10;
+        lat = s.domain(d, function(d) { return d.lat; }).ticks(m);
+        lng = s.domain(d, function(d) { return d.lng; }).ticks(m);
+      } else {
+        lat = pv.range(-80, 81, 10);
+        lng = pv.range(-180, 181, 10);
+      }
+      return lng.map(function(lng) {
+        return lat.map(function(lat) {
+          return {lat: lat, lng: lng};
+        });
+      });
+    },
+
+    /**
+     * Returns latitude ticks.
+     *
+     * @function
+     * @param {number} [m] the desired number of ticks.
+     * @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
+     * @name pv.Geo.scale.prototype.ticks.prototype.lat
+     */
+    lat: function(m) {
+      return pv.transpose(scale.ticks.lng(m));
+    }
+  };
+
+  /**
+   * Inverts the specified value in the output range, returning the
+   * corresponding value in the input domain. This is frequently used to convert
+   * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
+   * domain. Inversion is only supported for numeric ranges, and not colors.
+   *
+   * <p>Note that this method does not do any rounding or bounds checking. If
+   * the input domain is discrete (e.g., an array index), the returned value
+   * should be rounded. If the specified <tt>y</tt> value is outside the range,
+   * the returned value may be equivalently outside the input domain.
+   *
+   * @function
+   * @name pv.Geo.scale.prototype.invert
+   * @param {number} y a value in the output range (a pixel location).
+   * @returns {number} a value in the input domain.
+   */
+  scale.invert = function(p) {
+    return invert({x: x.invert(p.x), y: y.invert(p.y)});
+  };
+
+  /**
+   * Sets or gets the input domain. Note that unlike quantitative scales, the
+   * domain cannot be reduced to a simple rectangle (i.e., minimum and maximum
+   * values for latitude and longitude). Instead, the domain values must be
+   * projected to normalized space, effectively finding the domain in normalized
+   * space rather than in terms of latitude and longitude. Thus, changing the
+   * projection requires recomputing the normalized domain.
+   *
+   * <p>This method can be invoked several ways:
+   *
+   * <p>1. <tt>domain(values...)</tt>
+   *
+   * <p>Specifying the domain as a series of {@link pv.Geo.LatLng}s is the most
+   * explicit and recommended approach. However, if the domain values are
+   * derived from data, you may find the second method more appropriate.
+   *
+   * <p>2. <tt>domain(array, f)</tt>
+   *
+   * <p>Rather than enumerating the domain explicitly, you can specify a single
+   * argument of an array. In addition, you can specify an optional accessor
+   * function to extract the domain values (as {@link pv.Geo.LatLng}s) from the
+   * array. If the specified array has fewer than two elements, this scale will
+   * default to the full normalized domain.
+   *
+   * <p>2. <tt>domain()</tt>
+   *
+   * <p>Invoking the <tt>domain</tt> method with no arguments returns the
+   * current domain as an array.
+   *
+   * @function
+   * @name pv.Geo.scale.prototype.domain
+   * @param {...} domain... domain values.
+   * @returns {pv.Geo.scale} <tt>this</tt>, or the current domain.
+   */
+  scale.domain = function(array, f) {
+    if (arguments.length) {
+      d = (array instanceof Array)
+          ? ((arguments.length > 1) ? pv.map(array, f) : array)
+          : Array.prototype.slice.call(arguments);
+      if (d.length > 1) {
+        var lngs = d.map(function(c) { return c.lng; });
+        var lats = d.map(function(c) { return c.lat; });
+        c = {
+          lng: (pv.max(lngs) + pv.min(lngs)) / 2,
+          lat: (pv.max(lats) + pv.min(lats)) / 2
+        };
+        var n = d.map(project); // normalized domain
+        x.domain(n, function(p) { return p.x; });
+        y.domain(n, function(p) { return p.y; });
+      } else {
+        c = {lng: 0, lat: 0};
+        x.domain(-1, 1);
+        y.domain(-1, 1);
+      }
+      lastLatLng = null; // invalidate the cache
+      return this;
+    }
+    return d;
+  };
+
+  /**
+   * Sets or gets the output range. This method can be invoked several ways:
+   *
+   * <p>1. <tt>range(min, max)</tt>
+   *
+   * <p>If two objects are specified, the arguments should be {@link pv.Vector}s
+   * which specify the minimum and maximum values of the x- and y-coordinates
+   * explicitly.
+   *
+   * <p>2. <tt>range(width, height)</tt>
+   *
+   * <p>If two numbers are specified, the arguments specify the maximum values
+   * of the x- and y-coordinates explicitly; the minimum values are implicitly
+   * zero.
+   *
+   * <p>3. <tt>range()</tt>
+   *
+   * <p>Invoking the <tt>range</tt> method with no arguments returns the current
+   * range as an array of two {@link pv.Vector}s: the minimum (top-left) and
+   * maximum (bottom-right) values.
+   *
+   * @function
+   * @name pv.Geo.scale.prototype.range
+   * @param {...} range... range values.
+   * @returns {pv.Geo.scale} <tt>this</tt>, or the current range.
+   */
+  scale.range = function(min, max) {
+    if (arguments.length) {
+      if (typeof min == "object") {
+        rmin = {x: Number(min.x), y: Number(min.y)};
+        rmax = {x: Number(max.x), y: Number(max.y)};
+      } else {
+        rmin = {x: 0, y: 0};
+        rmax = {x: Number(min), y: Number(max)};
+      }
+      x.range(rmin.x, rmax.x);
+      y.range(rmax.y, rmin.y); // XXX flipped?
+      lastLatLng = null; // invalidate the cache
+      return this;
+    }
+    return [rmin, rmax];
+  };
+
+  /**
+   * Sets or gets the projection. This method can be invoked several ways:
+   *
+   * <p>1. <tt>projection(string)</tt>
+   *
+   * <p>Specifying a string sets the projection to the given named projection in
+   * {@link pv.Geo.projections}. If no such projection is found, the identity
+   * projection is used.
+   *
+   * <p>2. <tt>projection(object)</tt>
+   *
+   * <p>Specifying an object sets the projection to the given custom projection,
+   * which must implement the <i>forward</i> and <i>inverse</i> methods per the
+   * {@link pv.Geo.Projection} interface.
+   *
+   * <p>3. <tt>projection()</tt>
+   *
+   * <p>Invoking the <tt>projection</tt> method with no arguments returns the
+   * current object that defined the projection.
+   *
+   * @function
+   * @name pv.Scale.geo.prototype.projection
+   * @param {...} range... range values.
+   * @returns {pv.Scale.geo} <tt>this</tt>, or the current range.
+   */
+  scale.projection = function(p) {
+    if (arguments.length) {
+      j = typeof p == "string"
+          ? pv.Geo.projections[p] || pv.Geo.projections.identity
+          : p;
+      return this.domain(d); // recompute normalized domain
+    }
+    return p;
+  };
+
+  /**
+   * Returns a view of this scale by the specified accessor function <tt>f</tt>.
+   * Given a scale <tt>g</tt>, <tt>g.by(function(d) d.foo)</tt> is equivalent to
+   * <tt>function(d) g(d.foo)</tt>. This method should be used judiciously; it
+   * is typically more clear to invoke the scale directly, passing in the value
+   * to be scaled.
+   *
+   * @function
+   * @name pv.Geo.scale.prototype.by
+   * @param {function} f an accessor function.
+   * @returns {pv.Geo.scale} a view of this scale by the specified accessor
+   * function.
+   */
+  scale.by = function(f) {
+    function by() { return scale(f.apply(this, arguments)); }
+    for (var method in scale) by[method] = scale[method];
+    return by;
+  };
+
+  if (arguments.length) scale.projection(p);
+  return scale;
+};
diff --git a/src/allmydata/web/protovis-r3.2.js b/src/allmydata/web/protovis-r3.2.js
new file mode 100644
index 0000000..95bb3be
--- /dev/null
+++ b/src/allmydata/web/protovis-r3.2.js
@@ -0,0 +1,277 @@
+// fba9dc2
+var a;if(!Array.prototype.map)Array.prototype.map=function(b,c){for(var d=this.length,f=new Array(d),g=0;g<d;g++)if(g in this)f[g]=b.call(c,this[g],g,this);return f};if(!Array.prototype.filter)Array.prototype.filter=function(b,c){for(var d=this.length,f=[],g=0;g<d;g++)if(g in this){var h=this[g];b.call(c,h,g,this)&&f.push(h)}return f};if(!Array.prototype.forEach)Array.prototype.forEach=function(b,c){for(var d=this.length>>>0,f=0;f<d;f++)f in this&&b.call(c,this[f],f,this)};
+if(!Array.prototype.reduce)Array.prototype.reduce=function(b,c){var d=this.length;if(!d&&arguments.length==1)throw new Error("reduce: empty array, no initial value");var f=0;if(arguments.length<2)for(;;){if(f in this){c=this[f++];break}if(++f>=d)throw new Error("reduce: no values, no initial value");}for(;f<d;f++)if(f in this)c=b(c,this[f],f,this);return c};var pv={};pv.version={major:3,minor:2};pv.identity=function(b){return b};pv.index=function(){return this.index};pv.child=function(){return this.childIndex};
+pv.parent=function(){return this.parent.index};pv.extend=function(b){function c(){}c.prototype=b.prototype||b;return new c};
+try{eval("pv.parse = function(x) x;")}catch(e){pv.parse=function(b){for(var c=new RegExp("function\\s*(\\b\\w+)?\\s*\\([^)]*\\)\\s*","mg"),d,f,g=0,h="";d=c.exec(b);){d=d.index+d[0].length;if(b.charAt(d)!="{"){h+=b.substring(g,d)+"{return ";g=d;for(var i=0;i>=0&&d<b.length;d++){var j=b.charAt(d);switch(j){case '"':case "'":for(;++d<b.length&&(f=b.charAt(d))!=j;)f=="\\"&&d++;break;case "[":case "(":i++;break;case "]":case ")":i--;break;case ";":case ",":i==0&&i--;break}}h+=pv.parse(b.substring(g,--d))+
+";}";g=d}c.lastIndex=d}h+=b.substring(g);return h}}pv.css=function(b,c){return window.getComputedStyle?window.getComputedStyle(b,null).getPropertyValue(c):b.currentStyle[c]};pv.error=function(b){typeof console=="undefined"?alert(b):console.error(b)};pv.listen=function(b,c,d){d=pv.listener(d);return b.addEventListener?b.addEventListener(c,d,false):b.attachEvent("on"+c,d)};pv.listener=function(b){return b.$listener||(b.$listener=function(c){try{pv.event=c;return b.call(this,c)}finally{delete pv.event}})};
+pv.ancestor=function(b,c){for(;c;){if(c==b)return true;c=c.parentNode}return false};pv.id=function(){var b=1;return function(){return b++}}();pv.functor=function(b){return typeof b=="function"?b:function(){return b}};pv.listen(window,"load",function(){for(pv.$={i:0,x:document.getElementsByTagName("script")};pv.$.i<pv.$.x.length;pv.$.i++){pv.$.s=pv.$.x[pv.$.i];if(pv.$.s.type=="text/javascript+protovis")try{window.eval(pv.parse(pv.$.s.text))}catch(b){pv.error(b)}}delete pv.$});pv.Format={};
+pv.Format.re=function(b){return b.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g,"\\$&")};pv.Format.pad=function(b,c,d){c=c-String(d).length;return c<1?d:(new Array(c+1)).join(b)+d};
+pv.Format.date=function(b){function c(f){return b.replace(/%[a-zA-Z0-9]/g,function(g){switch(g){case "%a":return["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][f.getDay()];case "%A":return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][f.getDay()];case "%h":case "%b":return["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][f.getMonth()];case "%B":return["January","February","March","April","May","June","July","August","September","October","November","December"][f.getMonth()];
+case "%c":return f.toLocaleString();case "%C":return d("0",2,Math.floor(f.getFullYear()/100)%100);case "%d":return d("0",2,f.getDate());case "%x":case "%D":return d("0",2,f.getMonth()+1)+"/"+d("0",2,f.getDate())+"/"+d("0",2,f.getFullYear()%100);case "%e":return d(" ",2,f.getDate());case "%H":return d("0",2,f.getHours());case "%I":return(g=f.getHours()%12)?d("0",2,g):12;case "%m":return d("0",2,f.getMonth()+1);case "%M":return d("0",2,f.getMinutes());case "%n":return"\n";case "%p":return f.getHours()<
+12?"AM":"PM";case "%T":case "%X":case "%r":g=f.getHours()%12;return(g?d("0",2,g):12)+":"+d("0",2,f.getMinutes())+":"+d("0",2,f.getSeconds())+" "+(f.getHours()<12?"AM":"PM");case "%R":return d("0",2,f.getHours())+":"+d("0",2,f.getMinutes());case "%S":return d("0",2,f.getSeconds());case "%Q":return d("0",3,f.getMilliseconds());case "%t":return"\t";case "%u":return(g=f.getDay())?g:1;case "%w":return f.getDay();case "%y":return d("0",2,f.getFullYear()%100);case "%Y":return f.getFullYear();case "%%":return"%"}return g})}
+var d=pv.Format.pad;c.format=c;c.parse=function(f){var g=1970,h=0,i=1,j=0,l=0,k=0,q=[function(){}],o=pv.Format.re(b).replace(/%[a-zA-Z0-9]/g,function(n){switch(n){case "%b":q.push(function(m){h={Jan:0,Feb:1,Mar:2,Apr:3,May:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11}[m]});return"([A-Za-z]+)";case "%h":case "%B":q.push(function(m){h={January:0,February:1,March:2,April:3,May:4,June:5,July:6,August:7,September:8,October:9,November:10,December:11}[m]});return"([A-Za-z]+)";case "%e":case "%d":q.push(function(m){i=
+m});return"([0-9]+)";case "%I":case "%H":q.push(function(m){j=m});return"([0-9]+)";case "%m":q.push(function(m){h=m-1});return"([0-9]+)";case "%M":q.push(function(m){l=m});return"([0-9]+)";case "%p":q.push(function(m){if(j==12){if(m=="am")j=0}else if(m=="pm")j=Number(j)+12});return"(am|pm)";case "%S":q.push(function(m){k=m});return"([0-9]+)";case "%y":q.push(function(m){m=Number(m);g=m+(0<=m&&m<69?2E3:m>=69&&m<100?1900:0)});return"([0-9]+)";case "%Y":q.push(function(m){g=m});return"([0-9]+)";case "%%":q.push(function(){});
+return"%"}return n});(f=f.match(o))&&f.forEach(function(n,m){q[m](n)});return new Date(g,h,i,j,l,k)};return c};
+pv.Format.time=function(b){function c(f){f=Number(f);switch(b){case "short":if(f>=31536E6)return(f/31536E6).toFixed(1)+" years";else if(f>=6048E5)return(f/6048E5).toFixed(1)+" weeks";else if(f>=864E5)return(f/864E5).toFixed(1)+" days";else if(f>=36E5)return(f/36E5).toFixed(1)+" hours";else if(f>=6E4)return(f/6E4).toFixed(1)+" minutes";return(f/1E3).toFixed(1)+" seconds";case "long":var g=[],h=f%36E5/6E4>>0;g.push(d("0",2,f%6E4/1E3>>0));if(f>=36E5){var i=f%864E5/36E5>>0;g.push(d("0",2,h));if(f>=864E5){g.push(d("0",
+2,i));g.push(Math.floor(f/864E5).toFixed())}else g.push(i.toFixed())}else g.push(h.toFixed());return g.reverse().join(":")}}var d=pv.Format.pad;c.format=c;c.parse=function(f){switch(b){case "short":for(var g=/([0-9,.]+)\s*([a-z]+)/g,h,i=0;h=g.exec(f);){var j=parseFloat(h[0].replace(",","")),l=0;switch(h[2].toLowerCase()){case "year":case "years":l=31536E6;break;case "week":case "weeks":l=6048E5;break;case "day":case "days":l=864E5;break;case "hour":case "hours":l=36E5;break;case "minute":case "minutes":l=
+6E4;break;case "second":case "seconds":l=1E3;break}i+=j*l}return i;case "long":h=f.replace(",","").split(":").reverse();i=0;if(h.length)i+=parseFloat(h[0])*1E3;if(h.length>1)i+=parseFloat(h[1])*6E4;if(h.length>2)i+=parseFloat(h[2])*36E5;if(h.length>3)i+=parseFloat(h[3])*864E5;return i}};return c};
+pv.Format.number=function(){function b(n){if(Infinity>h)n=Math.round(n*i)/i;var m=String(Math.abs(n)).split("."),r=m[0];n=n<0?"-":"";if(r.length>d)r=r.substring(r.length-d);if(k&&r.length<c)r=n+(new Array(c-r.length+1)).join(j)+r;if(r.length>3)r=r.replace(/\B(?=(?:\d{3})+(?!\d))/g,o);if(!k&&r.length<f)r=(new Array(f-r.length+1)).join(j)+n+r;m[0]=r;r=m[1]||"";if(r.length<g)m[1]=r+(new Array(g-r.length+1)).join(l);return m.join(q)}var c=0,d=Infinity,f=0,g=0,h=0,i=1,j="0",l="0",k=true,q=".",o=",";b.format=
+b;b.parse=function(n){var m=pv.Format.re;n=String(n).replace(new RegExp("^("+m(j)+")*"),"").replace(new RegExp("("+m(l)+")*$"),"").split(q);m=n[0].replace(new RegExp(m(o),"g"),"");if(m.length>d)m=m.substring(m.length-d);n=n[1]?Number("0."+n[1]):0;if(Infinity>h)n=Math.round(n*i)/i;return Math.round(m)+n};b.integerDigits=function(n,m){if(arguments.length){c=Number(n);d=arguments.length>1?Number(m):c;f=c+Math.floor(c/3)*o.length;return this}return[c,d]};b.fractionDigits=function(n,m){if(arguments.length){g=
+Number(n);h=arguments.length>1?Number(m):g;i=Math.pow(10,h);return this}return[g,h]};b.integerPad=function(n){if(arguments.length){j=String(n);k=/\d/.test(j);return this}return j};b.fractionPad=function(n){if(arguments.length){l=String(n);return this}return l};b.decimal=function(n){if(arguments.length){q=String(n);return this}return q};b.group=function(n){if(arguments.length){o=n?String(n):"";f=c+Math.floor(c/3)*o.length;return this}return o};return b};
+pv.map=function(b,c){var d={};return c?b.map(function(f,g){d.index=g;return c.call(d,f)}):b.slice()};pv.repeat=function(b,c){if(arguments.length==1)c=2;return pv.blend(pv.range(c).map(function(){return b}))};pv.cross=function(b,c){for(var d=[],f=0,g=b.length,h=c.length;f<g;f++)for(var i=0,j=b[f];i<h;i++)d.push([j,c[i]]);return d};pv.blend=function(b){return Array.prototype.concat.apply([],b)};
+pv.transpose=function(b){var c=b.length,d=pv.max(b,function(i){return i.length});if(d>c){b.length=d;for(var f=c;f<d;f++)b[f]=new Array(c);for(f=0;f<c;f++)for(var g=f+1;g<d;g++){var h=b[f][g];b[f][g]=b[g][f];b[g][f]=h}}else{for(f=0;f<d;f++)b[f].length=c;for(f=0;f<c;f++)for(g=0;g<f;g++){h=b[f][g];b[f][g]=b[g][f];b[g][f]=h}}b.length=d;for(f=0;f<d;f++)b[f].length=c;return b};pv.normalize=function(b,c){b=pv.map(b,c);c=pv.sum(b);for(var d=0;d<b.length;d++)b[d]/=c;return b};
+pv.permute=function(b,c,d){if(!d)d=pv.identity;var f=new Array(c.length),g={};c.forEach(function(h,i){g.index=h;f[i]=d.call(g,b[h])});return f};pv.numerate=function(b,c){if(!c)c=pv.identity;var d={},f={};b.forEach(function(g,h){f.index=h;d[c.call(f,g)]=h});return d};pv.uniq=function(b,c){if(!c)c=pv.identity;var d={},f=[],g={},h;b.forEach(function(i,j){g.index=j;h=c.call(g,i);h in d||(d[h]=f.push(h))});return f};pv.naturalOrder=function(b,c){return b<c?-1:b>c?1:0};
+pv.reverseOrder=function(b,c){return c<b?-1:c>b?1:0};pv.search=function(b,c,d){if(!d)d=pv.identity;for(var f=0,g=b.length-1;f<=g;){var h=f+g>>1,i=d(b[h]);if(i<c)f=h+1;else if(i>c)g=h-1;else return h}return-f-1};pv.search.index=function(b,c,d){b=pv.search(b,c,d);return b<0?-b-1:b};
+pv.range=function(b,c,d){if(arguments.length==1){c=b;b=0}if(d==undefined)d=1;if((c-b)/d==Infinity)throw new Error("range must be finite");var f=[],g=0,h;if(d<0)for(;(h=b+d*g++)>c;)f.push(h);else for(;(h=b+d*g++)<c;)f.push(h);return f};pv.random=function(b,c,d){if(arguments.length==1){c=b;b=0}if(d==undefined)d=1;return d?Math.floor(Math.random()*(c-b)/d)*d+b:Math.random()*(c-b)+b};
+pv.sum=function(b,c){var d={};return b.reduce(c?function(f,g,h){d.index=h;return f+c.call(d,g)}:function(f,g){return f+g},0)};pv.max=function(b,c){if(c==pv.index)return b.length-1;return Math.max.apply(null,c?pv.map(b,c):b)};pv.max.index=function(b,c){if(!b.length)return-1;if(c==pv.index)return b.length-1;if(!c)c=pv.identity;for(var d=0,f=-Infinity,g={},h=0;h<b.length;h++){g.index=h;var i=c.call(g,b[h]);if(i>f){f=i;d=h}}return d};
+pv.min=function(b,c){if(c==pv.index)return 0;return Math.min.apply(null,c?pv.map(b,c):b)};pv.min.index=function(b,c){if(!b.length)return-1;if(c==pv.index)return 0;if(!c)c=pv.identity;for(var d=0,f=Infinity,g={},h=0;h<b.length;h++){g.index=h;var i=c.call(g,b[h]);if(i<f){f=i;d=h}}return d};pv.mean=function(b,c){return pv.sum(b,c)/b.length};
+pv.median=function(b,c){if(c==pv.index)return(b.length-1)/2;b=pv.map(b,c).sort(pv.naturalOrder);if(b.length%2)return b[Math.floor(b.length/2)];c=b.length/2;return(b[c-1]+b[c])/2};pv.variance=function(b,c){if(b.length<1)return NaN;if(b.length==1)return 0;var d=pv.mean(b,c),f=0,g={};if(!c)c=pv.identity;for(var h=0;h<b.length;h++){g.index=h;var i=c.call(g,b[h])-d;f+=i*i}return f};pv.deviation=function(b,c){return Math.sqrt(pv.variance(b,c)/(b.length-1))};pv.log=function(b,c){return Math.log(b)/Math.log(c)};
+pv.logSymmetric=function(b,c){return b==0?0:b<0?-pv.log(-b,c):pv.log(b,c)};pv.logAdjusted=function(b,c){if(!isFinite(b))return b;var d=b<0;if(b<c)b+=(c-b)/c;return d?-pv.log(b,c):pv.log(b,c)};pv.logFloor=function(b,c){return b>0?Math.pow(c,Math.floor(pv.log(b,c))):-Math.pow(c,-Math.floor(-pv.log(-b,c)))};pv.logCeil=function(b,c){return b>0?Math.pow(c,Math.ceil(pv.log(b,c))):-Math.pow(c,-Math.ceil(-pv.log(-b,c)))};
+(function(){var b=Math.PI/180,c=180/Math.PI;pv.radians=function(d){return b*d};pv.degrees=function(d){return c*d}})();pv.keys=function(b){var c=[];for(var d in b)c.push(d);return c};pv.entries=function(b){var c=[];for(var d in b)c.push({key:d,value:b[d]});return c};pv.values=function(b){var c=[];for(var d in b)c.push(b[d]);return c};pv.dict=function(b,c){for(var d={},f={},g=0;g<b.length;g++)if(g in b){var h=b[g];f.index=g;d[h]=c.call(f,h)}return d};pv.dom=function(b){return new pv.Dom(b)};
+pv.Dom=function(b){this.$map=b};pv.Dom.prototype.$leaf=function(b){return typeof b!="object"};pv.Dom.prototype.leaf=function(b){if(arguments.length){this.$leaf=b;return this}return this.$leaf};pv.Dom.prototype.root=function(b){function c(g){var h=new pv.Dom.Node;for(var i in g){var j=g[i];h.appendChild(d(j)?new pv.Dom.Node(j):c(j)).nodeName=i}return h}var d=this.$leaf,f=c(this.$map);f.nodeName=b;return f};pv.Dom.prototype.nodes=function(){return this.root().nodes()};
+pv.Dom.Node=function(b){this.nodeValue=b;this.childNodes=[]};a=pv.Dom.Node.prototype;a.parentNode=null;a.firstChild=null;a.lastChild=null;a.previousSibling=null;a.nextSibling=null;
+a.removeChild=function(b){var c=this.childNodes.indexOf(b);if(c==-1)throw new Error("child not found");this.childNodes.splice(c,1);if(b.previousSibling)b.previousSibling.nextSibling=b.nextSibling;else this.firstChild=b.nextSibling;if(b.nextSibling)b.nextSibling.previousSibling=b.previousSibling;else this.lastChild=b.previousSibling;delete b.nextSibling;delete b.previousSibling;delete b.parentNode;return b};
+a.appendChild=function(b){b.parentNode&&b.parentNode.removeChild(b);b.parentNode=this;if(b.previousSibling=this.lastChild)this.lastChild.nextSibling=b;else this.firstChild=b;this.lastChild=b;this.childNodes.push(b);return b};
+a.insertBefore=function(b,c){if(!c)return this.appendChild(b);var d=this.childNodes.indexOf(c);if(d==-1)throw new Error("child not found");b.parentNode&&b.parentNode.removeChild(b);b.parentNode=this;b.nextSibling=c;if(b.previousSibling=c.previousSibling)c.previousSibling.nextSibling=b;else{if(c==this.lastChild)this.lastChild=b;this.firstChild=b}this.childNodes.splice(d,0,b);return b};
+a.replaceChild=function(b,c){var d=this.childNodes.indexOf(c);if(d==-1)throw new Error("child not found");b.parentNode&&b.parentNode.removeChild(b);b.parentNode=this;b.nextSibling=c.nextSibling;if(b.previousSibling=c.previousSibling)c.previousSibling.nextSibling=b;else this.firstChild=b;if(c.nextSibling)c.nextSibling.previousSibling=b;else this.lastChild=b;this.childNodes[d]=b;return c};a.visitBefore=function(b){function c(d,f){b(d,f);for(d=d.firstChild;d;d=d.nextSibling)c(d,f+1)}c(this,0)};
+a.visitAfter=function(b){function c(d,f){for(var g=d.firstChild;g;g=g.nextSibling)c(g,f+1);b(d,f)}c(this,0)};a.sort=function(b){if(this.firstChild){this.childNodes.sort(b);var c=this.firstChild=this.childNodes[0],d;delete c.previousSibling;for(var f=1;f<this.childNodes.length;f++){c.sort(b);d=this.childNodes[f];d.previousSibling=c;c=c.nextSibling=d}this.lastChild=c;delete c.nextSibling;c.sort(b)}return this};
+a.reverse=function(){var b=[];this.visitAfter(function(c){for(;c.lastChild;)b.push(c.removeChild(c.lastChild));for(var d;d=b.pop();)c.insertBefore(d,c.firstChild)});return this};a.nodes=function(){function b(d){c.push(d);d.childNodes.forEach(b)}var c=[];b(this,c);return c};
+a.toggle=function(b){if(b)return this.toggled?this.visitBefore(function(d){d.toggled&&d.toggle()}):this.visitAfter(function(d){d.toggled||d.toggle()});b=this;if(b.toggled){for(var c;c=b.toggled.pop();)b.appendChild(c);delete b.toggled}else if(b.lastChild)for(b.toggled=[];b.lastChild;)b.toggled.push(b.removeChild(b.lastChild))};pv.nodes=function(b){for(var c=new pv.Dom.Node,d=0;d<b.length;d++)c.appendChild(new pv.Dom.Node(b[d]));return c.nodes()};pv.tree=function(b){return new pv.Tree(b)};
+pv.Tree=function(b){this.array=b};pv.Tree.prototype.keys=function(b){this.k=b;return this};pv.Tree.prototype.value=function(b){this.v=b;return this};pv.Tree.prototype.map=function(){for(var b={},c={},d=0;d<this.array.length;d++){c.index=d;for(var f=this.array[d],g=this.k.call(c,f),h=b,i=0;i<g.length-1;i++)h=h[g[i]]||(h[g[i]]={});h[g[i]]=this.v?this.v.call(c,f):f}return b};pv.nest=function(b){return new pv.Nest(b)};pv.Nest=function(b){this.array=b;this.keys=[]};a=pv.Nest.prototype;
+a.key=function(b){this.keys.push(b);return this};a.sortKeys=function(b){this.keys[this.keys.length-1].order=b||pv.naturalOrder;return this};a.sortValues=function(b){this.order=b||pv.naturalOrder;return this};a.map=function(){for(var b={},c=[],d,f=0;f<this.array.length;f++){var g=this.array[f],h=b;for(d=0;d<this.keys.length-1;d++){var i=this.keys[d](g);h[i]||(h[i]={});h=h[i]}i=this.keys[d](g);if(!h[i]){d=[];c.push(d);h[i]=d}h[i].push(g)}if(this.order)for(d=0;d<c.length;d++)c[d].sort(this.order);return b};
+a.entries=function(){function b(d){var f=[];for(var g in d){var h=d[g];f.push({key:g,values:h instanceof Array?h:b(h)})}return f}function c(d,f){var g=this.keys[f].order;g&&d.sort(function(i,j){return g(i.key,j.key)});if(++f<this.keys.length)for(var h=0;h<d.length;h++)c.call(this,d[h].values,f);return d}return c.call(this,b(this.map()),0)};a.rollup=function(b){function c(d){for(var f in d){var g=d[f];if(g instanceof Array)d[f]=b(g);else c(g)}return d}return c(this.map())};pv.flatten=function(b){return new pv.Flatten(b)};
+pv.Flatten=function(b){this.map=b;this.keys=[]};pv.Flatten.prototype.key=function(b,c){this.keys.push({name:b,value:c});delete this.$leaf;return this};pv.Flatten.prototype.leaf=function(b){this.keys.length=0;this.$leaf=b;return this};
+pv.Flatten.prototype.array=function(){function b(i,j){if(j<f.length-1)for(var l in i){d.push(l);b(i[l],j+1);d.pop()}else c.push(d.concat(i))}var c=[],d=[],f=this.keys,g=this.$leaf;if(g){function h(i,j){if(g(i))c.push({keys:d.slice(),value:i});else for(var l in i){d.push(l);h(i[l],j+1);d.pop()}}h(this.map,0);return c}b(this.map,0);return c.map(function(i){for(var j={},l=0;l<f.length;l++){var k=f[l],q=i[l];j[k.name]=k.value?k.value.call(null,q):q}return j})};
+pv.vector=function(b,c){return new pv.Vector(b,c)};pv.Vector=function(b,c){this.x=b;this.y=c};a=pv.Vector.prototype;a.perp=function(){return new pv.Vector(-this.y,this.x)};a.norm=function(){var b=this.length();return this.times(b?1/b:1)};a.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)};a.times=function(b){return new pv.Vector(this.x*b,this.y*b)};a.plus=function(b,c){return arguments.length==1?new pv.Vector(this.x+b.x,this.y+b.y):new pv.Vector(this.x+b,this.y+c)};
+a.minus=function(b,c){return arguments.length==1?new pv.Vector(this.x-b.x,this.y-b.y):new pv.Vector(this.x-b,this.y-c)};a.dot=function(b,c){return arguments.length==1?this.x*b.x+this.y*b.y:this.x*b+this.y*c};pv.Transform=function(){};pv.Transform.prototype={k:1,x:0,y:0};pv.Transform.identity=new pv.Transform;pv.Transform.prototype.translate=function(b,c){var d=new pv.Transform;d.k=this.k;d.x=this.k*b+this.x;d.y=this.k*c+this.y;return d};
+pv.Transform.prototype.scale=function(b){var c=new pv.Transform;c.k=this.k*b;c.x=this.x;c.y=this.y;return c};pv.Transform.prototype.invert=function(){var b=new pv.Transform,c=1/this.k;b.k=c;b.x=-this.x*c;b.y=-this.y*c;return b};pv.Transform.prototype.times=function(b){var c=new pv.Transform;c.k=this.k*b.k;c.x=this.k*b.x+this.x;c.y=this.k*b.y+this.y;return c};pv.Scale=function(){};
+pv.Scale.interpolator=function(b,c){if(typeof b=="number")return function(d){return d*(c-b)+b};b=pv.color(b).rgb();c=pv.color(c).rgb();return function(d){var f=b.a*(1-d)+c.a*d;if(f<1.0E-5)f=0;return b.a==0?pv.rgb(c.r,c.g,c.b,f):c.a==0?pv.rgb(b.r,b.g,b.b,f):pv.rgb(Math.round(b.r*(1-d)+c.r*d),Math.round(b.g*(1-d)+c.g*d),Math.round(b.b*(1-d)+c.b*d),f)}};
+pv.Scale.quantitative=function(){function b(o){return new Date(o)}function c(o){var n=pv.search(d,o);if(n<0)n=-n-2;n=Math.max(0,Math.min(h.length-1,n));return h[n]((l(o)-f[n])/(f[n+1]-f[n]))}var d=[0,1],f=[0,1],g=[0,1],h=[pv.identity],i=Number,j=false,l=pv.identity,k=pv.identity,q=String;c.transform=function(o,n){l=function(m){return j?-o(-m):o(m)};k=function(m){return j?-n(-m):n(m)};f=d.map(l);return this};c.domain=function(o,n,m){if(arguments.length){var r;if(o instanceof Array){if(arguments.length<
+2)n=pv.identity;if(arguments.length<3)m=n;r=o.length&&n(o[0]);d=o.length?[pv.min(o,n),pv.max(o,m)]:[]}else{r=o;d=Array.prototype.slice.call(arguments).map(Number)}if(d.length){if(d.length==1)d=[d[0],d[0]]}else d=[-Infinity,Infinity];j=(d[0]||d[d.length-1])<0;f=d.map(l);i=r instanceof Date?b:Number;return this}return d.map(i)};c.range=function(){if(arguments.length){g=Array.prototype.slice.call(arguments);if(g.length){if(g.length==1)g=[g[0],g[0]]}else g=[-Infinity,Infinity];h=[];for(var o=0;o<g.length-
+1;o++)h.push(pv.Scale.interpolator(g[o],g[o+1]));return this}return g};c.invert=function(o){var n=pv.search(g,o);if(n<0)n=-n-2;n=Math.max(0,Math.min(h.length-1,n));return i(k(f[n]+(o-g[n])/(g[n+1]-g[n])*(f[n+1]-f[n])))};c.ticks=function(o){var n=d[0],m=d[d.length-1],r=m<n,s=r?m:n;m=r?n:m;var u=m-s;if(!u||!isFinite(u)){if(i==b)q=pv.Format.date("%x");return[i(s)]}if(i==b){function x(w,y){switch(y){case 31536E6:w.setMonth(0);case 2592E6:w.setDate(1);case 6048E5:y==6048E5&&w.setDate(w.getDate()-w.getDay());
+case 864E5:w.setHours(0);case 36E5:w.setMinutes(0);case 6E4:w.setSeconds(0);case 1E3:w.setMilliseconds(0)}}var t,p,v=1;if(u>=94608E6){n=31536E6;t="%Y";p=function(w){w.setFullYear(w.getFullYear()+v)}}else if(u>=7776E6){n=2592E6;t="%m/%Y";p=function(w){w.setMonth(w.getMonth()+v)}}else if(u>=18144E5){n=6048E5;t="%m/%d";p=function(w){w.setDate(w.getDate()+7*v)}}else if(u>=2592E5){n=864E5;t="%m/%d";p=function(w){w.setDate(w.getDate()+v)}}else if(u>=108E5){n=36E5;t="%I:%M %p";p=function(w){w.setHours(w.getHours()+
+v)}}else if(u>=18E4){n=6E4;t="%I:%M %p";p=function(w){w.setMinutes(w.getMinutes()+v)}}else if(u>=3E3){n=1E3;t="%I:%M:%S";p=function(w){w.setSeconds(w.getSeconds()+v)}}else{n=1;t="%S.%Qs";p=function(w){w.setTime(w.getTime()+v)}}q=pv.Format.date(t);s=new Date(s);t=[];x(s,n);u=u/n;if(u>10)switch(n){case 36E5:v=u>20?6:3;s.setHours(Math.floor(s.getHours()/v)*v);break;case 2592E6:v=3;s.setMonth(Math.floor(s.getMonth()/v)*v);break;case 6E4:v=u>30?15:u>15?10:5;s.setMinutes(Math.floor(s.getMinutes()/v)*v);
+break;case 1E3:v=u>90?15:u>60?10:5;s.setSeconds(Math.floor(s.getSeconds()/v)*v);break;case 1:v=u>1E3?250:u>200?100:u>100?50:u>50?25:5;s.setMilliseconds(Math.floor(s.getMilliseconds()/v)*v);break;default:v=pv.logCeil(u/15,10);if(u/v<2)v/=5;else if(u/v<5)v/=2;s.setFullYear(Math.floor(s.getFullYear()/v)*v);break}for(;;){p(s);if(s>m)break;t.push(new Date(s))}return r?t.reverse():t}arguments.length||(o=10);v=pv.logFloor(u/o,10);n=o/(u/v);if(n<=0.15)v*=10;else if(n<=0.35)v*=5;else if(n<=0.75)v*=2;n=Math.ceil(s/
+v)*v;m=Math.floor(m/v)*v;q=pv.Format.number().fractionDigits(Math.max(0,-Math.floor(pv.log(v,10)+0.01)));m=pv.range(n,m+v,v);return r?m.reverse():m};c.tickFormat=function(o){return q(o)};c.nice=function(){if(d.length!=2)return this;var o=d[0],n=d[d.length-1],m=n<o,r=m?n:o;o=m?o:n;n=o-r;if(!n||!isFinite(n))return this;n=Math.pow(10,Math.round(Math.log(n)/Math.log(10))-1);d=[Math.floor(r/n)*n,Math.ceil(o/n)*n];m&&d.reverse();f=d.map(l);return this};c.by=function(o){function n(){return c(o.apply(this,
+arguments))}for(var m in c)n[m]=c[m];return n};c.domain.apply(c,arguments);return c};pv.Scale.linear=function(){var b=pv.Scale.quantitative();b.domain.apply(b,arguments);return b};
+pv.Scale.log=function(){var b=pv.Scale.quantitative(1,10),c,d,f=function(h){return Math.log(h)/d},g=function(h){return Math.pow(c,h)};b.ticks=function(){var h=b.domain(),i=h[0]<0,j=Math.floor(i?-f(-h[0]):f(h[0])),l=Math.ceil(i?-f(-h[1]):f(h[1])),k=[];if(i)for(k.push(-g(-j));j++<l;)for(i=c-1;i>0;i--)k.push(-g(-j)*i);else{for(;j<l;j++)for(i=1;i<c;i++)k.push(g(j)*i);k.push(g(j))}for(j=0;k[j]<h[0];j++);for(l=k.length;k[l-1]>h[1];l--);return k.slice(j,l)};b.tickFormat=function(h){return h.toPrecision(1)};
+b.nice=function(){var h=b.domain();return b.domain(pv.logFloor(h[0],c),pv.logCeil(h[1],c))};b.base=function(h){if(arguments.length){c=Number(h);d=Math.log(c);b.transform(f,g);return this}return c};b.domain.apply(b,arguments);return b.base(10)};pv.Scale.root=function(){var b=pv.Scale.quantitative();b.power=function(c){if(arguments.length){var d=Number(c),f=1/d;b.transform(function(g){return Math.pow(g,f)},function(g){return Math.pow(g,d)});return this}return d};b.domain.apply(b,arguments);return b.power(2)};
+pv.Scale.ordinal=function(){function b(g){g in d||(d[g]=c.push(g)-1);return f[d[g]%f.length]}var c=[],d={},f=[];b.domain=function(g,h){if(arguments.length){g=g instanceof Array?arguments.length>1?pv.map(g,h):g:Array.prototype.slice.call(arguments);c=[];for(var i={},j=0;j<g.length;j++){var l=g[j];if(!(l in i)){i[l]=true;c.push(l)}}d=pv.numerate(c);return this}return c};b.range=function(g,h){if(arguments.length){f=g instanceof Array?arguments.length>1?pv.map(g,h):g:Array.prototype.slice.call(arguments);
+if(typeof f[0]=="string")f=f.map(pv.color);return this}return f};b.split=function(g,h){var i=(h-g)/this.domain().length;f=pv.range(g+i/2,h,i);return this};b.splitFlush=function(g,h){var i=this.domain().length,j=(h-g)/(i-1);f=i==1?[(g+h)/2]:pv.range(g,h+j/2,j);return this};b.splitBanded=function(g,h,i){if(arguments.length<3)i=1;if(i<0){var j=this.domain().length;j=(h-g- -i*j)/(j+1);f=pv.range(g+j,h,j-i);f.band=-i}else{j=(h-g)/(this.domain().length+(1-i));f=pv.range(g+j*(1-i),h,j);f.band=j*i}return this};
+b.by=function(g){function h(){return b(g.apply(this,arguments))}for(var i in b)h[i]=b[i];return h};b.domain.apply(b,arguments);return b};
+pv.Scale.quantile=function(){function b(i){return h(Math.max(0,Math.min(d,pv.search.index(f,i)-1))/d)}var c=-1,d=-1,f=[],g=[],h=pv.Scale.linear();b.quantiles=function(i){if(arguments.length){c=Number(i);if(c<0){f=[g[0]].concat(g);d=g.length-1}else{f=[];f[0]=g[0];for(var j=1;j<=c;j++)f[j]=g[~~(j*(g.length-1)/c)];d=c-1}return this}return f};b.domain=function(i,j){if(arguments.length){g=i instanceof Array?pv.map(i,j):Array.prototype.slice.call(arguments);g.sort(pv.naturalOrder);b.quantiles(c);return this}return g};
+b.range=function(){if(arguments.length){h.range.apply(h,arguments);return this}return h.range()};b.by=function(i){function j(){return b(i.apply(this,arguments))}for(var l in b)j[l]=b[l];return j};b.domain.apply(b,arguments);return b};
+pv.histogram=function(b,c){var d=true;return{bins:function(f){var g=pv.map(b,c),h=[];arguments.length||(f=pv.Scale.linear(g).ticks());for(var i=0;i<f.length-1;i++){var j=h[i]=[];j.x=f[i];j.dx=f[i+1]-f[i];j.y=0}for(i=0;i<g.length;i++){j=pv.search.index(f,g[i])-1;j=h[Math.max(0,Math.min(h.length-1,j))];j.y++;j.push(b[i])}if(!d)for(i=0;i<h.length;i++)h[i].y/=g.length;return h},frequency:function(f){if(arguments.length){d=Boolean(f);return this}return d}}};
+pv.color=function(b){if(b.rgb)return b.rgb();var c=/([a-z]+)\((.*)\)/i.exec(b);if(c){var d=c[2].split(","),f=1;switch(c[1]){case "hsla":case "rgba":f=parseFloat(d[3]);if(!f)return pv.Color.transparent;break}switch(c[1]){case "hsla":case "hsl":b=parseFloat(d[0]);var g=parseFloat(d[1])/100;d=parseFloat(d[2])/100;return(new pv.Color.Hsl(b,g,d,f)).rgb();case "rgba":case "rgb":function h(l){var k=parseFloat(l);return l[l.length-1]=="%"?Math.round(k*2.55):k}g=h(d[0]);var i=h(d[1]),j=h(d[2]);return pv.rgb(g,
+i,j,f)}}if(f=pv.Color.names[b])return f;if(b.charAt(0)=="#"){if(b.length==4){g=b.charAt(1);g+=g;i=b.charAt(2);i+=i;j=b.charAt(3);j+=j}else if(b.length==7){g=b.substring(1,3);i=b.substring(3,5);j=b.substring(5,7)}return pv.rgb(parseInt(g,16),parseInt(i,16),parseInt(j,16),1)}return new pv.Color(b,1)};pv.Color=function(b,c){this.color=b;this.opacity=c};pv.Color.prototype.brighter=function(b){return this.rgb().brighter(b)};pv.Color.prototype.darker=function(b){return this.rgb().darker(b)};
+pv.rgb=function(b,c,d,f){return new pv.Color.Rgb(b,c,d,arguments.length==4?f:1)};pv.Color.Rgb=function(b,c,d,f){pv.Color.call(this,f?"rgb("+b+","+c+","+d+")":"none",f);this.r=b;this.g=c;this.b=d;this.a=f};pv.Color.Rgb.prototype=pv.extend(pv.Color);a=pv.Color.Rgb.prototype;a.red=function(b){return pv.rgb(b,this.g,this.b,this.a)};a.green=function(b){return pv.rgb(this.r,b,this.b,this.a)};a.blue=function(b){return pv.rgb(this.r,this.g,b,this.a)};
+a.alpha=function(b){return pv.rgb(this.r,this.g,this.b,b)};a.rgb=function(){return this};a.brighter=function(b){b=Math.pow(0.7,arguments.length?b:1);var c=this.r,d=this.g,f=this.b;if(!c&&!d&&!f)return pv.rgb(30,30,30,this.a);if(c&&c<30)c=30;if(d&&d<30)d=30;if(f&&f<30)f=30;return pv.rgb(Math.min(255,Math.floor(c/b)),Math.min(255,Math.floor(d/b)),Math.min(255,Math.floor(f/b)),this.a)};
+a.darker=function(b){b=Math.pow(0.7,arguments.length?b:1);return pv.rgb(Math.max(0,Math.floor(b*this.r)),Math.max(0,Math.floor(b*this.g)),Math.max(0,Math.floor(b*this.b)),this.a)};pv.hsl=function(b,c,d,f){return new pv.Color.Hsl(b,c,d,arguments.length==4?f:1)};pv.Color.Hsl=function(b,c,d,f){pv.Color.call(this,"hsl("+b+","+c*100+"%,"+d*100+"%)",f);this.h=b;this.s=c;this.l=d;this.a=f};pv.Color.Hsl.prototype=pv.extend(pv.Color);a=pv.Color.Hsl.prototype;
+a.hue=function(b){return pv.hsl(b,this.s,this.l,this.a)};a.saturation=function(b){return pv.hsl(this.h,b,this.l,this.a)};a.lightness=function(b){return pv.hsl(this.h,this.s,b,this.a)};a.alpha=function(b){return pv.hsl(this.h,this.s,this.l,b)};
+a.rgb=function(){function b(j){if(j>360)j-=360;else if(j<0)j+=360;if(j<60)return i+(h-i)*j/60;if(j<180)return h;if(j<240)return i+(h-i)*(240-j)/60;return i}function c(j){return Math.round(b(j)*255)}var d=this.h,f=this.s,g=this.l;d%=360;if(d<0)d+=360;f=Math.max(0,Math.min(f,1));g=Math.max(0,Math.min(g,1));var h=g<=0.5?g*(1+f):g+f-g*f,i=2*g-h;return pv.rgb(c(d+120),c(d),c(d-120),this.a)};
+pv.Color.names={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",
+darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",
+ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",
+lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",
+moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",
+seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",transparent:pv.Color.transparent=pv.rgb(0,0,0,0)};(function(){var b=pv.Color.names;for(var c in b)b[c]=pv.color(b[c])})();
+pv.colors=function(){var b=pv.Scale.ordinal();b.range.apply(b,arguments);return b};pv.Colors={};pv.Colors.category10=function(){var b=pv.colors("#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf");b.domain.apply(b,arguments);return b};
+pv.Colors.category20=function(){var b=pv.colors("#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5");b.domain.apply(b,arguments);return b};
+pv.Colors.category19=function(){var b=pv.colors("#9c9ede","#7375b5","#4a5584","#cedb9c","#b5cf6b","#8ca252","#637939","#e7cb94","#e7ba52","#bd9e39","#8c6d31","#e7969c","#d6616b","#ad494a","#843c39","#de9ed6","#ce6dbd","#a55194","#7b4173");b.domain.apply(b,arguments);return b};pv.ramp=function(){var b=pv.Scale.linear();b.range.apply(b,arguments);return b};
+pv.Scene=pv.SvgScene={svg:"http://www.w3.org/2000/svg",xmlns:"http://www.w3.org/2000/xmlns",xlink:"http://www.w3.org/1999/xlink",xhtml:"http://www.w3.org/1999/xhtml",scale:1,events:["DOMMouseScroll","mousewheel","mousedown","mouseup","mouseover","mouseout","mousemove","click","dblclick"],implicit:{svg:{"shape-rendering":"auto","pointer-events":"painted",x:0,y:0,dy:0,"text-anchor":"start",transform:"translate(0,0)",fill:"none","fill-opacity":1,stroke:"none","stroke-opacity":1,"stroke-width":1.5,"stroke-linejoin":"miter"},
+css:{font:"10px sans-serif"}}};pv.SvgScene.updateAll=function(b){if(b.length&&b[0].reverse&&b.type!="line"&&b.type!="area"){for(var c=pv.extend(b),d=0,f=b.length-1;f>=0;d++,f--)c[d]=b[f];b=c}this.removeSiblings(this[b.type](b))};pv.SvgScene.create=function(b){return document.createElementNS(this.svg,b)};
+pv.SvgScene.expect=function(b,c,d,f){if(b){if(b.tagName=="a")b=b.firstChild;if(b.tagName!=c){c=this.create(c);b.parentNode.replaceChild(c,b);b=c}}else b=this.create(c);for(var g in d){c=d[g];if(c==this.implicit.svg[g])c=null;c==null?b.removeAttribute(g):b.setAttribute(g,c)}for(g in f){c=f[g];if(c==this.implicit.css[g])c=null;if(c==null)b.style.removeProperty(g);else b.style[g]=c}return b};
+pv.SvgScene.append=function(b,c,d){b.$scene={scenes:c,index:d};b=this.title(b,c[d]);b.parentNode||c.$g.appendChild(b);return b.nextSibling};pv.SvgScene.title=function(b,c){var d=b.parentNode;if(d&&d.tagName!="a")d=null;if(c.title){if(!d){d=this.create("a");b.parentNode&&b.parentNode.replaceChild(d,b);d.appendChild(b)}d.setAttributeNS(this.xlink,"title",c.title);return d}d&&d.parentNode.replaceChild(b,d);return b};
+pv.SvgScene.dispatch=pv.listener(function(b){var c=b.target.$scene;if(c){var d=b.type;switch(d){case "DOMMouseScroll":d="mousewheel";b.wheel=-480*b.detail;break;case "mousewheel":b.wheel=(window.opera?12:1)*b.wheelDelta;break}pv.Mark.dispatch(d,c.scenes,c.index)&&b.preventDefault()}});pv.SvgScene.removeSiblings=function(b){for(;b;){var c=b.nextSibling;b.parentNode.removeChild(b);b=c}};pv.SvgScene.undefined=function(){};
+pv.SvgScene.pathBasis=function(){function b(f,g,h,i,j){return{x:f[0]*g.left+f[1]*h.left+f[2]*i.left+f[3]*j.left,y:f[0]*g.top+f[1]*h.top+f[2]*i.top+f[3]*j.top}}var c=[[1/6,2/3,1/6,0],[0,2/3,1/3,0],[0,1/3,2/3,0],[0,1/6,2/3,1/6]],d=function(f,g,h,i){var j=b(c[1],f,g,h,i),l=b(c[2],f,g,h,i);f=b(c[3],f,g,h,i);return"C"+j.x+","+j.y+","+l.x+","+l.y+","+f.x+","+f.y};d.segment=function(f,g,h,i){var j=b(c[0],f,g,h,i),l=b(c[1],f,g,h,i),k=b(c[2],f,g,h,i);f=b(c[3],f,g,h,i);return"M"+j.x+","+j.y+"C"+l.x+","+l.y+
+","+k.x+","+k.y+","+f.x+","+f.y};return d}();pv.SvgScene.curveBasis=function(b){if(b.length<=2)return"";var c="",d=b[0],f=d,g=d,h=b[1];c+=this.pathBasis(d,f,g,h);for(var i=2;i<b.length;i++){d=f;f=g;g=h;h=b[i];c+=this.pathBasis(d,f,g,h)}c+=this.pathBasis(f,g,h,h);c+=this.pathBasis(g,h,h,h);return c};
+pv.SvgScene.curveBasisSegments=function(b){if(b.length<=2)return"";var c=[],d=b[0],f=d,g=d,h=b[1],i=this.pathBasis.segment(d,f,g,h);d=f;f=g;g=h;h=b[2];c.push(i+this.pathBasis(d,f,g,h));for(i=3;i<b.length;i++){d=f;f=g;g=h;h=b[i];c.push(this.pathBasis.segment(d,f,g,h))}c.push(this.pathBasis.segment(f,g,h,h)+this.pathBasis(g,h,h,h));return c};
+pv.SvgScene.curveHermite=function(b,c){if(c.length<1||b.length!=c.length&&b.length!=c.length+2)return"";var d=b.length!=c.length,f="",g=b[0],h=b[1],i=c[0],j=i,l=1;if(d){f+="Q"+(h.left-i.x*2/3)+","+(h.top-i.y*2/3)+","+h.left+","+h.top;g=b[1];l=2}if(c.length>1){j=c[1];h=b[l];l++;f+="C"+(g.left+i.x)+","+(g.top+i.y)+","+(h.left-j.x)+","+(h.top-j.y)+","+h.left+","+h.top;for(g=2;g<c.length;g++,l++){h=b[l];j=c[g];f+="S"+(h.left-j.x)+","+(h.top-j.y)+","+h.left+","+h.top}}if(d){b=b[l];f+="Q"+(h.left+j.x*2/
+3)+","+(h.top+j.y*2/3)+","+b.left+","+b.top}return f};
+pv.SvgScene.curveHermiteSegments=function(b,c){if(c.length<1||b.length!=c.length&&b.length!=c.length+2)return[];var d=b.length!=c.length,f=[],g=b[0],h=g,i=c[0],j=i,l=1;if(d){h=b[1];f.push("M"+g.left+","+g.top+"Q"+(h.left-j.x*2/3)+","+(h.top-j.y*2/3)+","+h.left+","+h.top);l=2}for(var k=1;k<c.length;k++,l++){g=h;i=j;h=b[l];j=c[k];f.push("M"+g.left+","+g.top+"C"+(g.left+i.x)+","+(g.top+i.y)+","+(h.left-j.x)+","+(h.top-j.y)+","+h.left+","+h.top)}if(d){b=b[l];f.push("M"+h.left+","+h.top+"Q"+(h.left+j.x*
+2/3)+","+(h.top+j.y*2/3)+","+b.left+","+b.top)}return f};pv.SvgScene.cardinalTangents=function(b,c){var d=[];c=(1-c)/2;for(var f=b[0],g=b[1],h=b[2],i=3;i<b.length;i++){d.push({x:c*(h.left-f.left),y:c*(h.top-f.top)});f=g;g=h;h=b[i]}d.push({x:c*(h.left-f.left),y:c*(h.top-f.top)});return d};pv.SvgScene.curveCardinal=function(b,c){if(b.length<=2)return"";return this.curveHermite(b,this.cardinalTangents(b,c))};
+pv.SvgScene.curveCardinalSegments=function(b,c){if(b.length<=2)return"";return this.curveHermiteSegments(b,this.cardinalTangents(b,c))};
+pv.SvgScene.monotoneTangents=function(b){var c=[],d=[],f=[],g=[],h=0;for(h=0;h<b.length-1;h++)d[h]=(b[h+1].top-b[h].top)/(b[h+1].left-b[h].left);f[0]=d[0];g[0]=b[1].left-b[0].left;for(h=1;h<b.length-1;h++){f[h]=(d[h-1]+d[h])/2;g[h]=(b[h+1].left-b[h-1].left)/2}f[h]=d[h-1];g[h]=b[h].left-b[h-1].left;for(h=0;h<b.length-1;h++)if(d[h]==0){f[h]=0;f[h+1]=0}for(h=0;h<b.length-1;h++)if(!(Math.abs(f[h])<1.0E-5||Math.abs(f[h+1])<1.0E-5)){var i=f[h]/d[h],j=f[h+1]/d[h],l=i*i+j*j;if(l>9){l=3/Math.sqrt(l);f[h]=
+l*i*d[h];f[h+1]=l*j*d[h]}}for(h=0;h<b.length;h++){d=1+f[h]*f[h];c.push({x:g[h]/3/d,y:f[h]*g[h]/3/d})}return c};pv.SvgScene.curveMonotone=function(b){if(b.length<=2)return"";return this.curveHermite(b,this.monotoneTangents(b))};pv.SvgScene.curveMonotoneSegments=function(b){if(b.length<=2)return"";return this.curveHermiteSegments(b,this.monotoneTangents(b))};
+pv.SvgScene.area=function(b){function c(o,n){for(var m=[],r=[],s=n;o<=s;o++,n--){var u=b[o],x=b[n];u=u.left+","+u.top;x=x.left+x.width+","+(x.top+x.height);if(o<s){var t=b[o+1],p=b[n-1];switch(g.interpolate){case "step-before":u+="V"+t.top;x+="H"+(p.left+p.width);break;case "step-after":u+="H"+t.left;x+="V"+(p.top+p.height);break}}m.push(u);r.push(x)}return m.concat(r).join("L")}function d(o,n){for(var m=[],r=[],s=n;o<=s;o++,n--){var u=b[n];m.push(b[o]);r.push({left:u.left+u.width,top:u.top+u.height})}if(g.interpolate==
+"basis"){o=pv.SvgScene.curveBasis(m);n=pv.SvgScene.curveBasis(r)}else if(g.interpolate=="cardinal"){o=pv.SvgScene.curveCardinal(m,g.tension);n=pv.SvgScene.curveCardinal(r,g.tension)}else{o=pv.SvgScene.curveMonotone(m);n=pv.SvgScene.curveMonotone(r)}return m[0].left+","+m[0].top+o+"L"+r[0].left+","+r[0].top+n}var f=b.$g.firstChild;if(!b.length)return f;var g=b[0];if(g.segmented)return this.areaSegment(b);if(!g.visible)return f;var h=g.fillStyle,i=g.strokeStyle;if(!h.opacity&&!i.opacity)return f;for(var j=
+[],l,k=0;k<b.length;k++){l=b[k];if(l.width||l.height){for(var q=k+1;q<b.length;q++){l=b[q];if(!l.width&&!l.height)break}k&&g.interpolate!="step-after"&&k--;q<b.length&&g.interpolate!="step-before"&&q++;j.push((q-k>2&&(g.interpolate=="basis"||g.interpolate=="cardinal"||g.interpolate=="monotone")?d:c)(k,q-1));k=q-1}}if(!j.length)return f;f=this.expect(f,"path",{"shape-rendering":g.antialias?null:"crispEdges","pointer-events":g.events,cursor:g.cursor,d:"M"+j.join("ZM")+"Z",fill:h.color,"fill-opacity":h.opacity||
+null,stroke:i.color,"stroke-opacity":i.opacity||null,"stroke-width":i.opacity?g.lineWidth/this.scale:null});return this.append(f,b,0)};
+pv.SvgScene.areaSegment=function(b){var c=b.$g.firstChild,d=b[0],f,g;if(d.interpolate=="basis"||d.interpolate=="cardinal"||d.interpolate=="monotone"){f=[];g=[];for(var h=0,i=b.length;h<i;h++){var j=b[i-h-1];f.push(b[h]);g.push({left:j.left+j.width,top:j.top+j.height})}if(d.interpolate=="basis"){f=this.curveBasisSegments(f);g=this.curveBasisSegments(g)}else if(d.interpolate=="cardinal"){f=this.curveCardinalSegments(f,d.tension);g=this.curveCardinalSegments(g,d.tension)}else{f=this.curveMonotoneSegments(f);
+g=this.curveMonotoneSegments(g)}}h=0;for(i=b.length-1;h<i;h++){d=b[h];var l=b[h+1];if(d.visible&&l.visible){var k=d.fillStyle,q=d.strokeStyle;if(k.opacity||q.opacity){if(f){j=f[h];l="L"+g[i-h-1].substr(1);j=j+l+"Z"}else{var o=d;j=l;switch(d.interpolate){case "step-before":o=l;break;case "step-after":j=d;break}j="M"+d.left+","+o.top+"L"+l.left+","+j.top+"L"+(l.left+l.width)+","+(j.top+j.height)+"L"+(d.left+d.width)+","+(o.top+o.height)+"Z"}c=this.expect(c,"path",{"shape-rendering":d.antialias?null:
+"crispEdges","pointer-events":d.events,cursor:d.cursor,d:j,fill:k.color,"fill-opacity":k.opacity||null,stroke:q.color,"stroke-opacity":q.opacity||null,"stroke-width":q.opacity?d.lineWidth/this.scale:null});c=this.append(c,b,h)}}}return c};
+pv.SvgScene.bar=function(b){for(var c=b.$g.firstChild,d=0;d<b.length;d++){var f=b[d];if(f.visible){var g=f.fillStyle,h=f.strokeStyle;if(g.opacity||h.opacity){c=this.expect(c,"rect",{"shape-rendering":f.antialias?null:"crispEdges","pointer-events":f.events,cursor:f.cursor,x:f.left,y:f.top,width:Math.max(1.0E-10,f.width),height:Math.max(1.0E-10,f.height),fill:g.color,"fill-opacity":g.opacity||null,stroke:h.color,"stroke-opacity":h.opacity||null,"stroke-width":h.opacity?f.lineWidth/this.scale:null});
+c=this.append(c,b,d)}}}return c};
+pv.SvgScene.dot=function(b){for(var c=b.$g.firstChild,d=0;d<b.length;d++){var f=b[d];if(f.visible){var g=f.fillStyle,h=f.strokeStyle;if(g.opacity||h.opacity){var i=f.radius,j=null;switch(f.shape){case "cross":j="M"+-i+","+-i+"L"+i+","+i+"M"+i+","+-i+"L"+-i+","+i;break;case "triangle":j=i;var l=i*1.1547;j="M0,"+j+"L"+l+","+-j+" "+-l+","+-j+"Z";break;case "diamond":i*=Math.SQRT2;j="M0,"+-i+"L"+i+",0 0,"+i+" "+-i+",0Z";break;case "square":j="M"+-i+","+-i+"L"+i+","+-i+" "+i+","+i+" "+-i+","+i+"Z";break;
+case "tick":j="M0,0L0,"+-f.size;break;case "bar":j="M0,"+f.size/2+"L0,"+-(f.size/2);break}g={"shape-rendering":f.antialias?null:"crispEdges","pointer-events":f.events,cursor:f.cursor,fill:g.color,"fill-opacity":g.opacity||null,stroke:h.color,"stroke-opacity":h.opacity||null,"stroke-width":h.opacity?f.lineWidth/this.scale:null};if(j){g.transform="translate("+f.left+","+f.top+")";if(f.angle)g.transform+=" rotate("+180*f.angle/Math.PI+")";g.d=j;c=this.expect(c,"path",g)}else{g.cx=f.left;g.cy=f.top;g.r=
+i;c=this.expect(c,"circle",g)}c=this.append(c,b,d)}}}return c};
+pv.SvgScene.image=function(b){for(var c=b.$g.firstChild,d=0;d<b.length;d++){var f=b[d];if(f.visible){c=this.fill(c,b,d);if(f.image){c=this.expect(c,"foreignObject",{cursor:f.cursor,x:f.left,y:f.top,width:f.width,height:f.height});var g=c.firstChild||c.appendChild(document.createElementNS(this.xhtml,"canvas"));g.$scene={scenes:b,index:d};g.style.width=f.width;g.style.height=f.height;g.width=f.imageWidth;g.height=f.imageHeight;g.getContext("2d").putImageData(f.image,0,0)}else{c=this.expect(c,"image",
+{preserveAspectRatio:"none",cursor:f.cursor,x:f.left,y:f.top,width:f.width,height:f.height});c.setAttributeNS(this.xlink,"href",f.url)}c=this.append(c,b,d);c=this.stroke(c,b,d)}}return c};
+pv.SvgScene.label=function(b){for(var c=b.$g.firstChild,d=0;d<b.length;d++){var f=b[d];if(f.visible){var g=f.textStyle;if(g.opacity&&f.text){var h=0,i=0,j=0,l="start";switch(f.textBaseline){case "middle":j=".35em";break;case "top":j=".71em";i=f.textMargin;break;case "bottom":i="-"+f.textMargin;break}switch(f.textAlign){case "right":l="end";h="-"+f.textMargin;break;case "center":l="middle";break;case "left":h=f.textMargin;break}c=this.expect(c,"text",{"pointer-events":f.events,cursor:f.cursor,x:h,
+y:i,dy:j,transform:"translate("+f.left+","+f.top+")"+(f.textAngle?" rotate("+180*f.textAngle/Math.PI+")":"")+(this.scale!=1?" scale("+1/this.scale+")":""),fill:g.color,"fill-opacity":g.opacity||null,"text-anchor":l},{font:f.font,"text-shadow":f.textShadow,"text-decoration":f.textDecoration});if(c.firstChild)c.firstChild.nodeValue=f.text;else c.appendChild(document.createTextNode(f.text));c=this.append(c,b,d)}}}return c};
+pv.SvgScene.line=function(b){var c=b.$g.firstChild;if(b.length<2)return c;var d=b[0];if(d.segmented)return this.lineSegment(b);if(!d.visible)return c;var f=d.fillStyle,g=d.strokeStyle;if(!f.opacity&&!g.opacity)return c;var h="M"+d.left+","+d.top;if(b.length>2&&(d.interpolate=="basis"||d.interpolate=="cardinal"||d.interpolate=="monotone"))switch(d.interpolate){case "basis":h+=this.curveBasis(b);break;case "cardinal":h+=this.curveCardinal(b,d.tension);break;case "monotone":h+=this.curveMonotone(b);
+break}else for(var i=1;i<b.length;i++)h+=this.pathSegment(b[i-1],b[i]);c=this.expect(c,"path",{"shape-rendering":d.antialias?null:"crispEdges","pointer-events":d.events,cursor:d.cursor,d:h,fill:f.color,"fill-opacity":f.opacity||null,stroke:g.color,"stroke-opacity":g.opacity||null,"stroke-width":g.opacity?d.lineWidth/this.scale:null,"stroke-linejoin":d.lineJoin});return this.append(c,b,0)};
+pv.SvgScene.lineSegment=function(b){var c=b.$g.firstChild,d=b[0],f;switch(d.interpolate){case "basis":f=this.curveBasisSegments(b);break;case "cardinal":f=this.curveCardinalSegments(b,d.tension);break;case "monotone":f=this.curveMonotoneSegments(b);break}d=0;for(var g=b.length-1;d<g;d++){var h=b[d],i=b[d+1];if(h.visible&&i.visible){var j=h.strokeStyle,l=pv.Color.transparent;if(j.opacity){if(h.interpolate=="linear"&&h.lineJoin=="miter"){l=j;j=pv.Color.transparent;i=this.pathJoin(b[d-1],h,i,b[d+2])}else i=
+f?f[d]:"M"+h.left+","+h.top+this.pathSegment(h,i);c=this.expect(c,"path",{"shape-rendering":h.antialias?null:"crispEdges","pointer-events":h.events,cursor:h.cursor,d:i,fill:l.color,"fill-opacity":l.opacity||null,stroke:j.color,"stroke-opacity":j.opacity||null,"stroke-width":j.opacity?h.lineWidth/this.scale:null,"stroke-linejoin":h.lineJoin});c=this.append(c,b,d)}}}return c};
+pv.SvgScene.pathSegment=function(b,c){var d=1;switch(b.interpolate){case "polar-reverse":d=0;case "polar":var f=c.left-b.left,g=c.top-b.top;b=1-b.eccentricity;f=Math.sqrt(f*f+g*g)/(2*b);if(b<=0||b>1)break;return"A"+f+","+f+" 0 0,"+d+" "+c.left+","+c.top;case "step-before":return"V"+c.top+"H"+c.left;case "step-after":return"H"+c.left+"V"+c.top}return"L"+c.left+","+c.top};pv.SvgScene.lineIntersect=function(b,c,d,f){return b.plus(c.times(d.minus(b).dot(f.perp())/c.dot(f.perp())))};
+pv.SvgScene.pathJoin=function(b,c,d,f){var g=pv.vector(c.left,c.top);d=pv.vector(d.left,d.top);var h=d.minus(g),i=h.perp().norm(),j=i.times(c.lineWidth/(2*this.scale));c=g.plus(j);var l=d.plus(j),k=d.minus(j);j=g.minus(j);if(b&&b.visible){b=g.minus(b.left,b.top).perp().norm().plus(i);j=this.lineIntersect(g,b,j,h);c=this.lineIntersect(g,b,c,h)}if(f&&f.visible){f=pv.vector(f.left,f.top).minus(d).perp().norm().plus(i);k=this.lineIntersect(d,f,k,h);l=this.lineIntersect(d,f,l,h)}return"M"+c.x+","+c.y+
+"L"+l.x+","+l.y+" "+k.x+","+k.y+" "+j.x+","+j.y};
+pv.SvgScene.panel=function(b){for(var c=b.$g,d=c&&c.firstChild,f=0;f<b.length;f++){var g=b[f];if(g.visible){if(!b.parent){g.canvas.style.display="inline-block";if(c&&c.parentNode!=g.canvas)d=(c=g.canvas.firstChild)&&c.firstChild;if(!c){c=g.canvas.appendChild(this.create("svg"));c.setAttribute("font-size","10px");c.setAttribute("font-family","sans-serif");c.setAttribute("fill","none");c.setAttribute("stroke","none");c.setAttribute("stroke-width",1.5);for(var h=0;h<this.events.length;h++)c.addEventListener(this.events[h],
+this.dispatch,false);d=c.firstChild}b.$g=c;c.setAttribute("width",g.width+g.left+g.right);c.setAttribute("height",g.height+g.top+g.bottom)}if(g.overflow=="hidden"){h=pv.id().toString(36);var i=this.expect(d,"g",{"clip-path":"url(#"+h+")"});i.parentNode||c.appendChild(i);b.$g=c=i;d=i.firstChild;d=this.expect(d,"clipPath",{id:h});h=d.firstChild||d.appendChild(this.create("rect"));h.setAttribute("x",g.left);h.setAttribute("y",g.top);h.setAttribute("width",g.width);h.setAttribute("height",g.height);d.parentNode||
+c.appendChild(d);d=d.nextSibling}d=this.fill(d,b,f);var j=this.scale,l=g.transform,k=g.left+l.x,q=g.top+l.y;this.scale*=l.k;for(h=0;h<g.children.length;h++){g.children[h].$g=d=this.expect(d,"g",{transform:"translate("+k+","+q+")"+(l.k!=1?" scale("+l.k+")":"")});this.updateAll(g.children[h]);d.parentNode||c.appendChild(d);d=d.nextSibling}this.scale=j;d=this.stroke(d,b,f);if(g.overflow=="hidden"){b.$g=c=i.parentNode;d=i.nextSibling}}}return d};
+pv.SvgScene.fill=function(b,c,d){var f=c[d],g=f.fillStyle;if(g.opacity||f.events=="all"){b=this.expect(b,"rect",{"shape-rendering":f.antialias?null:"crispEdges","pointer-events":f.events,cursor:f.cursor,x:f.left,y:f.top,width:f.width,height:f.height,fill:g.color,"fill-opacity":g.opacity,stroke:null});b=this.append(b,c,d)}return b};
+pv.SvgScene.stroke=function(b,c,d){var f=c[d],g=f.strokeStyle;if(g.opacity||f.events=="all"){b=this.expect(b,"rect",{"shape-rendering":f.antialias?null:"crispEdges","pointer-events":f.events=="all"?"stroke":f.events,cursor:f.cursor,x:f.left,y:f.top,width:Math.max(1.0E-10,f.width),height:Math.max(1.0E-10,f.height),fill:null,stroke:g.color,"stroke-opacity":g.opacity,"stroke-width":f.lineWidth/this.scale});b=this.append(b,c,d)}return b};
+pv.SvgScene.rule=function(b){for(var c=b.$g.firstChild,d=0;d<b.length;d++){var f=b[d];if(f.visible){var g=f.strokeStyle;if(g.opacity){c=this.expect(c,"line",{"shape-rendering":f.antialias?null:"crispEdges","pointer-events":f.events,cursor:f.cursor,x1:f.left,y1:f.top,x2:f.left+f.width,y2:f.top+f.height,stroke:g.color,"stroke-opacity":g.opacity,"stroke-width":f.lineWidth/this.scale});c=this.append(c,b,d)}}}return c};
+pv.SvgScene.wedge=function(b){for(var c=b.$g.firstChild,d=0;d<b.length;d++){var f=b[d];if(f.visible){var g=f.fillStyle,h=f.strokeStyle;if(g.opacity||h.opacity){var i=f.innerRadius,j=f.outerRadius,l=Math.abs(f.angle);if(l>=2*Math.PI)i=i?"M0,"+j+"A"+j+","+j+" 0 1,1 0,"+-j+"A"+j+","+j+" 0 1,1 0,"+j+"M0,"+i+"A"+i+","+i+" 0 1,1 0,"+-i+"A"+i+","+i+" 0 1,1 0,"+i+"Z":"M0,"+j+"A"+j+","+j+" 0 1,1 0,"+-j+"A"+j+","+j+" 0 1,1 0,"+j+"Z";else{var k=Math.min(f.startAngle,f.endAngle),q=Math.max(f.startAngle,f.endAngle),
+o=Math.cos(k),n=Math.cos(q);k=Math.sin(k);q=Math.sin(q);i=i?"M"+j*o+","+j*k+"A"+j+","+j+" 0 "+(l<Math.PI?"0":"1")+",1 "+j*n+","+j*q+"L"+i*n+","+i*q+"A"+i+","+i+" 0 "+(l<Math.PI?"0":"1")+",0 "+i*o+","+i*k+"Z":"M"+j*o+","+j*k+"A"+j+","+j+" 0 "+(l<Math.PI?"0":"1")+",1 "+j*n+","+j*q+"L0,0Z"}c=this.expect(c,"path",{"shape-rendering":f.antialias?null:"crispEdges","pointer-events":f.events,cursor:f.cursor,transform:"translate("+f.left+","+f.top+")",d:i,fill:g.color,"fill-rule":"evenodd","fill-opacity":g.opacity||
+null,stroke:h.color,"stroke-opacity":h.opacity||null,"stroke-width":h.opacity?f.lineWidth/this.scale:null});c=this.append(c,b,d)}}}return c};pv.Mark=function(){this.$properties=[];this.$handlers={}};pv.Mark.prototype.properties={};pv.Mark.cast={};pv.Mark.prototype.property=function(b,c){if(!this.hasOwnProperty("properties"))this.properties=pv.extend(this.properties);this.properties[b]=true;pv.Mark.prototype.propertyMethod(b,false,pv.Mark.cast[b]=c);return this};
+pv.Mark.prototype.propertyMethod=function(b,c,d){d||(d=pv.Mark.cast[b]);this[b]=function(f){if(c&&this.scene){var g=this.scene.defs;if(arguments.length){g[b]={id:f==null?0:pv.id(),value:f!=null&&d?d(f):f};return this}return g[b]?g[b].value:null}if(arguments.length){g=!c<<1|typeof f=="function";this.propertyValue(b,g&1&&d?function(){var h=f.apply(this,arguments);return h!=null?d(h):null}:f!=null&&d?d(f):f).type=g;return this}return this.instance()[b]}};
+pv.Mark.prototype.propertyValue=function(b,c){var d=this.$properties;c={name:b,id:pv.id(),value:c};for(var f=0;f<d.length;f++)if(d[f].name==b){d.splice(f,1);break}d.push(c);return c};pv.Mark.prototype.property("data").property("visible",Boolean).property("left",Number).property("right",Number).property("top",Number).property("bottom",Number).property("cursor",String).property("title",String).property("reverse",Boolean).property("antialias",Boolean).property("events",String);a=pv.Mark.prototype;
+a.childIndex=-1;a.index=-1;a.scale=1;a.defaults=(new pv.Mark).data(function(b){return[b]}).visible(true).antialias(true).events("painted");a.extend=function(b){this.proto=b;return this};a.add=function(b){return this.parent.add(b).extend(this)};a.def=function(b,c){this.propertyMethod(b,true);return this[b](arguments.length>1?c:null)};
+a.anchor=function(b){function c(g){for(var h=d,i=[];!(f=h.scene);){g=g.parent;i.push({index:g.index,childIndex:h.childIndex});h=h.parent}for(;i.length;){g=i.pop();f=f[g.index].children[g.childIndex]}if(d.hasOwnProperty("index")){i=pv.extend(f[d.index]);i.right=i.top=i.left=i.bottom=0;return[i]}return f}var d=this,f;b||(b="center");return(new pv.Anchor(this)).name(b).def("$mark.anchor",function(){f=this.scene.target=c(this)}).data(function(){return f.map(function(g){return g.data})}).visible(function(){return f[this.index].visible}).left(function(){var g=
+f[this.index],h=g.width||0;switch(this.name()){case "bottom":case "top":case "center":return g.left+h/2;case "left":return null}return g.left+h}).top(function(){var g=f[this.index],h=g.height||0;switch(this.name()){case "left":case "right":case "center":return g.top+h/2;case "top":return null}return g.top+h}).right(function(){var g=f[this.index];return this.name()=="left"?g.right+(g.width||0):null}).bottom(function(){var g=f[this.index];return this.name()=="top"?g.bottom+(g.height||0):null}).textAlign(function(){switch(this.name()){case "bottom":case "top":case "center":return"center";
+case "right":return"right"}return"left"}).textBaseline(function(){switch(this.name()){case "right":case "left":case "center":return"middle";case "top":return"top"}return"bottom"})};a.anchorTarget=function(){return this.proto.anchorTarget()};a.margin=function(b){return this.left(b).right(b).top(b).bottom(b)};a.instance=function(b){var c=this.scene||this.parent.instance(-1).children[this.childIndex],d=!arguments.length||this.hasOwnProperty("index")?this.index:b;return c[d<0?c.length-1:d]};a.first=function(){return this.scene[0]};
+a.last=function(){return this.scene[this.scene.length-1]};a.sibling=function(){return this.index==0?null:this.scene[this.index-1]};a.cousin=function(){var b=this.parent;return(b=b&&b.sibling())&&b.children?b.children[this.childIndex][this.index]:null};
+a.render=function(){function b(i,j,l){i.scale=l;if(j<g.length){f.unshift(null);if(i.hasOwnProperty("index"))c(i,j,l);else{for(var k=0,q=i.scene.length;k<q;k++){i.index=k;c(i,j,l)}delete i.index}f.shift()}else{i.build();pv.Scene.scale=l;pv.Scene.updateAll(i.scene)}delete i.scale}function c(i,j,l){var k=i.scene[i.index],q;if(k.visible){var o=g[j],n=i.children[o];for(q=0;q<o;q++)i.children[q].scene=k.children[q];f[0]=k.data;if(n.scene)b(n,j+1,l*k.transform.k);else{n.scene=k.children[o];b(n,j+1,l*k.transform.k);
+delete n.scene}for(q=0;q<o;q++)delete i.children[q].scene}}var d=this.parent,f=pv.Mark.stack;if(d&&!this.root.scene)this.root.render();else{for(var g=[],h=this;h.parent;h=h.parent)g.unshift(h.childIndex);for(this.bind();d&&!d.hasOwnProperty("index");)d=d.parent;this.context(d?d.scene:undefined,d?d.index:-1,function(){b(this.root,0,1)})}};pv.Mark.stack=[];a=pv.Mark.prototype;
+a.bind=function(){function b(j){do for(var l=j.$properties,k=l.length-1;k>=0;k--){var q=l[k];if(!(q.name in c)){c[q.name]=q;switch(q.name){case "data":f=q;break;case "visible":g=q;break;default:d[q.type].push(q);break}}}while(j=j.proto)}var c={},d=[[],[],[],[]],f,g;b(this);b(this.defaults);d[1].reverse();d[3].reverse();var h=this;do for(var i in h.properties)i in c||d[2].push(c[i]={name:i,type:2,value:null});while(h=h.proto);h=d[0].concat(d[1]);for(i=0;i<h.length;i++)this.propertyMethod(h[i].name,
+true);this.binds={properties:c,data:f,defs:h,required:[g],optional:pv.blend(d)}};
+a.build=function(){var b=this.scene,c=pv.Mark.stack;if(!b){b=this.scene=[];b.mark=this;b.type=this.type;b.childIndex=this.childIndex;if(this.parent){b.parent=this.parent.scene;b.parentIndex=this.parent.index}}if(this.binds.defs.length){var d=b.defs;if(!d)b.defs=d={};for(var f=0;f<this.binds.defs.length;f++){var g=this.binds.defs[f],h=d[g.name];if(!h||g.id>h.id)d[g.name]={id:0,value:g.type&1?g.value.apply(this,c):g.value}}}d=this.binds.data;d=d.type&1?d.value.apply(this,c):d.value;c.unshift(null);
+b.length=d.length;for(f=0;f<d.length;f++){pv.Mark.prototype.index=this.index=f;(g=b[f])||(b[f]=g={});g.data=c[0]=d[f];this.buildInstance(g)}pv.Mark.prototype.index=-1;delete this.index;c.shift();return this};a.buildProperties=function(b,c){for(var d=0,f=c.length;d<f;d++){var g=c[d],h=g.value;switch(g.type){case 0:case 1:h=this.scene.defs[g.name].value;break;case 3:h=h.apply(this,pv.Mark.stack);break}b[g.name]=h}};
+a.buildInstance=function(b){this.buildProperties(b,this.binds.required);if(b.visible){this.buildProperties(b,this.binds.optional);this.buildImplied(b)}};
+a.buildImplied=function(b){var c=b.left,d=b.right,f=b.top,g=b.bottom,h=this.properties,i=h.width?b.width:0,j=h.height?b.height:0,l=this.parent?this.parent.width():i+c+d;if(i==null)i=l-(d=d||0)-(c=c||0);else if(d==null)d=l-i-(c=c||0);else if(c==null)c=l-i-(d=d||0);l=this.parent?this.parent.height():j+f+g;if(j==null)j=l-(f=f||0)-(g=g||0);else if(g==null)g=l-j-(f=f||0);else if(f==null)f=l-j-(g=g||0);b.left=c;b.right=d;b.top=f;b.bottom=g;if(h.width)b.width=i;if(h.height)b.height=j;if(h.textStyle&&!b.textStyle)b.textStyle=
+pv.Color.transparent;if(h.fillStyle&&!b.fillStyle)b.fillStyle=pv.Color.transparent;if(h.strokeStyle&&!b.strokeStyle)b.strokeStyle=pv.Color.transparent};
+a.mouse=function(){var b=pv.event.pageX||0,c=pv.event.pageY||0,d=this.root.canvas();do{b-=d.offsetLeft;c-=d.offsetTop}while(d=d.offsetParent);d=pv.Transform.identity;var f=this.properties.transform?this:this.parent,g=[];do g.push(f);while(f=f.parent);for(;f=g.pop();)d=d.translate(f.left(),f.top()).times(f.transform());d=d.invert();return pv.vector(b*d.k+d.x,c*d.k+d.y)};a.event=function(b,c){this.$handlers[b]=pv.functor(c);return this};
+a.context=function(b,c,d){function f(k,q){pv.Mark.scene=k;h.index=q;if(k){var o=k.mark,n=o,m=[];do{m.push(n);i.push(k[q].data);n.index=q;n.scene=k;q=k.parentIndex;k=k.parent}while(n=n.parent);k=m.length-1;for(q=1;k>0;k--){n=m[k];n.scale=q;q*=n.scene[n.index].transform.k}if(o.children){k=0;for(m=o.children.length;k<m;k++){n=o.children[k];n.scene=o.scene[o.index].children[k];n.scale=q}}}}function g(k){if(k){k=k.mark;var q;if(k.children)for(var o=0,n=k.children.length;o<n;o++){q=k.children[o];delete q.scene;
+delete q.scale}q=k;do{i.pop();if(q.parent){delete q.scene;delete q.scale}delete q.index}while(q=q.parent)}}var h=pv.Mark.prototype,i=pv.Mark.stack,j=pv.Mark.scene,l=h.index;g(j,l);f(b,c);try{d.apply(this,i)}finally{g(b,c);f(j,l)}};pv.Mark.dispatch=function(b,c,d){var f=c.mark,g=c.parent,h=f.$handlers[b];if(!h)return g&&pv.Mark.dispatch(b,g,c.parentIndex);f.context(c,d,function(){(f=h.apply(f,pv.Mark.stack))&&f.render&&f.render()});return true};
+pv.Anchor=function(b){pv.Mark.call(this);this.target=b;this.parent=b.parent};pv.Anchor.prototype=pv.extend(pv.Mark).property("name",String);pv.Anchor.prototype.anchorTarget=function(){return this.target};pv.Area=function(){pv.Mark.call(this)};
+pv.Area.prototype=pv.extend(pv.Mark).property("width",Number).property("height",Number).property("lineWidth",Number).property("strokeStyle",pv.color).property("fillStyle",pv.color).property("segmented",Boolean).property("interpolate",String).property("tension",Number);pv.Area.prototype.type="area";pv.Area.prototype.defaults=(new pv.Area).extend(pv.Mark.prototype.defaults).lineWidth(1.5).fillStyle(pv.Colors.category20().by(pv.parent)).interpolate("linear").tension(0.7);
+pv.Area.prototype.buildImplied=function(b){if(b.height==null)b.height=0;if(b.width==null)b.width=0;pv.Mark.prototype.buildImplied.call(this,b)};pv.Area.fixed={lineWidth:1,lineJoin:1,strokeStyle:1,fillStyle:1,segmented:1,interpolate:1,tension:1};
+pv.Area.prototype.bind=function(){pv.Mark.prototype.bind.call(this);var b=this.binds,c=b.required;b=b.optional;for(var d=0,f=b.length;d<f;d++){var g=b[d];g.fixed=g.name in pv.Area.fixed;if(g.name=="segmented"){c.push(g);b.splice(d,1);d--;f--}}this.binds.$required=c;this.binds.$optional=b};
+pv.Area.prototype.buildInstance=function(b){var c=this.binds;if(this.index){var d=c.fixed;if(!d){d=c.fixed=[];function f(i){return!i.fixed||(d.push(i),false)}c.required=c.required.filter(f);if(!this.scene[0].segmented)c.optional=c.optional.filter(f)}c=0;for(var g=d.length;c<g;c++){var h=d[c].name;b[h]=this.scene[0][h]}}else{c.required=c.$required;c.optional=c.$optional;c.fixed=null}pv.Mark.prototype.buildInstance.call(this,b)};
+pv.Area.prototype.anchor=function(b){var c;return pv.Mark.prototype.anchor.call(this,b).def("$area.anchor",function(){c=this.scene.target}).interpolate(function(){return c[this.index].interpolate}).eccentricity(function(){return c[this.index].eccentricity}).tension(function(){return c[this.index].tension})};pv.Bar=function(){pv.Mark.call(this)};
+pv.Bar.prototype=pv.extend(pv.Mark).property("width",Number).property("height",Number).property("lineWidth",Number).property("strokeStyle",pv.color).property("fillStyle",pv.color);pv.Bar.prototype.type="bar";pv.Bar.prototype.defaults=(new pv.Bar).extend(pv.Mark.prototype.defaults).lineWidth(1.5).fillStyle(pv.Colors.category20().by(pv.parent));pv.Dot=function(){pv.Mark.call(this)};
+pv.Dot.prototype=pv.extend(pv.Mark).property("size",Number).property("radius",Number).property("shape",String).property("angle",Number).property("lineWidth",Number).property("strokeStyle",pv.color).property("fillStyle",pv.color);pv.Dot.prototype.type="dot";pv.Dot.prototype.defaults=(new pv.Dot).extend(pv.Mark.prototype.defaults).size(20).shape("circle").lineWidth(1.5).strokeStyle(pv.Colors.category10().by(pv.parent));
+pv.Dot.prototype.anchor=function(b){var c;return pv.Mark.prototype.anchor.call(this,b).def("$wedge.anchor",function(){c=this.scene.target}).left(function(){var d=c[this.index];switch(this.name()){case "bottom":case "top":case "center":return d.left;case "left":return null}return d.left+d.radius}).right(function(){var d=c[this.index];return this.name()=="left"?d.right+d.radius:null}).top(function(){var d=c[this.index];switch(this.name()){case "left":case "right":case "center":return d.top;case "top":return null}return d.top+
+d.radius}).bottom(function(){var d=c[this.index];return this.name()=="top"?d.bottom+d.radius:null}).textAlign(function(){switch(this.name()){case "left":return"right";case "bottom":case "top":case "center":return"center"}return"left"}).textBaseline(function(){switch(this.name()){case "right":case "left":case "center":return"middle";case "bottom":return"top"}return"bottom"})};
+pv.Dot.prototype.buildImplied=function(b){if(b.radius==null)b.radius=Math.sqrt(b.size);else if(b.size==null)b.size=b.radius*b.radius;pv.Mark.prototype.buildImplied.call(this,b)};pv.Label=function(){pv.Mark.call(this)};
+pv.Label.prototype=pv.extend(pv.Mark).property("text",String).property("font",String).property("textAngle",Number).property("textStyle",pv.color).property("textAlign",String).property("textBaseline",String).property("textMargin",Number).property("textDecoration",String).property("textShadow",String);pv.Label.prototype.type="label";pv.Label.prototype.defaults=(new pv.Label).extend(pv.Mark.prototype.defaults).events("none").text(pv.identity).font("10px sans-serif").textAngle(0).textStyle("black").textAlign("left").textBaseline("bottom").textMargin(3);
+pv.Line=function(){pv.Mark.call(this)};pv.Line.prototype=pv.extend(pv.Mark).property("lineWidth",Number).property("lineJoin",String).property("strokeStyle",pv.color).property("fillStyle",pv.color).property("segmented",Boolean).property("interpolate",String).property("eccentricity",Number).property("tension",Number);a=pv.Line.prototype;a.type="line";a.defaults=(new pv.Line).extend(pv.Mark.prototype.defaults).lineJoin("miter").lineWidth(1.5).strokeStyle(pv.Colors.category10().by(pv.parent)).interpolate("linear").eccentricity(0).tension(0.7);
+a.bind=pv.Area.prototype.bind;a.buildInstance=pv.Area.prototype.buildInstance;a.anchor=function(b){return pv.Area.prototype.anchor.call(this,b).textAlign(function(){switch(this.name()){case "left":return"right";case "bottom":case "top":case "center":return"center";case "right":return"left"}}).textBaseline(function(){switch(this.name()){case "right":case "left":case "center":return"middle";case "top":return"bottom";case "bottom":return"top"}})};pv.Rule=function(){pv.Mark.call(this)};
+pv.Rule.prototype=pv.extend(pv.Mark).property("width",Number).property("height",Number).property("lineWidth",Number).property("strokeStyle",pv.color);pv.Rule.prototype.type="rule";pv.Rule.prototype.defaults=(new pv.Rule).extend(pv.Mark.prototype.defaults).lineWidth(1).strokeStyle("black").antialias(false);pv.Rule.prototype.anchor=pv.Line.prototype.anchor;
+pv.Rule.prototype.buildImplied=function(b){var c=b.left,d=b.right;if(b.width!=null||c==null&&d==null||d!=null&&c!=null)b.height=0;else b.width=0;pv.Mark.prototype.buildImplied.call(this,b)};pv.Panel=function(){pv.Bar.call(this);this.children=[];this.root=this;this.$dom=pv.$&&pv.$.s};pv.Panel.prototype=pv.extend(pv.Bar).property("transform").property("overflow",String).property("canvas",function(b){return typeof b=="string"?document.getElementById(b):b});a=pv.Panel.prototype;a.type="panel";
+a.defaults=(new pv.Panel).extend(pv.Bar.prototype.defaults).fillStyle(null).overflow("visible");a.anchor=function(b){b=pv.Bar.prototype.anchor.call(this,b);b.parent=this;return b};a.add=function(b){b=new b;b.parent=this;b.root=this.root;b.childIndex=this.children.length;this.children.push(b);return b};a.bind=function(){pv.Mark.prototype.bind.call(this);for(var b=0;b<this.children.length;b++)this.children[b].bind()};
+a.buildInstance=function(b){pv.Bar.prototype.buildInstance.call(this,b);if(b.visible){if(!b.children)b.children=[];var c=this.scale*b.transform.k,d,f=this.children.length;pv.Mark.prototype.index=-1;for(var g=0;g<f;g++){d=this.children[g];d.scene=b.children[g];d.scale=c;d.build()}for(g=0;g<f;g++){d=this.children[g];b.children[g]=d.scene;delete d.scene;delete d.scale}b.children.length=f}};
+a.buildImplied=function(b){if(!this.parent){var c=b.canvas;if(c){if(c.$panel!=this)for(c.$panel=this;c.lastChild;)c.removeChild(c.lastChild);var d;if(b.width==null){d=parseFloat(pv.css(c,"width"));b.width=d-b.left-b.right}if(b.height==null){d=parseFloat(pv.css(c,"height"));b.height=d-b.top-b.bottom}}else{d=this.$canvas||(this.$canvas=[]);if(!(c=d[this.index])){c=d[this.index]=document.createElement("span");if(this.$dom)this.$dom.parentNode.insertBefore(c,this.$dom);else{for(d=document.body;d.lastChild&&
+d.lastChild.tagName;)d=d.lastChild;if(d!=document.body)d=d.parentNode;d.appendChild(c)}}}b.canvas=c}if(!b.transform)b.transform=pv.Transform.identity;pv.Mark.prototype.buildImplied.call(this,b)};pv.Image=function(){pv.Bar.call(this)};pv.Image.prototype=pv.extend(pv.Bar).property("url",String).property("imageWidth",Number).property("imageHeight",Number);a=pv.Image.prototype;a.type="image";a.defaults=(new pv.Image).extend(pv.Bar.prototype.defaults).fillStyle(null);
+a.image=function(b){this.$image=function(){var c=b.apply(this,arguments);return c==null?pv.Color.transparent:typeof c=="string"?pv.color(c):c};return this};a.bind=function(){pv.Bar.prototype.bind.call(this);var b=this.binds,c=this;do b.image=c.$image;while(!b.image&&(c=c.proto))};
+a.buildImplied=function(b){pv.Bar.prototype.buildImplied.call(this,b);if(b.visible){if(b.imageWidth==null)b.imageWidth=b.width;if(b.imageHeight==null)b.imageHeight=b.height;if(b.url==null&&this.binds.image){var c=this.$canvas||(this.$canvas=document.createElement("canvas")),d=c.getContext("2d"),f=b.imageWidth,g=b.imageHeight,h=pv.Mark.stack;c.width=f;c.height=g;b=(b.image=d.createImageData(f,g)).data;h.unshift(null,null);for(d=c=0;c<g;c++){h[1]=c;for(var i=0;i<f;i++){h[0]=i;var j=this.binds.image.apply(this,
+h);b[d++]=j.r;b[d++]=j.g;b[d++]=j.b;b[d++]=255*j.a}}h.splice(0,2)}}};pv.Wedge=function(){pv.Mark.call(this)};pv.Wedge.prototype=pv.extend(pv.Mark).property("startAngle",Number).property("endAngle",Number).property("angle",Number).property("innerRadius",Number).property("outerRadius",Number).property("lineWidth",Number).property("strokeStyle",pv.color).property("fillStyle",pv.color);a=pv.Wedge.prototype;a.type="wedge";
+a.defaults=(new pv.Wedge).extend(pv.Mark.prototype.defaults).startAngle(function(){var b=this.sibling();return b?b.endAngle:-Math.PI/2}).innerRadius(0).lineWidth(1.5).strokeStyle(null).fillStyle(pv.Colors.category20().by(pv.index));a.midRadius=function(){return(this.innerRadius()+this.outerRadius())/2};a.midAngle=function(){return(this.startAngle()+this.endAngle())/2};
+a.anchor=function(b){function c(h){return h.innerRadius||h.angle<2*Math.PI}function d(h){return(h.innerRadius+h.outerRadius)/2}function f(h){return(h.startAngle+h.endAngle)/2}var g;return pv.Mark.prototype.anchor.call(this,b).def("$wedge.anchor",function(){g=this.scene.target}).left(function(){var h=g[this.index];if(c(h))switch(this.name()){case "outer":return h.left+h.outerRadius*Math.cos(f(h));case "inner":return h.left+h.innerRadius*Math.cos(f(h));case "start":return h.left+d(h)*Math.cos(h.startAngle);
+case "center":return h.left+d(h)*Math.cos(f(h));case "end":return h.left+d(h)*Math.cos(h.endAngle)}return h.left}).top(function(){var h=g[this.index];if(c(h))switch(this.name()){case "outer":return h.top+h.outerRadius*Math.sin(f(h));case "inner":return h.top+h.innerRadius*Math.sin(f(h));case "start":return h.top+d(h)*Math.sin(h.startAngle);case "center":return h.top+d(h)*Math.sin(f(h));case "end":return h.top+d(h)*Math.sin(h.endAngle)}return h.top}).textAlign(function(){var h=g[this.index];if(c(h))switch(this.name()){case "outer":return pv.Wedge.upright(f(h))?
+"right":"left";case "inner":return pv.Wedge.upright(f(h))?"left":"right"}return"center"}).textBaseline(function(){var h=g[this.index];if(c(h))switch(this.name()){case "start":return pv.Wedge.upright(h.startAngle)?"top":"bottom";case "end":return pv.Wedge.upright(h.endAngle)?"bottom":"top"}return"middle"}).textAngle(function(){var h=g[this.index],i=0;if(c(h))switch(this.name()){case "center":case "inner":case "outer":i=f(h);break;case "start":i=h.startAngle;break;case "end":i=h.endAngle;break}return pv.Wedge.upright(i)?
+i:i+Math.PI})};pv.Wedge.upright=function(b){b%=2*Math.PI;b=b<0?2*Math.PI+b:b;return b<Math.PI/2||b>=3*Math.PI/2};pv.Wedge.prototype.buildImplied=function(b){if(b.angle==null)b.angle=b.endAngle-b.startAngle;else if(b.endAngle==null)b.endAngle=b.startAngle+b.angle;pv.Mark.prototype.buildImplied.call(this,b)};pv.simulation=function(b){return new pv.Simulation(b)};pv.Simulation=function(b){for(var c=0;c<b.length;c++)this.particle(b[c])};a=pv.Simulation.prototype;
+a.particle=function(b){b.next=this.particles;if(isNaN(b.px))b.px=b.x;if(isNaN(b.py))b.py=b.y;if(isNaN(b.fx))b.fx=0;if(isNaN(b.fy))b.fy=0;this.particles=b;return this};a.force=function(b){b.next=this.forces;this.forces=b;return this};a.constraint=function(b){b.next=this.constraints;this.constraints=b;return this};
+a.stabilize=function(b){var c;arguments.length||(b=3);for(var d=0;d<b;d++){var f=new pv.Quadtree(this.particles);for(c=this.constraints;c;c=c.next)c.apply(this.particles,f)}for(c=this.particles;c;c=c.next){c.px=c.x;c.py=c.y}return this};
+a.step=function(){var b;for(b=this.particles;b;b=b.next){var c=b.px,d=b.py;b.px=b.x;b.py=b.y;b.x+=b.vx=b.x-c+b.fx;b.y+=b.vy=b.y-d+b.fy}c=new pv.Quadtree(this.particles);for(b=this.constraints;b;b=b.next)b.apply(this.particles,c);for(b=this.particles;b;b=b.next)b.fx=b.fy=0;for(b=this.forces;b;b=b.next)b.apply(this.particles,c)};
+pv.Quadtree=function(b){function c(k,q,o,n,m,r){if(!(isNaN(q.x)||isNaN(q.y)))if(k.leaf)if(k.p){if(!(Math.abs(k.p.x-q.x)+Math.abs(k.p.y-q.y)<0.01)){var s=k.p;k.p=null;d(k,s,o,n,m,r)}d(k,q,o,n,m,r)}else k.p=q;else d(k,q,o,n,m,r)}function d(k,q,o,n,m,r){var s=(o+m)*0.5,u=(n+r)*0.5,x=q.x>=s,t=q.y>=u;k.leaf=false;switch((t<<1)+x){case 0:k=k.c1||(k.c1=new pv.Quadtree.Node);break;case 1:k=k.c2||(k.c2=new pv.Quadtree.Node);break;case 2:k=k.c3||(k.c3=new pv.Quadtree.Node);break;case 3:k=k.c4||(k.c4=new pv.Quadtree.Node);
+break}if(x)o=s;else m=s;if(t)n=u;else r=u;c(k,q,o,n,m,r)}var f,g=Number.POSITIVE_INFINITY,h=g,i=Number.NEGATIVE_INFINITY,j=i;for(f=b;f;f=f.next){if(f.x<g)g=f.x;if(f.y<h)h=f.y;if(f.x>i)i=f.x;if(f.y>j)j=f.y}f=i-g;var l=j-h;if(f>l)j=h+f;else i=g+l;this.xMin=g;this.yMin=h;this.xMax=i;this.yMax=j;this.root=new pv.Quadtree.Node;for(f=b;f;f=f.next)c(this.root,f,g,h,i,j)};pv.Quadtree.Node=function(){this.leaf=true;this.p=this.c4=this.c3=this.c2=this.c1=null};pv.Force={};
+pv.Force.charge=function(b){function c(k){function q(m){c(m);k.cn+=m.cn;o+=m.cn*m.cx;n+=m.cn*m.cy}var o=0,n=0;k.cn=0;if(!k.leaf){k.c1&&q(k.c1);k.c2&&q(k.c2);k.c3&&q(k.c3);k.c4&&q(k.c4)}if(k.p){k.cn+=b;o+=b*k.p.x;n+=b*k.p.y}k.cx=o/k.cn;k.cy=n/k.cn}function d(k,q,o,n,m,r){var s=k.cx-q.x,u=k.cy-q.y,x=1/Math.sqrt(s*s+u*u);if(k.leaf&&k.p!=q||(m-o)*x<j){if(!(x<i)){if(x>g)x=g;k=k.cn*x*x*x;s=s*k;u=u*k;q.fx+=s;q.fy+=u}}else if(!k.leaf){var t=(o+m)*0.5,p=(n+r)*0.5;k.c1&&d(k.c1,q,o,n,t,p);k.c2&&d(k.c2,q,t,n,
+m,p);k.c3&&d(k.c3,q,o,p,t,r);k.c4&&d(k.c4,q,t,p,m,r);if(!(x<i)){if(x>g)x=g;if(k.p&&k.p!=q){k=b*x*x*x;s=s*k;u=u*k;q.fx+=s;q.fy+=u}}}}var f=2,g=1/f,h=500,i=1/h,j=0.9,l={};arguments.length||(b=-40);l.constant=function(k){if(arguments.length){b=Number(k);return l}return b};l.domain=function(k,q){if(arguments.length){f=Number(k);g=1/f;h=Number(q);i=1/h;return l}return[f,h]};l.theta=function(k){if(arguments.length){j=Number(k);return l}return j};l.apply=function(k,q){c(q.root);for(k=k;k;k=k.next)d(q.root,
+k,q.xMin,q.yMin,q.xMax,q.yMax)};return l};pv.Force.drag=function(b){var c={};arguments.length||(b=0.1);c.constant=function(d){if(arguments.length){b=d;return c}return b};c.apply=function(d){if(b)for(d=d;d;d=d.next){d.fx-=b*d.vx;d.fy-=b*d.vy}};return c};
+pv.Force.spring=function(b){var c=0.1,d=20,f,g,h={};arguments.length||(b=0.1);h.links=function(i){if(arguments.length){f=i;g=i.map(function(j){return 1/Math.sqrt(Math.max(j.sourceNode.linkDegree,j.targetNode.linkDegree))});return h}return f};h.constant=function(i){if(arguments.length){b=Number(i);return h}return b};h.damping=function(i){if(arguments.length){c=Number(i);return h}return c};h.length=function(i){if(arguments.length){d=Number(i);return h}return d};h.apply=function(){for(var i=0;i<f.length;i++){var j=
+f[i].sourceNode,l=f[i].targetNode,k=j.x-l.x,q=j.y-l.y,o=Math.sqrt(k*k+q*q),n=o?1/o:1;n=(b*g[i]*(o-d)+c*g[i]*(k*(j.vx-l.vx)+q*(j.vy-l.vy))*n)*n;k=-n*(o?k:0.01*(0.5-Math.random()));q=-n*(o?q:0.01*(0.5-Math.random()));j.fx+=k;j.fy+=q;l.fx-=k;l.fy-=q}};return h};pv.Constraint={};
+pv.Constraint.collision=function(b){function c(k,q,o,n,m,r){if(!k.leaf){var s=(o+m)*0.5,u=(n+r)*0.5,x=u<j,t=s>g,p=s<i;if(u>h){k.c1&&t&&c(k.c1,q,o,n,s,u);k.c2&&p&&c(k.c2,q,s,n,m,u)}if(x){k.c3&&t&&c(k.c3,q,o,u,s,r);k.c4&&p&&c(k.c4,q,s,u,m,r)}}if(k.p&&k.p!=q){o=q.x-k.p.x;n=q.y-k.p.y;m=Math.sqrt(o*o+n*n);r=f+b(k.p);if(m<r){m=(m-r)/m*0.5;o*=m;n*=m;q.x-=o;q.y-=n;k.p.x+=o;k.p.y+=n}}}var d=1,f,g,h,i,j,l={};arguments.length||(f=10);l.repeat=function(k){if(arguments.length){d=Number(k);return l}return d};l.apply=
+function(k,q){var o,n,m=-Infinity;for(o=k;o;o=o.next){n=b(o);if(n>m)m=n}for(var r=0;r<d;r++)for(o=k;o;o=o.next){n=(f=b(o))+m;g=o.x-n;i=o.x+n;h=o.y-n;j=o.y+n;c(q.root,o,q.xMin,q.yMin,q.xMax,q.yMax)}};return l};pv.Constraint.position=function(b){var c=1,d={};arguments.length||(b=function(f){return f.fix});d.alpha=function(f){if(arguments.length){c=Number(f);return d}return c};d.apply=function(f){for(f=f;f;f=f.next){var g=b(f);if(g){f.x+=(g.x-f.x)*c;f.y+=(g.y-f.y)*c;f.fx=f.fy=f.vx=f.vy=0}}};return d};
+pv.Constraint.bound=function(){var b={},c,d;b.x=function(f,g){if(arguments.length){c={min:Math.min(f,g),max:Math.max(f,g)};return this}return c};b.y=function(f,g){if(arguments.length){d={min:Math.min(f,g),max:Math.max(f,g)};return this}return d};b.apply=function(f){if(c)for(var g=f;g;g=g.next)g.x=g.x<c.min?c.min:g.x>c.max?c.max:g.x;if(d)for(g=f;g;g=g.next)g.y=g.y<d.min?d.min:g.y>d.max?d.max:g.y};return b};pv.Layout=function(){pv.Panel.call(this)};pv.Layout.prototype=pv.extend(pv.Panel);
+pv.Layout.prototype.property=function(b,c){if(!this.hasOwnProperty("properties"))this.properties=pv.extend(this.properties);this.properties[b]=true;this.propertyMethod(b,false,pv.Mark.cast[b]=c);return this};
+pv.Layout.Network=function(){pv.Layout.call(this);var b=this;this.$id=pv.id();(this.node=(new pv.Mark).data(function(){return b.nodes()}).strokeStyle("#1f77b4").fillStyle("#fff").left(function(c){return c.x}).top(function(c){return c.y})).parent=this;this.link=(new pv.Mark).extend(this.node).data(function(c){return[c.sourceNode,c.targetNode]}).fillStyle(null).lineWidth(function(c,d){return d.linkValue*1.5}).strokeStyle("rgba(0,0,0,.2)");this.link.add=function(c){return b.add(pv.Panel).data(function(){return b.links()}).add(c).extend(this)};
+(this.label=(new pv.Mark).extend(this.node).textMargin(7).textBaseline("middle").text(function(c){return c.nodeName||c.nodeValue}).textAngle(function(c){c=c.midAngle;return pv.Wedge.upright(c)?c:c+Math.PI}).textAlign(function(c){return pv.Wedge.upright(c.midAngle)?"left":"right"})).parent=this};
+pv.Layout.Network.prototype=pv.extend(pv.Layout).property("nodes",function(b){return b.map(function(c,d){if(typeof c!="object")c={nodeValue:c};c.index=d;c.linkDegree=0;return c})}).property("links",function(b){return b.map(function(c){if(isNaN(c.linkValue))c.linkValue=isNaN(c.value)?1:c.value;return c})});pv.Layout.Network.prototype.reset=function(){this.$id=pv.id();return this};
+pv.Layout.Network.prototype.buildProperties=function(b,c){if((b.$id||0)<this.$id)pv.Layout.prototype.buildProperties.call(this,b,c)};pv.Layout.Network.prototype.buildImplied=function(b){pv.Layout.prototype.buildImplied.call(this,b);if(b.$id>=this.$id)return true;b.$id=this.$id;b.links.forEach(function(c){var d=c.linkValue;(c.sourceNode||(c.sourceNode=b.nodes[c.source])).linkDegree+=d;(c.targetNode||(c.targetNode=b.nodes[c.target])).linkDegree+=d})};
+pv.Layout.Hierarchy=function(){pv.Layout.Network.call(this);this.link.strokeStyle("#ccc")};pv.Layout.Hierarchy.prototype=pv.extend(pv.Layout.Network);pv.Layout.Hierarchy.prototype.buildImplied=function(b){if(!b.links)b.links=pv.Layout.Hierarchy.links.call(this);pv.Layout.Network.prototype.buildImplied.call(this,b)};pv.Layout.Hierarchy.links=function(){return this.nodes().filter(function(b){return b.parentNode}).map(function(b){return{sourceNode:b,targetNode:b.parentNode,linkValue:1}})};
+pv.Layout.Hierarchy.NodeLink={buildImplied:function(b){function c(m){return m.parentNode?m.depth*(o-q)+q:0}function d(m){return m.parentNode?(m.breadth-0.25)*2*Math.PI:0}function f(m){switch(i){case "left":return m.depth*l;case "right":return l-m.depth*l;case "top":return m.breadth*l;case "bottom":return l-m.breadth*l;case "radial":return l/2+c(m)*Math.cos(m.midAngle)}}function g(m){switch(i){case "left":return m.breadth*k;case "right":return k-m.breadth*k;case "top":return m.depth*k;case "bottom":return k-
+m.depth*k;case "radial":return k/2+c(m)*Math.sin(m.midAngle)}}var h=b.nodes,i=b.orient,j=/^(top|bottom)$/.test(i),l=b.width,k=b.height;if(i=="radial"){var q=b.innerRadius,o=b.outerRadius;if(q==null)q=0;if(o==null)o=Math.min(l,k)/2}for(b=0;b<h.length;b++){var n=h[b];n.midAngle=i=="radial"?d(n):j?Math.PI/2:0;n.x=f(n);n.y=g(n);if(n.firstChild)n.midAngle+=Math.PI}}};
+pv.Layout.Hierarchy.Fill={constructor:function(){this.node.strokeStyle("#fff").fillStyle("#ccc").width(function(b){return b.dx}).height(function(b){return b.dy}).innerRadius(function(b){return b.innerRadius}).outerRadius(function(b){return b.outerRadius}).startAngle(function(b){return b.startAngle}).angle(function(b){return b.angle});this.label.textAlign("center").left(function(b){return b.x+b.dx/2}).top(function(b){return b.y+b.dy/2});delete this.link},buildImplied:function(b){function c(p,v){return(p+
+v)/(1+v)}function d(p){switch(o){case "left":return c(p.minDepth,s)*m;case "right":return(1-c(p.maxDepth,s))*m;case "top":return p.minBreadth*m;case "bottom":return(1-p.maxBreadth)*m;case "radial":return m/2}}function f(p){switch(o){case "left":return p.minBreadth*r;case "right":return(1-p.maxBreadth)*r;case "top":return c(p.minDepth,s)*r;case "bottom":return(1-c(p.maxDepth,s))*r;case "radial":return r/2}}function g(p){switch(o){case "left":case "right":return(p.maxDepth-p.minDepth)/(1+s)*m;case "top":case "bottom":return(p.maxBreadth-
+p.minBreadth)*m;case "radial":return p.parentNode?(p.innerRadius+p.outerRadius)*Math.cos(p.midAngle):0}}function h(p){switch(o){case "left":case "right":return(p.maxBreadth-p.minBreadth)*r;case "top":case "bottom":return(p.maxDepth-p.minDepth)/(1+s)*r;case "radial":return p.parentNode?(p.innerRadius+p.outerRadius)*Math.sin(p.midAngle):0}}function i(p){return Math.max(0,c(p.minDepth,s/2))*(x-u)+u}function j(p){return c(p.maxDepth,s/2)*(x-u)+u}function l(p){return(p.parentNode?p.minBreadth-0.25:0)*
+2*Math.PI}function k(p){return(p.parentNode?p.maxBreadth-p.minBreadth:1)*2*Math.PI}var q=b.nodes,o=b.orient,n=/^(top|bottom)$/.test(o),m=b.width,r=b.height,s=-q[0].minDepth;if(o=="radial"){var u=b.innerRadius,x=b.outerRadius;if(u==null)u=0;if(u)s*=2;if(x==null)x=Math.min(m,r)/2}for(b=0;b<q.length;b++){var t=q[b];t.x=d(t);t.y=f(t);if(o=="radial"){t.innerRadius=i(t);t.outerRadius=j(t);t.startAngle=l(t);t.angle=k(t);t.midAngle=t.startAngle+t.angle/2}else t.midAngle=n?-Math.PI/2:0;t.dx=g(t);t.dy=h(t)}}};
+pv.Layout.Grid=function(){pv.Layout.call(this);var b=this;(this.cell=(new pv.Mark).data(function(){return b.scene[b.index].$grid}).width(function(){return b.width()/b.cols()}).height(function(){return b.height()/b.rows()}).left(function(){return this.width()*(this.index%b.cols())}).top(function(){return this.height()*Math.floor(this.index/b.cols())})).parent=this};pv.Layout.Grid.prototype=pv.extend(pv.Layout).property("rows").property("cols");pv.Layout.Grid.prototype.defaults=(new pv.Layout.Grid).extend(pv.Layout.prototype.defaults).rows(1).cols(1);
+pv.Layout.Grid.prototype.buildImplied=function(b){pv.Layout.prototype.buildImplied.call(this,b);var c=b.rows,d=b.cols;if(typeof d=="object")c=pv.transpose(d);if(typeof c=="object"){b.$grid=pv.blend(c);b.rows=c.length;b.cols=c[0]?c[0].length:0}else b.$grid=pv.repeat([b.data],c*d)};
+pv.Layout.Stack=function(){function b(i){return function(){return f[i](this.parent.index,this.index)}}pv.Layout.call(this);var c=this,d=function(){return null},f={t:d,l:d,r:d,b:d,w:d,h:d},g,h=c.buildImplied;this.buildImplied=function(i){h.call(this,i);var j=i.layers,l=j.length,k,q=i.orient,o=/^(top|bottom)\b/.test(q),n=this.parent[o?"height":"width"](),m=[],r=[],s=[],u=pv.Mark.stack,x={parent:{parent:this}};u.unshift(null);g=[];for(var t=0;t<l;t++){s[t]=[];r[t]=[];x.parent.index=t;u[0]=j[t];g[t]=
+this.$values.apply(x.parent,u);if(!t)k=g[t].length;u.unshift(null);for(var p=0;p<k;p++){u[0]=g[t][p];x.index=p;t||(m[p]=this.$x.apply(x,u));s[t][p]=this.$y.apply(x,u)}u.shift()}u.shift();switch(i.order){case "inside-out":var v=s.map(function(A){return pv.max.index(A)});x=pv.range(l).sort(function(A,D){return v[A]-v[D]});j=s.map(function(A){return pv.sum(A)});var w=u=0,y=[],z=[];for(t=0;t<l;t++){p=x[t];if(u<w){u+=j[p];y.push(p)}else{w+=j[p];z.push(p)}}j=z.reverse().concat(y);break;case "reverse":j=
+pv.range(l-1,-1,-1);break;default:j=pv.range(l);break}switch(i.offset){case "silohouette":for(p=0;p<k;p++){for(t=x=0;t<l;t++)x+=s[t][p];r[j[0]][p]=(n-x)/2}break;case "wiggle":for(t=x=0;t<l;t++)x+=s[t][0];r[j[0]][0]=x=(n-x)/2;for(p=1;p<k;p++){u=n=0;w=m[p]-m[p-1];for(t=0;t<l;t++)n+=s[t][p];for(t=0;t<l;t++){y=(s[j[t]][p]-s[j[t]][p-1])/(2*w);for(i=0;i<t;i++)y+=(s[j[i]][p]-s[j[i]][p-1])/w;u+=y*s[j[t]][p]}r[j[0]][p]=x-=n?u/n*w:0}break;case "expand":for(p=0;p<k;p++){for(t=i=r[j[0]][p]=0;t<l;t++)i+=s[t][p];
+if(i){i=n/i;for(t=0;t<l;t++)s[t][p]*=i}else{i=n/l;for(t=0;t<l;t++)s[t][p]=i}}break;default:for(p=0;p<k;p++)r[j[0]][p]=0;break}for(p=0;p<k;p++){x=r[j[0]][p];for(t=1;t<l;t++){x+=s[j[t-1]][p];r[j[t]][p]=x}}t=q.indexOf("-");l=o?"h":"w";o=t<0?o?"l":"b":q.charAt(t+1);q=q.charAt(0);for(var C in f)f[C]=d;f[o]=function(A,D){return m[D]};f[q]=function(A,D){return r[A][D]};f[l]=function(A,D){return s[A][D]}};this.layer=(new pv.Mark).data(function(){return g[this.parent.index]}).top(b("t")).left(b("l")).right(b("r")).bottom(b("b")).width(b("w")).height(b("h"));
+this.layer.add=function(i){return c.add(pv.Panel).data(function(){return c.layers()}).add(i).extend(this)}};pv.Layout.Stack.prototype=pv.extend(pv.Layout).property("orient",String).property("offset",String).property("order",String).property("layers");a=pv.Layout.Stack.prototype;a.defaults=(new pv.Layout.Stack).extend(pv.Layout.prototype.defaults).orient("bottom-left").offset("zero").layers([[]]);a.$x=pv.Layout.Stack.prototype.$y=function(){return 0};a.x=function(b){this.$x=pv.functor(b);return this};
+a.y=function(b){this.$y=pv.functor(b);return this};a.$values=pv.identity;a.values=function(b){this.$values=pv.functor(b);return this};
+pv.Layout.Treemap=function(){pv.Layout.Hierarchy.call(this);this.node.strokeStyle("#fff").fillStyle("rgba(31, 119, 180, .25)").width(function(b){return b.dx}).height(function(b){return b.dy});this.label.visible(function(b){return!b.firstChild}).left(function(b){return b.x+b.dx/2}).top(function(b){return b.y+b.dy/2}).textAlign("center").textAngle(function(b){return b.dx>b.dy?0:-Math.PI/2});(this.leaf=(new pv.Mark).extend(this.node).fillStyle(null).strokeStyle(null).visible(function(b){return!b.firstChild})).parent=
+this;delete this.link};pv.Layout.Treemap.prototype=pv.extend(pv.Layout.Hierarchy).property("round",Boolean).property("paddingLeft",Number).property("paddingRight",Number).property("paddingTop",Number).property("paddingBottom",Number).property("mode",String).property("order",String);a=pv.Layout.Treemap.prototype;a.defaults=(new pv.Layout.Treemap).extend(pv.Layout.Hierarchy.prototype.defaults).mode("squarify").order("ascending");a.padding=function(b){return this.paddingLeft(b).paddingRight(b).paddingTop(b).paddingBottom(b)};
+a.$size=function(b){return Number(b.nodeValue)};a.size=function(b){this.$size=pv.functor(b);return this};
+a.buildImplied=function(b){function c(r,s,u,x,t,p,v){for(var w=0,y=0;w<r.length;w++){var z=r[w];if(u){z.x=x+y;z.y=t;y+=z.dx=n(p*z.size/s);z.dy=v}else{z.x=x;z.y=t+y;z.dx=p;y+=z.dy=n(v*z.size/s)}}if(z)if(u)z.dx+=p-y;else z.dy+=v-y}function d(r,s){for(var u=-Infinity,x=Infinity,t=0,p=0;p<r.length;p++){var v=r[p].size;if(v<x)x=v;if(v>u)u=v;t+=v}t*=t;s*=s;return Math.max(s*u/t,t/(s*x))}function f(r,s){function u(A){var D=p==y,G=pv.sum(A,o),E=y?n(G/y):0;c(A,G,D,x,t,D?p:E,D?E:v);if(D){t+=E;v-=E}else{x+=
+E;p-=E}y=Math.min(p,v);return D}var x=r.x+j,t=r.y+k,p=r.dx-j-l,v=r.dy-k-q;if(m!="squarify")c(r.childNodes,r.size,m=="slice"?true:m=="dice"?false:s&1,x,t,p,v);else{var w=[];s=Infinity;var y=Math.min(p,v),z=p*v/r.size;if(!(r.size<=0)){r.visitBefore(function(A){A.size*=z});for(r=r.childNodes.slice();r.length;){var C=r[r.length-1];if(C.size){w.push(C);z=d(w,y);if(z<=s){r.pop();s=z}else{w.pop();u(w);w.length=0;s=Infinity}}else r.pop()}if(u(w))for(s=0;s<w.length;s++)w[s].dy+=v;else for(s=0;s<w.length;s++)w[s].dx+=
+p}}}if(!pv.Layout.Hierarchy.prototype.buildImplied.call(this,b)){var g=this,h=b.nodes[0],i=pv.Mark.stack,j=b.paddingLeft,l=b.paddingRight,k=b.paddingTop,q=b.paddingBottom,o=function(r){return r.size},n=b.round?Math.round:Number,m=b.mode;i.unshift(null);h.visitAfter(function(r,s){r.depth=s;r.x=r.y=r.dx=r.dy=0;r.size=r.firstChild?pv.sum(r.childNodes,function(u){return u.size}):g.$size.apply(g,(i[0]=r,i))});i.shift();switch(b.order){case "ascending":h.sort(function(r,s){return r.size-s.size});break;
+case "descending":h.sort(function(r,s){return s.size-r.size});break;case "reverse":h.reverse();break}h.x=0;h.y=0;h.dx=b.width;h.dy=b.height;h.visitBefore(f)}};pv.Layout.Tree=function(){pv.Layout.Hierarchy.call(this)};pv.Layout.Tree.prototype=pv.extend(pv.Layout.Hierarchy).property("group",Number).property("breadth",Number).property("depth",Number).property("orient",String);pv.Layout.Tree.prototype.defaults=(new pv.Layout.Tree).extend(pv.Layout.Hierarchy.prototype.defaults).group(1).breadth(15).depth(60).orient("top");
+pv.Layout.Tree.prototype.buildImplied=function(b){function c(p){var v,w,y;if(p.firstChild){v=p.firstChild;w=p.lastChild;for(var z=y=v;z;z=z.nextSibling){c(z);y=f(z,y)}j(p);w=0.5*(v.prelim+w.prelim);if(v=p.previousSibling){p.prelim=v.prelim+k(p.depth,true);p.mod=p.prelim-w}else p.prelim=w}else if(v=p.previousSibling)p.prelim=v.prelim+k(p.depth,true)}function d(p,v,w){p.breadth=p.prelim+v;v+=p.mod;for(p=p.firstChild;p;p=p.nextSibling)d(p,v,w)}function f(p,v){var w=p.previousSibling;if(w){var y=p,z=
+p,C=w;w=p.parentNode.firstChild;var A=y.mod,D=z.mod,G=C.mod,E=w.mod;C=h(C);for(y=g(y);C&&y;){C=C;y=y;w=g(w);z=h(z);z.ancestor=p;var B=C.prelim+G-(y.prelim+A)+k(C.depth,false);if(B>0){i(l(C,p,v),p,B);A+=B;D+=B}G+=C.mod;A+=y.mod;E+=w.mod;D+=z.mod;C=h(C);y=g(y)}if(C&&!h(z)){z.thread=C;z.mod+=G-D}if(y&&!g(w)){w.thread=y;w.mod+=A-E;v=p}}return v}function g(p){return p.firstChild||p.thread}function h(p){return p.lastChild||p.thread}function i(p,v,w){var y=v.number-p.number;v.change-=w/y;v.shift+=w;p.change+=
+w/y;v.prelim+=w;v.mod+=w}function j(p){var v=0,w=0;for(p=p.lastChild;p;p=p.previousSibling){p.prelim+=v;p.mod+=v;w+=p.change;v+=p.shift+w}}function l(p,v,w){return p.ancestor.parentNode==v.parentNode?p.ancestor:w}function k(p,v){return(v?1:u+1)/(m=="radial"?p:1)}function q(p){return m=="radial"?p.breadth/r:0}function o(p){switch(m){case "left":return p.depth;case "right":return x-p.depth;case "top":case "bottom":return p.breadth+x/2;case "radial":return x/2+p.depth*Math.cos(q(p))}}function n(p){switch(m){case "left":case "right":return p.breadth+
+t/2;case "top":return p.depth;case "bottom":return t-p.depth;case "radial":return t/2+p.depth*Math.sin(q(p))}}if(!pv.Layout.Hierarchy.prototype.buildImplied.call(this,b)){var m=b.orient,r=b.depth,s=b.breadth,u=b.group,x=b.width,t=b.height;b=b.nodes[0];b.visitAfter(function(p,v){p.ancestor=p;p.prelim=0;p.mod=0;p.change=0;p.shift=0;p.number=p.previousSibling?p.previousSibling.number+1:0;p.depth=v});c(b);d(b,-b.prelim,0);b.visitAfter(function(p){p.breadth*=s;p.depth*=r;p.midAngle=q(p);p.x=o(p);p.y=n(p);
+if(p.firstChild)p.midAngle+=Math.PI;delete p.breadth;delete p.depth;delete p.ancestor;delete p.prelim;delete p.mod;delete p.change;delete p.shift;delete p.number;delete p.thread})}};pv.Layout.Indent=function(){pv.Layout.Hierarchy.call(this);this.link.interpolate("step-after")};pv.Layout.Indent.prototype=pv.extend(pv.Layout.Hierarchy).property("depth",Number).property("breadth",Number);pv.Layout.Indent.prototype.defaults=(new pv.Layout.Indent).extend(pv.Layout.Hierarchy.prototype.defaults).depth(15).breadth(15);
+pv.Layout.Indent.prototype.buildImplied=function(b){function c(i,j,l){i.x=g+l++*f;i.y=h+j++*d;i.midAngle=0;for(i=i.firstChild;i;i=i.nextSibling)j=c(i,j,l);return j}if(!pv.Layout.Hierarchy.prototype.buildImplied.call(this,b)){var d=b.breadth,f=b.depth,g=0,h=0;c(b.nodes[0],1,1)}};pv.Layout.Pack=function(){pv.Layout.Hierarchy.call(this);this.node.radius(function(b){return b.radius}).strokeStyle("rgb(31, 119, 180)").fillStyle("rgba(31, 119, 180, .25)");this.label.textAlign("center");delete this.link};
+pv.Layout.Pack.prototype=pv.extend(pv.Layout.Hierarchy).property("spacing",Number).property("order",String);pv.Layout.Pack.prototype.defaults=(new pv.Layout.Pack).extend(pv.Layout.Hierarchy.prototype.defaults).spacing(1).order("ascending");pv.Layout.Pack.prototype.$radius=function(){return 1};pv.Layout.Pack.prototype.size=function(b){this.$radius=typeof b=="function"?function(){return Math.sqrt(b.apply(this,arguments))}:(b=Math.sqrt(b),function(){return b});return this};
+pv.Layout.Pack.prototype.buildImplied=function(b){function c(o){var n=pv.Mark.stack;n.unshift(null);for(var m=0,r=o.length;m<r;m++){var s=o[m];if(!s.firstChild)s.radius=i.$radius.apply(i,(n[0]=s,n))}n.shift()}function d(o){var n=[];for(o=o.firstChild;o;o=o.nextSibling){if(o.firstChild)o.radius=d(o);o.n=o.p=o;n.push(o)}switch(b.order){case "ascending":n.sort(function(m,r){return m.radius-r.radius});break;case "descending":n.sort(function(m,r){return r.radius-m.radius});break;case "reverse":n.reverse();
+break}return f(n)}function f(o){function n(B){u=Math.min(B.x-B.radius,u);x=Math.max(B.x+B.radius,x);t=Math.min(B.y-B.radius,t);p=Math.max(B.y+B.radius,p)}function m(B,F){var H=B.n;B.n=F;F.p=B;F.n=H;H.p=F}function r(B,F){B.n=F;F.p=B}function s(B,F){var H=F.x-B.x,I=F.y-B.y;B=B.radius+F.radius;return B*B-H*H-I*I>0.0010}var u=Infinity,x=-Infinity,t=Infinity,p=-Infinity,v,w,y,z,C;v=o[0];v.x=-v.radius;v.y=0;n(v);if(o.length>1){w=o[1];w.x=w.radius;w.y=0;n(w);if(o.length>2){y=o[2];g(v,w,y);n(y);m(v,y);v.p=
+y;m(y,w);w=v.n;for(var A=3;A<o.length;A++){g(v,w,y=o[A]);var D=0,G=1,E=1;for(z=w.n;z!=w;z=z.n,G++)if(s(z,y)){D=1;break}if(D==1)for(C=v.p;C!=z.p;C=C.p,E++)if(s(C,y)){if(E<G){D=-1;z=C}break}if(D==0){m(v,y);w=y;n(y)}else if(D>0){r(v,z);w=z;A--}else if(D<0){r(z,w);v=z;A--}}}}v=(u+x)/2;w=(t+p)/2;for(A=y=0;A<o.length;A++){z=o[A];z.x-=v;z.y-=w;y=Math.max(y,z.radius+Math.sqrt(z.x*z.x+z.y*z.y))}return y+b.spacing}function g(o,n,m){var r=n.radius+m.radius,s=o.radius+m.radius,u=n.x-o.x;n=n.y-o.y;var x=Math.sqrt(u*
+u+n*n),t=(s*s+x*x-r*r)/(2*s*x);r=Math.acos(t);t=t*s;s=Math.sin(r)*s;u/=x;n/=x;m.x=o.x+t*u+s*n;m.y=o.y+t*n-s*u}function h(o,n,m,r){for(var s=o.firstChild;s;s=s.nextSibling){s.x+=o.x;s.y+=o.y;h(s,n,m,r)}o.x=n+r*o.x;o.y=m+r*o.y;o.radius*=r}if(!pv.Layout.Hierarchy.prototype.buildImplied.call(this,b)){var i=this,j=b.nodes,l=j[0];c(j);l.x=0;l.y=0;l.radius=d(l);j=this.width();var k=this.height(),q=1/Math.max(2*l.radius/j,2*l.radius/k);h(l,j/2,k/2,q)}};
+pv.Layout.Force=function(){pv.Layout.Network.call(this);this.link.lineWidth(function(b,c){return Math.sqrt(c.linkValue)*1.5});this.label.textAlign("center")};
+pv.Layout.Force.prototype=pv.extend(pv.Layout.Network).property("bound",Boolean).property("iterations",Number).property("dragConstant",Number).property("chargeConstant",Number).property("chargeMinDistance",Number).property("chargeMaxDistance",Number).property("chargeTheta",Number).property("springConstant",Number).property("springDamping",Number).property("springLength",Number);pv.Layout.Force.prototype.defaults=(new pv.Layout.Force).extend(pv.Layout.Network.prototype.defaults).dragConstant(0.1).chargeConstant(-40).chargeMinDistance(2).chargeMaxDistance(500).chargeTheta(0.9).springConstant(0.1).springDamping(0.3).springLength(20);
+pv.Layout.Force.prototype.buildImplied=function(b){function c(q){return q.fix?1:q.vx*q.vx+q.vy*q.vy}if(pv.Layout.Network.prototype.buildImplied.call(this,b)){if(b=b.$force){b.next=this.binds.$force;this.binds.$force=b}}else{for(var d=this,f=b.nodes,g=b.links,h=b.iterations,i=b.width,j=b.height,l=0,k;l<f.length;l++){k=f[l];if(isNaN(k.x))k.x=i/2+40*Math.random()-20;if(isNaN(k.y))k.y=j/2+40*Math.random()-20}k=pv.simulation(f);k.force(pv.Force.drag(b.dragConstant));k.force(pv.Force.charge(b.chargeConstant).domain(b.chargeMinDistance,
+b.chargeMaxDistance).theta(b.chargeTheta));k.force(pv.Force.spring(b.springConstant).damping(b.springDamping).length(b.springLength).links(g));k.constraint(pv.Constraint.position());b.bound&&k.constraint(pv.Constraint.bound().x(6,i-6).y(6,j-6));if(h==null){k.step();k.step();b.$force=this.binds.$force={next:this.binds.$force,nodes:f,min:1.0E-4*(g.length+1),sim:k};if(!this.$timer)this.$timer=setInterval(function(){for(var q=false,o=d.binds.$force;o;o=o.next)if(pv.max(o.nodes,c)>o.min){o.sim.step();
+q=true}q&&d.render()},42)}else for(l=0;l<h;l++)k.step()}};pv.Layout.Cluster=function(){pv.Layout.Hierarchy.call(this);var b,c=this.buildImplied;this.buildImplied=function(d){c.call(this,d);b=/^(top|bottom)$/.test(d.orient)?"step-before":/^(left|right)$/.test(d.orient)?"step-after":"linear"};this.link.interpolate(function(){return b})};
+pv.Layout.Cluster.prototype=pv.extend(pv.Layout.Hierarchy).property("group",Number).property("orient",String).property("innerRadius",Number).property("outerRadius",Number);pv.Layout.Cluster.prototype.defaults=(new pv.Layout.Cluster).extend(pv.Layout.Hierarchy.prototype.defaults).group(0).orient("top");
+pv.Layout.Cluster.prototype.buildImplied=function(b){if(!pv.Layout.Hierarchy.prototype.buildImplied.call(this,b)){var c=b.nodes[0],d=b.group,f,g,h=0,i=0.5-d/2,j=undefined;c.visitAfter(function(l){if(l.firstChild)l.depth=1+pv.max(l.childNodes,function(k){return k.depth});else{if(d&&j!=l.parentNode){j=l.parentNode;h+=d}h++;l.depth=0}});f=1/h;g=1/c.depth;j=undefined;c.visitAfter(function(l){if(l.firstChild)l.breadth=pv.mean(l.childNodes,function(k){return k.breadth});else{if(d&&j!=l.parentNode){j=l.parentNode;
+i+=d}l.breadth=f*i++}l.depth=1-l.depth*g});c.visitAfter(function(l){l.minBreadth=l.firstChild?l.firstChild.minBreadth:l.breadth-f/2;l.maxBreadth=l.firstChild?l.lastChild.maxBreadth:l.breadth+f/2});c.visitBefore(function(l){l.minDepth=l.parentNode?l.parentNode.maxDepth:0;l.maxDepth=l.parentNode?l.depth+c.depth:l.minDepth+2*c.depth});c.minDepth=-g;pv.Layout.Hierarchy.NodeLink.buildImplied.call(this,b)}};pv.Layout.Cluster.Fill=function(){pv.Layout.Cluster.call(this);pv.Layout.Hierarchy.Fill.constructor.call(this)};
+pv.Layout.Cluster.Fill.prototype=pv.extend(pv.Layout.Cluster);pv.Layout.Cluster.Fill.prototype.buildImplied=function(b){pv.Layout.Cluster.prototype.buildImplied.call(this,b)||pv.Layout.Hierarchy.Fill.buildImplied.call(this,b)};pv.Layout.Partition=function(){pv.Layout.Hierarchy.call(this)};pv.Layout.Partition.prototype=pv.extend(pv.Layout.Hierarchy).property("order",String).property("orient",String).property("innerRadius",Number).property("outerRadius",Number);
+pv.Layout.Partition.prototype.defaults=(new pv.Layout.Partition).extend(pv.Layout.Hierarchy.prototype.defaults).orient("top");pv.Layout.Partition.prototype.$size=function(){return 1};pv.Layout.Partition.prototype.size=function(b){this.$size=b;return this};
+pv.Layout.Partition.prototype.buildImplied=function(b){if(!pv.Layout.Hierarchy.prototype.buildImplied.call(this,b)){var c=this,d=b.nodes[0],f=pv.Mark.stack,g=0;f.unshift(null);d.visitAfter(function(i,j){if(j>g)g=j;i.size=i.firstChild?pv.sum(i.childNodes,function(l){return l.size}):c.$size.apply(c,(f[0]=i,f))});f.shift();switch(b.order){case "ascending":d.sort(function(i,j){return i.size-j.size});break;case "descending":d.sort(function(i,j){return j.size-i.size});break}var h=1/g;d.minBreadth=0;d.breadth=
+0.5;d.maxBreadth=1;d.visitBefore(function(i){for(var j=i.minBreadth,l=i.maxBreadth-j,k=i.firstChild;k;k=k.nextSibling){k.minBreadth=j;k.maxBreadth=j+=k.size/i.size*l;k.breadth=(j+k.minBreadth)/2}});d.visitAfter(function(i,j){i.minDepth=(j-1)*h;i.maxDepth=i.depth=j*h});pv.Layout.Hierarchy.NodeLink.buildImplied.call(this,b)}};pv.Layout.Partition.Fill=function(){pv.Layout.Partition.call(this);pv.Layout.Hierarchy.Fill.constructor.call(this)};pv.Layout.Partition.Fill.prototype=pv.extend(pv.Layout.Partition);
+pv.Layout.Partition.Fill.prototype.buildImplied=function(b){pv.Layout.Partition.prototype.buildImplied.call(this,b)||pv.Layout.Hierarchy.Fill.buildImplied.call(this,b)};pv.Layout.Arc=function(){pv.Layout.Network.call(this);var b,c,d,f=this.buildImplied;this.buildImplied=function(g){f.call(this,g);c=g.directed;b=g.orient=="radial"?"linear":"polar";d=g.orient=="right"||g.orient=="top"};this.link.data(function(g){var h=g.sourceNode;g=g.targetNode;return d!=(c||h.breadth<g.breadth)?[h,g]:[g,h]}).interpolate(function(){return b})};
+pv.Layout.Arc.prototype=pv.extend(pv.Layout.Network).property("orient",String).property("directed",Boolean);pv.Layout.Arc.prototype.defaults=(new pv.Layout.Arc).extend(pv.Layout.Network.prototype.defaults).orient("bottom");pv.Layout.Arc.prototype.sort=function(b){this.$sort=b;return this};
+pv.Layout.Arc.prototype.buildImplied=function(b){function c(m){switch(h){case "top":return-Math.PI/2;case "bottom":return Math.PI/2;case "left":return Math.PI;case "right":return 0;case "radial":return(m-0.25)*2*Math.PI}}function d(m){switch(h){case "top":case "bottom":return m*l;case "left":return 0;case "right":return l;case "radial":return l/2+q*Math.cos(c(m))}}function f(m){switch(h){case "top":return 0;case "bottom":return k;case "left":case "right":return m*k;case "radial":return k/2+q*Math.sin(c(m))}}
+if(!pv.Layout.Network.prototype.buildImplied.call(this,b)){var g=b.nodes,h=b.orient,i=this.$sort,j=pv.range(g.length),l=b.width,k=b.height,q=Math.min(l,k)/2;i&&j.sort(function(m,r){return i(g[m],g[r])});for(b=0;b<g.length;b++){var o=g[j[b]],n=o.breadth=(b+0.5)/g.length;o.x=d(n);o.y=f(n);o.midAngle=c(n)}}};
+pv.Layout.Horizon=function(){pv.Layout.call(this);var b=this,c,d,f,g,h,i,j=this.buildImplied;this.buildImplied=function(l){j.call(this,l);c=l.bands;d=l.mode;f=Math.round((d=="color"?0.5:1)*l.height);g=l.backgroundStyle;h=pv.ramp(g,l.negativeStyle).domain(0,c);i=pv.ramp(g,l.positiveStyle).domain(0,c)};c=(new pv.Panel).data(function(){return pv.range(c*2)}).overflow("hidden").height(function(){return f}).top(function(l){return d=="color"?(l&1)*f:0}).fillStyle(function(l){return l?null:g});this.band=
+(new pv.Mark).top(function(l,k){return d=="mirror"&&k&1?(k+1>>1)*f:null}).bottom(function(l,k){return d=="mirror"?k&1?null:(k+1>>1)*-f:(k&1||-1)*(k+1>>1)*f}).fillStyle(function(l,k){return(k&1?h:i)((k>>1)+1)});this.band.add=function(l){return b.add(pv.Panel).extend(c).add(l).extend(this)}};pv.Layout.Horizon.prototype=pv.extend(pv.Layout).property("bands",Number).property("mode",String).property("backgroundStyle",pv.color).property("positiveStyle",pv.color).property("negativeStyle",pv.color);
+pv.Layout.Horizon.prototype.defaults=(new pv.Layout.Horizon).extend(pv.Layout.prototype.defaults).bands(2).mode("offset").backgroundStyle("white").positiveStyle("#1f77b4").negativeStyle("#d62728");
+pv.Layout.Rollup=function(){pv.Layout.Network.call(this);var b=this,c,d,f=b.buildImplied;this.buildImplied=function(g){f.call(this,g);c=g.$rollup.nodes;d=g.$rollup.links};this.node.data(function(){return c}).size(function(g){return g.nodes.length*20});this.link.interpolate("polar").eccentricity(0.8);this.link.add=function(g){return b.add(pv.Panel).data(function(){return d}).add(g).extend(this)}};pv.Layout.Rollup.prototype=pv.extend(pv.Layout.Network).property("directed",Boolean);
+pv.Layout.Rollup.prototype.x=function(b){this.$x=pv.functor(b);return this};pv.Layout.Rollup.prototype.y=function(b){this.$y=pv.functor(b);return this};
+pv.Layout.Rollup.prototype.buildImplied=function(b){function c(r){return i[r]+","+j[r]}if(!pv.Layout.Network.prototype.buildImplied.call(this,b)){var d=b.nodes,f=b.links,g=b.directed,h=d.length,i=[],j=[],l=0,k={},q={},o=pv.Mark.stack,n={parent:this};o.unshift(null);for(var m=0;m<h;m++){n.index=m;o[0]=d[m];i[m]=this.$x.apply(n,o);j[m]=this.$y.apply(n,o)}o.shift();for(m=0;m<d.length;m++){h=c(m);o=k[h];if(!o){o=k[h]=pv.extend(d[m]);o.index=l++;o.x=i[m];o.y=j[m];o.nodes=[]}o.nodes.push(d[m])}for(m=0;m<
+f.length;m++){l=f[m].targetNode;d=k[c(f[m].sourceNode.index)];l=k[c(l.index)];h=!g&&d.index>l.index?l.index+","+d.index:d.index+","+l.index;(o=q[h])||(o=q[h]={sourceNode:d,targetNode:l,linkValue:0,links:[]});o.links.push(f[m]);o.linkValue+=f[m].linkValue}b.$rollup={nodes:pv.values(k),links:pv.values(q)}}};
+pv.Layout.Matrix=function(){pv.Layout.Network.call(this);var b,c,d,f,g,h=this.buildImplied;this.buildImplied=function(i){h.call(this,i);b=i.nodes.length;c=i.width/b;d=i.height/b;f=i.$matrix.labels;g=i.$matrix.pairs};this.link.data(function(){return g}).left(function(){return c*(this.index%b)}).top(function(){return d*Math.floor(this.index/b)}).width(function(){return c}).height(function(){return d}).lineWidth(1.5).strokeStyle("#fff").fillStyle(function(i){return i.linkValue?"#555":"#eee"}).parent=
+this;delete this.link.add;this.label.data(function(){return f}).left(function(){return this.index&1?c*((this.index>>1)+0.5):null}).top(function(){return this.index&1?null:d*((this.index>>1)+0.5)}).textMargin(4).textAlign(function(){return this.index&1?"left":"right"}).textAngle(function(){return this.index&1?-Math.PI/2:0});delete this.node};pv.Layout.Matrix.prototype=pv.extend(pv.Layout.Network).property("directed",Boolean);pv.Layout.Matrix.prototype.sort=function(b){this.$sort=b;return this};
+pv.Layout.Matrix.prototype.buildImplied=function(b){if(!pv.Layout.Network.prototype.buildImplied.call(this,b)){var c=b.nodes,d=b.links,f=this.$sort,g=c.length,h=pv.range(g),i=[],j=[],l={};b.$matrix={labels:i,pairs:j};f&&h.sort(function(m,r){return f(c[m],c[r])});for(var k=0;k<g;k++)for(var q=0;q<g;q++){var o=h[k],n=h[q];j.push(l[o+"."+n]={row:k,col:q,sourceNode:c[o],targetNode:c[n],linkValue:0})}for(k=0;k<g;k++){o=h[k];i.push(c[o],c[o])}for(k=0;k<d.length;k++){i=d[k];g=i.sourceNode.index;h=i.targetNode.index;
+i=i.linkValue;l[g+"."+h].linkValue+=i;b.directed||(l[h+"."+g].linkValue+=i)}}};
+pv.Layout.Bullet=function(){pv.Layout.call(this);var b=this,c=b.buildImplied,d=b.x=pv.Scale.linear(),f,g,h,i,j;this.buildImplied=function(l){c.call(this,j=l);f=l.orient;g=/^left|right$/.test(f);h=pv.ramp("#bbb","#eee").domain(0,Math.max(1,j.ranges.length-1));i=pv.ramp("steelblue","lightsteelblue").domain(0,Math.max(1,j.measures.length-1))};(this.range=new pv.Mark).data(function(){return j.ranges}).reverse(true).left(function(){return f=="left"?0:null}).top(function(){return f=="top"?0:null}).right(function(){return f==
+"right"?0:null}).bottom(function(){return f=="bottom"?0:null}).width(function(l){return g?d(l):null}).height(function(l){return g?null:d(l)}).fillStyle(function(){return h(this.index)}).antialias(false).parent=b;(this.measure=new pv.Mark).extend(this.range).data(function(){return j.measures}).left(function(){return f=="left"?0:g?null:this.parent.width()/3.25}).top(function(){return f=="top"?0:g?this.parent.height()/3.25:null}).right(function(){return f=="right"?0:g?null:this.parent.width()/3.25}).bottom(function(){return f==
+"bottom"?0:g?this.parent.height()/3.25:null}).fillStyle(function(){return i(this.index)}).parent=b;(this.marker=new pv.Mark).data(function(){return j.markers}).left(function(l){return f=="left"?d(l):g?null:this.parent.width()/2}).top(function(l){return f=="top"?d(l):g?this.parent.height()/2:null}).right(function(l){return f=="right"?d(l):null}).bottom(function(l){return f=="bottom"?d(l):null}).strokeStyle("black").shape("bar").angle(function(){return g?0:Math.PI/2}).parent=b;(this.tick=new pv.Mark).data(function(){return d.ticks(7)}).left(function(l){return f==
+"left"?d(l):null}).top(function(l){return f=="top"?d(l):null}).right(function(l){return f=="right"?d(l):g?null:-6}).bottom(function(l){return f=="bottom"?d(l):g?-8:null}).height(function(){return g?6:null}).width(function(){return g?null:6}).parent=b};pv.Layout.Bullet.prototype=pv.extend(pv.Layout).property("orient",String).property("ranges").property("markers").property("measures").property("maximum",Number);pv.Layout.Bullet.prototype.defaults=(new pv.Layout.Bullet).extend(pv.Layout.prototype.defaults).orient("left").ranges([]).markers([]).measures([]);
+pv.Layout.Bullet.prototype.buildImplied=function(b){pv.Layout.prototype.buildImplied.call(this,b);var c=this.parent[/^left|right$/.test(b.orient)?"width":"height"]();b.maximum=b.maximum||pv.max([].concat(b.ranges,b.markers,b.measures));this.x.domain(0,b.maximum).range(0,c)};pv.Behavior={};
+pv.Behavior.drag=function(){function b(l){g=this.index;f=this.scene;var k=this.mouse();i=((h=l).fix=pv.vector(l.x,l.y)).minus(k);j={x:this.parent.width()-(l.dx||0),y:this.parent.height()-(l.dy||0)};f.mark.context(f,g,function(){this.render()});pv.Mark.dispatch("dragstart",f,g)}function c(){if(f){f.mark.context(f,g,function(){var l=this.mouse();h.x=h.fix.x=Math.max(0,Math.min(i.x+l.x,j.x));h.y=h.fix.y=Math.max(0,Math.min(i.y+l.y,j.y));this.render()});pv.Mark.dispatch("drag",f,g)}}function d(){if(f){h.fix=
+null;f.mark.context(f,g,function(){this.render()});pv.Mark.dispatch("dragend",f,g);f=null}}var f,g,h,i,j;pv.listen(window,"mousemove",c);pv.listen(window,"mouseup",d);return b};
+pv.Behavior.point=function(b){function c(k,q){k=k[q];q={cost:Infinity};for(var o=0,n=k.visible&&k.children.length;o<n;o++){var m=k.children[o],r=m.mark,s;if(r.type=="panel"){r.scene=m;for(var u=0,x=m.length;u<x;u++){r.index=u;s=c(m,u);if(s.cost<q.cost)q=s}delete r.scene;delete r.index}else if(r.$handlers.point){r=r.mouse();u=0;for(x=m.length;u<x;u++){var t=m[u];s=r.x-t.left-(t.width||0)/2;t=r.y-t.top-(t.height||0)/2;var p=i*s*s+j*t*t;if(p<q.cost){q.distance=s*s+t*t;q.cost=p;q.scene=m;q.index=u}}}}return q}
+function d(){var k=c(this.scene,this.index);if(k.cost==Infinity||k.distance>l)k=null;if(g){if(k&&g.scene==k.scene&&g.index==k.index)return;pv.Mark.dispatch("unpoint",g.scene,g.index)}if(g=k){pv.Mark.dispatch("point",k.scene,k.index);pv.listen(this.root.canvas(),"mouseout",f)}}function f(k){if(g&&!pv.ancestor(this,k.relatedTarget)){pv.Mark.dispatch("unpoint",g.scene,g.index);g=null}}var g,h=null,i=1,j=1,l=arguments.length?b*b:900;d.collapse=function(k){if(arguments.length){h=String(k);switch(h){case "y":i=
+1;j=0;break;case "x":i=0;j=1;break;default:j=i=1;break}return d}return h};return d};
+pv.Behavior.select=function(){function b(j){g=this.index;f=this.scene;i=this.mouse();h=j;h.x=i.x;h.y=i.y;h.dx=h.dy=0;pv.Mark.dispatch("selectstart",f,g)}function c(){if(f){f.mark.context(f,g,function(){var j=this.mouse();h.x=Math.max(0,Math.min(i.x,j.x));h.y=Math.max(0,Math.min(i.y,j.y));h.dx=Math.min(this.width(),Math.max(j.x,i.x))-h.x;h.dy=Math.min(this.height(),Math.max(j.y,i.y))-h.y;this.render()});pv.Mark.dispatch("select",f,g)}}function d(){if(f){pv.Mark.dispatch("selectend",f,g);f=null}}var f,
+g,h,i;pv.listen(window,"mousemove",c);pv.listen(window,"mouseup",d);return b};
+pv.Behavior.resize=function(b){function c(l){h=this.index;g=this.scene;j=this.mouse();i=l;switch(b){case "left":j.x=i.x+i.dx;break;case "right":j.x=i.x;break;case "top":j.y=i.y+i.dy;break;case "bottom":j.y=i.y;break}pv.Mark.dispatch("resizestart",g,h)}function d(){if(g){g.mark.context(g,h,function(){var l=this.mouse();i.x=Math.max(0,Math.min(j.x,l.x));i.y=Math.max(0,Math.min(j.y,l.y));i.dx=Math.min(this.parent.width(),Math.max(l.x,j.x))-i.x;i.dy=Math.min(this.parent.height(),Math.max(l.y,j.y))-i.y;
+this.render()});pv.Mark.dispatch("resize",g,h)}}function f(){if(g){pv.Mark.dispatch("resizeend",g,h);g=null}}var g,h,i,j;pv.listen(window,"mousemove",d);pv.listen(window,"mouseup",f);return c};
+pv.Behavior.pan=function(){function b(){g=this.index;f=this.scene;i=pv.vector(pv.event.pageX,pv.event.pageY);h=this.transform();j=1/(h.k*this.scale);if(l)l={x:(1-h.k)*this.width(),y:(1-h.k)*this.height()}}function c(){if(f){f.mark.context(f,g,function(){var k=h.translate((pv.event.pageX-i.x)*j,(pv.event.pageY-i.y)*j);if(l){k.x=Math.max(l.x,Math.min(0,k.x));k.y=Math.max(l.y,Math.min(0,k.y))}this.transform(k).render()});pv.Mark.dispatch("pan",f,g)}}function d(){f=null}var f,g,h,i,j,l;b.bound=function(k){if(arguments.length){l=
+Boolean(k);return this}return Boolean(l)};pv.listen(window,"mousemove",c);pv.listen(window,"mouseup",d);return b};
+pv.Behavior.zoom=function(b){function c(){var f=this.mouse(),g=pv.event.wheel*b;f=this.transform().translate(f.x,f.y).scale(g<0?1E3/(1E3-g):(1E3+g)/1E3).translate(-f.x,-f.y);if(d){f.k=Math.max(1,f.k);f.x=Math.max((1-f.k)*this.width(),Math.min(0,f.x));f.y=Math.max((1-f.k)*this.height(),Math.min(0,f.y))}this.transform(f).render();pv.Mark.dispatch("zoom",this.scene,this.index)}var d;arguments.length||(b=1/48);c.bound=function(f){if(arguments.length){d=Boolean(f);return this}return Boolean(d)};return c};
+pv.Geo=function(){};
+pv.Geo.projections={mercator:{project:function(b){return{x:b.lng/180,y:b.lat>85?1:b.lat<-85?-1:Math.log(Math.tan(Math.PI/4+pv.radians(b.lat)/2))/Math.PI}},invert:function(b){return{lng:b.x*180,lat:pv.degrees(2*Math.atan(Math.exp(b.y*Math.PI))-Math.PI/2)}}},"gall-peters":{project:function(b){return{x:b.lng/180,y:Math.sin(pv.radians(b.lat))}},invert:function(b){return{lng:b.x*180,lat:pv.degrees(Math.asin(b.y))}}},sinusoidal:{project:function(b){return{x:pv.radians(b.lng)*Math.cos(pv.radians(b.lat))/Math.PI,
+y:b.lat/90}},invert:function(b){return{lng:pv.degrees(b.x*Math.PI/Math.cos(b.y*Math.PI/2)),lat:b.y*90}}},aitoff:{project:function(b){var c=pv.radians(b.lng);b=pv.radians(b.lat);var d=Math.acos(Math.cos(b)*Math.cos(c/2));return{x:2*(d?Math.cos(b)*Math.sin(c/2)*d/Math.sin(d):0)/Math.PI,y:2*(d?Math.sin(b)*d/Math.sin(d):0)/Math.PI}},invert:function(b){var c=b.y*Math.PI/2;return{lng:pv.degrees(b.x*Math.PI/2/Math.cos(c)),lat:pv.degrees(c)}}},hammer:{project:function(b){var c=pv.radians(b.lng);b=pv.radians(b.lat);
+var d=Math.sqrt(1+Math.cos(b)*Math.cos(c/2));return{x:2*Math.SQRT2*Math.cos(b)*Math.sin(c/2)/d/3,y:Math.SQRT2*Math.sin(b)/d/1.5}},invert:function(b){var c=b.x*3;b=b.y*1.5;var d=Math.sqrt(1-c*c/16-b*b/4);return{lng:pv.degrees(2*Math.atan2(d*c,2*(2*d*d-1))),lat:pv.degrees(Math.asin(d*b))}}},identity:{project:function(b){return{x:b.lng/180,y:b.lat/90}},invert:function(b){return{lng:b.x*180,lat:b.y*90}}}};
+pv.Geo.scale=function(b){function c(m){if(!o||m.lng!=o.lng||m.lat!=o.lat){o=m;m=d(m);n={x:l(m.x),y:k(m.y)}}return n}function d(m){return j.project({lng:m.lng-q.lng,lat:m.lat})}function f(m){m=j.invert(m);m.lng+=q.lng;return m}var g={x:0,y:0},h={x:1,y:1},i=[],j=pv.Geo.projections.identity,l=pv.Scale.linear(-1,1).range(0,1),k=pv.Scale.linear(-1,1).range(1,0),q={lng:0,lat:0},o,n;c.x=function(m){return c(m).x};c.y=function(m){return c(m).y};c.ticks={lng:function(m){var r;if(i.length>1){var s=pv.Scale.linear();
+if(m==undefined)m=10;r=s.domain(i,function(u){return u.lat}).ticks(m);m=s.domain(i,function(u){return u.lng}).ticks(m)}else{r=pv.range(-80,81,10);m=pv.range(-180,181,10)}return m.map(function(u){return r.map(function(x){return{lat:x,lng:u}})})},lat:function(m){return pv.transpose(c.ticks.lng(m))}};c.invert=function(m){return f({x:l.invert(m.x),y:k.invert(m.y)})};c.domain=function(m,r){if(arguments.length){i=m instanceof Array?arguments.length>1?pv.map(m,r):m:Array.prototype.slice.call(arguments);
+if(i.length>1){var s=i.map(function(x){return x.lng}),u=i.map(function(x){return x.lat});q={lng:(pv.max(s)+pv.min(s))/2,lat:(pv.max(u)+pv.min(u))/2};s=i.map(d);l.domain(s,function(x){return x.x});k.domain(s,function(x){return x.y})}else{q={lng:0,lat:0};l.domain(-1,1);k.domain(-1,1)}o=null;return this}return i};c.range=function(m,r){if(arguments.length){if(typeof m=="object"){g={x:Number(m.x),y:Number(m.y)};h={x:Number(r.x),y:Number(r.y)}}else{g={x:0,y:0};h={x:Number(m),y:Number(r)}}l.range(g.x,h.x);
+k.range(h.y,g.y);o=null;return this}return[g,h]};c.projection=function(m){if(arguments.length){j=typeof m=="string"?pv.Geo.projections[m]||pv.Geo.projections.identity:m;return this.domain(i)}return m};c.by=function(m){function r(){return c(m.apply(this,arguments))}for(var s in c)r[s]=c[s];return r};arguments.length&&c.projection(b);return c};
diff --git a/src/allmydata/web/root.py b/src/allmydata/web/root.py
index 3af15d9..14a83e4 100644
--- a/src/allmydata/web/root.py
+++ b/src/allmydata/web/root.py
@@ -164,6 +164,12 @@ class Root(rend.Page):
         self.child_named = FileHandler(client)
         self.child_status = status.Status(client.get_history())
         self.child_statistics = status.Statistics(client.stats_provider)
+        def f(name):
+            return nevow_File(resource_filename('allmydata.web', name))
+        self.putChild("jquery.js", f("jquery.js"))
+        self.putChild("download_status_timeline.js", f("download_status_timeline.js"))
+        self.putChild("protovis-r3.2.js", f("protovis-r3.2.js"))
+        self.putChild("protovis-d3.2.js", f("protovis-d3.2.js"))
 
     def child_helper_status(self, ctx):
         # the Helper isn't attached until after the Tub starts, so this child
diff --git a/src/allmydata/web/status.py b/src/allmydata/web/status.py
index 9f96f1d..6c785e1 100644
--- a/src/allmydata/web/status.py
+++ b/src/allmydata/web/status.py
@@ -331,6 +331,18 @@ class DownloadResultsRendererMixin(RateAndTimeMixin):
         d.addCallback(_render)
         return d
 
+def tfmt(when):
+    #return when * 1000.0 # stupid JS timestamps
+    return "%.6f" % when
+    # the timeline markers represent UTC. To make these events line up, we
+    # must supply the "Z" suffix.
+    #return "%.2f" % (1000*when)
+    t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(when))
+    fract = "%.6f" % (when % 1.0)
+    if fract.startswith("0."):
+        fract = fract[2:]
+    return t+"."+fract+"Z"
+
 class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
     docFactory = getxmlfile("download-status.xhtml")
 
@@ -338,14 +350,17 @@ class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
         rend.Page.__init__(self, data)
         self.download_status = data
 
+    def child_timeline(self, ctx):
+        return DownloadStatusTimelinePage(self.download_status)
+
     def download_results(self):
         return defer.maybeDeferred(self.download_status.get_results)
 
     def relative_time(self, t):
         if t is None:
             return t
-        if self.download_status.started is not None:
-            return t - self.download_status.started
+        if self.download_status.first_timestamp is not None:
+            return t - self.download_status.first_timestamp
         return t
     def short_relative_time(self, t):
         t = self.relative_time(t)
@@ -353,32 +368,159 @@ class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
             return ""
         return "+%.6fs" % t
 
-    def renderHTTP(self, ctx):
+    def OFFrenderHTTP(self, ctx):
         req = inevow.IRequest(ctx)
         t = get_arg(req, "t")
         if t == "json":
             return self.json(req)
         return rend.Page.renderHTTP(self, ctx)
 
-    def json(self, req):
-        req.setHeader("content-type", "text/plain")
-        data = {}
-        dyhb_events = []
-        for serverid,requests in self.download_status.dyhb_requests.iteritems():
-            for req in requests:
-                dyhb_events.append( (base32.b2a(serverid),) + req )
-        dyhb_events.sort(key=lambda req: req[1])
-        data["dyhb"] = dyhb_events
-        request_events = []
-        for serverid,requests in self.download_status.requests.iteritems():
-            for req in requests:
-                request_events.append( (base32.b2a(serverid),) + req )
-        request_events.sort(key=lambda req: (req[4],req[1]))
-        data["requests"] = request_events
-        data["segment"] = self.download_status.segment_events
-        data["read"] = self.download_status.read_events
+    def _find_overlap(self, events, start_key, end_key):
+        # given a list of event dicts, return a new list in which each event
+        # has an extra "row" key (an int, starting at 0). This is a hint to
+        # our JS frontend about how to overlap the parts of the graph it is
+        # drawing.
+
+        # we must always make a copy, since we're going to be adding "row"
+        # keys and don't want to change the original objects. If we're
+        # stringifying serverids, we'll also be changing the serverid keys.
+        new_events = []
+        rows = []
+        for ev in events:
+            ev = ev.copy()
+            if "serverid" in ev:
+                ev["serverid"] = base32.b2a(ev["serverid"])
+            # find an empty slot in the rows
+            free_slot = None
+            for row,finished in enumerate(rows):
+                if finished is not None:
+                    if ev[start_key] > finished:
+                        free_slot = row
+                        break
+            if free_slot is None:
+                free_slot = len(rows)
+                rows.append(ev[end_key])
+            else:
+                rows[free_slot] = ev[end_key]
+            ev["row"] = free_slot
+            new_events.append(ev)
+        return new_events
+
+    def _find_overlap_requests(self, events):
+        """We compute a three-element 'row tuple' for each event: (serverid,
+        shnum, row). All elements are ints. The first is a mapping from
+        serverid to group number, the second is a mapping from shnum to
+        subgroup number. The third is a row within the subgroup.
+
+        We also return a list of lists of rowcounts, so renderers can decide
+        how much vertical space to give to each row.
+        """
+
+        serverid_to_group = {}
+        serverid_and_shnum_to_subgroup = {}
+        groupnum_to_rows = {} # maps groupnum to a table of rows. Each table
+                              # is a list with an element for each row number
+                              # (int starting from 0) that contains a
+                              # finish_time, indicating that the row is empty
+                              # beyond that time. If finish_time is None, it
+                              # indicate a response that has not yet
+                              # completed, so the row cannot be reused.
+        new_events = []
+        for ev in events:
+            # DownloadStatus promises to give us events in temporal order
+            ev = ev.copy()
+            ev["serverid"] = base32.b2a(ev["serverid"])
+            if ev["serverid"] not in serverid_to_group:
+                groupnum = len(serverid_to_group)
+                serverid_to_group[ev["serverid"]] = groupnum
+            groupnum = serverid_to_group[ev["serverid"]]
+            if groupnum not in groupnum_to_rows:
+                groupnum_to_rows[groupnum] = []
+            rows = groupnum_to_rows[groupnum]
+            # find an empty slot in the rows
+            free_slot = None
+            for row,finished in enumerate(rows):
+                if finished is not None:
+                    if ev["start_time"] > finished:
+                        free_slot = row
+                        break
+            if free_slot is None:
+                free_slot = len(rows)
+                rows.append(ev["finish_time"])
+            else:
+                rows[free_slot] = ev["finish_time"]
+            ev["row"] = (groupnum, free_slot)
+            new_events.append(ev)
+        # maybe also return serverid_to_group, groupnum_to_rows, and some
+        # indication of the highest finish_time
+        #
+        # actually, return the highest rownum for each groupnum
+        highest_rownums = [len(groupnum_to_rows[groupnum])
+                           for groupnum in range(len(serverid_to_group))]
+        return new_events, highest_rownums
+
+    def child_timeline_parameters(self, ctx):
+        ds = self.download_status
+        d = { "start": tfmt(ds.started),
+              "end": tfmt(ds.started+2.0),
+              }
+        return simplejson.dumps(d, indent=1) + "\n"
+
+    def child_event_json(self, ctx):
+        inevow.IRequest(ctx).setHeader("content-type", "text/plain")
+        data = { } # this will be returned to the GET
+        ds = self.download_status
+
+        data["misc"] = self._find_overlap(ds.misc_events,
+                                          "start_time", "finish_time")
+        data["read"] = self._find_overlap(ds.read_events,
+                                          "start_time", "finish_time")
+        data["segment"] = self._find_overlap(ds.segment_events,
+                                             "start_time", "finish_time")
+        # TODO: overlap on DYHB isn't very useful, and usually gets in the
+        # way. So don't do it.
+        data["dyhb"] = self._find_overlap(ds.dyhb_requests,
+                                          "start_time", "finish_time")
+        data["block"],data["block_rownums"] = self._find_overlap_requests(ds.block_requests)
+
+        servernums = {}
+        serverid_strings = {}
+        for d_ev in data["dyhb"]:
+            if d_ev["serverid"] not in servernums:
+                servernum = len(servernums)
+                servernums[d_ev["serverid"]] = servernum
+                #title= "%s: %s" % ( ",".join([str(shnum) for shnum in shnums]))
+                serverid_strings[servernum] = d_ev["serverid"][:4]
+        data["server_info"] = dict([(serverid, {"num": servernums[serverid],
+                                                "color": self.color(base32.a2b(serverid)),
+                                                "short": serverid_strings[servernums[serverid]],
+                                                })
+                                   for serverid in servernums.keys()])
+        data["num_serverids"] = len(serverid_strings)
+        # we'd prefer the keys of serverids[] to be ints, but this is JSON,
+        # so they get converted to strings. Stupid javascript.
+        data["serverids"] = serverid_strings
+        data["bounds"] = {"min": ds.first_timestamp,
+                          "max": ds.last_timestamp,
+                          }
+        # for testing
+        ## data["bounds"]["max"] = tfmt(max([d_ev["finish_time"]
+        ##                                   for d_ev in data["dyhb"]
+        ##                                   if d_ev["finish_time"] is not None]
+        ##                                  ))
         return simplejson.dumps(data, indent=1) + "\n"
 
+    def render_timeline_link(self, ctx, data):
+        from nevow import url
+        return T.a(href=url.URL.fromContext(ctx).child("timeline"))["timeline"]
+
+    def _rate_and_time(self, bytes, seconds):
+        time_s = self.render_time(None, seconds)
+        if seconds != 0:
+            rate = self.render_rate(None, 1.0 * bytes / seconds)
+            return T.span(title=rate)[time_s]
+        return T.span[time_s]
+
     def render_events(self, ctx, data):
         if not self.download_status.storage_index:
             return
@@ -388,13 +530,11 @@ class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
         t = T.table(class_="status-download-events")
         t[T.tr[T.td["serverid"], T.td["sent"], T.td["received"],
                T.td["shnums"], T.td["RTT"]]]
-        dyhb_events = []
-        for serverid,requests in self.download_status.dyhb_requests.iteritems():
-            for req in requests:
-                dyhb_events.append( (serverid,) + req )
-        dyhb_events.sort(key=lambda req: req[1])
-        for d_ev in dyhb_events:
-            (serverid, sent, shnums, received) = d_ev
+        for d_ev in self.download_status.dyhb_requests:
+            serverid = d_ev["serverid"]
+            sent = d_ev["start_time"]
+            shnums = d_ev["response_shnums"]
+            received = d_ev["finish_time"]
             serverid_s = idlib.shortnodeid_b2a(serverid)
             rtt = None
             if received is not None:
@@ -413,67 +553,74 @@ class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
                T.td["time"], T.td["decrypttime"], T.td["pausedtime"],
                T.td["speed"]]]
         for r_ev in self.download_status.read_events:
-            (start, length, requesttime, finishtime, bytes, decrypt, paused) = r_ev
-            if finishtime is not None:
-                rtt = finishtime - requesttime - paused
+            start = r_ev["start"]
+            length = r_ev["length"]
+            bytes = r_ev["bytes_returned"]
+            decrypt_time = ""
+            if bytes:
+                decrypt_time = self._rate_and_time(bytes, r_ev["decrypt_time"])
+            speed, rtt = "",""
+            if r_ev["finish_time"] is not None:
+                rtt = r_ev["finish_time"] - r_ev["start_time"] - r_ev["paused_time"]
                 speed = self.render_rate(None, compute_rate(bytes, rtt))
                 rtt = self.render_time(None, rtt)
-                decrypt = self.render_time(None, decrypt)
-                paused = self.render_time(None, paused)
-            else:
-                speed, rtt, decrypt, paused = "","","",""
+            paused = self.render_time(None, r_ev["paused_time"])
+
             t[T.tr[T.td["[%d:+%d]" % (start, length)],
-                   T.td[srt(requesttime)], T.td[srt(finishtime)],
-                   T.td[bytes], T.td[rtt], T.td[decrypt], T.td[paused],
+                   T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
+                   T.td[bytes], T.td[rtt],
+                   T.td[decrypt_time], T.td[paused],
                    T.td[speed],
                    ]]
         l["Read Events:", t]
 
         t = T.table(class_="status-download-events")
-        t[T.tr[T.td["type"], T.td["segnum"], T.td["when"], T.td["range"],
+        t[T.tr[T.td["segnum"], T.td["start"], T.td["active"], T.td["finish"],
+               T.td["range"],
                T.td["decodetime"], T.td["segtime"], T.td["speed"]]]
-        reqtime = (None, None)
         for s_ev in self.download_status.segment_events:
-            (etype, segnum, when, segstart, seglen, decodetime) = s_ev
-            if etype == "request":
-                t[T.tr[T.td["request"], T.td["seg%d" % segnum],
-                       T.td[srt(when)]]]
-                reqtime = (segnum, when)
-            elif etype == "delivery":
-                if reqtime[0] == segnum:
-                    segtime = when - reqtime[1]
+            range_s = ""
+            segtime_s = ""
+            speed = ""
+            decode_time = ""
+            if s_ev["finish_time"] is not None:
+                if s_ev["success"]:
+                    segtime = s_ev["finish_time"] - s_ev["active_time"]
+                    segtime_s = self.render_time(None, segtime)
+                    seglen = s_ev["segment_length"]
+                    range_s = "[%d:+%d]" % (s_ev["segment_start"], seglen)
                     speed = self.render_rate(None, compute_rate(seglen, segtime))
-                    segtime = self.render_time(None, segtime)
+                    decode_time = self._rate_and_time(seglen, s_ev["decode_time"])
                 else:
-                    segtime, speed = "", ""
-                t[T.tr[T.td["delivery"], T.td["seg%d" % segnum],
-                       T.td[srt(when)],
-                       T.td["[%d:+%d]" % (segstart, seglen)],
-                       T.td[self.render_time(None,decodetime)],
-                       T.td[segtime], T.td[speed]]]
-            elif etype == "error":
-                t[T.tr[T.td["error"], T.td["seg%d" % segnum]]]
+                    # error
+                    range_s = "error"
+            else:
+                # not finished yet
+                pass
+
+            t[T.tr[T.td["seg%d" % s_ev["segment_number"]],
+                   T.td[srt(s_ev["start_time"])],
+                   T.td[srt(s_ev["active_time"])],
+                   T.td[srt(s_ev["finish_time"])],
+                   T.td[range_s],
+                   T.td[decode_time],
+                   T.td[segtime_s], T.td[speed]]]
         l["Segment Events:", t]
 
         t = T.table(border="1")
         t[T.tr[T.td["serverid"], T.td["shnum"], T.td["range"],
-               T.td["txtime"], T.td["rxtime"], T.td["received"], T.td["RTT"]]]
-        reqtime = (None, None)
-        request_events = []
-        for serverid,requests in self.download_status.requests.iteritems():
-            for req in requests:
-                request_events.append( (serverid,) + req )
-        request_events.sort(key=lambda req: (req[4],req[1]))
-        for r_ev in request_events:
-            (peerid, shnum, start, length, sent, receivedlen, received) = r_ev
+               T.td["txtime"], T.td["rxtime"],
+               T.td["received"], T.td["RTT"]]]
+        for r_ev in self.download_status.block_requests:
             rtt = None
-            if received is not None:
-                rtt = received - sent
-            peerid_s = idlib.shortnodeid_b2a(peerid)
-            t[T.tr(style="background: %s" % self.color(peerid))[
-                T.td[peerid_s], T.td[shnum],
-                T.td["[%d:+%d]" % (start, length)],
-                T.td[srt(sent)], T.td[srt(received)], T.td[receivedlen],
+            if r_ev["finish_time"] is not None:
+                rtt = r_ev["finish_time"] - r_ev["start_time"]
+            serverid_s = idlib.shortnodeid_b2a(r_ev["serverid"])
+            t[T.tr(style="background: %s" % self.color(r_ev["serverid"]))[
+                T.td[serverid_s], T.td[r_ev["shnum"]],
+                T.td["[%d:+%d]" % (r_ev["start"], r_ev["length"])],
+                T.td[srt(r_ev["start_time"])], T.td[srt(r_ev["finish_time"])],
+                T.td[r_ev["response_length"] or ""],
                 T.td[self.render_time(None, rtt)],
                 ]]
         l["Requests:", t]
@@ -524,6 +671,39 @@ class DownloadStatusPage(DownloadResultsRendererMixin, rend.Page):
     def render_status(self, ctx, data):
         return data.get_status()
 
+class DownloadStatusTimelinePage(rend.Page):
+    docFactory = getxmlfile("download-status-timeline.xhtml")
+
+    def render_started(self, ctx, data):
+        TIME_FORMAT = "%H:%M:%S %d-%b-%Y"
+        started_s = time.strftime(TIME_FORMAT,
+                                  time.localtime(data.get_started()))
+        return started_s + " (%s)" % data.get_started()
+
+    def render_si(self, ctx, data):
+        si_s = base32.b2a_or_none(data.get_storage_index())
+        if si_s is None:
+            si_s = "(None)"
+        return si_s
+
+    def render_helper(self, ctx, data):
+        return {True: "Yes",
+                False: "No"}[data.using_helper()]
+
+    def render_total_size(self, ctx, data):
+        size = data.get_size()
+        if size is None:
+            return "(unknown)"
+        return size
+
+    def render_progress(self, ctx, data):
+        progress = data.get_progress()
+        # TODO: make an ascii-art bar
+        return "%.1f%%" % (100.0 * progress)
+
+    def render_status(self, ctx, data):
+        return data.get_status()
+
 class RetrieveStatusPage(rend.Page, RateAndTimeMixin):
     docFactory = getxmlfile("retrieve-status.xhtml")
 
diff --git a/viz-notes.org b/viz-notes.org
new file mode 100644
index 0000000..1ae033d
--- /dev/null
+++ b/viz-notes.org
@@ -0,0 +1,25 @@
+
+* layout
+** read() requests
+   - possibly overlapping: code should find minimum number of rows
+** segment events (request/delivery/error)
+   - also possibly overlapping, use minimum rows
+   - might be nice to show which is active at any given time
+** DYHB queries+responses
+   - completely overlapping, use exactly one row per server
+** server block-read requests (send/receive/error)
+   - use one cluster per server
+   - lots of overlapping reads
+   - within a cluster, use lowest available row
+   - 3-tuple Y axis: (serverid, shnum, overlaps)
+** ideally, tahoe should serve raw data and let JS do the sorting
+   - but my JS is not that good
+   - maybe just provide a hint: include a row number in each event, which
+     tells you how to overlap them
+   - multiple parts, joined with "-", use as JS dict keys
+
+* a graph that shows Y=segment-offset, X=start/finish time
+
+* a scatter plot that shows segnum-tree-height versus finish-start
+  - a local download showed segments that needed a lot of hash nodes taking
+    way more time than others
