diff --git a/CHANGES.md b/CHANGES.md
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -5,24 +5,274 @@
  \ V  V /  __/ |_) |
   \_/\_/ \___|_.__/
 
-Breaking changes
+Item order: security fixes first, then breaking changes, then the rest.
+Section headings: "Security" first if any, then "Breaking changes"
+if any; then topic headings,
+or a suitable generic heading (eg Fixes, Improvements), as needed.
 
-Fixes
+-->
 
-Features
+User-visible changes in hledger-web.
+See also the hledger changelog.
 
-Improvements
 
-Docs
+# 2.0 2026-12-01
 
-API
+All changes since hledger-web 1.52.4.
+For the 1.99.x preview releases, and 2.0's changes since the last of them (1.99.6),
+see <https://hledger.org/relnotes199.html>.
+See also the hledger changelog, for changes affecting all the hledger tools
+(lot tracking, commodity aliases, new queries, translations, faster starts and reloads, etc.)
 
--->
+## Highlights
 
-User-visible changes in hledger-web.
-See also the hledger changelog.
+The most notable changes since hledger-web 1.52; each is described below.
 
+- More reports (balance sheet, income statement, cashflow, holdings and more), with options, and new charts. (Reports)
+- Paged journal and register views. (Reports)
+- A dark mode, and a tidier look. (Appearance)
+- Keyboard navigation, like hledger-ui's. (Navigation and keys)
+- Translations. (Translations)
+- Security hardening. (Security)
+- Changes that would make the journal unreadable are refused. (Fixes)
+- Less javascript. (Other improvements)
 
+## Security
+
+- hledger-web now sends a Content-Security-Policy header with every page.
+  This tells your browser to load scripts, styles, images and fonts only from hledger-web itself,
+  and to run only hledger-web's own scripts; so if anything script-like ever reached a page,
+  eg through data in your journal, the browser would refuse to run it.
+  In normal use you should notice no difference.
+  (Arthur Cinader, [#2703])
+
+- hledger-web now sends the `X-Frame-Options: SAMEORIGIN` and `X-Content-Type-Options: nosniff` security headers
+  on every response, so other sites can't frame its pages for clickjacking, and browsers won't second-guess content types.
+  (Arthur Cinader)
+
+- Nothing is loaded from third parties any more; two dead third-party script tags, and the unused (always disabled)
+  Google Analytics hook, have been removed.
+  (Arthur Cinader)
+
+- (The XSS and include-injection fixes of 1.52.2 and 1.52.3 are of course included.)
+
+## Breaking changes
+
+- When listening on a non-local address (set with `--host`), hledger-web now allows only read-only access by default.
+  Add `--allow=add` or `--allow=edit` to allow changes.
+
+- Startup options and query arguments now set up the opening page, as url parameters,
+  instead of acting as invisible server-side defaults and filters.
+  So every view is described by its url, and a shared link shows the same view to everyone.
+  But a startup query no longer restricts what hledger-web serves:
+  it becomes the first page's search, which a viewer can edit or clear, and the JSON API serves the whole journal.
+  To serve a restricted view, serve a restricted file.
+  (Arthur Cinader)
+
+- Pages are now shown in the viewer's language, when a translation is available (see Translations below).
+  `--lang en` keeps hledger-web in English.
+
+- Some keyboard shortcuts have changed, to match hledger-ui (see Navigation and keys below).
+
+- In JSON output, postings' `ptype` field is renamed to `preal`.
+
+- `--tldr` is renamed to `--examples` (see the hledger changelog).
+
+## Fixes
+
+- The add form, JSON API (PUT /add), edit and upload now refuse a change which would make the journal unreadable.
+  They check it as the next read (with hledger-web's startup options) would, and on failure leave the file unchanged.
+  Eg /add can no longer add unbalanced transactions, the add form now checks balance assertions,
+  and edit and upload now respect `--strict` and `-I`.
+  ([#2864], [#2869])
+
+- hledger-web no longer exits prematurely when its page is in a background browser tab
+  (browsers may run background tabs' timers much less often).
+  Now it exits 15 minutes after its last page is closed (was 2 minutes), and a page pings as soon as it is foregrounded again.
+  And when a page can't reach the server, it shows a notice saying hledger-web is no longer running and how to continue,
+  instead of failing silently on the next click.
+  (Arthur Cinader, [#2722])
+
+- The register now shows the to/from account names when restricted by a `type:` query, instead of blank cells.
+  (Arthur Cinader)
+
+- The upload form now shows the name of the chosen file.
+  (Arthur Cinader)
+
+- /favicon.ico and /robots.txt no longer return 404 when hledger-web is run outside its source directory.
+  robots.txt now also asks crawlers not to index the site.
+  (Arthur Cinader)
+
+- Browsers now check for updated scripts and styles, so they don't keep using old ones after an upgrade.
+
+## Reports
+
+- hledger's balance, balance sheet, income statement, cashflow and holdings reports are now available in hledger-web.
+  Every amount links to the register it is derived from, column headings link to the report for that period,
+  and a "Report:" row links the report pages to one another.
+  The balance sheet has Equity as an option, and the balance report is called All accounts, as in hledger-ui.
+  The holdings report is for journals using lots; in tree mode, accounts are heading rows with subtotals,
+  and lots fold beneath their holdings. When its report period has a start date, it shows the gains during that period.
+  It can also show a report interval, like `holdings -M`, with a Gains option choosing what the gain columns cover.
+  Gains and losses are shown in green or red, and the `z` key shows or hides closed positions.
+  (Henning Thielemann, Arthur Cinader, Simon Michael)
+
+- hledger-web now opens on the balance sheet, rather than the journal,
+  and with a default report interval, chosen to suit the period shown (monthly for up to two years, quarterly for up to six, otherwise yearly).
+  Pages show depth 1 by default: just the top-level accounts, so that tables and charts start simple and readable.
+  `-` and `+` steps and a List/Tree switch beside a table's Account heading make deeper accounts easy to reach.
+
+- The report pages have an Options panel, offering most of hledger's report options and filters
+  (report interval, changes or end balances, depth, valuation, lots etc.), so reports can be reshaped in the browser.
+  The options are kept as you move between pages, and every view has a shareable url.
+  (Arthur Cinader, Simon Michael)
+
+- Reports show a chart at the top, drawn by hledger's new chart engine (see the hledger changelog).
+  The Chart and Data buttons, or the `c` and `d` keys, show or hide the chart and the data (persistently),
+  so you can use hledger-web with either or both visible.
+  When there's more than one commodity, `[` and `]` step between their charts.
+  Charts are redrawn to fit when the page's width changes, and show their tooltips immediately, also on touch screens.
+  This replaces the old register chart; jQuery and Flot are no longer used.
+  (Simon Michael, Arthur Cinader, [#2800], [#2784])
+
+- The Chart option chooses the Diverging (default) or Grouped layout, and the `N` key shows or hides the net total line.
+  The `--chart` startup option accepts the same values as the commands' `--chart`: a layout, `net`, and SCALE amounts.
+
+- The sidebar now always lists the full account tree, for navigation, whatever the search.
+  It has its own persistent depth, starting at 1, adjustable with the fold carets, its `-` and `+` controls, or a shift-DIGIT key.
+  Its balances are now hidden by default, making pages with a large journal about twice as fast, and smaller;
+  clicking the Balances heading, or pressing the `b` key, toggles them.
+  They are now historical balances, as of the report's end date (previously, the changes during the search's period).
+  A button shows or hides the sidebar, on all screen sizes.
+
+- The journal and register views are now paged, showing the newest 1000 matching transactions and page navigation links.
+  When the matches span more than one year, a years row links to each year (grouped by decade when there are more than twenty).
+  Account links from a transaction open the account register at the appropriate page.
+  (Arthur Cinader, [#586])
+
+- The register can start from the balance brought forward (`accum=historical`), so its running balance is the account's balance
+  rather than a total of the transactions shown. The oldest row shows the brought-forward balance, and links to the earlier transactions.
+  A running balance of many commodities shows just the row's own commodities, eliding the others.
+  (Arthur Cinader, [#2784])
+
+- Tree mode now folds items at the requested depth, and you can click individual items to expand them.
+  Boring parent accounts are squashed, and the depth limit corresponds to account depth, as on the command line.
+  In list mode, account names show their parent path dimmed, and a prefix shared by all the accounts is shown once.
+  (Arthur Cinader, Simon Michael)
+
+- Links in the journal, register and sidebar now behave consistently: an account name opens its view,
+  an amount opens the register it comes from, and a date narrows to that day.
+  The sidebar's amounts are now links, and its Journal link keeps the current search.
+  (Arthur Cinader)
+
+- Report urls are simpler, and queries and parameters are used more consistently,
+  eg `/register?account=assets:bank` or `interval=monthly`. Old bookmarks still work.
+  (Simon Michael, Henning Thielemann)
+
+- Search supports hledger's new query types: `::` (`find:`), `change:` and `balance:`, and `amt:` with a commodity symbol.
+  The search help is updated. (See the hledger changelog.)
+
+- Percentages that can't be calculated now show plain amounts with an explanation, instead of an error page.
+  (Arthur Cinader)
+
+## Appearance
+
+- hledger-web now has a dark mode, enabled automatically when the browser or system is in dark mode.
+  (Arthur Cinader, [#2706])
+
+- The journal and register tables have been tidied up: digits in amounts are shown with equal width, so numbers line up neatly
+  in a column; column headers are small and muted; and the zebra striping is replaced by a faint highlight on the row under the pointer.
+  Amounts and their commodity symbol no longer break across lines.
+  (Arthur Cinader, [#2718])
+
+- Transaction tooltips, shown when hovering over a transaction in the journal or a register, are now drawn in a fixed-width font,
+  so amounts and comments line up as in the journal; long lines wrap, and the tooltip stays within the window.
+  (Arthur Cinader, [#2716])
+
+- The sidebar keeps its scroll position when you click an account or navigate, and on wider screens
+  the sidebar and the main content scroll independently. A long or multi-commodity balance no longer covers its account name.
+  Pages keep their scroll position too.
+  (Arthur Cinader, [#2679])
+
+- Journal and register headings name the search's dates, like other pages.
+
+- hledger-web now has its own favicon: a gold coin struck with an equals sign.
+  (Arthur Cinader)
+
+## Navigation and keys
+
+- Navigation links are now also shown at the top of the page, so you can navigate with the sidebar closed.
+  (Arthur Cinader)
+
+- `g` then a key goes to another page, via a dropdown menu, so you can navigate to most places with the keyboard.
+
+- Keyboard shortcuts for adjusting report options are provided, similar to hledger-ui's.
+  (Arthur Cinader, Simon Michael)
+
+- `a` (open the add form) now works on all pages. `f` toggles full window mode, showing only the report.
+  `/` puts the cursor at the end of the search field. `escape` exits the search field or full window mode, in addition to cancelling things.
+  `delete` and `backspace` clear the search, as in hledger-ui.
+
+- `n` and `p` go to the next and previous page; `n` no longer opens the add form (use `a` for that).
+
+- Keyboard focus is managed better; after a page load or a search, keyboard scrolling and shortcuts work
+  without having to click the page first.
+
+- The help popup has been cleaned up, and links to hledger-web's manual on the website.
+  (Arthur Cinader, Simon Michael)
+
+## Translations
+
+- hledger-web can be shown in 12 languages (see the hledger changelog).
+  The language is chosen by a `_LANG` query parameter (which saves a browser cookie), a previously saved cookie,
+  or the browser's Accept-Language header; or it can be fixed at startup with the `--lang` option.
+  See the manual's LANGUAGE section.
+  (Arthur Cinader)
+
+## Other improvements
+
+- `--port 0` lets the OS choose a free port. The chosen port is reported in the startup message and used in the default base url,
+  so scripts can discover it. This works in the default `--serve-browse` mode too.
+  (Arthur Cinader, [#2559])
+
+- hledger-webs running at different ports on one host remember their own report and display options.
+  (Simon Michael, Arthur Cinader)
+
+- Changes to CSV rules files now trigger a reload, like changes to data files.
+
+- The web UI's javascript has been modernised, replacing all the vendored libraries (jQuery, Bootstrap's scripts, Flot and others)
+  with standard browser features: autocomplete suggestions use a native `<datalist>`,
+  the button beside the date field opens the browser's own date picker (typed smart dates like "today" still work),
+  and the add and help dialogs use the native `<dialog>` element. Pages load much less javascript.
+  (Arthur Cinader, [#2702])
+
+- The `-?` and `--webman` flags are added (see the hledger changelog).
+
+- hledger-web now requires wai-app-static >=3.1.9 and yesod-form >=1.4.12, and no longer depends on lucid ([#2737]).
+  megaparsec 9.8.0 is excluded, to avoid a position marker bug in error messages
+  ([megaparsec#572](https://github.com/mrkkrp/megaparsec/issues/572)).
+
+## Docs
+
+- The manual has new WEB UI, REPORTS, URL PARAMETERS and LANGUAGE sections, an updated JSON API section,
+  and says `--allow=edit` / `--allow=add` instead of the old "capability" terms.
+
+[#586]: https://github.com/hledgerorg/hledger/issues/586
+[#2559]: https://github.com/hledgerorg/hledger/issues/2559
+[#2679]: https://github.com/hledgerorg/hledger/issues/2679
+[#2702]: https://github.com/hledgerorg/hledger/issues/2702
+[#2703]: https://github.com/hledgerorg/hledger/issues/2703
+[#2706]: https://github.com/hledgerorg/hledger/issues/2706
+[#2716]: https://github.com/hledgerorg/hledger/issues/2716
+[#2718]: https://github.com/hledgerorg/hledger/issues/2718
+[#2722]: https://github.com/hledgerorg/hledger/issues/2722
+[#2737]: https://github.com/hledgerorg/hledger/issues/2737
+[#2784]: https://github.com/hledgerorg/hledger/issues/2784
+[#2800]: https://github.com/hledgerorg/hledger/issues/2800
+[#2864]: https://github.com/hledgerorg/hledger/issues/2864
+[#2869]: https://github.com/hledgerorg/hledger/issues/2869
+
+
 # 1.52.4 2026-09-10
 
 Fixes
@@ -71,8 +321,8 @@
   tree, now use aeson 2.3, avoiding a denial of service bug.
   (<https://haskell.github.io/security-advisories/advisory/HSEC-2026-0007.html>)
 
-[#2700]: https://github.com/simonmichael/hledger/issues/2700
-[#2704]: https://github.com/simonmichael/hledger/issues/2704
+[#2700]: https://github.com/hledgerorg/hledger/issues/2700
+[#2704]: https://github.com/hledgerorg/hledger/issues/2704
 
 # 1.52.2 2026-08-24
 
@@ -116,7 +366,7 @@
 - openapi.yaml (the OpenAPI spec for hledger-web's JSON API) has been updated.
   (n0vdd)
 
-[#2544]: https://github.com/simonmichael/hledger/issues/2544
+[#2544]: https://github.com/hledgerorg/hledger/issues/2544
 
 
 # 1.51.2 2026-01-08
@@ -125,7 +375,7 @@
 
 - Allow base 4.22 / ghc 9.14.
 
-[#2520]: https://github.com/simonmichael/hledger/issues/2520
+[#2520]: https://github.com/hledgerorg/hledger/issues/2520
 
 
 # 1.51.1 2025-12-08
@@ -133,16 +383,16 @@
 - Uses hledger 1.51.1.
 
 
-# 1.51 2025-12-05
+# 1.50.5 2025-12-08
 
-Improvements
+- Uses hledger 1.50.5.
 
-- Uses hledger 1.51.
 
+# 1.51 2025-12-05
 
-# 1.50.5 2025-12-08
+Improvements
 
-- Uses hledger 1.50.5.
+- Uses hledger 1.51.
 
 
 # 1.50.4 2025-12-04
@@ -325,7 +575,7 @@
   This is also applicable to `hledger print`'s JSON output format.
 
 [ghc-debug]: https://gitlab.haskell.org/ghc/ghc-debug
-[openapi.yaml]: https://github.com/simonmichael/hledger/blob/master/hledger-web/config/openapi.yaml
+[openapi.yaml]: https://github.com/hledgerorg/hledger/blob/master/hledger-web/config/openapi.yaml
 [tldr]: https://tldr.sh
 
 
@@ -361,9 +611,9 @@
   the non-display of costs,
   and non-zeros that look like zero because of hidden costs.
 
-[#2140]: https://github.com/simonmichael/hledger/issues/2140
-[#2163]: https://github.com/simonmichael/hledger/issues/2163
-[#2166]: https://github.com/simonmichael/hledger/issues/2166
+[#2140]: https://github.com/hledgerorg/hledger/issues/2140
+[#2163]: https://github.com/hledgerorg/hledger/issues/2163
+[#2166]: https://github.com/hledgerorg/hledger/issues/2166
 
 # 1.32.3 2024-01-28
 
@@ -541,20 +791,20 @@
 Fixes
 
 - Toggle showing zero items properly even when called with --empty. 
-  ([#1237](https://github.com/simonmichael/hledger/issues/1237), Stephen Morgan)
+  ([#1237](https://github.com/hledgerorg/hledger/issues/1237), Stephen Morgan)
 
 - Do not hide empty accounts if they have non-empty subaccounts. 
-  ([#1237](https://github.com/simonmichael/hledger/issues/1237), Stephen Morgan)
+  ([#1237](https://github.com/hledgerorg/hledger/issues/1237), Stephen Morgan)
 
 - Allow unbalanced postings (parenthesised account name) in the add transaction form. 
-  ([#1058](https://github.com/simonmichael/hledger/issues/1058), Stephen Morgan)
+  ([#1058](https://github.com/hledgerorg/hledger/issues/1058), Stephen Morgan)
 
 - An XSS (cross-site scripting) vulnerability has been fixed.
   Previously (since hledger-web 0.24), javascript code could be added 
   to any autocompleteable field and could be executed automatically 
   by subsequent visitors viewing the journal.
   Thanks to Gaspard Baye and Hamidullah Muslih for reporting this vulnerability.
-  ([#1525](https://github.com/simonmichael/hledger/issues/1525), Arsen Arsenović)
+  ([#1525](https://github.com/hledgerorg/hledger/issues/1525), Arsen Arsenović)
 
 API changes
 
diff --git a/Hledger/Web/App.hs b/Hledger/Web/App.hs
--- a/Hledger/Web/App.hs
+++ b/Hledger/Web/App.hs
@@ -10,41 +10,65 @@
 {-# LANGUAGE MultiParamTypeClasses #-}
 {-# LANGUAGE NamedFieldPuns        #-}
 {-# LANGUAGE OverloadedStrings     #-}
+{-# LANGUAGE PackageImports        #-}
 {-# LANGUAGE QuasiQuotes           #-}
 {-# LANGUAGE TemplateHaskell       #-}
+{-# LANGUAGE TupleSections         #-}
 {-# LANGUAGE TypeFamilies          #-}
 {-# LANGUAGE ViewPatterns          #-}
 
 module Hledger.Web.App where
 
 import Control.Applicative ((<|>))
-import Control.Monad (join, when, unless)
+import Control.Monad (join, mfilter, unless, void, when)
 -- import Control.Monad.Except (runExceptT)  -- now re-exported by Hledger
+import "base64-bytestring" Data.ByteString.Base64 qualified as B64  -- not base64's module of the same name
 import Data.ByteString.Char8 qualified as BC
+import Data.Foldable (for_)
+import Data.Map qualified as M
 import Data.Traversable (for)
 import Data.IORef (IORef, readIORef, writeIORef)
-import Data.Maybe (fromMaybe)
+import Data.Maybe (catMaybes, fromMaybe, isJust, listToMaybe)
 import Data.Text (Text)
 import Data.Text qualified as T
-import Data.Time.Calendar (Day)
+import Data.Text.Encoding qualified as TE
+import Data.Time.Calendar (Day, addDays)
+import Data.Time.Clock.POSIX (getPOSIXTime)
 import Network.HTTP.Conduit (Manager)
 import Network.HTTP.Types (status403)
-import Network.Wai (requestHeaders)
+import Network.Wai (rawPathInfo, rawQueryString, requestHeaders, requestMethod)
+import Safe (atMay, readMay)
 import System.Directory (XdgDirectory (..), createDirectoryIfMissing,
                          getXdgDirectory)
+import System.Entropy (getEntropy)
 import System.FilePath (takeFileName, (</>))
 import Text.Blaze (Markup)
 import Text.Hamlet (hamletFile)
 import Yesod
 import Yesod.Default.Config
+import Yesod.Form.I18n.Chinese (chineseFormMessage)
+import Yesod.Form.I18n.French (frenchFormMessage)
+import Yesod.Form.I18n.German (germanFormMessage)
+import Yesod.Form.I18n.Japanese (japaneseFormMessage)
+import Yesod.Form.I18n.Portuguese (portugueseFormMessage)
+import Yesod.Form.I18n.Russian (russianFormMessage)
+import Yesod.Form.I18n.Spanish (spanishFormMessage)
 
+import Hledger.Utils.I18n (Translations(..), i18n, langTagCandidates, resolveLang, tr, trc, trf)
 import Hledger
-import Hledger.Cli (CliOpts(..), journalReloadIfChanged)
-import Hledger.Web.Settings (Extra(..), widgetFile)
+import Hledger.Cli (CliOpts(..), journalCheckChange, journalPrepareLotDetail, journalReloadIfChanged, writeFileWithBackupIfChanged)
+import Hledger.Cli.Chart (ChartArg(..), chartArg)
+import Hledger.Cli.Commands.Balancesheet (balancesheetSpec)
+import Hledger.Cli.Commands.Cashflow (cashflowSpec)
+import Hledger.Cli.Commands.Incomestatement (incomestatementSpec)
+import Hledger.Cli.CompoundBalanceCommand (CompoundBalanceCommandSpec(..))
+import Hledger.Web.Param (Param(..), lookupParam)
+import Hledger.Web.ReportPage (AmountMode(..), accumParam, amountModeOf, calcParam, chartParam, deepestDepth, intervalPeriodExpr, listParam, parseValue, registerKeptParams, reportLinks, setAmountMode, sortParam)
+import Hledger.Web.Settings (Extra(..), webmanualurl, widgetFile)
 import Hledger.Web.Settings.StaticFiles
 import Hledger.Web.WebOptions
-import Hledger.Web.Widget.Common (balanceReportAsHtml)
-import Data.List (isPrefixOf)
+import Hledger.Web.Widget.Common (MovedOptions(..), accountParams, balanceReportAsHtml, normalisedSearch)
+import Data.List (findIndex, isPrefixOf)
 
 -- | The site argument for your application. This can be a good place to
 -- keep settings and values requiring initialization before your application
@@ -56,12 +80,39 @@
     , httpManager :: Manager
       --
     , appOpts    :: WebOpts
-    , appJournal :: IORef Journal
-        -- ^ the current journal, filtered by the initial command line query
-        --   but ignoring any depth limit.
+    , appJournal :: IORef JournalState
+        -- ^ the current journal and its derived forms, reloaded from
+        --   its files when they change.
+    , appTranslations :: M.Map Text Translations
+        -- ^ the translation catalogs available to viewers, by language tag
+        --   (built-in and from the user's config directory), loaded at startup.
     }
 
+-- | The shared journal state: the current journal as loaded, with any
+-- lot detail (lot subaccounts and synthetic postings) retained - the
+-- journal is always loaded with --lots forced on (see Main.hs) - plus
+-- forms derived from it once per (re)load.
+-- The collapsed forms are made lazily, on a page's first need for them.
+data JournalState = JournalState
+  { jsFull            :: Journal  -- ^ the journal as loaded, lot detail retained
+  , jsCollapsed       :: Journal  -- ^ the same with lot detail collapsed, as pages show by default
+  , jsCollapsedAtCost :: Journal  -- ^ collapsed after converting to cost basis, for pages at cost
+  , jsCollapsedGain   :: Journal  -- ^ collapsed after setting lot costs to their basis, for gains
+  , jsHasLots         :: Bool     -- ^ does the journal use lots at all ? (cached; it scans all postings)
+  }
 
+-- | Make the journal state for a newly (re)loaded journal.
+mkJournalState :: Journal -> JournalState
+mkJournalState j = JournalState
+  { jsFull            = j
+  , jsCollapsed       = collapse defreportopts
+  , jsCollapsedAtCost = collapse defreportopts{conversionop_ = Just ToCost}
+  , jsCollapsedGain   = collapse defreportopts{balancecalc_ = CalcGain}
+  , jsHasLots         = journalHasLotFeatures j
+  }
+  where collapse ropts = journalPrepareLotDetail ropts False j
+
+
 -- This is where we define all of the routes in our application. For a full
 -- explanation of the syntax, please see:
 -- http://www.yesodweb.com/book/handler
@@ -124,29 +175,146 @@
 
     master <- getYesod
     here <- fromMaybe RootR <$> getCurrentRoute
-    VD{opts, j, qparam, q, qopts, perms} <- getViewData
+    VD{opts, j, jHasLots, qparam, q, account, perms, trs} <- getViewData
     msg <- getMessage
+    -- Unless --lang fixes the language: an explicit ?_LANG= choice is
+    -- remembered in a cookie, which Yesod's languages reads on later
+    -- requests; only a tag naming an available catalog is accepted. And
+    -- since the page varies by language, say so for any cache in front of
+    -- a shared server.
+    unless (langFixed master) $ do
+      mlangparam <- lookupGetParam "_LANG"
+      for_ (mlangparam >>= \l -> resolveLang (M.keys $ appTranslations master) [l]) $ \l ->
+        addHeader "Set-Cookie" $ "_LANG=" <> l <> "; Path=/; Max-Age=31536000; SameSite=Lax"
+      addHeader "Vary" "Cookie, Accept-Language"
+    let lang = trLang trs
     showSidebar <- shouldShowSidebar
+    chartHidden <- (== Just "0") <$> uiCookie "showchart"
+    tableHidden <- (== Just "0") <$> uiCookie "showtable"
+    -- and the charts' total or net lines, hidden until chosen (the N key),
+    -- or with --chart=net, shown until chosen
+    let netAtFirst = caNet $ chartArg M.empty $ cliopts_ $ appOpts master
+    netShown <- maybe netAtFirst (== "1") <$> uiCookie "shownet"
+    -- and the sidebar's balances, hidden or shown by their heading:
+    -- hidden until chosen, since on a large journal they cost much of
+    -- each page's time
+    balancesHidden <- (/= Just "1") <$> uiCookie "showbalances"
+    -- The policy is sent from here rather than from a middleware, so that
+    -- the header and the page's script tags always carry the same nonce;
+    -- error pages come through here too, in a handler state of their own.
+    nonce <- liftIO newCspNonce
+    addHeader "Content-Security-Policy" $ cspHeader nonce
+    -- In browse mode the page pings the server while it is open (hledger.js);
+    -- the body attribute this sets is how the page knows to.
+    let browsemode = server_mode_ opts == ServeBrowse
 
+    -- The sidebar shows amounts the way the page does: converted as the
+    -- value parameter asks, with inferred market prices if asked.
+    mvalmode <- either (const Nothing) id . parseValue <$> lookupGetParam "value"
+    inferparam <- (== Just "1") <$> lookupGetParam "infer"
     let rspec = reportspec_ (cliopts_ opts)
-        ropts = _rsReportOpts rspec
-        ropts' = (_rsReportOpts rspec)
-          {accountlistmode_ = ALTree  -- force tree mode for sidebar
+        ropts' = maybe id setAmountMode mvalmode $ (_rsReportOpts rspec)
+          {accountlistmode_ = ALTree  -- always the account tree, with fold carets
           ,empty_           = True    -- show zero items by default
+          ,interval_        = NoInterval  -- one balance per account, over the search's own span
+          ,balanceaccum_    = Historical  -- the balance at the end of that span, not the change within it
+          ,infer_prices_    = infer_prices_ (_rsReportOpts rspec) || inferparam
+          ,no_elide_        = True    -- every level its own row, so the tree can fold at any level
           }
-        rspec' = rspec{_rsQuery=q,_rsReportOpts=ropts'}
+        -- The sidebar is always the whole account tree, every account,
+        -- whatever the search and the page's depth limit, so that it stays
+        -- the same to navigate by; it is folded in the browser to a depth
+        -- of its own, by its carets and its - and + buttons (the inline
+        -- script in default-layout.hamlet). Only the search's dates, by
+        -- their end, decide the date of its (historical) balances.
+        sidebarQ = filterQuery queryIsDateOrDate2 q
+        rspec' = rspec{_rsQuery=sidebarQ,_rsReportOpts=ropts'}
 
-    hideEmptyAccts <- if empty_ ropts
-                         then return True
-                         else (== Just "1") . lookup "hideemptyaccts" . reqCookies <$> getRequest
+    -- The parameters the search form and its clear button keep, so that
+    -- a search does not reset the page: a report page's interval, depth,
+    -- accumulation mode, and amount conversion, and the register's modes.
+    -- The accumulation mode is kept only when it is not the default, as
+    -- the pages' own links carry it.
+    let keepable :: Text -> Text -> Bool
+        keepable k v | k == paramName accumParam = v `elem` keptAccums here
+                     | otherwise                = not (T.null v)
+    keptParams <- fmap catMaybes . for (keptParamNames here) $ \name ->
+      fmap (name,) . mfilter (keepable name) <$> lookupGetParam name
 
-    let accounts =
-          balanceReportAsHtml (JournalR, RegisterR) here hideEmptyAccts j qparam qopts $
-          styleAmounts (journalCommodityStylesWith HardRounding j) $
-          balanceReport rspec' j
+    hideEmptyAccts <- hideEmptyAccounts
 
-        topShowmd = if showSidebar then "col-md-4" else "col-any-0" :: Text
-        topShowsm = if showSidebar then "col-sm-4" else "" :: Text
+    -- The sidebar's links keep the search, minus any account term,
+    -- which the reports ignore, and the sticky report state the page
+    -- keeps; the page-local parameters (accum, costs) stay behind.
+    let sidebarReports = reportLinkItems $ reportMenuFor jHasLots
+        sidebarParams =
+          [p | p@("interval", _) <- keptParams] ++
+          [("q", qparam) | not (T.null qparam)] ++
+          [p | p@(k, _) <- keptParams, k /= "interval", k `elem` stickyParamNames]
+        -- The pages g then a key goes to (hledger.js), with the sidebar
+        -- links' parameters.
+        goItems :: [(Text, (Route App, [(Text, Text)]), Text, Text)]
+        goItems = [ (rmGoKey i, (rmRoute i, sidebarParams), tr trs (rmLabel i), tr trs (rmTitle i)) | i <- reportMenuFor jHasLots ]
+        -- The pages the n and p keys go to (hledger.js): the next or
+        -- previous in the go menu's order, going round; from a page not in
+        -- the menu, the first or the last.
+        pageSteps :: [(Text, (Route App, [(Text, Text)]))]
+        pageSteps =
+          [ (key, (rmRoute i, sidebarParams))
+          | (key, step) <- [("n", 1), ("p", -1)]
+          , Just i <- [goStep step] ]
+        goMenu = reportMenuFor jHasLots
+        goStep step = atMay goMenu $ case findIndex ((== here) . rmRoute) goMenu of
+          Just i  -> (i + step) `mod` length goMenu
+          Nothing -> if step > 0 then 0 else length goMenu - 1
+        -- The links to the journal and reports at the top of every page,
+        -- above the search, with the sidebar links' parameters.
+        reportsRow = reportLinks trs here sidebarParams $ reportLinkItems $ reportMenuFor jHasLots
+        -- The sidebar's bottom row, the sum of every account, which shows
+        -- what is left unbalanced (more at balancing-the-accounting-equation.md).
+        (totlabel, tottitle) = case amountModeOf ropts' of
+            Just AtCost ->
+              (tr trs "Total at cost:",
+               tr trs "The sum of every account, converted to cost. Not zero when something is unbalanced.")
+            Just (AtVal _) ->
+              (tr trs "Total at value:",
+               tr trs "The sum of every account at market value. Not zero when values have changed and no entry records the gain or loss, eg unrealized investment gains.")
+            _ ->
+              (tr trs "Total:",
+               tr trs "The sum of every account. Not zero when something is unbalanced, eg conversions using @ without --infer-equity.")
+        -- The - and + buttons above the sidebar's accounts, which fold or
+        -- open a level of them, where there is more than one level.
+        sidebarStepper = deepestDepth j > 1
+        -- The date of the sidebar's balances, above its accounts: the last
+        -- day of its report's span, the search's dates or else the
+        -- journal's (none if the journal has no transactions).
+        balancesCaption =
+          -- TRANSLATORS: above the sidebar's accounts, the date of their balances (eg "Balances on 2024-12-31"), and its tooltip.
+          [ (trf trs "Balances on {date}" [("date", showDate d)],
+             tr trs "Each account's balance at the end of this day: the end of the search's dates, or else the journal's last date")
+          | Just e <- [balancesEnd], let d = addDays (-1) e ]
+        balancesEnd = spanEnd $ fst $ reportSpan j rspec'
+        accounts =
+          balanceReportAsHtml RegisterR here sidebarReports sidebarParams (registerKeptParams sidebarParams) hideEmptyAccts totlabel tottitle (listToMaybe balancesCaption) sidebarStepper (not balancesHidden) trs j qparam account
+            sidebarRows
+        -- Every account, declared or posted to, with its parents, in the
+        -- report's order, with its balance if they are shown (from the
+        -- balance report, which lists only those with postings by then;
+        -- none for the others), and their total. With the balances hidden,
+        -- the balance report is not run.
+        sidebarRows =
+          ( [ (a, accountLeafName a, accountNameLevel a - 1, M.findWithDefault nullmixedamt a bals)
+            | a <- sortAccountNamesByDeclaration j True $ expandAccountNames $ journalAccountNamesDeclaredOrImplied j ]
+          , total )
+          where
+            (bals, total)
+              | balancesHidden = (M.empty, nullmixedamt)
+              | otherwise =
+                  let (items, tot) = styleAmounts (journalCommodityStylesWith HardRounding j) $ balanceReport rspec' j
+                  in (M.fromList [(a, amt) | (a, _, _, amt) <- items], tot)
+
+        topShow = if showSidebar then "col-sm-4 col-md-4" else "sidebar-hidden" :: Text
+        sidebarExpanded = if showSidebar then "true" else "false" :: Text
         sideShowmd = if showSidebar then "col-md-4" else "col-any-0" :: Text
         sideShowsm = if showSidebar then "col-sm-4" else "" :: Text
         mainShowmd = if showSidebar then "col-md-8" else "col-md-12" :: Text
@@ -159,35 +327,97 @@
     -- you to use normal widget features in default-layout.
     pc <- widgetToPageContent $ do
       addStylesheet $ StaticR css_bootstrap_min_css
-      addStylesheet $ StaticR css_bootstrap_datepicker_standalone_min_css
-      -- load these things early, in HEAD:
-      toWidgetHead [hamlet|
-        <script type="text/javascript" src="@{StaticR js_jquery_min_js}">
-        <script type="text/javascript" src="@{StaticR js_typeahead_bundle_min_js}">
-      |]
-      addScript $ StaticR js_bootstrap_min_js
-      addScript $ StaticR js_bootstrap_datepicker_min_js
-      addScript $ StaticR js_jquery_url_js
-      addScript $ StaticR js_jquery_cookie_js
-      addScript $ StaticR js_jquery_hotkeys_js
-      addScript $ StaticR js_jquery_flot_min_js
-      addScript $ StaticR js_jquery_flot_selection_min_js
-      addScript $ StaticR js_jquery_flot_time_min_js
-      addScript $ StaticR js_jquery_flot_tooltip_min_js
-      toWidget [hamlet| \<!--[if lte IE 8]> <script type="text/javascript" src="@{StaticR js_excanvas_min_js}"></script> <![endif]--> |]
       addStylesheet $ StaticR hledger_css
       addScript $ StaticR hledger_js
       $(widgetFile "default-layout")
 
     withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
 
--- This instance is required to use forms. You can modify renderMessage to
--- achieve customized and internationalized form validation messages.
+----------------------------------------------------------------------
+-- translations
+
+-- | The translations for a viewer. When hledger-web was started with a
+-- --lang naming a language, that one, whatever the viewer asks for.
+-- Otherwise the first available one in the viewer's preferences (as listed
+-- by Yesod's 'languages': the _LANG query parameter, cookie and session
+-- variable, then the Accept-Language header), trying each preference with
+-- its subtags dropped before moving on to the next; falling back to English,
+-- or with --lang=auto, the language of hledger-web's environment.
+translationsFor :: App -> [Lang] -> Translations
+translationsFor app@App{appTranslations} langs
+  | langFixed app = servertrs
+  | otherwise = fromMaybe servertrs $ (`M.lookup` appTranslations) =<< resolveLang (M.keys appTranslations) langs
+  where servertrs = translations_ $ _rsReportOpts $ reportspec_ $ cliopts_ $ appOpts app
+
+-- | Was hledger-web started with a --lang naming a language, which then
+-- applies to every page? (--lang=auto leaves the choice to each viewer.)
+langFixed :: App -> Bool
+langFixed = maybe False (/= "auto") . maybestringopt "lang" . rawopts_ . cliopts_ . appOpts
+
+-- | The translations for the current request's language.
+requestTranslations :: Handler Translations
+requestTranslations = translationsFor <$> getYesod <*> languages
+
+-- | A translatable text, for @_{HMsg "..."}@ in templates and 'setMessageI'.
+newtype HMsg = HMsg Text
+
+instance RenderMessage App HMsg where
+  renderMessage app langs (HMsg s) = tr (translationsFor app langs) s
+
+-- | Like 'HMsg', with a context disambiguating a short text used in
+-- more than one sense, eg @_{HMsgc "column heading" "Total"}@.
+data HMsgc = HMsgc Text Text
+
+instance RenderMessage App HMsgc where
+  renderMessage app langs (HMsgc ctx s) = trc (translationsFor app langs) ctx s
+
+-- | yesod-form's validation messages, in the request's language when
+-- yesod-form ships that language.
 instance RenderMessage App FormMessage where
-    renderMessage _ _ = defaultFormMessage
+  renderMessage app langs = fromMaybe defaultFormMessage $ listToMaybe
+    [ m | c <- langTagCandidates (trLang $ translationsFor app langs), Just m <- [lookup c formMessages] ]
+    where
+      formMessages =
+        [ ("de",      germanFormMessage)
+        , ("es",      spanishFormMessage)
+        , ("fr",      frenchFormMessage)
+        , ("ja",      japaneseFormMessage)
+        , ("pt-BR",   portugueseFormMessage)
+        , ("ru",      russianFormMessage)
+        , ("zh-Hans", chineseFormMessage)
+        ]
 
 
 ----------------------------------------------------------------------
+-- content security policy
+
+-- | The Content-Security-Policy sent with every HTML page. Everything loads
+-- from our own origin, and the only inline scripts allowed are the ones
+-- carrying this response's nonce: the two in default-layout.hamlet and its
+-- wrapper. The templates have no inline styles or event handlers, and
+-- hledger.js sets its styles through the CSSOM, which the policy does not govern.
+-- frame-ancestors stops the pages being framed by another origin
+-- (clickjacking of the add and edit forms); the other responses get
+-- X-Frame-Options instead, see Application.hs.
+--
+-- 'self' assumes the static files come from our own origin. If --file-url
+-- (extraStaticRoot, #2139) is ever re-enabled, that origin has to be added
+-- to default-src as well, or every page will lose its styles and scripts.
+cspHeader :: Text -> Text
+cspHeader nonce = T.intercalate "; "
+  [ "default-src 'self'"
+  , "script-src 'self' 'nonce-" <> nonce <> "'"
+  , "object-src 'none'"
+  , "base-uri 'self'"
+  , "form-action 'self'"
+  , "frame-ancestors 'self'"
+  ]
+
+-- | A nonce for the policy above: 16 random bytes, base64 encoded.
+newCspNonce :: IO Text
+newCspNonce = TE.decodeUtf8 . B64.encode <$> getEntropy 16
+
+----------------------------------------------------------------------
 -- template and handler utilities
 
 -- view data, used by the add form and handlers
@@ -197,11 +427,23 @@
 data ViewData = VD
   { opts  :: WebOpts    -- ^ the command-line options at startup
   , today :: Day        -- ^ today's date (for queries containing relative dates)
-  , j     :: Journal    -- ^ the up-to-date parsed unfiltered journal    -- XXX rename
+  , j     :: Journal    -- ^ the up-to-date parsed unfiltered journal, as displayed:
+                        --   lot detail collapsed unless lotsShown    -- XXX rename
+  , jfull :: Journal    -- ^ the same journal with lot detail retained,
+                        --   for reports that aggregate lots themselves
+  , jHasLots :: Bool    -- ^ does the journal use lots at all ?
+  , lotsShown :: Bool   -- ^ is lot detail shown, by the lots=1 parameter ?
   , qparam :: Text       -- ^ the current "q" request parameter
-  , q     :: Query      -- ^ a query parsed from the q parameter
+  , q     :: Query      -- ^ a query parsed from the q parameter. A depth parameter's limit
+                        --   is also added hereas a Depth term, since the reports use it.
   , qopts :: [QueryOpt] -- ^ query options parsed from the q parameter
+  , account :: Maybe (AccountName, Bool)  -- ^ the account an account register is for, from the account
+                        --   parameter, and whether with its subaccounts (not with subs=0)
   , perms :: [Permission]  -- ^ permissions enabled for this request (by --allow and/or X-Sandstorm-Permissions)
+  , trs   :: Translations  -- ^ translations for this request's language
+  , hideEmpty :: Bool      -- ^ hide zero-balance accounts ? (the empty parameter, cf hideEmptyAccounts)
+  , controlsOpen :: Bool   -- ^ is the controls disclosure open ? (the showcontrols cookie)
+  , commoditiesOpen :: Bool -- ^ is the commodity filter's list open ? (the showcommodities cookie)
   } deriving (Show)
 
 instance Show Text.Blaze.Markup where show _ = "<blaze markup>"
@@ -210,28 +452,64 @@
 getViewData :: Handler ViewData
 getViewData = do
   App{
-    appOpts=opts@WebOpts{ cliopts_=copts@CliOpts{ reportspec_=rspec@ReportSpec{_rsReportOpts, _rsQuery} } },
+    appOpts=opts0@WebOpts{ cliopts_=copts@CliOpts{ reportspec_=rspec@ReportSpec{_rsReportOpts} } },
     appJournal
   } <- getYesod
+  -- With --debug, show each request's url as received
+  req <- waiRequest
+  dbg1IO "url" $ BC.unpack (rawPathInfo req) ++ BC.unpack (rawQueryString req)
   let today = _rsDay rspec
+  -- the request's language, applied to the options too so that any
+  -- report text rendered by hledger-lib matches the page
+  trs <- requestTranslations
+  let opts1 = opts0{cliopts_ = copts{reportspec_ = rspec{_rsReportOpts = _rsReportOpts{translations_ = trs}}}}
 
   -- try to read the latest journal content, keeping the old content
   -- if there's an error
-  (j, mjerr) <- getCurrentJournal
-                appJournal
-                copts{reportspec_=rspec{_rsReportOpts=_rsReportOpts{no_elide_=True}}}
-                today
+  (js, mjerr) <- getCurrentJournal appJournal (journalReadOpts copts) today
 
+  -- With lots=1, show lot detail (lot subaccounts and per-lot postings),
+  -- which is collapsed by default. Collapsed, a page at cost or showing
+  -- gains needs the lot postings' cost bases kept through the collapse:
+  -- the value and calc parameters say so (startup's options become url
+  -- parameters, see startupUrlState).
+  lotsShown <- (== Just "1") <$> lookupGetParam "lots"
+  mvalue <- either (const Nothing) id . parseValue <$> lookupGetParam "value"
+  gain <- (== Just CalcGain) <$> lookupParam calcParam
+  let jHasLots = jsHasLots js
+      jfull = jsFull js
+      atCost = conversionop_ (maybe id setAmountMode mvalue _rsReportOpts) == Just ToCost
+      j | lotsShown = jfull
+        | gain      = jsCollapsedGain js
+        | atCost    = jsCollapsedAtCost js
+        | otherwise = jsCollapsed js
+
   -- Get the query specified by the q request parameter, or no query if this fails.
   qparam <- fromMaybe "" <$> lookupGetParam "q"
-  (q1, qopts, mqerr) <- do
+  normaliseUrlState today qparam
+  -- The depth parameter's limit joins the parsed query, as a depth:N term
+  -- would, since the reports read depth limits from the query (as the
+  -- command line's --depth does); qparam, the search text that the search
+  -- box and links show, is left as it is. Without the parameter, the
+  -- depth is 1: the simplest charts, and a short list of accounts to
+  -- start from. depth=all is no limit.
+  mdepthparam <- lookupGetParam "depth"
+  let mdepth = case mdepthparam of
+        Just "all" -> Nothing
+        Just t     -> mfilter (>= 0) $ readMay $ T.unpack t
+        Nothing    -> Just 1
+  -- Its change:/balance: terms, if any, go to the report spec, which the reports apply them from.
+  (q, rowq, qopts, mqerr) <- do
     case parseQuery today qparam of
-      Right (q0, qopts) -> return (q0, qopts, Nothing)
-      Left err         -> return (Any, [], Just err)
-  -- To this, add any depth limit from the initial startup query, preserving that.
-  let
-    initialdepthq = filterQuery queryIsDepth _rsQuery
-    q = simplifyQuery $ And [q1, initialdepthq]
+      Right (q0, qopts) -> do
+        let (rowq, q1) = either (const (Any, q0)) id $ querySplitRowTerms q0  -- parseQuery has checked this succeeds
+        return (maybe q1 (\d -> simplifyQuery $ And [q1, Depth d]) mdepth, rowq, qopts, Nothing)
+      Left err         -> return (Any, Any, [], Just err)
+  let opts = opts1{cliopts_ = (cliopts_ opts1){reportspec_ = (reportspec_ $ cliopts_ opts1){_rsRowQuery = rowq}}}
+  subs <- (/= Just "0") <$> lookupGetParam "subs"
+  account <- fmap (, subs) . mfilter (not . T.null) <$> lookupGetParam "account"
+  dbg1IO "q parameter" qparam
+  dbg1IO "query" q
 
   -- if either of the above gave an error, display it
   maybe (pure ()) (setMessage . toHtml) $ mjerr <|> mqerr
@@ -248,8 +526,45 @@
     -- otherwise take them from the access level specified by --allow's access level
     cliaccess -> pure $ accessLevelToPermissions cliaccess
 
-  return VD{opts, today, j, qparam, q, qopts, perms}
+  -- the view preferences: zero balances hidden, and the disclosures' state
+  hideEmpty <- hideEmptyAccounts
+  controlsOpen <- showControls
+  commoditiesOpen <- showCommodities
 
+  return VD{opts, today, j, jfull, jHasLots, lotsShown, qparam, q, qopts, account, perms, trs, hideEmpty, controlsOpen, commoditiesOpen}
+
+-- | Move the report options in a page's search, and in the old period
+-- parameter, to their own parameters, by reloading the page: the search
+-- holds the terms selecting data, and the parameters, set by the
+-- controls, the report's shape. A depth:N term (typed, or from a link
+-- written before hledger-web had a depth parameter) becomes the depth
+-- parameter, a date:INTERVAL term's interval the interval parameter,
+-- leaving its date span in the search, where the old period parameter's
+-- span goes too, and an inacct: or inacctonly: term the account (and
+-- subs) parameters naming an account register's account. See
+-- normalisedSearch.
+normaliseUrlState :: Day -> Text -> Handler ()
+normaliseUrlState today qparam = do
+  isget <- (== "GET") . requestMethod <$> waiRequest
+  mroute <- getCurrentRoute
+  mperiod <- lookupGetParam "period"
+  case (isget, mroute, normalisedSearch today qparam (mfilter (not . T.null) mperiod)) of
+    (True, Just route, Just MovedOptions{moSearch, moDepth, moInterval, moAccount}) -> do
+      params <- reqGetParams <$> getRequest
+      let mivltext = intervalPeriodExpr =<< moInterval
+          -- the holdings page's interval is its own
+          ivlparam = if route == HoldingsR then "hinterval" else "interval"
+          replaced = ["q", "period"] ++ ["depth" | isJust moDepth] ++ [ivlparam | isJust mivltext]
+                     ++ concat [["account", "subs"] | isJust moAccount]
+          params' =
+            [("q", moSearch) | not (T.null moSearch)] ++
+            maybe [] (\(a, subs) -> accountParams subs a) moAccount ++
+            [p | p@(k, _) <- params, k `notElem` replaced] ++
+            [(ivlparam, w) | Just w <- [mivltext]] ++
+            [("depth", T.pack (show n)) | Just n <- [moDepth]]
+      redirect (route, params')
+    _ -> return ()
+
 checkServerSideUiEnabled :: Handler ()
 checkServerSideUiEnabled = do
   VD{opts=WebOpts{server_mode_}} <- getViewData
@@ -258,34 +573,182 @@
     --  permissionDenied "server-side UI is disabled due to --serve-api"
     sendResponseStatus status403 ("server-side UI is disabled due to --serve-api" :: Text)
 
+-- | A page as the menus show it: the journal, or a report page.
+data ReportMenuItem = ReportMenuItem {
+    rmRoute     :: Route App,
+    rmLabel     :: Text,
+    rmTitle     :: Text,
+    rmAccum     :: Maybe BalanceAccumulation,
+      -- ^ a report page's default accumulation mode: its command's own for
+      --   a statement, balance changes for the balance report, gains since
+      --   acquisition for holdings (with a report interval); the journal,
+      --   not a report page, has none
+    rmGoKey     :: Text
+      -- ^ the key that goes to it after g (hledger.js); not translated,
+      --   like the other keys
+}
+
+-- | The pages, in menu order, as in the sidebar and the row of report links:
+-- the journal, the named reports, then All accounts.
+reportMenu :: [ReportMenuItem]
+reportMenu =
+  -- TRANSLATORS: the report links above each report page and in the sidebar: each link's text, and its tooltip.
+  [ ReportMenuItem JournalR            (i18n "Journal")                   (i18n "Show general journal entries, most recent first")     Nothing                                  "j"
+  , ReportMenuItem BalancesheetR       (i18n "Balance sheet")             (i18n "Show assets, liabilities, and net worth")             (Just $ cbcaccum balancesheetSpec)       "b"
+  , ReportMenuItem IncomestatementR    (i18n "Income statement")          (i18n "Show revenues and expenses")                          (Just $ cbcaccum incomestatementSpec)    "i"
+  , ReportMenuItem CashflowR           (i18n "Cashflow statement")        (i18n "Show changes in liquid assets")                       (Just $ cbcaccum cashflowSpec)           "c"
+  , ReportMenuItem HoldingsR           (i18n "Holdings")                  (i18n "Show investment holdings, lots, and gains")           (Just Historical)                        "h"
+  , ReportMenuItem BalanceR            (i18n "All accounts")              (i18n "Show the balances of all accounts, by period, like the balance command") (Just PerPeriod) "a"
+  ]
+
+-- | The pages that apply to this journal: a journal with no lot features
+-- gets no Holdings page.
+reportMenuFor :: Bool -> [ReportMenuItem]
+reportMenuFor hasLots = [i | i <- reportMenu, hasLots || rmRoute i /= HoldingsR]
+
+-- | The pages' routes, labels, and titles, for a row of links.
+reportLinkItems :: [ReportMenuItem] -> [(Route App, Text, Text)]
+reportLinkItems items = [(rmRoute i, rmLabel i, rmTitle i) | i <- items]
+
+-- | The report pages: those that take a period and an accumulation mode.
+reportRoutes :: [Route App]
+reportRoutes = [rmRoute i | i <- reportMenu, isJust (rmAccum i)]
+
+-- | The accum parameter values a page's links keep: the modes that are
+-- not the page's default. (The register totals the period by default.)
+keptAccums :: Route App -> [Text]
+keptAccums route =
+  case [dflt | i <- reportMenu, rmRoute i == route, Just dflt <- [rmAccum i]] of
+    [dflt]                 -> [paramWord accumParam a | a <- paramModes accumParam, a /= dflt]
+    _ | route == RegisterR -> ["historical"]
+    _                      -> []
+
+-- | The query parameters a page's own links keep: the sticky report
+-- state, which every page shows and preserves even where it shapes
+-- nothing (the journal is the landing page, and the url hledger-web
+-- opens for its startup options), plus the page-local parameters, the
+-- accumulation mode (each page has its own default) and the register's
+-- account and costs.
+keptParamNames :: Route App -> [Text]
+keptParamNames route
+  | route == HoldingsR        = "closed" : paramName accumParam : stickyParamNames
+  | route `elem` reportRoutes = paramName accumParam : stickyParamNames
+  | route == RegisterR        = "account" : "subs" : paramName accumParam : "costs" : stickyParamNames
+  | route == JournalR         = stickyParamNames
+  | otherwise                 = []
+
+-- | The report-state parameters every page preserves: a link changes
+-- only the control it names. date2 has no control, being deprecated,
+-- but is preserved like the rest.
+stickyParamNames :: [Text]
+stickyParamNames = ["interval", "hinterval", "depth", "value", paramName listParam, "total", "avg", paramName sortParam, "pct", paramName calcParam, "infer", "date2", "empty", "lots", paramName chartParam]
+
+-- | Are zero-balance accounts hidden ? The empty parameter says (1
+-- shows them, 0 hides them, the direction of the command line's
+-- -E/--empty); without one, they are hidden when hledger-web was
+-- started with -E, and shown otherwise.
+hideEmptyAccounts :: Handler Bool
+hideEmptyAccounts = do
+  App{appOpts} <- getYesod
+  memptyp <- lookupGetParam "empty"
+  return $ case memptyp of
+    Just "0" -> True
+    Just "1" -> False
+    _        -> empty_ $ _rsReportOpts $ reportspec_ $ cliopts_ appOpts
+
 -- | Find out if the sidebar should be visible. Show it, unless there is a
 -- showsidebar cookie set to "0", or a ?sidebar=0 query parameter.
 shouldShowSidebar :: Handler Bool
 shouldShowSidebar = do
   msidebarparam <- lookupGetParam "sidebar"
-  msidebarcookie <- lookup "showsidebar" . reqCookies <$> getRequest
+  msidebarcookie <- uiCookie "showsidebar"
   return $
     let disablevalues = ["","0"]
     in maybe True (`notElem` disablevalues) $ msidebarparam <|> msidebarcookie
 
+-- | Is the report controls disclosure open? Only when the showcontrols
+-- cookie, which the browser sets when it is toggled (hledger.js), says
+-- so. Read server side, so each page is born the way the last one was
+-- left and nothing moves after paint.
+showControls :: Handler Bool
+showControls = (== Just "1") <$> uiCookie "showcontrols"
+
+-- | Is the commodity filter's collapsed list open? Like showControls,
+-- via the showcommodities cookie.
+showCommodities :: Handler Bool
+showCommodities = (== Just "1") <$> uiCookie "showcommodities"
+
+-- | One of the cookies in which the browser remembers this hledger-web's
+-- UI state (set by hledger.js, or by setUiCookie). A browser shares cookies between all servers on
+-- a host, whatever their port, so their names end with the port (see
+-- uiCookieSuffix), keeping several hledger-webs' states apart.
+-- Cookies, because the server renders this state; full window mode, which
+-- it needn't know, is kept in the browser's session storage instead.
+uiCookie :: Text -> Handler (Maybe Text)
+uiCookie name = do
+  App{appOpts} <- getYesod
+  lookup (name <> uiCookieSuffix appOpts) . reqCookies <$> getRequest
+
+-- | Have the browser remember some UI state in one of this hledger-web's
+-- cookies (see uiCookie), as hledger.js's setCookie does.
+setUiCookie :: Text -> Text -> Handler ()
+setUiCookie name val = do
+  App{appOpts} <- getYesod
+  addHeader "Set-Cookie" $
+    name <> uiCookieSuffix appOpts <> "=" <> val <> "; Path=/; Max-Age=31536000; SameSite=Lax"
+
+-- | The end of this hledger-web's UI cookie names, also given to the
+-- page's script (default-layout-wrapper.hamlet).
+uiCookieSuffix :: WebOpts -> Text
+uiCookieSuffix wopts = "_" <> T.pack (show $ port_ wopts)
+
 -- | Update our copy of the journal if the file changed. If there is an
 -- error while reloading, keep the old one and return the error, and set a
 -- ui message.
-getCurrentJournal :: IORef Journal -> CliOpts -> Day -> Handler (Journal, Maybe String)
+getCurrentJournal :: IORef JournalState -> CliOpts -> Day -> Handler (JournalState, Maybe String)
 getCurrentJournal jref opts d = do
-  -- re-apply any initial filter specified at startup
-  let depthlessinitialq = filterQuery (not . queryIsDepth) $ _rsQuery $ reportspec_ opts
   -- XXX put this inside atomicModifyIORef' for thread safety
-  j <- liftIO (readIORef jref)
-  ej <- liftIO . runExceptT $ journalReloadIfChanged opts d j
+  js <- liftIO (readIORef jref)
+  ej <- liftIO . runExceptT $ journalReloadIfChanged opts d (jsFull js)
   case ej of
     Left e -> do
       setMessage "error while reading journal"
-      return (j, Just e)
+      return (js, Just e)
     Right (j', True) -> do
-      liftIO . writeIORef jref $ filterJournalTransactions depthlessinitialq j'
-      return (j',Nothing)
-    Right (_, False) -> return (j, Nothing)
+      let js' = mkJournalState j'
+      liftIO $ writeIORef jref js'
+      return (js', Nothing)
+    Right (_, False) -> return (js, Nothing)
+
+-- | The options the journal is read and reloaded with: the startup options, with amounts not elided.
+journalReadOpts :: CliOpts -> CliOpts
+journalReadOpts copts@CliOpts{reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}} =
+  copts{reportspec_=rspec{_rsReportOpts=ropts{no_elide_=True}}}
+
+-- | Write a change to one of the journal's files, only if the journal would still be readable after it.
+-- First the change is checked by re-reading the journal with the file's new text supplied from memory,
+-- with the options the journal is reloaded with (see 'journalCheckChange'), so it gets exactly the checks
+-- the next read would make (balancing, assertions, lots, strict checks..), in the context of all the files.
+-- If that read fails, nothing is written and its error is returned.
+-- Otherwise the write action is run (it should write that text, eg by appending), and the journal just read
+-- becomes the current one, marked as read after the write, so the next request need not read it again.
+checkedJournalWrite :: FilePath -> Text -> IO () -> Handler (Either String ())
+checkedJournalWrite f newtxt write = do
+  App{appOpts=WebOpts{cliopts_=copts}, appJournal} <- getYesod
+  ej <- liftIO . runExceptT $ journalCheckChange (journalReadOpts copts) f newtxt
+  for ej $ \j -> liftIO $ do
+    write
+    t <- getPOSIXTime
+    writeIORef appJournal $ mkJournalState $ journalSetLastReadTime t j
+
+-- | Replace the text of one of the journal's files (eg from the edit or upload form),
+-- if the journal would still be readable afterward (see 'checkedJournalWrite').
+-- Line endings are normalised to \n first, as form data has \r\n and the reader and
+-- writeFileWithBackupIfChanged need \n (cf formatdirectivep, #1194).
+-- The file is written (with a backup) only if its text has changed.
+writeJournalFileChecked :: FilePath -> Text -> Handler (Either String ())
+writeJournalFileChecked f t = checkedJournalWrite f t' (void $ writeFileWithBackupIfChanged f t')
+  where t' = T.replace "\r" "" t
 
 -- | In a request handler, check for the given permission
 -- and fail with a message if it's not present.
diff --git a/Hledger/Web/Application.hs b/Hledger/Web/Application.hs
--- a/Hledger/Web/Application.hs
+++ b/Hledger/Web/Application.hs
@@ -15,12 +15,14 @@
   ) where
 
 import Data.IORef (newIORef, writeIORef)
+import Network.Wai.Middleware.AddHeaders (addHeaders)
 import Network.Wai.Middleware.RequestLogger (logStdoutDev, logStdout)
 import Network.HTTP.Client (defaultManagerSettings)
 import Network.HTTP.Conduit (newManager)
 import Yesod.Default.Config
 
 import Hledger.Data (Journal, nulljournal)
+import Hledger.Utils.I18n (loadAllTranslations)
 
 import Hledger.Web.Handler.AddR
 import Hledger.Web.Handler.MiscR
@@ -28,6 +30,9 @@
 import Hledger.Web.Handler.UploadR
 import Hledger.Web.Handler.JournalR
 import Hledger.Web.Handler.RegisterR
+import Hledger.Web.Handler.BalanceR
+import Hledger.Web.Handler.HoldingsR
+import Hledger.Web.Handler.StatementsR
 import Hledger.Web.Import
 import Hledger.Web.WebOptions (ServerMode(..), WebOpts(server_mode_), corsPolicy)
 
@@ -43,12 +48,23 @@
 makeApplication :: WebOpts -> Journal -> AppConfig DefaultEnv Extra -> IO Application
 makeApplication opts' j' conf' = do
     app <- makeApp conf' opts'
-    writeIORef (appJournal app) j'
-    (logWare . (corsPolicy opts')) <$> toWaiApp app
+    writeIORef (appJournal app) (mkJournalState j')
+    (logWare . corsPolicy opts' . securityHeaders) <$> toWaiApp app
   where
     logWare | development  = logStdoutDev
             | server_mode_ opts' `elem` [Serve, ServeJson] = logStdout
             | otherwise    = id
+    -- Headers for every response, at the WAI level so that error pages and
+    -- the static subsite get them too. X-Content-Type-Options stops the
+    -- browser guessing a content type other than the one we send;
+    -- X-Frame-Options stops any response being framed from another origin.
+    -- HTML pages also carry a Content-Security-Policy (cspHeader in App.hs),
+    -- whose frame-ancestors says the same thing and takes precedence in
+    -- browsers that understand it; this covers everything else.
+    securityHeaders = addHeaders
+      [ ("X-Content-Type-Options", "nosniff")
+      , ("X-Frame-Options", "SAMEORIGIN")
+      ]
 
 makeApp :: AppConfig DefaultEnv Extra -> WebOpts -> IO App
 makeApp = makeAppWith nulljournal
@@ -60,11 +76,13 @@
 makeAppWith j' aconf wopts = do
   s    <- staticSite
   m    <- newManager defaultManagerSettings
-  jref <- newIORef j'
+  jref <- newIORef (mkJournalState j')
+  trs  <- loadAllTranslations
   return App{
       settings    = aconf
     , getStatic   = s
     , httpManager = m
     , appOpts     = wopts
     , appJournal  = jref
+    , appTranslations = trs
     }
diff --git a/Hledger/Web/Handler/AddR.hs b/Hledger/Web/Handler/AddR.hs
--- a/Hledger/Web/Handler/AddR.hs
+++ b/Hledger/Web/Handler/AddR.hs
@@ -1,4 +1,5 @@
 {-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE LambdaCase #-}
 {-# LANGUAGE NamedFieldPuns #-}
 {-# LANGUAGE OverloadedStrings #-}
 {-# LANGUAGE QuasiQuotes #-}
@@ -18,7 +19,9 @@
 import Yesod
 
 import Hledger
-import Hledger.Cli.Commands.Add (appendToJournalFileOrStdout, journalAddTransaction)
+import Hledger.Cli (CliOpts(..))
+import Hledger.Cli.Commands.Add (appendToJournalFileOrStdout, journalFileTextAfterAppends)
+import Hledger.Cli.Commands.Print (layoutFromRawOpts)
 import Hledger.Web.Import
 import Hledger.Web.WebOptions (WebOpts(..))
 import Hledger.Web.Widget.AddForm (addForm)
@@ -59,38 +62,50 @@
   case res of
     FormSuccess (t,f) -> do
       let t' = txnTieKnot $ transactionCollapseNewlines t
-      liftIO $ do
-        ensureJournalFileExists f
-        appendToJournalFileOrStdout f (showTransaction t')
-      setMessage "Transaction added."
-      redirect JournalR
+      appendTransactionChecked f (showTransaction t') >>= \case
+        Left e -> showErrors [T.pack e] >> showForm view enctype
+        Right () -> do
+          setMessageI (HMsg "Transaction added.")
+          redirect JournalR
     FormMissing -> showForm view enctype
-    FormFailure errs -> do
-      -- Escape each error, then join the lines with <br>. An unbalanced
-      -- transaction's error embeds an excerpt of the submitted entry (account
-      -- names, amounts), so it must be escaped; only the <br> we insert is
-      -- raw. (Cf EditR, which uses toHtml.)
-      mapM_ (setMessage . mconcat . intersperse (preEscapedToHtml ("<br>" :: T.Text)) . map toHtml . T.lines) errs
-      showForm view enctype
+    FormFailure errs -> showErrors errs >> showForm view enctype
   where
+    -- Escape each error, then join the lines with <br>. An unbalanced
+    -- transaction's error embeds an excerpt of the submitted entry (account
+    -- names, amounts), so it must be escaped; only the <br> we insert is
+    -- raw. (Cf EditR, which uses toHtml.)
+    showErrors = mapM_ (setMessage . mconcat . intersperse (preEscapedToHtml ("<br>" :: T.Text)) . map toHtml . T.lines)
     showForm view enctype =
       sendResponse =<< defaultLayout [whamlet|
         <h2>Add transaction
-        <div .row style="margin-top:1em">
+        <div .row.add-page>
           <form#addform.form.col-xs-12.col-sm-11 method=post enctype=#{enctype}>
             ^{view}
       |]
 
 -- Add a single new transaction, send as JSON via PUT, to the journal.
 -- The web form handler above should probably use PUT as well.
+-- If the journal would not be readable with it added (see 'appendTransactionChecked'),
+-- the error is returned with status 400 and the journal is not changed (#2864, #2869).
 putAddR :: Handler RepJson
 putAddR = do
-  VD{j, opts} <- getViewData
+  VD{jfull, opts} <- getViewData
   require AddPermission
 
   (r :: Result Transaction) <- parseCheckJsonBody
   case r of
     Error err -> sendStatusJSON status400 ("could not parse json: " ++ err ::String)
     Success t -> do
-      void $ liftIO $ journalAddTransaction j (cliopts_ opts) $ transactionCollapseNewlines t
-      sendResponseCreated TransactionsR
+      let showtxn = showTransactionWithLayout (layoutFromRawOpts $ rawopts_ $ cliopts_ opts)
+      appendTransactionChecked (journalFilePath jfull) (showtxn $ transactionCollapseNewlines t) >>= \case
+        Left err -> sendStatusJSON status400 err
+        Right () -> sendResponseCreated TransactionsR
+
+-- | Append a transaction, rendered as journal text, to one of the journal's files,
+-- if the journal would still be readable with it added: checked as the next read
+-- would check it, with the server's options (see 'checkedJournalWrite').
+-- Otherwise write nothing and return the error message.
+appendTransactionChecked :: FilePath -> Text -> Handler (Either String ())
+appendTransactionChecked f txt = do
+  newtxt <- liftIO $ journalFileTextAfterAppends f [txt]
+  checkedJournalWrite f newtxt (appendToJournalFileOrStdout f txt)
diff --git a/Hledger/Web/Handler/BalanceR.hs b/Hledger/Web/Handler/BalanceR.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/Handler/BalanceR.hs
@@ -0,0 +1,204 @@
+-- | /balance handlers.
+
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Hledger.Web.Handler.BalanceR where
+
+import Text.Blaze.Html5 qualified as H
+import Yesod qualified
+
+import Hledger
+import Hledger.Cli.Chart (balanceReportAsChart, multiBalanceReportAsChart)
+import Hledger.Write.Chart (BarLayout(..), setChartLayout)
+import Hledger.Cli.CliOptions
+import Hledger.Cli.Commands.Balance qualified as Balance
+import Data.Text qualified as T
+import Hledger.Utils.I18n (tr, trc, trf)
+
+import Hledger.Web.Import
+import Hledger.Web.Widget.AddForm (addModal)
+import Hledger.Web.Paging (yearsRow)
+import Hledger.Web.Param (Param(..), paramLinks, paramSettings)
+import Hledger.Web.ReportPage
+import Hledger.Web.WebOptions
+import Hledger.Web.Widget.Chart (reportChart)
+import Hledger.Web.Widget.Common
+  (amountLinks, columnsLinks, commodityLinks, controlsHint, controlsToggle,
+   depthLinks, lotsLinks,
+   percentLinks, pricesLinks, realLinks,
+   statusLinks, typeLinks, zeroBalanceLinks)
+
+
+-- | The balance or multi-period balance view, with sidebar.
+getBalanceR :: Handler Html
+getBalanceR = do
+  checkServerSideUiEnabled
+  VD{perms, j, jHasLots, lotsShown, q, qopts, qparam, opts, today, trs, hideEmpty, controlsOpen, commoditiesOpen} <- getViewData
+  require ViewPermission
+  params <- reqGetParams <$> getRequest
+  urlrender <- getUrlRenderParams
+  -- the title names the dates, and the depth limit is an option, not a filter
+  let dateless = filterQuery (\x -> not (queryIsDateOrDate2 x || queryIsDepth x))
+      withFilter t = if dateless q /= Any then trf trs "{title}, filtered" [("title", t)] else t
+      rspecOrig = reportspec_ $ cliopts_ opts
+      roptsOrig = _rsReportOpts rspecOrig
+      deepest = deepestDepth j
+
+  defaultLayout $ do
+    -- the add form, which the a key opens
+    when (AddPermission `elem` perms) $ addModal AddR j today
+    -- TRANSLATORS: the browser tab title of this page.
+    setTitleI (HMsg "balance - hledger-web")
+    case reportParams rspecOrig (journalDateSpan False j) qparam q qopts hideEmpty params of
+      Left err -> Yesod.toWidget $ do
+        H.h2 $ H.toHtml $ withFilter $ reportTitle roptsOrig $ tr trs "All accounts"
+        paramError trs err
+      Right ReportParams{rpRopts, rpRspec, rpInterval, rpAccum, rpValue, rpChartLayout} -> do
+        let -- The page shows balance changes unless another mode was asked for.
+            accum = fromMaybe PerPeriod rpAccum
+            ropts = rpRopts{balanceaccum_ = accum}
+            rspec = rpRspec{_rsReportOpts = ropts}
+            styles = journalCommodityStylesWith HardRounding j
+            mbrAsked = styleAmounts styles $ multiBalanceReport rspec j
+        -- Percentages divide each amount by its column's total, which
+        -- needs them in one commodity; whether they are is in the data,
+        -- so the report, not reportParams, raises the error. Probe for
+        -- it, and show plain amounts with an explanation instead of an
+        -- error page. Only the report falls back: the links and the
+        -- Numbers row keep the url's percent state.
+        pctErr <- if percent_ ropts then liftIO $ reportProbe mbrAsked else pure Nothing
+        let roptsR = if isJust pctErr then ropts{percent_ = False} else ropts
+            rspecR = rspec{_rsReportOpts = roptsR}
+            mbr | isJust pctErr = styleAmounts styles $ multiBalanceReport rspecR j
+                | otherwise = mbrAsked
+            br = styleAmounts styles $ balanceReport rspecR j
+            -- The chart, as balance --chart draws it, of the report clipped at
+            -- any depth limit the table folds at. Its total (for all accounts, only
+            -- what conversions or valuation leave over) is hidden until the N key shows it.
+            clipped report rpt = maybe rpt (\rs -> styleAmounts styles $ report rs j) $ chartReportSpec q rspecR
+            brClipped = clipped balanceReport br
+            mbrClipped = clipped multiBalanceReport mbr
+            -- With no interval, a bar per account; but grouped, the whole period as one, with a bar per account type,
+            -- as balance --chart=grouped draws it.
+            chart = setChartLayout (Just rpChartLayout) $ case (rpInterval, rpChartLayout) of
+              (NoInterval, Diverging) -> balanceReportAsChart (journalAccountType j) roptsR "" brClipped
+              _ -> multiBalanceReportAsChart (journalAccountType j) roptsR "" mbrClipped
+            colspans = prDates mbr
+            -- What links staying on this page keep: the period as given, and each
+            -- report-shaping parameter that is not at its default.
+            -- (only a chosen interval: the automatic one follows the report's span),
+            -- and the holdings page's own interval, carried along for it
+            intervalParams = [p | p@(k, _) <- params, k `elem` ["interval", "hinterval"]]
+            accumParams = paramSettings accumParam PerPeriod accum
+            valParams = valueParams roptsOrig rpValue
+            listParams  = paramSettings listParam (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+            totalParams = [("total", "1") | row_total_ ropts]
+            avgParams   = [("avg", "1") | average_ ropts]
+            sortParams  = paramSettings sortParam False (sort_amount_ ropts)
+            pctParams   = [("pct", "1") | percent_ ropts]
+            calcParams  = paramSettings calcParam CalcChange (balancecalc_ ropts)
+            chartParams = paramSettings chartParam Diverging rpChartLayout
+            inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)]
+            date2Params = [("date2", "1") | date2_ ropts, not (date2_ roptsOrig)]
+            emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= empty_ roptsOrig]
+            lotsParams  = [("lots", "1") | lotsShown]
+            pageParams =
+              dbg1 "balance pageParams" $
+              intervalParams ++ accumParams ++ valParams ++ listParams ++
+              totalParams ++ avgParams ++ sortParams ++ pctParams ++ calcParams ++
+              inferParams ++ date2Params ++ emptyParams ++ lotsParams ++ chartParams ++ depthParams q
+            qParams = [("q", qparam) | not (T.null qparam)]
+            -- The figures' registers convert amounts as the report does. One
+            -- showing them as recorded must say so when the register's
+            -- default, the startup options', converts them. The sticky
+            -- report state travels along too; the link rewrites only the
+            -- search's dates.
+            registerParams =
+              [("value", "none") | amountModeOf ropts == Just AsRecorded, amountModeOf roptsOrig /= Just AsRecorded] ++
+              removeAttributes [paramName accumParam, "value"] pageParams
+            -- TRANSLATORS: the name of a depth 0 report's one row, all accounts in one.
+            relink = map (map (labelAllAccounts (trc trs "accounts" "All") . addLinkParams registerParams))
+            headinglink = urlrender BalanceR . headingParams qparam params
+            -- The heading, and the report's rows in three parts, for the
+            -- table's thead, tbody, and tfoot.
+            (title, header, body, totals) = case rpInterval of
+              NoInterval ->
+                let (h, b, t) =
+                      Balance.balanceReportAsSpreadsheetParts oneLineNoCostFmt roptsR br
+                    -- The plain page has its own name; one narrowed to a
+                    -- period, or showing ending balances, says so like the
+                    -- multi-period page does.
+                    dflt | queryDateSpan (date2_ ropts) (_rsQuery rspec) == nulldatespan && accum == PerPeriod = tr trs "All accounts"
+                         | otherwise = trimColon $ Balance.multiBalanceReportTitle roptsR mbr
+                in (reportTitle ropts dflt, [toList h], relink $ map toList b, relink $ map toList t)
+              _ ->
+                let (h, b, t) = Balance.multiBalanceReportAsSpreadsheetParts oneLineNoCostFmt roptsR mbr
+                in ( reportTitle ropts $ trimColon $ Balance.multiBalanceReportTitle roptsR mbr
+                   , map (relinkDateHeaders trs (columnHeading ropts colspans) headinglink colspans) h, relink b, relink t)
+            -- The depth 0 report's rows, which a tree folded at depth 0
+            -- shows above the full tree.
+            allRows = relink $ case rpInterval of
+              NoInterval -> let (_, b, _) = Balance.balanceReportAsSpreadsheetParts oneLineNoCostFmt roptsR brClipped in map toList b
+              _ -> let (_, b, _) = Balance.multiBalanceReportAsSpreadsheetParts oneLineNoCostFmt roptsR mbrClipped in b
+        let isTree = accountlistmode_ ropts == ALTree
+            mfold = fold_depth_ ropts
+            -- Beside the account heading: the list/tree switch, and the depth
+            -- limit's - and + steps (in tree mode, they fold or open a level
+            -- of the whole tree).
+            stepper =
+              paramSwitch listParam trs (urlrender BalanceR) (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+              <> (if deepest > 1 then depthStepper trs (urlrender BalanceR) (qParams ++ pageParams) deepest else mempty)
+            -- In flat mode the account names' shared prefix is shown once,
+            -- as a group heading, and each row shows only the rest, its
+            -- remaining parent path dimmed (see splitAccountNames).
+            (acctsPrefix, body')
+              | mfold == Just 0 = (Nothing, nestUnderAll allRows body)
+              | isTree = (Nothing, body)
+              | otherwise = splitAccountNames body
+            -- The years the search matches in, ignoring all date
+            -- narrowing, as a row of links among the controls; the year
+            -- links rewrite the search's date narrowing themselves.
+            yearsDays = map tdate $
+              entriesReport rspecOrig{_rsQuery = filterQuery (\x -> not (queryIsDateOrDate2 x || queryIsDepth x)) q} j
+            yearsNav = yearsRow trs BalanceR qparam today pageParams yearsDays
+            controlRows = controlsToggle trs controlsOpen (optionsSummary trs deepest $ withIntervalInEffect rpInterval pageParams) $ \render -> foldMap ($ render) $
+              [ paramLinks accumParam trs BalanceR (qParams ++ pageParams) PerPeriod accum
+              , intervalLinks trs BalanceR (removeAttributes ["interval"] pageParams) qparam rpInterval
+              , yearsNav
+              , statusLinks trs BalanceR pageParams qparam
+              , realLinks trs BalanceR pageParams qparam
+              , typeLinks trs BalanceR pageParams qparam j
+              -- TRANSLATORS: the hint below the account type filter row.
+              , controlsHint $ tr trs "Shift-click selects several types."
+              , commodityLinks trs BalanceR pageParams qparam commoditiesOpen
+                  -- TRANSLATORS: the hint below the commodity filter row.
+                  (tr trs "Shift-click selects several commodities.") j ] ++
+              [ depthLinks trs BalanceR pageParams qparam deepest | deepest > 1 ] ++
+              [ paramLinks listParam trs BalanceR (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+              , amountLinks trs BalanceR (qParams ++ removeAttributes ["value"] pageParams) (amountModeOf roptsOrig) (amountModeOf ropts)
+              , pricesLinks trs BalanceR (qParams ++ removeAttributes ["infer"] pageParams) (infer_prices_ ropts)
+              , zeroBalanceLinks trs BalanceR (qParams ++ removeAttributes ["empty"] pageParams) (empty_ roptsOrig) hideEmpty ] ++
+              [ lotsLinks trs BalanceR (qParams ++ removeAttributes ["lots"] pageParams) lotsShown | jHasLots ] ++
+              [ columnsLinks trs BalanceR (qParams ++ removeAttributes ["total", "avg"] pageParams) (row_total_ ropts) (average_ ropts)
+              | rpInterval /= NoInterval ] ++
+              [ paramLinks sortParam trs BalanceR (qParams ++ pageParams) False (sort_amount_ ropts)
+              , percentLinks trs BalanceR (qParams ++ removeAttributes ["pct"] pageParams) (percent_ ropts)
+              , paramLinks calcParam trs BalanceR (qParams ++ pageParams) CalcChange (balancecalc_ ropts)
+              , paramLinks chartParam trs BalanceR (qParams ++ pageParams) Diverging rpChartLayout ]
+        Yesod.toWidget controlRows
+        Yesod.toWidget $ H.h2 $ H.toHtml $ withFilter title
+        for_ pctErr $ Yesod.toWidget . pctError trs
+        reportChart trs (withFilter title) chart
+        Yesod.toWidget $ reportTable isTree mfold stepper header [(acctsPrefix, body', [])] totals
+
+-- | The heading for a report: --title if one was given, otherwise the
+-- given default.
+reportTitle :: ReportOpts -> Text -> Text
+reportTitle ropts dflt = fromMaybe dflt $ title_ ropts
+
+-- | Drop the trailing colon of a command line report title, which a heading
+-- does not want. A translation of it may end in " :" or "：" instead,
+-- so drop whichever is there.
+trimColon :: Text -> Text
+trimColon = T.dropWhileEnd (`elem` (":\65306 " :: String))
diff --git a/Hledger/Web/Handler/EditR.hs b/Hledger/Web/Handler/EditR.hs
--- a/Hledger/Web/Handler/EditR.hs
+++ b/Hledger/Web/Handler/EditR.hs
@@ -10,13 +10,14 @@
   , postEditR
   ) where
 
-import Control.Monad.Except (runExceptT)
+import Data.Text qualified as T
+import Hledger.Utils.I18n (Translations, tr, trf)
 import Hledger.Web.Import
 import Hledger.Web.Widget.Common
-       (fromFormSuccess, helplink, journalFile404, writeJournalTextIfValidAndChanged)
+       (fromFormSuccess, helplink, journalFile404)
 
-editForm :: FilePath -> Text -> Form Text
-editForm f txt =
+editForm :: Translations -> FilePath -> Text -> Form Text
+editForm trs f txt =
   identifyForm "edit" $ \extra -> do
     (tRes, tView) <- mreq textareaField fs (Just (Textarea txt))
     pure (unTextarea <$> tRes, $(widgetFile "edit-form"))
@@ -31,21 +32,21 @@
 postEditR :: FilePath -> Handler ()
 postEditR f = do
   checkServerSideUiEnabled
-  VD {j} <- getViewData
+  VD {j, trs} <- getViewData
   require EditPermission
 
   (f', txt) <- journalFile404 f j
-  ((res, view), enctype) <- runFormPost (editForm f' txt)
+  ((res, view), enctype) <- runFormPost (editForm trs f' txt)
   newtxt <- fromFormSuccess (showForm view enctype) res
-  runExceptT (writeJournalTextIfValidAndChanged f newtxt) >>= \case
+  writeJournalFileChecked f newtxt >>= \case
     Left e -> do
-      setMessage $ "Failed to load journal: " <> toHtml e
+      setMessage $ toHtml $ trf trs "Failed to load journal: {error}" [("error", T.pack e)]
       showForm view enctype
     Right () -> do
-      setMessage $ "Saved journal " <> toHtml f <> "\n"
+      setMessage $ toHtml $ trf trs "Saved journal {file}" [("file", T.pack f)] <> "\n"
       redirect JournalR
   where
     showForm view enctype =
       sendResponse <=< defaultLayout $ do
-        setTitle "Edit journal"
+        setTitleI (HMsg "Edit journal")
         [whamlet|<form method=post enctype=#{enctype}>^{view}|]
diff --git a/Hledger/Web/Handler/HoldingsR.hs b/Hledger/Web/Handler/HoldingsR.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/Handler/HoldingsR.hs
@@ -0,0 +1,434 @@
+-- | /holdings handlers.
+
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Hledger.Web.Handler.HoldingsR where
+
+import Data.List.Extra (nubSort, zipWith4)
+import Data.Text qualified as T
+import Text.Blaze.Html5 ((!))
+import Text.Blaze.Html5 qualified as H
+import Text.Blaze.Html5.Attributes qualified as A
+import Yesod qualified
+
+import Hledger
+import Hledger.Cli.Anchor (dateTerm)
+import Hledger.Cli.CliOptions
+import Hledger.Cli.Commands.Holdings
+import Hledger.Utils.I18n (tr, trf)
+import Hledger.Write.Spreadsheet (Cell(..), Class(..), Type(..),
+  addHeaderBorders, defaultCell, headerCell)
+
+import Hledger.Web.Import
+import Hledger.Web.Widget.AddForm (addModal)
+import Hledger.Web.Handler.BalanceR (reportTitle)
+import Hledger.Web.Paging (yearsRow)
+import Hledger.Web.Param (Param(..), paramLinks, paramSettings)
+import Hledger.Web.ReportPage
+import Hledger.Web.WebOptions
+import Hledger.Web.Widget.Chart (reportChart)
+import Hledger.Web.Widget.Common
+  (accountParams, closedLinks, commodityLinks, controlsToggle,
+   depthLinks, holdingsValueLinks,
+   lotsLinks, pricesLinks, realLinks, removeDates, searchTerms,
+   statusLinks, zeroBalanceLinks)
+
+-- | The holdings view: investment holdings and their performance at the
+-- report end date, as the holdings command shows them. In tree mode the
+-- positions are grouped under account heading rows. With lots=1, each
+-- position's lots are shown: one row per lot in list mode, or beneath
+-- their position in tree mode. With a report interval, the holdings'
+-- totals at each period's end, a row per period, as holdings -M shows
+-- them.
+getHoldingsR :: Handler Html
+getHoldingsR = do
+  checkServerSideUiEnabled
+  VD{perms, j, jfull, lotsShown, q, qopts, qparam, opts, today, trs, hideEmpty, controlsOpen, commoditiesOpen} <- getViewData
+  require ViewPermission
+  params <- reqGetParams <$> getRequest
+  urlrender <- getUrlRenderParams
+  mclosedparam <- lookupGetParam "closed"
+  let withFilter t = if filterQuery (not . queryIsDepth) q /= Any then trf trs "{title}, filtered" [("title", t)] else t
+      rspecOrig = reportspec_ $ cliopts_ opts
+      roptsOrig = _rsReportOpts rspecOrig
+      -- The journal as displayed: with lots shown it includes the lot
+      -- subaccounts, so the Depth row extends to them, as in hledger-ui.
+      deepest = deepestDepth j
+      -- Fully closed positions are hidden by default, as on the command
+      -- line; the closed parameter (or startup -E) shows them, and here
+      -- the z key toggles it (hledger.js). They have their own parameter
+      -- because the empty parameter keeps its usual meaning here: the
+      -- sidebar's zero-balance accounts, which are shown by default.
+      closedShown = case mclosedparam of
+        Just "1" -> True
+        Just "0" -> False
+        _        -> empty_ roptsOrig
+      -- Holdings are valued at a single date, so value=then has no
+      -- meaning here, as on the command line.
+      checkValue rp@ReportParams{rpRopts} = case value_ rpRopts of
+        Just (AtThen _) -> Left ValueThenUnsupported
+        _               -> Right rp
+      -- This page has an interval of its own, the hinterval parameter,
+      -- since one makes it a different report (the holdings over time),
+      -- rather than adding columns. The other report pages' shared
+      -- interval parameter it only carries along, for them.
+      hintervalParams = [p | p@("hinterval", _) <- params]
+      foreignIntervalParams = [p | p@("interval", _) <- params]
+      -- the parameters as this page reads them: its own interval as the
+      -- interval
+      ownParams = [("interval", v) | (_, v) <- hintervalParams] ++ [p | p@(k, _) <- params, k `notElem` ["interval", "hinterval"]]
+
+  defaultLayout $ do
+    -- the add form, which the a key opens
+    when (AddPermission `elem` perms) $ addModal AddR j today
+    -- TRANSLATORS: the browser tab title of this page.
+    setTitleI (HMsg "holdings - hledger-web")
+    case reportParams rspecOrig (journalDateSpan False j) qparam q qopts hideEmpty ownParams >>= checkValue of
+      Left err -> Yesod.toWidget $ do
+        H.h2 $ H.toHtml $ withFilter $ reportTitle roptsOrig $ tr trs "Holdings"
+        paramError trs err
+      Right ReportParams{rpRopts, rpRspec, rpInterval, rpAccum, rpValue} -> do
+        let ropts = rpRopts{empty_ = closedShown}
+            -- Unlike the other report pages, a depth limit clips the tree
+            -- here too, as on the command line, rather than folding it:
+            -- clipping merges each clipped account's positions by
+            -- commodity, which folding the full tree could not show.
+            rspec = rpRspec{_rsQuery = q, _rsReportOpts = ropts}
+            -- The report's display lines: flat positions (or lots with
+            -- lots shown), or account sections in tree mode (see
+            -- holdingsTreeLines).
+            rpt = holdingsReport
+                    HoldingsReportOpts{hroLots = lotsShown, hroRounding = HardRounding, hroPriceOracle = Nothing}
+                    rspec jfull
+            -- How many closed positions (an account's commodity, fully
+            -- disposed) are hidden, which the totals' RGain and XIRR
+            -- still include: the note below the table says so.
+            closedHidden = holdingsClosedHidden
+              HoldingsReportOpts{hroLots = False, hroRounding = HardRounding, hroPriceOracle = Nothing} rspec jfull
+            title = reportTitle ropts $
+              if periodic then holdingsPeriodsTitle trs ivl gains prpts else
+              -- TRANSLATORS: the holdings page's heading; {date} is the report date, {period} the report period (eg 2026-11, or 2026-11-01..2026-11-14) if it has a start date.
+              case hrGainsPeriod rpt of
+                Nothing  -> trf trs "Holdings on {date}" [("date", showDate (hrDate rpt))]
+                Just spn -> trf trs "Holdings on {date}, gains in {period}" [("date", showDate (hrDate rpt)), ("period", showDateSpan spn)]
+
+            -- With a report interval, the holdings at each period's end,
+            -- with gains since acquisition, in each period, or since the
+            -- first period's start (the accum parameter), as holdings -M
+            -- shows them. Only a chosen interval (the hinterval parameter)
+            -- makes this page periodic: unlike the other report pages, it
+            -- picks none to suit the report's span, nor takes a startup one.
+            intervalChosen = isJust (mfilter (not . T.null) $ lookup "hinterval" params) || isJust (intervalFromQueryOpts qopts)
+            ivl = if intervalChosen then rpInterval else NoInterval
+            periodic = ivl /= NoInterval
+            gains = fromMaybe Historical rpAccum
+            prpts = holdingsPeriodReports
+                      HoldingsReportOpts{hroLots = False, hroRounding = HardRounding, hroPriceOracle = Just $ journalPriceOracle (infer_prices_ ropts) jfull}
+                      gains rspec{_rsReportOpts = ropts{interval_ = ivl}} jfull
+
+            -- What links staying on this page keep: each report-shaping
+            -- parameter that is not at its default, including its interval,
+            -- and with an interval, the gains; and the other pages' interval.
+            intervalParams = hintervalParams ++ foreignIntervalParams
+            gainsParams = if periodic then paramSettings holdingsGainsParam Historical gains else []
+            valParams   = valueParams roptsOrig rpValue
+            listParams  = paramSettings listParam (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+            sortParams  = paramSettings sortParam False (sort_amount_ ropts)
+            inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)]
+            closedParams = [("closed", if closedShown then "1" else "0") | closedShown /= empty_ roptsOrig]
+            emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= empty_ roptsOrig]
+            lotsParams  = [("lots", "1") | lotsShown]
+            pageParams =
+              dbg1 "holdings pageParams" $
+              intervalParams ++ gainsParams ++ valParams ++ listParams ++ sortParams ++
+              inferParams ++ closedParams ++ emptyParams ++ lotsParams ++ depthParams q
+            qParams = [("q", qparam) | not (T.null qparam)]
+            -- An account cell links to the account's register, keeping
+            -- the states that page reads.
+            registerKept = removeAttributes [paramName holdingsGainsParam, paramName sortParam, "closed"] pageParams
+            acctlink acct = urlrender RegisterR $
+              qParams ++ accountParams True acct ++ registerKept
+            -- A position's cell links to that register filtered to the
+            -- holding's commodity: the transactions behind the row's figures.
+            poslink acct com = urlrender RegisterR $
+              ("q", T.unwords $
+                 map quoteIfSpaced (filter (not . T.isPrefixOf "cur:") (searchTerms qparam))
+                 ++ [quoteIfSpaced $ "cur:" <> regexEscape com]) : accountParams True acct ++ registerKept
+
+            -- TRANSLATORS: the holdings table's column headings. The cost
+            -- heading is "Unit cost", "Avg cost", or "Unit/Avg cost".
+            colheadings = colheadingsWith (tr trs (hrUnitCostHeading rpt))
+            colheadingsWith costheading =
+              [ tr trs "Date", tr trs "Age", tr trs "Units", costheading
+              , tr trs "Unit price", tr trs "Total cost", tr trs "Total value", tr trs "Weight"
+              , tr trs "UGain", tr trs "UGain%", tr trs "RGain", tr trs "XIRR" ]
+            -- The figure columns' headings carry .amount too, aligning
+            -- them over their right-aligned figures (hledger.css).
+            header = [ addHeaderBorders $ zipWith3 hcell (TypeString : coltypes) ("account" : colclasses) (tr trs "Account" : colheadings) ]
+            hcell typ cls t = (headerCell t){cellClass = Class $ if typ == TypeString then cls else cls <> " amount"}
+            -- per-column css classes, as the holdings command's html output has
+            colclasses = ["date","age","units","unitcost","unitprice","totalcost","totalvalue","weight","ugain","ugainpct","rgain","xirr"]
+            -- which columns' cell parts are amounts, each shown in its own span
+            amountcols = [False, False, True, True, True, True, True, False, True, False, True, False]
+            -- the types give body cells their alignment: dates left, the rest right
+            coltypes = TypeString : repeat TypeMixedAmount
+
+            showpct  = showPercentWith (hrStyles rpt)
+            showxirr = showpct . realToFrac
+            showamt  = T.pack . showAmountWith noCostFmt
+            showamtz = T.pack . showAmountWith noCostFmt{displayZeroCommodity=True}
+
+            isTree = accountlistmode_ ropts == ALTree
+
+            -- In list mode, what the account names share above their leaves
+            -- is shown once, as a group heading over the table, and each row
+            -- shows only the rest, with the part before its leaf dimmed
+            -- (acct-split; see reportTable and .acct-path in hledger.css).
+            -- The register links and their tooltips keep the full names.
+            prefix
+              | isTree = []
+              | otherwise = case map (accountNameComponents . prrFullName . fst) (hrRows rpt) of
+                  []    -> []
+                  comps -> foldl1 commonPrefix (map init comps)  -- init: each leaf stays in its row
+            commonPrefix (x:xs) (y:ys) | x == y = x : commonPrefix xs ys
+            commonPrefix _ _ = []
+            mprefixHeading = if null prefix then Nothing else Just (accountNameFromComponents prefix)
+            strippedName = accountNameFromComponents . drop (length prefix) . accountNameComponents
+
+            acctcell acct =
+              (defaultCell $ strippedName acct)
+                { cellClass = Class $ T.unwords $
+                    ["account", "acct-split"] ++
+                    ["lot" | isJust $ lotSubaccountName acct]
+                , cellAnchor = acctlink acct
+                , cellTitle = acct <> "\n" <>
+                    -- TRANSLATORS: the tooltip of an account heading or lot's register link.
+                    tr trs "Show this account's register"
+                }
+
+            -- In tree mode, an account, commodity, or lot cell at the given
+            -- indent (a fold point; hledger.js), linking to the register.
+            treecell d extracls content acct =
+              (defaultCell content)
+                { cellClass = Class $ T.unwords $
+                    ["account", "indent-" <> T.pack (show (d :: Int))] ++ extracls
+                , cellAnchor = acctlink acct
+                , cellTitle = acct <> "\n" <> tr trs "Show this account's register"
+                }
+
+            -- A class coloring a gain green and a loss red, as the holdings
+            -- command does (hledger.css). The command colors each amount;
+            -- a cell here mixing gains and losses (in several cost
+            -- commodities) is left uncolored.
+            signcls qs
+              | any (> 0) qs && all (>= 0) qs = " gain"
+              | any (< 0) qs && all (<= 0) qs = " loss"
+              | otherwise = ""
+            amtscls = signcls . map aquantity
+            pctcls = signcls . maybeToList
+
+            -- a holding's cells (cf the holdings command's holdingCellParts)
+            holdingRow acctc h =
+              acctc :
+              zipWith4 datacell coltypes
+                [ "date", "age", "units", "unitcost", "unitprice", "totalcost", "totalvalue", "weight"
+                , "ugain" <> amtscls (hUgain h), "ugainpct" <> pctcls (hUgainPct h)
+                , "rgain" <> amtscls (hRgain h), "xirr" <> pctcls (realToFrac <$> hXirr h) ]
+                amountcols
+                [ [maybe "" showDate (hDate h)]
+                , [maybe "" showage (hAge h)]
+                , [T.pack $ showAmountWith noCostFmt{displayZeroCommodity=True} (hUnits h)]
+                , [maybe "" showamt (hUnitCost h)]
+                , map showamt $ hPrice h
+                , map showamt $ hCost h
+                , map showamtz $ hValue h
+                , [maybe "" showpct (hWeight h)]
+                , map showamtz $ hUgain h
+                , [maybe "" showpct (hUgainPct h)]
+                , map showamt $ hRgain h
+                , [maybe "" showxirr (hXirr h)]
+                ]
+            datacell typ cls isamount parts =
+              (defaultCell $ T.intercalate ", " parts')
+                { cellType = typ
+                , cellClass = Class cls
+                , cellParts = if isamount then parts' else []
+                }
+              where parts' = filter (not . T.null) parts
+
+            -- A display line's row. In tree mode the lines are account
+            -- sections (see holdingsTreeLines): heading rows showing each
+            -- account's subtree totals, its positions named by their
+            -- commodity beneath it, and with lots shown, each position's
+            -- lots beneath it.
+            lineRow (HoldingsHeading d acct disp tot) = headingRow d disp acct tot
+            lineRow (HoldingsPosition d acct disp islot h)
+              | isTree    = holdingRow (positioned $ treecell d cls disp acct) h
+              | otherwise = holdingRow (positioned $ acctcell acct) h
+              where
+                cls | islot                 = ["lot"]
+                    | disp == hCommodity h  = ["commodity"]
+                    | otherwise             = []
+                -- A lot subaccount's register holds only its commodity, so
+                -- a lot cell keeps the plain account link.
+                positioned c
+                  | islot = c
+                  | otherwise = c
+                      { cellAnchor = poslink acct (hCommodity h)
+                      , cellTitle = acct <> "\n" <>
+                          -- TRANSLATORS: the tooltip of a position's register link, which filters to its commodity.
+                          tr trs "Show this holding's register"
+                      }
+
+            -- An account heading row: the account's subtree totals,
+            -- computed like the totals row (see hrAccountTotals).
+            headingRow d disp acct tot =
+              treecell d ["acctheading"] disp acct :
+              zipWith4 datacell coltypes (totalsClasses tot) amountcols (totalsParts (hrStyles rpt) tot)
+
+            -- A totals row's data cell classes, with gains and losses
+            -- colored.
+            totalsClasses tot =
+              [ "date", "age", "units", "unitcost", "unitprice", "totalcost", "totalvalue", "weight"
+              , "ugain" <> amtscls (fromMaybe [] $ htUgain tot), "ugainpct" <> pctcls (htUgainPct tot)
+              , "rgain" <> amtscls (htRgain tot), "xirr" <> pctcls (realToFrac <$> htXirr tot) ]
+
+            -- A totals row's data cell parts, showing percentages with
+            -- the given styles: the grand total's, an account heading
+            -- row's, or a period's.
+            totalsParts styles tot =
+              [ []
+              , []
+              , maybe [] ((:[]) . showamt) (htUnits tot)
+              , maybe [] ((:[]) . showamt) (htAvgCost tot)
+              , []
+              , map showamt (htCost tot)
+              , maybe [] (map showamt) (htValue tot)
+              , [maybe "" pct (htWeight tot)]
+              , maybe [] (map showamtz) (htUgain tot)
+              , [maybe "" pct (htUgainPct tot)]
+              , map showamt (htRgain tot)
+              , [maybe "" (pct . realToFrac) (htXirr tot)]
+              ]
+              where pct = showPercentWith styles
+
+            body = map lineRow (hrLines rpt)
+
+            totals =
+              [ zipWith4 datacell (TypeString : coltypes)
+                  ("account coltotal" : map (<> " coltotal") (totalsClasses $ hrTotals rpt))
+                  (False : amountcols) $
+                  -- TRANSLATORS: the heading of the holdings table's totals row.
+                  [tr trs "Total:"] : totalsParts (hrStyles rpt) (hrTotals rpt)
+              ]
+
+            -- The periods' table: a row per period end, showing the
+            -- cells of its holdings' totals that make sense over time (not
+            -- Date, Age, or Weight), and their unit price, as holdings -M
+            -- does. The units columns are shown when some period has a
+            -- single commodity. Each date links to the holdings on that
+            -- date, with gains for the same time as the row's.
+            showunits = any (isJust . htUnits . hrTotals . snd) prpts
+            periodCols :: [a] -> [a]
+            periodCols cols = case cols of
+              [_, _, units, avgcost, price, cost, val, _, ugain, ugainpct, rgain, xirr] ->
+                [c | (c, shown) <- zip [units, avgcost, price, cost, val, ugain, ugainpct, rgain, xirr] (replicate 3 showunits ++ repeat True), shown]
+              _ -> []
+            pheader =
+              [ addHeaderBorders $
+                  (headerCell (tr trs "Date")){cellClass = Class "date"} :
+                  periodCols (zipWith (hcell TypeMixedAmount) colclasses (colheadingsWith (tr trs "Avg cost"))) ]
+            pbody =
+              [ (defaultCell $ showDate (hrDate r) <> if null (totalsLeftOut tot) then "" else "*")
+                  { cellClass = Class "date"
+                  , cellAnchor = urlrender HoldingsR $ periodParams spn
+                    -- TRANSLATORS: the tooltip of a period's date in the holdings page's table with an interval.
+                  , cellTitle = tr trs "Show the holdings on this date"
+                  } :
+                zipWith4 datacell (repeat TypeMixedAmount) (periodCols $ totalsClasses tot) (periodCols amountcols)
+                  (periodCols $ withPrice $ totalsParts (hrStyles r) tot)
+              | (spn, r) <- prpts
+              , let tot = hrTotals r
+                    withPrice ps = take 4 ps ++ [maybe [] ((:[]) . showamt) (htPrice tot)] ++ drop 5 ps ]
+            -- the single-date page at a period's end, with its gains since
+            -- acquisition, during the period, or since the first period's start
+            periodParams (DateSpan mb me) =
+              [("q", T.unwords qt) | let qt = dateTerm False (DateSpan mstart me) ++ removeDates qparam, not (null qt)] ++
+              removeAttributes ["hinterval", paramName holdingsGainsParam] pageParams
+              where
+                mstart = case gains of
+                  Historical -> Nothing
+                  PerPeriod  -> mb
+                  Cumulative -> case prpts of
+                    (DateSpan mfirst _, _) : _ -> mfirst
+                    []                         -> Nothing
+            -- The years the search matches in, ignoring all date
+            -- narrowing: a year link sets the period, so the page shows
+            -- the holdings at that year's end.
+            yearsDays = map tdate $
+              entriesReport rspecOrig{_rsQuery = filterQuery (\x -> not (queryIsDateOrDate2 x || queryIsDepth x)) q} jfull
+            yearsNav = yearsRow trs HoldingsR qparam today pageParams yearsDays
+            -- the options in effect, this page's interval among them
+            summaryParams = [(if k == "hinterval" then "interval" else k, v) | (k, v) <- pageParams, k /= "interval"]
+            controlRows = controlsToggle trs controlsOpen (optionsSummaryWith holdingsGainsParam trs deepest summaryParams) $ \render -> foldMap ($ render) $
+              [ intervalLinksWith "hinterval" trs HoldingsR (removeAttributes ["hinterval"] pageParams) qparam ivl ] ++
+              [ paramLinks holdingsGainsParam trs HoldingsR (qParams ++ pageParams) Historical gains | periodic ] ++
+              [ yearsNav
+              , statusLinks trs HoldingsR pageParams qparam
+              , realLinks trs HoldingsR pageParams qparam
+              , commodityLinks trs HoldingsR pageParams qparam commoditiesOpen
+                  -- TRANSLATORS: the hint below the commodity filter row.
+                  (tr trs "Shift-click selects several commodities.") jfull ] ++
+              [ depthLinks trs HoldingsR pageParams qparam deepest | deepest > 1 ] ++
+              [ paramLinks listParam trs HoldingsR (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+              , holdingsValueLinks trs HoldingsR (qParams ++ removeAttributes ["value"] pageParams) (isJust $ value_ ropts)
+              , pricesLinks trs HoldingsR (qParams ++ removeAttributes ["infer"] pageParams) (infer_prices_ ropts)
+              , zeroBalanceLinks trs HoldingsR (qParams ++ removeAttributes ["empty"] pageParams) (empty_ roptsOrig) hideEmpty
+              , lotsLinks trs HoldingsR (qParams ++ removeAttributes ["lots"] pageParams) lotsShown
+              , closedLinks trs HoldingsR (qParams ++ removeAttributes ["closed"] pageParams) (not $ empty_ roptsOrig) (not closedShown)
+              , paramLinks sortParam trs HoldingsR (qParams ++ pageParams) False (sort_amount_ ropts) ]
+        Yesod.toWidget controlRows
+        Yesod.toWidget $ H.h2 $ H.toHtml $ withFilter title
+        -- the chart, as holdings --chart draws it (a bar per holding, or
+        -- per lot, or with an interval, per period end), then the table
+        if periodic
+        then do
+          reportChart trs (withFilter title) $ holdingsReportsAsChart ropts gains "" prpts
+          Yesod.toWidget $ reportTable False Nothing mempty pheader [(Nothing, pbody, [])] []
+          -- the starred periods' totals exclude holdings with no market price
+          reportNote $ ("* " <>) <$> holdingsUnpricedNote trs (nubSort $ concatMap (totalsLeftOut . hrTotals . snd) prpts)
+        else do
+          reportChart trs (withFilter title) $ holdingsReportAsChart ropts "" rpt
+          Yesod.toWidget $ reportTable isTree Nothing mempty header [(mprefixHeading, body, [])] totals
+          -- the totals exclude holdings with no market price
+          reportNote $ holdingsUnpricedNote trs $ totalsLeftOut $ hrTotals rpt
+          -- and their RGain and XIRR include the hidden closed positions
+          forM_ (holdingsClosedNote trs closedHidden) $ \note -> Yesod.toWidget $ H.p ! A.class_ "report-note closed-note" $ do
+            H.toHtml note
+            " ("
+            H.a ! A.href (H.toValue $ urlrender HoldingsR $
+                            qParams ++ removeAttributes ["closed"] pageParams ++ [("closed", "1") | not (empty_ roptsOrig)])
+                -- TRANSLATORS: the link after the holdings page's closed positions note, in parentheses.
+                $ H.toHtml $ tr trs "show them"
+            ")"
+  where
+    reportNote = mapM_ $ Yesod.toWidget . (H.p ! A.class_ "report-note") . H.toHtml
+
+-- | The holdings page's accum parameter, shown with a report interval:
+-- what the gain columns cover, as the holdings command's --change,
+-- --cumulative, and -H flags choose, in their order. Gains since
+-- acquisition are the default. The H key toggles them, the last link,
+-- and gains in each period, the first (hledger.js).
+holdingsGainsParam :: Param BalanceAccumulation
+holdingsGainsParam = Param
+  { paramName  = paramName accumParam
+  , paramModes = [PerPeriod, Cumulative, Historical]
+  , paramWord  = paramWord accumParam
+  -- TRANSLATORS: the label before the holdings page's gains links (with a report interval), and the links' text and tooltips.
+  , paramRowLabel = \trs -> tr trs "Gains:"
+  , paramLabel = \trs a -> case a of
+      PerPeriod  -> (tr trs "In each period", tr trs "Show the gains during each period")
+      Cumulative -> (tr trs "Since report start", tr trs "Show the gains since the report's start date, up to each period's end")
+      Historical -> (tr trs "Since acquisition", tr trs "Show the gains since each holding was acquired, up to each period's end")
+  }
diff --git a/Hledger/Web/Handler/JournalR.hs b/Hledger/Web/Handler/JournalR.hs
--- a/Hledger/Web/Handler/JournalR.hs
+++ b/Hledger/Web/Handler/JournalR.hs
@@ -7,32 +7,137 @@
 
 module Hledger.Web.Handler.JournalR where
 
+import Data.Text qualified as T
+import Hledger.Utils.I18n (tr, trf)
 import Hledger
 import Hledger.Cli.CliOptions
 import Hledger.Web.Import
+import Hledger.Web.Paging
 import Hledger.Web.WebOptions
 import Hledger.Web.Widget.AddForm (addModal)
+import Hledger.Web.Param (lookupParam, paramLinks, paramSettings)
+import Hledger.Web.ReportPage (amountModeOf, calcParam, deepestDepth, depthParams, intervalLinks, listParam, optionsSummary, parseInterval, parseValue, removeAttributes, setAmountMode, sortParam, valueParams)
 import Hledger.Web.Widget.Common
-            (accountQuery, mixedAmountAsHtml,
-             transactionFragment, replaceInacct)
+            (accountParams, amountLinks, columnsLinks, commodityLinks,
+             controlsHint, controlsToggle, searchHeading,
+             depthLinks, inertControls, lotsLinks,
+             mixedAmountAsHtml, percentLinks, pricesLinks, realLinks,
+             statusLinks, typeLinks,
+             transactionFragment, journalDayQuery, zeroBalanceLinks)
 
 -- | The formatted journal view, with sidebar.
 getJournalR :: Handler Html
 getJournalR = do
   checkServerSideUiEnabled
-  VD{perms, j, q, opts, qparam, qopts, today} <- getViewData
+  VD{perms, j, jHasLots, lotsShown, q, opts, qparam, account, today, trs, hideEmpty, controlsOpen, commoditiesOpen} <- getViewData
   require ViewPermission
-  let title = case inAccount qopts of
-        Nothing -> "General Journal"
-        Just (a, inclsubs) -> "Transactions in " <> a <> if inclsubs then "" else " (excluding subaccounts)"
-      title' = title <> if q /= Any then ", filtered" else ""
-      acctlink a = (RegisterR, [("q", replaceInacct qparam $ accountQuery a)])
-      rspec = (reportspec_ $ cliopts_ opts){_rsQuery = filterQuery (not . queryIsDepth) q}
-      items = reverse $
+  mmode <- either (const Nothing) id . parseValue <$> lookupGetParam "value"
+  mlist <- lookupParam listParam
+  inferOn <- (== Just "1") <$> lookupGetParam "infer"
+  minterval <- lookupGetParam "interval"
+  mhinterval <- lookupGetParam "hinterval"
+  totalOn <- (== Just "1") <$> lookupGetParam "total"
+  avgOn   <- (== Just "1") <$> lookupGetParam "avg"
+  sortAmt <- fromMaybe False <$> lookupParam sortParam
+  pctOn   <- (== Just "1") <$> lookupGetParam "pct"
+  calcCur <- fromMaybe CalcChange <$> lookupParam calcParam
+  date2On <- (== Just "1") <$> lookupGetParam "date2"
+  pagereq <- pageRequest
+  let title = case account of
+        Nothing         -> tr trs "General Journal"
+        Just (a, True)  -> trf trs "Transactions in {account}" [("account", a)]
+        Just (a, False) -> trf trs "Transactions in {account} (excluding subaccounts)" [("account", a)]
+      title' = searchHeading trs (date2_ (_rsReportOpts (reportspec_ (cliopts_ opts))) || date2On) q title
+      -- An account's register, opened on the page holding this transaction.
+      acctlink a t = (RegisterR, [("q", qparam) | not (T.null qparam)] ++ accountParams True a ++ ("txn", T.pack $ show $ tindex t) : carried)
+      q' = filterQuery (not . queryIsDepth) q
+      rspec = (reportspec_ $ cliopts_ opts){_rsQuery = q'}
+      -- The matching transactions, newest first; this page shows one page of them.
+      alltxns = reverse $
         styleAmounts (journalCommodityStylesWith HardRounding j) $
         entriesReport rspec j
+      (page, items) = pageOf pagereq tindex alltxns
+      -- The years the search matches in, ignoring any date term in it.
+      years = map tdate $
+        maybe alltxns (\dq -> entriesReport rspec{_rsQuery = filterQuery (not . queryIsDepth) dq} j) $
+        datelessQuery today qparam
       transactionFrag = transactionFragment j
+      -- Links staying on this page keep the states that shape the
+      -- sidebar: zero balances, amounts, the accounts mode, and
+      -- inferred prices. The journal's entries always show as written.
+      roptsStartup = _rsReportOpts $ reportspec_ $ cliopts_ opts
+      dfltHidden = empty_ roptsStartup
+      emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= dfltHidden]
+      valParams = valueParams roptsStartup mmode
+      elist = fromMaybe (accountlistmode_ roptsStartup) mlist
+      listParams = paramSettings listParam (accountlistmode_ roptsStartup) elist
+      inferParams = [("infer", "1") | inferOn]
+      -- The report-shaping state shapes nothing here, but it is passed
+      -- along and shown dimmed below, so the startup options' url
+      -- survives this landing page and the url's state is never
+      -- invisible.
+      stickyParams =
+        [("interval", w) | Just w <- [mfilter (not . T.null) minterval]] ++
+        [("hinterval", w) | Just w <- [mfilter (not . T.null) mhinterval]] ++
+        [("total", "1") | totalOn] ++
+        [("avg", "1") | avgOn] ++
+        paramSettings sortParam False sortAmt ++
+        [("pct", "1") | pctOn] ++
+        paramSettings calcParam CalcChange calcCur ++
+        [("date2", "1") | date2On]
+      lotsParams = [("lots", "1") | lotsShown]
+      carried = dbg1 "journal carried params" $ stickyParams ++ valParams ++ listParams ++ inferParams ++ emptyParams ++ lotsParams ++ depthParams q
+      qps = [("q", qparam) | not (T.null qparam)]
+      -- An entry's date link: the journal on that date, same modes.
+      dayParams t = ("q", journalDayQuery qparam (tdate t)) : carried
+      -- the rows of links above the entries: the filters (status,
+      -- realness, type, tag, commodity, and depth), and the sidebar's
+      -- accounts and amounts modes
+      statusRow = statusLinks trs JournalR carried qparam
+      realRow = realLinks trs JournalR carried qparam
+      typeRow = typeLinks trs JournalR carried qparam j
+      -- TRANSLATORS: the hint below the account type filter row.
+      typeHintRow = controlsHint $ tr trs "Shift-click selects several types."
+      commodityRow = commodityLinks trs JournalR carried qparam commoditiesOpen
+        -- TRANSLATORS: the hint below the commodity filter row.
+        (tr trs "Shift-click selects several commodities.") j
+      -- The depth and the accounts mode take effect on the report pages
+      -- (the sidebar has a depth of its own, and is always a tree), so
+      -- they are shown dimmed, carried there.
+      deepest = deepestDepth j
+      depthRow = inertControls trs $ depthLinks trs JournalR carried qparam deepest
+      listRow = inertControls trs $ paramLinks listParam trs JournalR (qps ++ carried) (accountlistmode_ roptsStartup) elist
+      -- The amounts mode converts the sidebar's amounts; the journal's
+      -- entries always show as written.
+      amountsRow = amountLinks trs JournalR (qps ++ removeAttributes ["value"] carried)
+        (amountModeOf roptsStartup) (amountModeOf $ maybe id setAmountMode mmode roptsStartup)
+      pricesRow = pricesLinks trs JournalR (qps ++ removeAttributes ["infer"] carried) inferOn
+      zeroRow = zeroBalanceLinks trs JournalR (qps ++ removeAttributes ["empty"] carried) dfltHidden hideEmpty
+      -- Lot detail shows in the entries and the sidebar; row hidden
+      -- when the journal has no lots.
+      lotsRow = if jHasLots
+        then lotsLinks trs JournalR (qps ++ removeAttributes ["lots"] carried) lotsShown
+        else const mempty
+      -- The report-shaping controls, operative on the report pages,
+      -- shown dimmed with the url's state marked.
+      rpInterval = maybe NoInterval (either (const NoInterval) id . parseInterval) minterval
+      -- The years row; its links rewrite the search's date narrowing themselves.
+      yearsNav = yearsRow trs JournalR qparam today carried years
+      intervalRow = inertControls trs $
+        intervalLinks trs JournalR (removeAttributes ["interval"] carried) qparam rpInterval
+      inertRows = inertControls trs $ mconcat
+        [ columnsLinks trs JournalR (qps ++ removeAttributes ["total", "avg"] carried) totalOn avgOn
+        , paramLinks sortParam trs JournalR (qps ++ carried) False sortAmt
+        , percentLinks trs JournalR (qps ++ removeAttributes ["pct"] carried) pctOn
+        , paramLinks calcParam trs JournalR (qps ++ carried) CalcChange calcCur
+        ]
+      -- All of them behind the controls disclosure, closed by default,
+      -- in the same order as on the report pages.
+      controlsRows = controlsToggle trs controlsOpen (optionsSummary trs deepest carried) $ mconcat $
+        [intervalRow, yearsNav, statusRow, realRow, typeRow, typeHintRow, commodityRow] ++ [depthRow | deepest > 1] ++
+        [listRow, amountsRow, pricesRow, zeroRow, lotsRow, inertRows]
 
   defaultLayout $ do
-    setTitle "journal - hledger-web"
+    -- TRANSLATORS: the browser tab title of this page.
+    setTitleI (HMsg "journal - hledger-web")
     $(widgetFile "journal")
diff --git a/Hledger/Web/Handler/MiscR.hs b/Hledger/Web/Handler/MiscR.hs
--- a/Hledger/Web/Handler/MiscR.hs
+++ b/Hledger/Web/Handler/MiscR.hs
@@ -14,6 +14,7 @@
   , getCommoditiesR
   , getAccountsR
   , getAccounttransactionsR
+  , getChartCssR
   , getDownloadR
   , getFaviconR
   , getManageR
@@ -26,17 +27,41 @@
 import Data.Text qualified as T
 import Data.Yaml qualified as Yaml
 import Data.ByteString qualified as BS
-import Yesod.Default.Handlers (getFaviconR, getRobotsR)
+import Data.FileEmbed (embedFile)
+import Text.Printf (printf)
 
 import Hledger
+import Hledger.Write.Chart.Svg (chartStylesheet)
 import Hledger.Web.Import
 import Hledger.Web.WebOptions (packageversion)
 import Hledger.Web.Widget.Common (journalFile404)
 
+-- | Serve the favicon and robots.txt from copies of config/favicon.ico and
+-- config/robots.txt embedded in this executable at build time, so that they
+-- are served whatever directory hledger-web is run from.
+getFaviconR :: Handler TypedContent
+getFaviconR = return $ TypedContent "image/x-icon" $ toContent $(embedFile "config/favicon.ico")
+
+getRobotsR :: Handler TypedContent
+getRobotsR = return $ TypedContent typePlain $ toContent $(embedFile "config/robots.txt")
+
+-- | The chart stylesheet (see "Hledger.Write.Chart.Svg"), which the
+-- register page links rather than embedding it in its chart, since the
+-- Content-Security-Policy allows no inline styles. Its dark colors apply
+-- on screen only, like hledger.css's, so that a page prints light.
+-- The ETag, a checksum of the stylesheet, lets browsers keep it until a
+-- new build changes it.
+getChartCssR :: Handler TypedContent
+getChartCssR = do
+  setEtag $ T.pack $ printf "%x" $ T.foldl' (\h c -> h * 33 + fromIntegral (fromEnum c)) (5381 :: Word) css
+  return $ TypedContent typeCss $ toContent css
+  where
+    css = T.replace "@media (prefers-color-scheme:dark)" "@media screen and (prefers-color-scheme:dark)" $ chartStylesheet True
+
 getRootR :: Handler Html
 getRootR = do
   checkServerSideUiEnabled
-  redirect JournalR
+  redirect BalancesheetR
 
 getManageR :: Handler Html
 getManageR = do
@@ -44,7 +69,7 @@
   VD{j} <- getViewData
   require EditPermission
   defaultLayout $ do
-    setTitle "Edit journal"
+    setTitleI (HMsg "Edit journal")
     $(widgetFile "manage")
 
 getDownloadR :: FilePath -> Handler TypedContent
diff --git a/Hledger/Web/Handler/RegisterR.hs b/Hledger/Web/Handler/RegisterR.hs
--- a/Hledger/Web/Handler/RegisterR.hs
+++ b/Hledger/Web/Handler/RegisterR.hs
@@ -9,58 +9,243 @@
 
 module Hledger.Web.Handler.RegisterR where
 
-import Data.List (intersperse, nub, partition)
+import Data.List (intersperse, nub, partition, sortOn)
+import Data.Map qualified as M
+import Data.Ord (Down(..))
+import Data.Set qualified as S
 import Data.Text qualified as T
 import Safe (tailSafe)
+import Text.Blaze.Html5 qualified as H
 import Text.Hamlet (hamletFile)
 
+import Hledger.Utils.I18n (Translations, tr, trc, trf)
 import Hledger
+import Hledger.Cli.Chart (accountTransactionsReportAsChart)
 import Hledger.Cli.CliOptions
+import Hledger.Write.Chart (Chart(..))
+import Hledger.Write.Chart.Svg (SvgOptions(..), chartSvgMarkupWith, defaultSvgOptions)
 import Hledger.Web.Import
+import Hledger.Web.Paging
+import Hledger.Web.Widget.Chart (chartAtWidths, chartLegend, chartToggle, chartWidths, chartWithScales, dataToggle)
+import Hledger.Web.Param (Param(..), lookupParam, paramLinks, paramSetting, paramSettings)
+import Hledger.Web.ReportPage (accumParam, amountModeOf, calcParam, deepestDepth, depthParams, intervalLinks, listParam, optionsSummary, parseInterval, parseValue, removeAttributes, setAmountMode, sortParam, valueParams)
 import Hledger.Web.WebOptions
 import Hledger.Web.Widget.AddForm (addModal)
 import Hledger.Web.Widget.Common
-             (accountQuery, mixedAmountAsHtml,
-              transactionFragment, removeDates, removeInacct, replaceInacct)
+             (accountParams, accountRegisterQuery, amountLinks, columnsLinks,
+              commodityLinks, controlsHint, controlsToggle, searchHeading, costsLinks, depthLinks,
+              inertControls, lotsLinks, mixedAmountAsHtmlElided,
+              mixedAmountAsHtmlWith, moreCommodities, percentLinks, pricesLinks, realLinks,
+              runningBalanceAsHtml, statusLinks, typeLinks,
+              zeroBalanceLinks, transactionFragment, removeDates, journalDayQuery)
 
 -- | The main journal/account register view, with accounts sidebar.
 getRegisterR :: Handler Html
 getRegisterR = do
   checkServerSideUiEnabled
-  VD{perms, j, q, opts, qparam, qopts, today} <- getViewData
+  VD{jHasLots, lotsShown, perms, j, q, opts, qparam, account, today, trs, hideEmpty, controlsOpen, commoditiesOpen} <- getViewData
   require ViewPermission
+  -- With accum=historical the running balance is the account's balance,
+  -- starting from before the query's start date, rather than a total of
+  -- the transactions shown; a report's ending balance links here that way,
+  -- so that the balance ends on the figure clicked.
+  historical <- (== Just Historical) <$> lookupParam accumParam
+  -- With a value parameter amounts are converted as a report page's
+  -- figures were (see Hledger.Web.ReportPage.parseValue), so that its
+  -- figures' registers end on them. One it does not know is ignored.
+  mmode <- either (const Nothing) id . parseValue <$> lookupGetParam "value"
+  mlist <- lookupParam listParam
+  -- With costs=1 amounts keep the costs recorded with them (10 AAPL @ $95),
+  -- which are stripped by default.
+  costsOn <- (== Just "1") <$> lookupGetParam "costs"
+  inferOn <- (== Just "1") <$> lookupGetParam "infer"
+  date2On <- (== Just "1") <$> lookupGetParam "date2"
+  minterval <- lookupGetParam "interval"
+  mhinterval <- lookupGetParam "hinterval"
+  totalOn <- (== Just "1") <$> lookupGetParam "total"
+  avgOn   <- (== Just "1") <$> lookupGetParam "avg"
+  sortAmt <- fromMaybe False <$> lookupParam sortParam
+  pctOn   <- (== Just "1") <$> lookupGetParam "pct"
+  calcCur <- fromMaybe CalcChange <$> lookupParam calcParam
+  urlrender <- getUrlRenderParams
+  pagereq <- pageRequest
+  -- How wide to draw the chart: as wide as the page's main column, with the
+  -- sidebar shown and hidden.
+  chartwidths <- chartWidths
 
-  let (a,inclsubs) = fromMaybe ("all accounts",True) $ inAccount qopts
-      s1 = if inclsubs then "" else " (excluding subaccounts)"
-      s2 = if q /= Any then ", filtered" else ""
-      header = a <> s1 <> s2
+  let title = case account of
+        Nothing         -> tr trs "all accounts"
+        Just (a, True)  -> a
+        Just (a, False) -> trf trs "{account} (excluding subaccounts)" [("account", a)]
+      header = searchHeading trs (date2_ (_rsReportOpts (reportspec_ (cliopts_ opts))) || date2On) q title
+      -- what the chart's line is named in its tooltips: the account, or all accounts
+      chartacct = maybe title fst account
 
-  let rspec = reportspec_ (cliopts_ opts)
-      acctQuery = fromMaybe Any (inAccountQuery qopts)
-      acctlink acc = (RegisterR, [("q", replaceInacct qparam $ accountQuery acc)])
+  let rspec0 = reportspec_ (cliopts_ opts)
+      ropts = maybe id setAmountMode mmode $
+        (_rsReportOpts rspec0){
+          balanceaccum_ = if historical then Historical else PerPeriod,
+          show_costs_ = costsOn,
+          infer_prices_ = infer_prices_ (_rsReportOpts rspec0) || inferOn,
+          date2_ = date2_ (_rsReportOpts rspec0) || date2On}
+      rspec = rspec0{_rsReportOpts = ropts}
+      -- links staying on this register keep its modes
+      valParams = valueParams (_rsReportOpts rspec0) mmode
+      accumParams = [paramSetting accumParam Historical | historical]
+      costsParams = [("costs", "1") | costsOn]
+      inferParams = [("infer", "1") | inferOn]
+      date2Params = [("date2", "1") | date2On]
+      dfltHidden = empty_ $ _rsReportOpts rspec0
+      emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= dfltHidden]
+      elist = fromMaybe (accountlistmode_ $ _rsReportOpts rspec0) mlist
+      listParams = paramSettings listParam (accountlistmode_ (_rsReportOpts rspec0)) elist
+      -- The report-shaping state shapes nothing here, but it is passed
+      -- along and shown dimmed below, so it survives visiting a register.
+      stickyParams =
+        [("interval", w) | Just w <- [mfilter (not . T.null) minterval]] ++
+        [("hinterval", w) | Just w <- [mfilter (not . T.null) mhinterval]] ++
+        [("total", "1") | totalOn] ++
+        [("avg", "1") | avgOn] ++
+        paramSettings sortParam False sortAmt ++
+        [("pct", "1") | pctOn] ++
+        paramSettings calcParam CalcChange calcCur
+      lotsParams = [("lots", "1") | lotsShown]
+      -- The account this register is for, which its own links keep.
+      acctParams = maybe [] (\(a, subs) -> accountParams subs a) account
+      modeParams =
+        dbg1 "register modeParams" $
+        acctParams ++ stickyParams ++ accumParams ++ valParams ++ costsParams ++ inferParams ++ date2Params ++ emptyParams ++ listParams ++ lotsParams ++ depthParams q
+      -- Links to the journal carry the sticky state; the account, the
+      -- accumulation mode and the costs toggle are this page's own.
+      journalCarry = removeAttributes ["account", "subs", paramName accumParam, "costs"] modeParams
+      -- An entry's date link: the journal on that date, same modes.
+      dayParams t = ("q", journalDayQuery qparam (tdate t)) : journalCarry
+      -- the rows of links above the chart: the filters (status,
+      -- realness, type, tag, commodity, and depth), and the accounts,
+      -- amounts, and costs modes
+      statusRow = statusLinks trs RegisterR modeParams qparam
+      realRow = realLinks trs RegisterR modeParams qparam
+      typeRow = typeLinks trs RegisterR modeParams qparam j
+      -- TRANSLATORS: the hint below the account type filter row.
+      typeHintRow = controlsHint $ tr trs "Shift-click selects several types."
+      commodityRow = commodityLinks trs RegisterR modeParams qparam commoditiesOpen
+        -- TRANSLATORS: the hint below the commodity filter row.
+        (tr trs "Shift-click selects several commodities.") j
+      -- The depth and the accounts mode take effect on the report pages
+      -- (the sidebar has a depth of its own, and is always a tree; the
+      -- register's rows always show in full), so they are shown dimmed,
+      -- carried there.
+      deepest = deepestDepth j
+      depthRow = inertControls trs $ depthLinks trs RegisterR modeParams qparam deepest
+      listRow = inertControls trs $ paramLinks listParam trs RegisterR (qParams qparam ++ modeParams) (accountlistmode_ $ _rsReportOpts rspec0) elist
+      amountsRow = amountLinks trs RegisterR (qParams qparam ++ removeAttributes ["value"] modeParams)
+        (amountModeOf $ _rsReportOpts rspec0) (amountModeOf ropts)
+      costsRow = costsLinks trs RegisterR (qParams qparam ++ removeAttributes ["costs"] modeParams) costsOn
+      pricesRow = pricesLinks trs RegisterR (qParams qparam ++ removeAttributes ["infer"] modeParams) inferOn
+      zeroRow = zeroBalanceLinks trs RegisterR (qParams qparam ++ removeAttributes ["empty"] modeParams) dfltHidden hideEmpty
+      -- Lot detail shows lot subaccounts and per-lot postings; row
+      -- hidden when the journal has no lots.
+      lotsRow = if jHasLots
+        then lotsLinks trs RegisterR (qParams qparam ++ removeAttributes ["lots"] modeParams) lotsShown
+        else const mempty
+      -- The report-shaping controls, operative on the report pages,
+      -- shown dimmed with the url's state marked.
+      rpInterval = maybe NoInterval (either (const NoInterval) id . parseInterval) minterval
+      -- The years row; its links rewrite the search's date narrowing themselves.
+      yearsNav = yearsRow trs RegisterR qparam today modeParams years
+      intervalRow = inertControls trs $
+        intervalLinks trs RegisterR (removeAttributes ["interval"] modeParams) qparam rpInterval
+      inertRows = inertControls trs $ mconcat
+        [ columnsLinks trs RegisterR (qParams qparam ++ removeAttributes ["total", "avg"] modeParams) totalOn avgOn
+        , paramLinks sortParam trs RegisterR (qParams qparam ++ modeParams) False sortAmt
+        , percentLinks trs RegisterR (qParams qparam ++ removeAttributes ["pct"] modeParams) pctOn
+        , paramLinks calcParam trs RegisterR (qParams qparam ++ modeParams) CalcChange calcCur
+        ]
+      -- All of them behind the controls disclosure, closed by default,
+      -- in the same order as on the report pages.
+      controlsRows = controlsToggle trs controlsOpen (optionsSummary trs deepest modeParams) $ mconcat $
+        [intervalRow, yearsNav, statusRow, realRow, typeRow, typeHintRow, commodityRow] ++ [depthRow | deepest > 1] ++
+        [listRow, amountsRow, costsRow, pricesRow, zeroRow, lotsRow, inertRows]
+      -- the amount column's display format: with costs when asked
+      amtfmt = noCostFmt{displayZeroCommodity = True, displayCost = costsOn}
+      qParams t = [("q", t) | not (T.null t)]
+      acctQuery = maybe Any accountRegisterQuery account
+      -- An account's register, keeping this register's mode, opened on the
+      -- page holding this transaction.
+      acctlink acc t = (RegisterR, qParams qparam ++ accountParams True acc ++ ("txn", T.pack $ show $ tindex t) : removeAttributes ["account", "subs"] modeParams)
+      -- In an account's register a type: term selects the postings
+      -- totaled, not the accounts named beside them: a liability's
+      -- register names the accounts it was posted against, whatever their
+      -- types. A register of all accounts of a type names those accounts.
       otherTransAccounts =
           map (\(acct,(name,comma)) -> (acct, (T.pack name, T.pack comma))) .
           undecorateLinks . elideRightDecorated 40 . decorateLinks .
-          addCommas . preferReal . otherTransactionAccounts q acctQuery
+          addCommas . preferReal . otherTransactionAccounts j displayq acctQuery
+      displayq = if isJust account then filterQuery (not . queryIsType) q else q
+      -- An account name, which breaks after a colon where the column is
+      -- too narrow for it, rather than the amounts beside it.
+      breakAtColons = mconcat . intersperse (toHtml (":" :: Text) <> H.wbr) . map toHtml . T.splitOn ":"
       addCommas xs =
           zip xs $
           zip (map (T.unpack . accountSummarisedName . paccount) xs) $
           tailSafe (", "<$xs) ++ [""]
-      items =
-        styleAmounts (journalCommodityStylesWith HardRounding j) $
-        accountTransactionsReport rspec{_rsQuery=q} j acctQuery
+      styles = journalCommodityStylesWith HardRounding j
+      -- The matching transactions, newest first, and the balance brought
+      -- forward from before them; this page shows one page of them.
+      (startbal, allitems) =
+        bimap (styleAmounts styles) (styleAmounts styles) $
+        accountTransactionsReportWithStart rspec{_rsQuery=q} j acctQuery
+      (page, items) = pageOf pagereq (tindex . triOrigTransaction) allitems
+      -- The brought-forward row is older than every transaction, so it
+      -- ends the last page.
+      lastpage = pgNumber page >= pgCount page
+      -- The chart is of every matching transaction, not only this page's.
+      -- A point on this page links to its row; one on another page, to that
+      -- page, opened at the row.
+      onpage = S.fromList $ map (tindex . triOrigTransaction) items
+      chartLink t
+        | S.member (tindex t) onpage = frag
+        | otherwise = urlrender RegisterR (qParams qparam ++ modeParams ++ [("txn", T.pack $ show $ tindex t)]) <> frag
+        where frag = T.pack $ '#' : transactionFrag t
+      -- The years the search matches in, ignoring any date term in it. A
+      -- year's count is by register date, while its page matches date:YYYY
+      -- against each posting's date, so a transaction with postings dated in
+      -- two years is counted once and shown in both.
+      years = map triDate $
+        maybe allitems (\dq -> accountTransactionsReport rspec{_rsQuery = dq} j acctQuery) $
+        datelessQuery today qparam
       balancelabel
-        | isJust (inAccount qopts), balanceaccum_ (_rsReportOpts rspec) == Historical = "Historical Total"
-        | isJust (inAccount qopts) = "Period Total"
-        | otherwise                = "Total"
+        | historical               = trc trs "column heading" "Historical Total"
+        | isJust account           = trc trs "column heading" "Period Total"
+        | otherwise                = trc trs "column heading" "Total"
+      -- The balance column's heading switches the mode, keeping the
+      -- register's other modes.
+      accumToggle = (RegisterR, qParams qparam ++ removeAttributes [paramName accumParam] modeParams ++ [paramSetting accumParam Historical | not historical])
+      accumToggleTitle
+        | historical = tr trs "Click to show the running balance from the start of this period"
+        | otherwise  = tr trs "Click to show the running balance including everything before this period"
+      -- In historical mode with a start date, the balance brought forward
+      -- from before it is the oldest row, linking to the transactions
+      -- before the period: those before the start date by the kind of
+      -- date (primary or secondary) the report took it from, as the
+      -- report chooses the balance's cutoff.
+      mstart = asum [ (,) secondary <$> queryStartDate secondary q
+                    | secondary <- [date2_ ropts, not $ date2_ ropts] ]
+      broughtForwardLink (secondary, start) =
+        (RegisterR, [("q", T.unwords $
+          ((if secondary then "date2:.." else "date:..") <> showDate start) : removeDates qparam)] ++
+          removeAttributes [paramName accumParam] modeParams)
       transactionFrag = transactionFragment j
   defaultLayout $ do
-    setTitle "register - hledger-web"
+    -- TRANSLATORS: the browser tab title of this page.
+    setTitleI (HMsg "register - hledger-web")
+    -- the chart's styles
+    unless (null items) $ addStylesheet ChartCssR
     $(widgetFile "register")
 
 -- cf. Hledger.Reports.AccountTransactionsReport.accountTransactionsReportItems
-otherTransactionAccounts :: Query -> Query -> Transaction -> [Posting]
-otherTransactionAccounts reportq thisacctq torig
+otherTransactionAccounts :: Journal -> Query -> Query -> Transaction -> [Posting]
+otherTransactionAccounts j reportq thisacctq torig
     -- no current account ? summarise all matched postings
     | thisacctq == None  = reportps
     -- only postings to current account ? summarise those
@@ -68,7 +253,8 @@
     -- summarise matched postings to other account(s)
     | otherwise          = otheracctps
     where
-      reportps = tpostings $ filterTransactionPostings reportq torig
+      -- given the account types, so that a type: term matches postings here as in the report
+      reportps = tpostings $ filterTransactionPostingsExtra (journalAccountType j) reportq torig
       (thisacctps, otheracctps) = partition (matchesPosting thisacctq) reportps
       otheraccts = nub $ map paccount otheracctps
 
@@ -99,24 +285,77 @@
 decorateLinks = concatMap $ \(acct, (name, comma)) ->
     map (Just acct,) name ++ map (Nothing,) comma
 
--- | Generate javascript/html for a register balance line chart based on
--- the provided "AccountTransactionsReportItem"s.
-registerChartHtml :: Text -> String -> [(CommoditySymbol, [AccountTransactionsReportItem])] -> HtmlUrl AppRoute
-registerChartHtml q title percommoditytxnreports = $(hamletFile "templates/chart.hamlet")
- -- have to make sure plot is not called when our container (maincontent)
- -- is hidden, eg with add form toggled
+-- | The register's chart: hledger's SVG chart of the running balance (see
+-- "Hledger.Cli.Chart"), drawn from every matching transaction's row, not
+-- only this page's, as wide as the page's main column was last measured (or
+-- by default, 880px). It has a chart per commodity, each on its own scale;
+-- with several, a legend chooses the one shown, first the one with the most
+-- transactions, and a note says how many more than ten are left out
+-- (searching for a commodity, cur:, charts it). Each point links to its row
+-- (see the link function given), and dragging across a plot shows the
+-- transactions on those dates (registerChartInit, in hledger.js), so each
+-- plot gives its date scale, and the chart the register's url without its
+-- date terms. Its styles are served by ChartCssR, since the
+-- Content-Security-Policy allows no inline styles. --chart's SCALE amounts
+-- at startup fix its scales, as for aregister --chart.
+registerChartHtml ::
+  Translations -> CliOpts -> Journal -> Day -> [(Maybe Text, Double)] -> Text -> [(Text, Text)] -> (Transaction -> Text) -> Text -> Text ->
+  AccountTransactionsReport -> HtmlUrl AppRoute
+registerChartHtml trs copts j today widths q modeParams pointLink acct balancelabel items = $(hamletFile "templates/chart.hamlet")
  where
-   charttitle = if null title then "" else title ++ ":"
-   colorForCommodity = fromMaybe 0 . flip lookup commoditiesIndex
-   commoditiesIndex = zip (map fst percommoditytxnreports) [0..] :: [(CommoditySymbol,Int)]
-   simpleMixedAmountQuantity = maybe 0 aquantity . listToMaybe . amounts . mixedAmountStripCosts
-   showZeroCommodity = wbUnpack . showMixedAmountB oneLineNoCostFmt{displayCost=False,displayZeroCommodity=True}
-   shownull c = if null c then " " else c
-   nodatelink = (RegisterR, [("q", T.unwords $ removeDates q)])
-
--- | Makes a unix timestamp (milliseconds since epoch) corresponding to noon on the given date in UTC.
-dayToUtcNoonTimestamp :: Day -> Integer
-dayToUtcNoonTimestamp d =
-  read (formatTime defaultTimeLocale "%s" t) * 1000 -- XXX read
-  where
-    t = UTCTime d (secondsToDiffTime $ 12 * 60 * 60)
+   nodatelink = (RegisterR, [("q", t) | let t = T.unwords $ removeDates q, not (T.null t)] ++ modeParams)
+   -- The commodities charted: at most ten, those with the most transactions.
+   -- The balances keep only those before the chart is made.
+   counts = M.fromListWith (+) [(c, 1 :: Int) | i <- items, c <- nub $ map acommodity $ amounts $ triAmount i]
+   charted = take 10 . map fst . sortOn (\(c, n) -> (Down n, c)) $ M.toList counts
+   leftout = M.size counts - length charted
+   -- the rows oldest first, as the chart's x positions are, each at its date in the register.
+   -- A balance can hold every commodity, an amount one or two, so
+   -- only the oldest balance is cut to the charted commodities; each later one
+   -- is the one before plus its row's amount, cut, as the register sums them.
+   keep = filterMixedAmount ((`elem` charted) . acommodity)
+   rows = case reverse items of
+     [] -> []
+     (t, ta, s, as, a, b) : later -> scanl next (t, ta, s, as, a, keep b) later
+   next (_, _, _, _, _, bal) (t, ta, s, as, a, _) = (t, ta, s, as, a, bal `maPlus` keep a)
+   regdates = M.fromList [(tindex $ triOrigTransaction i, triDate i) | i <- rows]
+   regdate t = M.findWithDefault (tdate t) (tindex t) regdates
+   -- A chart for each commodity, with its one panel, and the rows its points
+   -- are at, by position, for their links. It is drawn from the rows where
+   -- the commodity's balance changes, and the first and last: the rest add
+   -- nothing to its line, and drawing them all is slow when there are many
+   -- rows and commodities.
+   charts =
+     [ (c, chart, M.fromDistinctAscList $ zip [0 ..] crows)
+     | c <- charted
+     , let crows = [(t, ta, s, as, a, filterMixedAmount ((== c) . acommodity) b) | (t, ta, s, as, a, b) <- changesIn c]
+           chart = chartWithScales copts $ accountTransactionsReportAsChart (journalAccountType j) "" acct regdate crows
+     , not $ null $ chPanels chart
+     ]
+   changesIn c = case rows of
+     [] -> []
+     r : later -> r : go (qty r) later
+     where
+       qty r = sum [aquantity a | a <- amountsRaw $ triBalance r, acommodity a == c]
+       go _ [] = []
+       go _ [r] = [r]
+       go n (r : more) = let n' = qty r in if n' == n then go n more else r : go n' more
+   -- the legend's entries: each chart's commodity's name, and the chart
+   legend = [(commodityName c, svg k c) | (k, c) <- indexed]
+   -- the charts, numbered for their ids
+   indexed = zip [0 :: Int ..] charts
+   -- TRANSLATORS: a chart legend's entry for amounts written without a commodity symbol.
+   commodityName (c, _, _) = if T.null c then tr trs "no symbol" else c
+   svgopts k sfx w rowsat = defaultSvgOptions
+     { svgStyles     = False
+     , svgWidth      = w
+     , svgPlotHeight = 150
+     , svgPointLink  = \j' -> pointLink . triOrigTransaction <$> M.lookup j' rowsat
+     , svgDateScale  = True
+     , svgToday      = Just today
+     , svgIds        = "register-chart-" <> T.pack (show k) <> sfx
+     }
+   -- a commodity's chart as SVG, at each width, named for screen readers by the balance and the commodity
+   svg k (c, chart, rowsat) = chartAtWidths widths $ \sfx w ->
+     chartSvgMarkupWith (svgopts k sfx w rowsat) chart H.! H.customAttribute "aria-label" (H.toValue label)
+     where label = if T.null c then balancelabel else balancelabel <> ": " <> c
diff --git a/Hledger/Web/Handler/StatementsR.hs b/Hledger/Web/Handler/StatementsR.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/Handler/StatementsR.hs
@@ -0,0 +1,252 @@
+-- | The financial statement pages: /balancesheet, /incomestatement, and
+-- /cashflow, showing the reports of the commands of the same names. The
+-- balance sheet shows balancesheetequity's report with an equity=1
+-- parameter; /balancesheetequity, its own page once, redirects there.
+
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Hledger.Web.Handler.StatementsR (
+  getBalancesheetR,
+  getBalancesheetequityR,
+  getIncomestatementR,
+  getCashflowR,
+) where
+
+import Text.Blaze.Html5 ((!))
+import Text.Blaze.Html5 qualified as H
+import Text.Blaze.Html5.Attributes qualified as A
+import Yesod qualified
+import Data.Text qualified as T
+
+import Hledger
+import Hledger.Cli.Chart (compoundBalanceReportAsChart)
+import Hledger.Cli.CliOptions
+import Hledger.Cli.Commands.Balancesheet (balancesheetSpec)
+import Hledger.Cli.Commands.Balancesheetequity (balancesheetequitySpec)
+import Hledger.Cli.Commands.Cashflow (cashflowSpec)
+import Hledger.Cli.Commands.Incomestatement (incomestatementSpec)
+import Hledger.Cli.CompoundBalanceCommand
+import Hledger.Utils.I18n (Translations, i18n, tr, trc, trf)
+import Hledger.Write.Chart (BarLayout(..), setChartLayout)
+import Hledger.Write.Spreadsheet qualified as Spr
+
+import Hledger.Web.Import
+import Hledger.Web.Widget.AddForm (addModal)
+import Hledger.Web.Paging (yearsRow)
+import Hledger.Web.Param (Param(..), paramLinks, paramSettings)
+import Hledger.Web.ReportPage
+import Hledger.Web.WebOptions
+import Hledger.Web.Widget.Chart (reportChart)
+import Hledger.Web.Widget.Common
+  (amountLinks, columnsLinks, commodityLinks, controlsToggle,
+   depthLinks, equityLinks, helplink,
+   lotsLinks, percentLinks, pricesLinks, realLinks,
+   statusLinks, zeroBalanceLinks)
+
+getBalancesheetR, getBalancesheetequityR, getIncomestatementR, getCashflowR :: Handler Html
+-- The balance sheet's equity choice is remembered: an equity parameter
+-- (1 or 0) shows or hides equity and saves that in the showequity cookie,
+-- which a request without one follows.
+-- TRANSLATORS: the browser tab titles of the statement pages.
+getBalancesheetR = do
+  mparam <- fmap (== "1") <$> lookupGetParam "equity"
+  for_ mparam $ \e -> setUiCookie "showequity" (if e then "1" else "0")
+  remembered <- (== Just "1") <$> uiCookie "showequity"
+  if fromMaybe remembered mparam
+    then statementPage BalancesheetR (i18n "balance sheet with equity - hledger-web") balancesheetequitySpec (Just True)
+    else statementPage BalancesheetR (i18n "balance sheet - hledger-web")             balancesheetSpec       (Just False)
+getIncomestatementR = statementPage IncomestatementR (i18n "income statement - hledger-web")   incomestatementSpec Nothing
+getCashflowR        = statementPage CashflowR        (i18n "cashflow statement - hledger-web") cashflowSpec        Nothing
+
+-- | The balance sheet with equity, once a page of its own, is now the
+-- balance sheet's equity=1; old links and bookmarks are sent there.
+getBalancesheetequityR = do
+  params <- reqGetParams <$> getRequest
+  redirect (BalancesheetR, filter ((/= "equity") . fst) params ++ [("equity", "1")])
+
+-- | A statement page: the command's report for the page's search and
+-- period, with sidebar. The report's own accumulation mode applies
+-- (ending balances for the balance sheets, changes for the others)
+-- unless an accum parameter overrides it, which the heading then says,
+-- as the command's does. On the balance sheet, an Equity row among the
+-- controls says whether equity is shown, by the report given.
+statementPage :: AppRoute -> Text -> CompoundBalanceCommandSpec -> Maybe Bool -> Handler Html
+statementPage here tabtitle spec mequity = do
+  checkServerSideUiEnabled
+  VD{perms, j, jHasLots, lotsShown, q, qopts, qparam, opts, today, trs, hideEmpty, controlsOpen, commoditiesOpen} <- getViewData
+  require ViewPermission
+  params <- reqGetParams <$> getRequest
+  urlrender <- getUrlRenderParams
+  -- the title names the dates, and the depth limit is an option, not a filter
+  let dateless = filterQuery (\x -> not (queryIsDateOrDate2 x || queryIsDepth x))
+      withFilter t = if dateless q /= Any then trf trs "{title}, filtered" [("title", t)] else t
+      rspecOrig = reportspec_ $ cliopts_ opts
+      roptsOrig = _rsReportOpts rspecOrig
+      deepest = deepestDepth j
+
+  defaultLayout $ do
+    -- the add form, which the a key opens
+    when (AddPermission `elem` perms) $ addModal AddR j today
+    setTitleI (HMsg tabtitle)
+    case reportParams rspecOrig (journalDateSpan False j) qparam q qopts hideEmpty params of
+      Left err -> Yesod.toWidget $ do
+        H.h2 $ H.toHtml $ withFilter $ effectiveTitle roptsOrig $ tr trs $ cbctitle spec NoInterval
+        paramError trs err
+      Right ReportParams{rpRopts, rpRspec, rpInterval, rpAccum, rpValue, rpChartLayout} -> do
+        let accum = fromMaybe (cbcaccum spec) rpAccum
+            override = mfilter (/= cbcaccum spec) rpAccum
+            ropts = rpRopts{balanceaccum_ = accum}
+            rspec = rpRspec{_rsReportOpts = ropts}
+            styles = journalCommodityStylesWith HardRounding j
+            cbrAsked = styleAmounts styles $ compoundBalanceReport rspec j (cbcqueries spec)
+        -- Percentages can be impossible in the data (amounts in mixed
+        -- commodities); probe the report for that error and show plain
+        -- amounts with an explanation instead of an error page, keeping
+        -- the url's percent state. See BalanceR.
+        pctErr <- if percent_ ropts then liftIO $ reportProbe cbrAsked else pure Nothing
+        let roptsR = if isJust pctErr then ropts{percent_ = False} else ropts
+            rspecR = rspec{_rsReportOpts = roptsR}
+            cbr0 | isJust pctErr = styleAmounts styles $ compoundBalanceReport rspecR j (cbcqueries spec)
+                 | otherwise = cbrAsked
+            cbr =
+              applySubreportTitles ropts $
+                cbr0{cbrTitle = effectiveTitle ropts $ compoundBalanceReportTitle spec rpRopts override cbr0}
+            colspans = cbrDates cbr
+            -- The chart, as the command's --chart draws it, of the report
+            -- clipped at any depth limit the table folds at.
+            cbrClipped =
+              maybe cbr (\rs -> cbr{cbrSubreports = cbrSubreports $ styleAmounts styles $ compoundBalanceReport rs j (cbcqueries spec)})
+                (chartReportSpec q rspecR)
+            chart = compoundBalanceReportAsChart (journalAccountType j) (compoundBalanceSectionTypes $ cbcqueries spec) roptsR cbrClipped
+            -- What links staying on this page keep: the period as given, the
+            -- accumulation mode when it is not the report's own, and each
+            -- report-shaping parameter that is not at its default.
+            -- (only a chosen interval: the automatic one follows the report's span),
+            -- and the holdings page's own interval, carried along for it
+            intervalParams = [p | p@(k, _) <- params, k `elem` ["interval", "hinterval"]]
+            accumParams = paramSettings accumParam (cbcaccum spec) accum
+            valParams = valueParams roptsOrig rpValue
+            listParams  = paramSettings listParam (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+            totalParams = [("total", "1") | row_total_ ropts]
+            avgParams   = [("avg", "1") | average_ ropts]
+            sortParams  = paramSettings sortParam False (sort_amount_ ropts)
+            pctParams   = [("pct", "1") | percent_ ropts]
+            calcParams  = paramSettings calcParam CalcChange (balancecalc_ ropts)
+            chartParams = paramSettings chartParam Diverging rpChartLayout
+            inferParams = [("infer", "1") | infer_prices_ ropts, not (infer_prices_ roptsOrig)]
+            date2Params = [("date2", "1") | date2_ ropts, not (date2_ roptsOrig)]
+            emptyParams = [("empty", if hideEmpty then "0" else "1") | hideEmpty /= empty_ roptsOrig]
+            lotsParams  = [("lots", "1") | lotsShown]
+            equityParams = [("equity", "1") | mequity == Just True]
+            pageParams =
+              dbg1 "statement pageParams" $
+              equityParams ++ intervalParams ++ accumParams ++ valParams ++ listParams ++
+              totalParams ++ avgParams ++ sortParams ++ pctParams ++ calcParams ++
+              inferParams ++ date2Params ++ emptyParams ++ lotsParams ++ chartParams ++ depthParams q
+            qParams = [("q", qparam) | not (T.null qparam)]
+            -- The figures' registers convert amounts as the report does. One
+            -- showing them as recorded must say so when the register's
+            -- default, the startup options', converts them.
+            registerParams =
+              [("value", "none") | amountModeOf ropts == Just AsRecorded, amountModeOf roptsOrig /= Just AsRecorded] ++
+              removeAttributes [paramName accumParam, "value", "equity"] pageParams
+            -- TRANSLATORS: the name of a depth 0 report's one row, all accounts in one.
+            relink = map (map (labelAllAccounts (trc trs "accounts" "All") . addLinkParams registerParams))
+            headinglink = urlrender here . headingParams qparam params
+            CompoundBalanceReportParts{cbrpLeadingHeaders, cbrpDataHeaders, cbrpSections, cbrpNetRows} =
+              compoundBalanceReportAsSpreadsheetParts oneLineNoCostFmt "account" roptsR (cbcqueries spec) cbr
+            -- The heading row with the classes the stylesheet aligns the
+            -- columns by, and this page's column headings and links.
+            withClass c cell = cell{Spr.cellClass = Spr.Class c}
+            header =
+              map (withClass "account") cbrpLeadingHeaders ++
+              relinkDateHeaders trs (columnHeading ropts colspans) headinglink colspans (map (withClass "amount") cbrpDataHeaders)
+            -- Folded at depth 0, each section shows its depth 0 row (from
+            -- the clipped report, whose sections match these one to one)
+            -- above its full tree.
+            allBodies
+              | fold_depth_ ropts == Just 0
+              , CompoundBalanceReportParts{cbrpSections = clippedSections} <-
+                  compoundBalanceReportAsSpreadsheetParts oneLineNoCostFmt "account" roptsR (cbcqueries spec) cbrClipped
+              = [Just $ relink b | (_, b, _) <- clippedSections] ++ repeat Nothing
+              | otherwise = repeat Nothing
+            sections =
+              [ (sectionTitle title prefix, maybe id nestUnderAll mall body', relink subtotals)
+              | ((title, body, subtotals), mall) <- zip cbrpSections allBodies
+              , let (prefix, body') = stripShared (relink body) ]
+            -- In flat mode each subreport's rows drop their shared account
+            -- prefix and dim the remaining parent path (splitAccountNames).
+            -- A single-component prefix is implied by the section title;
+            -- a deeper one is named beside it, or it would show nowhere.
+            stripShared body
+              | accountlistmode_ ropts == ALTree = (Nothing, body)
+              | otherwise = splitAccountNames body
+            sectionTitle title prefix = mfilter (not . T.null) $ Just $ case prefix of
+              Just p | T.any (== ':') p -> title <> " — " <> p
+              _ -> title
+            noRows = all (\(_, r, _) -> null $ prRows r) . cbrSubreports
+            empty = noRows cbr
+            -- An empty report with zero balances hidden may have them all: look again showing them.
+            zerosHidden = hideEmpty && not (noRows $ compoundBalanceReport rspecR{_rsReportOpts = roptsR{empty_ = True}} j (cbcqueries spec))
+        let isTree = accountlistmode_ ropts == ALTree
+            mfold = fold_depth_ ropts
+            -- Beside the account heading: the list/tree switch, and the depth
+            -- limit's - and + steps (in tree mode, they fold or open a level
+            -- of the whole tree).
+            stepper =
+              paramSwitch listParam trs (urlrender here) (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+              <> (if deepest > 1 then depthStepper trs (urlrender here) (qParams ++ pageParams) deepest else mempty)
+            -- No type row among the controls: the statements choose their
+            -- own account types.
+            -- The years the search matches in, ignoring all date
+            -- narrowing, as a row of links among the controls; the year
+            -- links rewrite the search's date narrowing themselves.
+            yearsDays = map tdate $
+              entriesReport rspecOrig{_rsQuery = filterQuery (\x -> not (queryIsDateOrDate2 x || queryIsDepth x)) q} j
+            yearsNav = yearsRow trs here qparam today pageParams yearsDays
+            controlRows = controlsToggle trs controlsOpen (optionsSummary trs deepest $ withIntervalInEffect rpInterval pageParams) $ \render -> foldMap ($ render) $
+              [ equityLinks trs here (qParams ++ removeAttributes ["equity"] pageParams) shown | Just shown <- [mequity] ] ++
+              [ paramLinks accumParam trs here (qParams ++ pageParams) (cbcaccum spec) accum
+              , intervalLinks trs here (removeAttributes ["interval"] pageParams) qparam rpInterval
+              , yearsNav
+              , statusLinks trs here pageParams qparam
+              , realLinks trs here pageParams qparam
+              , commodityLinks trs here pageParams qparam commoditiesOpen
+                  -- TRANSLATORS: the hint below the commodity filter row.
+                  (tr trs "Shift-click selects several commodities.") j ] ++
+              [ depthLinks trs here pageParams qparam deepest | deepest > 1 ] ++
+              [ paramLinks listParam trs here (qParams ++ pageParams) (accountlistmode_ roptsOrig) (accountlistmode_ ropts)
+              , amountLinks trs here (qParams ++ removeAttributes ["value"] pageParams) (amountModeOf roptsOrig) (amountModeOf ropts)
+              , pricesLinks trs here (qParams ++ removeAttributes ["infer"] pageParams) (infer_prices_ ropts)
+              , zeroBalanceLinks trs here (qParams ++ removeAttributes ["empty"] pageParams) (empty_ roptsOrig) hideEmpty ] ++
+              [ lotsLinks trs here (qParams ++ removeAttributes ["lots"] pageParams) lotsShown | jHasLots ] ++
+              [ columnsLinks trs here (qParams ++ removeAttributes ["total", "avg"] pageParams) (row_total_ ropts) (average_ ropts)
+              | rpInterval /= NoInterval ] ++
+              [ paramLinks sortParam trs here (qParams ++ pageParams) False (sort_amount_ ropts)
+              , percentLinks trs here (qParams ++ removeAttributes ["pct"] pageParams) (percent_ ropts)
+              , paramLinks calcParam trs here (qParams ++ pageParams) CalcChange (balancecalc_ ropts)
+              , paramLinks chartParam trs here (qParams ++ pageParams) Diverging rpChartLayout ]
+        Yesod.toWidget controlRows
+        Yesod.toWidget $ H.h2 $ H.toHtml $ withFilter $ cbrTitle cbr
+        for_ pctErr $ Yesod.toWidget . pctError trs
+        if empty
+          then Yesod.toWidget $ emptyNotice trs zerosHidden (filterQuery (not . queryIsDepth) q == Any)
+          else do
+            reportChart trs (withFilter $ cbrTitle cbr) $ setChartLayout (Just rpChartLayout) chart
+            Yesod.toWidget $ reportTable isTree mfold stepper [header] sections (relink cbrpNetRows)
+
+-- | What an empty statement shows instead of a table: that its accounts
+-- all have zero balances, which are hidden; or, for the whole journal,
+-- that it has no accounts of the types the report shows, with a pointer
+-- to how types are found; or, for a search or a period, that nothing
+-- matched.
+emptyNotice :: Translations -> Bool -> Bool -> HtmlUrl AppRoute
+emptyNotice trs zerosHidden whole render =
+  H.div ! A.class_ "alert alert-info" $
+    if zerosHidden then H.toHtml $ tr trs "All the accounts this report shows have zero balances, which are hidden. Press z to show them."
+    else if whole
+      then do
+        H.toHtml $ tr trs "No accounts of the types this report shows were found. Declare account types, or use hledger's standard top-level account names. "
+        helplink "account-types" (tr trs "How hledger finds account types") render
+      else H.toHtml $ tr trs "Nothing matches this search in this period."
diff --git a/Hledger/Web/Handler/UploadR.hs b/Hledger/Web/Handler/UploadR.hs
--- a/Hledger/Web/Handler/UploadR.hs
+++ b/Hledger/Web/Handler/UploadR.hs
@@ -9,14 +9,15 @@
   , postUploadR
   ) where
 
-import Control.Monad.Except (runExceptT)
 import Data.ByteString.Lazy qualified as BL
 import Data.Conduit (connect)
 import Data.Conduit.Binary (sinkLbs)
 import Data.Text.Encoding qualified as TE
 
+import Data.Text qualified as T
+import Hledger.Utils.I18n (trf)
 import Hledger.Web.Import
-import Hledger.Web.Widget.Common (fromFormSuccess, journalFile404, writeJournalTextIfValidAndChanged)
+import Hledger.Web.Widget.Common (fromFormSuccess, journalFile404)
 
 uploadForm :: FilePath -> Markup -> MForm Handler (FormResult FileInfo, Widget)
 uploadForm f =
@@ -35,7 +36,7 @@
 postUploadR :: FilePath -> Handler ()
 postUploadR f = do
   checkServerSideUiEnabled
-  VD {j} <- getViewData
+  VD {j, trs} <- getViewData
   require EditPermission
 
   (f', _) <- journalFile404 f j
@@ -47,21 +48,18 @@
   -- XXX Unfortunate - how to parse as system locale?
   newtxt <- case TE.decodeUtf8' lbs of
     Left e -> do
-      setMessage $
-        "Encoding error: '" <> toHtml (show e) <> "'. " <>
-        "If your file is not UTF-8 encoded, try the 'edit form', " <>
-        "where the transcoding should be handled by the browser."
+      setMessage $ toHtml $ trf trs "Encoding error: '{error}'. If your file is not UTF-8 encoded, try the 'edit form', where the transcoding should be handled by the browser." [("error", T.pack (show e))]
       showForm view enctype
     Right newtxt -> return newtxt
-  runExceptT (writeJournalTextIfValidAndChanged f newtxt) >>= \case
+  writeJournalFileChecked f newtxt >>= \case
     Left e -> do
-      setMessage $ "Failed to load journal: " <> toHtml e
+      setMessage $ toHtml $ trf trs "Failed to load journal: {error}" [("error", T.pack e)]
       showForm view enctype
     Right () -> do
-      setMessage $ "File " <> toHtml f <> " uploaded successfully"
+      setMessage $ toHtml $ trf trs "File {file} uploaded successfully" [("file", T.pack f)]
       redirect JournalR
   where
     showForm view enctype =
       sendResponse <=< defaultLayout $ do
-        setTitle "Upload journal"
+        setTitleI (HMsg "Upload journal")
         [whamlet|<form method=post enctype=#{enctype}>^{view}|]
diff --git a/Hledger/Web/Main.hs b/Hledger/Web/Main.hs
--- a/Hledger/Web/Main.hs
+++ b/Hledger/Web/Main.hs
@@ -24,29 +24,38 @@
 
 module Hledger.Web.Main where
 
+import Control.Concurrent (forkIO)
+import Control.Concurrent.Async (race)
 import Control.Exception (bracket)
 #if MIN_VERSION_base(4,20,0)
 import Control.Exception.Backtrace (setBacktraceMechanismState, BacktraceMechanism(..))
 #endif
-import Control.Monad (when)
+import Control.Monad (when, void)
+import Data.ByteString.Char8 qualified as BC
+import Data.IORef (IORef, atomicModifyIORef', newIORef, readIORef, writeIORef)
+import Data.Streaming.Network (bindRandomPortTCP)
 import Data.String (fromString)
 import Data.Text qualified as T
+import Data.Text.Encoding qualified as TE
+import GHC.Clock (getMonotonicTime)
+import Network.HTTP.Types (renderSimpleQuery, status204)
 import Network.Socket
-import Network.Wai (Application)
-import Network.Wai.Handler.Warp (runSettings, runSettingsSocket, defaultSettings, setHost, setPort)
-import Network.Wai.Handler.Launch (runHostPortFullUrl)
+import Network.Wai (Application, Middleware, pathInfo, responseLBS)
+import Network.Wai.Handler.Warp (Settings, runSettings, runSettingsSocket, defaultSettings, setBeforeMainLoop, setHost, setPort)
 import System.Directory (removeFile)
-import System.Environment ( getArgs, withArgs )
+import System.Environment (withArgs)
 import System.IO (hFlush, stdout)
 import System.PosixCompat.Files (getFileStatus, isSocket)
+import System.Time.Extra (sleep)
 import Text.Printf (printf)
 import Yesod.Default.Config
 import Yesod.Default.Main (defaultDevelApp)
 
 import Hledger
 import Hledger.Cli hiding (progname,prognameandversion)
+import Hledger.Cli.Commands.Quickref (showQuickref)
 import Hledger.Web.Application (makeApplication)
-import Hledger.Web.Settings (Extra(..), parseExtra)
+import Hledger.Web.Settings (Extra(..), parseExtra, defbaseurl)
 import Hledger.Web.Test (hledgerWebTest)
 import Hledger.Web.WebOptions
 
@@ -80,35 +89,51 @@
   wopts@WebOpts{cliopts_=copts@CliOpts{debug_, rawopts_}} <- getHledgerWebOpts
   when (debug_ > 0) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show wopts)
   if
+    | boolopt "quickref"        rawopts_ -> showQuickref
     | boolopt "help"            rawopts_ -> runPager $ showModeUsage webmode ++ "\n"
-    | boolopt "tldr"            rawopts_ -> runTldrForPage "hledger-web"
+    | boolopt "examples"        rawopts_ -> runTldrForPage "hledger-web"
     | boolopt "info"            rawopts_ -> runInfoForTopic "hledger-web" Nothing
     | boolopt "man"             rawopts_ -> runManForTopic  "hledger-web" Nothing
+    | boolopt "webman"          rawopts_ -> void $ openBrowserOn $ webManualUrl "hledger-web" Nothing
     | boolopt "version"         rawopts_ -> putStrLn prognameandversion
     -- boolopt "binary-filename" rawopts_ -> putStrLn (binaryfilename progname)
-    | boolopt "test"            rawopts_ -> do
-      -- remove --test and --, leaving other args for hspec
-      (`withArgs` hledgerWebTest) . filter (`notElem` ["--test","--"]) =<< getArgs
-    | otherwise                              -> withJournal copts (web wopts)
+    | Just pat <- maybestringopt "test" rawopts_ ->
+      withArgs ["--match=" <> pat | not $ null pat] hledgerWebTest
+    | otherwise                              -> do
+      -- always load the journal with full lot detail retained; the web app
+      -- collapses it per request for display (see JournalState), so the
+      -- uncollapsed journal stays available without re-reading files.
+      let copts' = copts{rawopts_ = setboolopt "lots" rawopts_}
+          wopts' = wopts{cliopts_ = copts'}
+      withJournal copts' (web wopts')
 
   when (ghcDebugMode == GDPauseAtEnd) $ ghcDebugPause'
 
 -- | The hledger web command.
 web :: WebOpts -> Journal -> IO ()
 web opts j = do
-  let depthlessinitialq = filterQuery (not . queryIsDepth) . _rsQuery . reportspec_ $ cliopts_ opts
-      j' = filterJournalTransactions depthlessinitialq j
-      h = host_ opts
-      p = port_ opts
-      u = base_url_ opts
+  let h = host_ opts
+      p0 = port_ opts
       staticRoot = T.pack <$> file_url_ opts  -- XXX not used #2139
+
+  -- --port 0 means "let the operating system choose a free port". To learn which
+  -- port it chose (so we can report it, build the base url, and open the browser
+  -- there), we must bind the listening socket ourselves rather than let warp do it.
+  mtcpsock <- if p0 == 0 && socket_ opts == Nothing
+                then Just <$> bindRandomPortTCP (fromString h)
+                else return Nothing
+  let p = maybe p0 fst mtcpsock
+      -- If the base url is the default one (built from host and port), rebuild it
+      -- with the chosen port; if the user set --base-url, leave it untouched.
+      u | base_url_ opts == defbaseurl h p0 = defbaseurl h p
+        | otherwise                         = base_url_ opts
       appconfig = AppConfig{appEnv = Development
                            ,appHost = fromString h
                            ,appPort = p
                            ,appRoot = T.pack u
-                           ,appExtra = Extra "" Nothing staticRoot
+                           ,appExtra = Extra "" staticRoot
                            }
-  app <- makeApplication opts j' appconfig
+  app <- makeApplication opts j appconfig
 
   -- show configuration
   let
@@ -128,21 +153,33 @@
     Just fu -> printf "and static files base url %s\n" fu
     Nothing -> pure ()
 
+  -- Startup report options and query arguments take effect as url state:
+  -- this is the url carrying them, which browse mode opens. Show it, so
+  -- that with --serve the link in the terminal carries the options too.
+  let starturl
+        | null (startup_params_ opts) = u
+        | otherwise =
+            u ++ "/balancesheet" ++ BC.unpack (renderSimpleQuery True
+              [(TE.encodeUtf8 k, TE.encodeUtf8 v) | (k, v) <- startup_params_ opts])
+  when (server_mode_ opts /= ServeJson && not (null $ startup_params_ opts)) $
+    printf "Web UI with the startup options: %s\n" starturl
+
   -- start server and maybe browser
+  let warpsettings = setHost (fromString h) (setPort p defaultSettings)
   if server_mode_ opts == ServeBrowse
     then do
-      putStrLn "This server will exit after 2m with no browser windows open (or press ctrl-c)"
+      putStrLn "This server will exit after 15m with no browser windows open (or press ctrl-c)"
       putStrLn "Opening web browser..."
       hFlush stdout
-      -- exits after 2m of inactivity (hardcoded)
-      Network.Wai.Handler.Launch.runHostPortFullUrl h p u app
+      -- returns normally only after the idle exit (ctrl-c or a server failure raises instead)
+      serveAndBrowse warpsettings (snd <$> mtcpsock) starturl app
+      putStrLn "No browser windows were open for 15m, exiting. (Use --serve to serve without this timeout.)"
 
     else do
       putStrLn "Press ctrl-c to quit"
       hFlush stdout
-      let warpsettings = setHost (fromString h) (setPort p defaultSettings)
-      case socket_ opts of
-        Just s -> do
+      case (socket_ opts, mtcpsock) of
+        (Just s, _) -> do
           if isUnixDomainSocketAvailable then
             bracket
               (do
@@ -162,5 +199,60 @@
               ,"Please try again without --socket."
               ]
 
-        Nothing -> Network.Wai.Handler.Warp.runSettings warpsettings app
+        -- --port 0: serve on the socket we already bound to the OS-chosen port.
+        (Nothing, Just (_, sock)) -> Network.Wai.Handler.Warp.runSettingsSocket warpsettings sock app
+        (Nothing, Nothing)        -> Network.Wai.Handler.Warp.runSettings warpsettings app
 
+-- | Browse mode: serve the app, open the default web browser on it once it
+-- is listening, and return when no browser window has shown it for
+-- browseIdleSeconds. A page says it is open by pinging /_ping while it is (see
+-- browsePingInit in static/hledger.js). The pings are answered here, before
+-- they reach the app, and the time of the latest one is kept.
+-- With --port 0 the listening socket is already bound (to the port the OS
+-- chose, which is the one in the url); serve on it rather than on host and port.
+serveAndBrowse :: Settings -> Maybe Socket -> String -> Application -> IO ()
+serveAndBrowse warpsettings msock u app = do
+  lastping <- newIORef =<< getMonotonicTime
+  let settings = setBeforeMainLoop (void $ forkIO $ void $ openBrowserOn u) warpsettings
+      serve = maybe (runSettings settings) (runSettingsSocket settings) msock
+  -- Run these concurrently: when either one finishes or fails, so does the other.
+  void $ race
+    (serve $ answerPings lastping app)
+    (waitForIdle lastping)
+
+-- | Answer /_ping with 204 No Content, noting the time; pass everything else to the app.
+answerPings :: IORef Double -> Middleware
+answerPings lastping app req send
+  | pathInfo req == ["_ping"] = do
+      writeIORef lastping =<< getMonotonicTime
+      send $ responseLBS status204 [] ""
+  | otherwise = app req send
+
+-- | Return once no ping has arrived for browseIdleSeconds.
+waitForIdle :: IORef Double -> IO ()
+waitForIdle lastping = do
+  t   <- readIORef lastping
+  now <- getMonotonicTime
+  let remaining = t + browseIdleSeconds - now
+  when (remaining > 0) $ do
+    sleep remaining
+    woke <- getMonotonicTime
+    -- On some platforms the clock runs on while the system sleeps, and no
+    -- page could ping meanwhile. If the wait overran by more than a ping
+    -- interval, allow one more interval before deciding.
+    when (woke - now - remaining > browsePingSeconds) $
+      atomicModifyIORef' lastping $ \lp ->
+        (max lp (woke + browsePingSeconds + 5 - browseIdleSeconds), ())
+    waitForIdle lastping
+
+-- | How long browse mode keeps serving after the last ping. The pages ask to
+-- ping every browsePingSeconds, but browsers slow down the timers of pages in
+-- background tabs, and Safari may let one run only every five minutes or so.
+-- This must outlast that, or the server would exit under a page that is
+-- still open.
+browseIdleSeconds :: Double
+browseIdleSeconds = 15 * 60
+
+-- | How often an open page pings, as set in hledger.js.
+browsePingSeconds :: Double
+browsePingSeconds = 30
diff --git a/Hledger/Web/Paging.hs b/Hledger/Web/Paging.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/Paging.hs
@@ -0,0 +1,181 @@
+-- | Paging for the journal and register pages, which show the newest
+-- transactions first, a page at a time, however large the journal is;
+-- and the row of years a search matches, for moving through history.
+
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE QuasiQuotes       #-}
+{-# LANGUAGE RecordWildCards   #-}
+{-# LANGUAGE TemplateHaskell   #-}
+
+module Hledger.Web.Paging
+  ( pageSize
+  , Page(..)
+  , PageRequest(..)
+  , pageRequest
+  , pageOf
+  , pageNumbers
+  , pagingLinks
+  , datelessQuery
+  , yearsRow
+  ) where
+
+import Data.Function (on)
+import Data.List (findIndex, groupBy, intercalate)
+import Data.Set qualified as S
+import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Time (Day, fromGregorian, toGregorian)
+import Text.Hamlet (hamletFile)
+import Text.Read (readMaybe)
+import Yesod (HtmlUrl, MonadHandler, lookupGetParam)
+
+import Hledger
+import Hledger.Query qualified as Query
+import Hledger.Utils.I18n (Translations, tr, trc, trf)
+import Hledger.Web.Widget.Common (removeDates)
+
+-- | How many transactions a journal or register page shows: the newest
+-- this many, with links to the older pages. It keeps a page to a megabyte
+-- or two and a few thousand table rows, which browsers render promptly,
+-- where a whole journal of tens of thousands of rows stalls some (#586).
+pageSize :: Int
+pageSize = 1000
+
+-- | Which page of a list is shown, and where it sits in the list.
+data Page = Page
+  { pgNumber :: Int  -- ^ this page's number, from 1
+  , pgCount  :: Int  -- ^ how many pages there are, at least 1
+  , pgFirst  :: Int  -- ^ the position of this page's first item, from 1; 0 when there are none
+  , pgLast   :: Int  -- ^ the position of this page's last item
+  , pgTotal  :: Int  -- ^ how many items there are in all
+  } deriving (Eq, Show)
+
+-- | Which page a request asks for: a page by number, or the page holding
+-- a transaction named by its index (a link from one view to a transaction
+-- in the other says which), or else the first.
+data PageRequest = PageNumber Int | PageOfTransaction Integer | FirstPage
+  deriving (Eq, Show)
+
+-- | The page the page and txn query parameters ask for. A page number
+-- that is not a positive integer is ignored; a number past the last page
+-- is brought back to it by 'pageOf'.
+pageRequest :: MonadHandler m => m PageRequest
+pageRequest = do
+  mpage <- (>>= readMaybe . T.unpack) <$> lookupGetParam "page"
+  mtxn  <- (>>= readMaybe . T.unpack) <$> lookupGetParam "txn"
+  return $ case (mpage, mtxn) of
+    (Just n, _)       -> PageNumber (clamp n)
+    (Nothing, Just i) -> PageOfTransaction i
+    _                 -> FirstPage
+  where
+    -- read as an Integer, so that a huge number stays past the end
+    -- rather than wrapping around
+    clamp :: Integer -> Int
+    clamp = fromInteger . max 1 . min (toInteger (maxBound :: Int))
+
+-- | The requested page of a list, and where it sits: the first page is the
+-- first 'pageSize' items, and a page number past the end gives the last
+-- page. The second argument gives an item's transaction index, for finding
+-- the page holding a transaction; an index not in the list gives the first
+-- page.
+pageOf :: PageRequest -> (a -> Integer) -> [a] -> (Page, [a])
+pageOf req indexOf xs = (Page{..}, items)
+  where
+    pgTotal  = length xs
+    pgCount  = max 1 $ (pgTotal + pageSize - 1) `div` pageSize
+    pgNumber = max 1 $ min pgCount $ case req of
+      PageNumber n        -> n
+      PageOfTransaction i -> maybe 1 (\k -> k `div` pageSize + 1) $ findIndex ((== i) . indexOf) xs
+      FirstPage           -> 1
+    items    = take pageSize $ drop ((pgNumber - 1) * pageSize) xs
+    pgFirst  = if pgTotal == 0 then 0 else (pgNumber - 1) * pageSize + 1
+    pgLast   = min pgTotal (pgNumber * pageSize)
+
+-- | The page numbers a pager shows: up to ten, in a window that slides
+-- along with the current page, as web pagers usually do.
+pageNumbers :: Int -> Int -> [Int]
+pageNumbers current count = [start .. min count (start + 9)]
+  where start = max 1 $ min (current - 4) (count - 9)
+
+-- | The line saying which of the matching transactions this page shows,
+-- and under it the row of pages: links to the newer and older pages and
+-- to the pages by number, the current one marked. Nothing when they all
+-- fit on one page. The links keep the search and the given parameters.
+pagingLinks :: Translations -> r -> Text -> [(Text, Text)] -> Page -> HtmlUrl r
+pagingLinks trs here qparam kept Page{..} = $(hamletFile "templates/paging.hamlet")
+  where
+    showing = trf trs "Showing {first} to {last} of {total} transactions"
+      [("first", withCommas pgFirst), ("last", withCommas pgLast), ("total", withCommas pgTotal)]
+    pageTitle n = trf trs "Show page {n}" [("n", T.pack (show n))]
+    pageLabel n = trf trs "Page {n}" [("n", T.pack (show n))]
+    link n = (here, [("q", qparam) | not (T.null qparam)] ++ kept ++ [("page", T.pack (show n)) | n > 1])
+    mnewer = if pgNumber > 1       then Just (pgNumber - 1) else Nothing
+    molder = if pgNumber < pgCount then Just (pgNumber + 1) else Nothing
+    numbers = pageNumbers pgNumber pgCount
+
+-- | The search without its date terms, parsed as the year links' searches
+-- will be; or Nothing when it has none, or when what is left does not
+-- parse. The years row counts what a search matches in any year by the
+-- same report the page shows, so a handler runs its report again on this,
+-- and the counts are what each year link's page shows.
+datelessQuery :: Day -> Text -> Maybe Query
+datelessQuery today qparam
+  | length rest == length terms = Nothing
+  | otherwise = case parseQuery today (T.unwords rest) of
+      Right (q, _) -> Just $ simplifyQuery q
+      Left _       -> Nothing
+  where
+    terms = filter (not . T.null) $ Query.words'' queryprefixes qparam
+    rest = removeDates qparam
+
+-- | The years in which a search matches transactions, each a link to the
+-- search narrowed to that year, after an All link that widens it again.
+-- Nothing when there is only one year, which has nowhere to go. More than
+-- twenty years are grouped by decade, a row each. The links keep the
+-- given parameters. Takes today's date, for parsing the search's date
+-- terms: the years the span they show covers in full are marked, so a
+-- range search (date:2023..2026, as a shift-click makes) marks each of
+-- its years.
+yearsRow :: Translations -> r -> Text -> Day -> [(Text, Text)] -> [Day] -> HtmlUrl r
+yearsRow trs here qparam today kept days = $(hamletFile "templates/years.hamlet")
+  where
+    showOnly y = trf trs "Show only {year}" [("year", T.pack (show y))]
+    -- TRANSLATORS: the hint below the years row.
+    rangeHint = tr trs "Shift-click selects a range of years."
+    years :: [Integer]
+    years = S.toAscList $ S.fromList [y | d <- days, let (y, _, _) = toGregorian d]
+    manyYears = length years > 1
+    byDecade = if length years > 20 then map decadeRow $ groupBy ((==) `on` decade) years else []
+    decadeRow ys@(y:_) = (show (decade y * 10) ++ "s", ys)
+    decadeRow [] = ("", [])
+    decade y = y `div` 10
+    terms = filter (not . T.null) $ Query.words'' queryprefixes qparam
+    isDateTerm t = any (`T.isPrefixOf` t) ["date:", "date2:"]
+    -- the search without its date terms, which each year link replaces
+    rest = removeDates qparam
+    -- The span being shown: the search's date terms'. A search narrowing
+    -- only by secondary date (date2:) sets the span too, so its years are
+    -- marked rather than All.
+    shownSpan =
+      either (const nulldatespan) (spanOf . fst) $
+        parseQuery today (T.unwords $ filter isDateTerm terms)
+    spanOf q =
+      let s = queryDateSpan False q
+      in if s == nulldatespan then queryDateSpan True q else s
+    -- A year is current when the shown span covers all of it.
+    isCurrent y =
+      shownSpan /= nulldatespan
+      && maybe True (<= fromGregorian y 1 1) (spanStart shownSpan)
+      && maybe True (fromGregorian (y + 1) 1 1 <=) (spanEnd shownSpan)
+    allCurrent = shownSpan == nulldatespan
+    yearlink y = (here, ("q", T.unwords $ ("date:" <> T.pack (show y)) : rest) : kept)
+    alllink = (here, [("q", T.unwords rest) | not (null rest)] ++ kept)
+
+-- | A count with thousands separators, as English prose has it: 1,234.
+withCommas :: Int -> Text
+withCommas n
+  | n < 0 = "-" <> withCommas (negate n)
+  | otherwise = T.pack . reverse . intercalate "," . chunks . reverse $ show n
+  where
+    chunks [] = []
+    chunks s = let (a, b) = splitAt 3 s in a : chunks b
diff --git a/Hledger/Web/Param.hs b/Hledger/Web/Param.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/Param.hs
@@ -0,0 +1,120 @@
+{-|
+The report pages' rows of links, and the generic part of their
+multiple-choice URL parameters: a parameter's name, modes, URL words,
+and labels, written once (the parameters themselves are in
+"Hledger.Web.ReportPage"), from which its parser, its row of links, the
+parameters that carry it, and its name in the options summary are made.
+-}
+
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE OverloadedStrings #-}
+
+module Hledger.Web.Param
+  ( linksRow
+  , linksRowClass
+  , linksRowGroups
+  , Param(..)
+  , parseParam
+  , lookupParam
+  , paramSetting
+  , paramSettings
+  , paramLinks
+  , paramPhrase
+  ) where
+
+import Control.Monad (unless)
+import Data.Foldable (find, for_)
+import Data.Text (Text)
+import Data.Text qualified as T
+import Text.Blaze ((!), (!?))
+import Text.Blaze.Html5 qualified as H
+import Text.Blaze.Html5.Attributes qualified as A
+import Yesod (HtmlUrl, MonadHandler, lookupGetParam)
+
+import Hledger.Utils.I18n (Translations)
+
+-- | A row of links above a report: a label, then each link's label,
+-- title, target, and whether it is the one being shown.
+-- Each label and title is a whole phrase, not a word slotted into a
+-- sentence: an adjective that fits one language's sentence does not fit
+-- another's, so a translation cannot be assembled from parts.
+linksRow :: Text -> [(Text, Text, (r, [(Text, Text)]), Bool)] -> HtmlUrl r
+linksRow = linksRowClass ""
+
+-- | 'linksRow' with an extra class on the row: a hook for hledger.js's
+-- keyboard shortcuts.
+linksRowClass :: Text -> Text -> [(Text, Text, (r, [(Text, Text)]), Bool)] -> HtmlUrl r
+linksRowClass cls rowlabel items = linksRowGroups cls rowlabel [items]
+
+-- | 'linksRowClass' with the links in groups, shown a little apart.
+linksRowGroups :: Text -> Text -> [[(Text, Text, (r, [(Text, Text)]), Bool)]] -> HtmlUrl r
+linksRowGroups cls rowlabel groups renderUrl =
+    H.p ! A.class_ (H.toValue $ T.unwords $ "report-links" : [cls | not (T.null cls)]) $ do
+      unless (T.null rowlabel) $ H.span ! A.class_ "row-label" $ H.toHtml rowlabel
+      for_ (zip [0 :: Int ..] groups) $ \(g, items) ->
+        for_ (zip [0 :: Int ..] items) $ \(i, (label, title, link, current)) ->
+          let classes = ["current" | current] ++ ["group-start" | g > 0, i == 0]
+          in H.a !? (not (null classes), A.class_ (H.toValue $ T.unwords classes))
+                 ! A.href (H.toValue $ uncurry renderUrl link)
+                 ! A.title (H.toValue title) $
+               H.toHtml label
+
+-- | A multiple-choice URL parameter, and its row of links.
+-- Where the parameter offers every constructor of its type, write
+-- 'paramWord' and 'paramLabel' as case expressions naming every
+-- constructor, with no catch-all case: then a constructor added to the
+-- type gives a missing-case warning until it has a word and a label.
+data Param a = Param
+  { paramName     :: Text
+    -- ^ The URL parameter's name, eg "calc". Also the class of its row
+    -- of links, which hledger.js's keyboard shortcuts look for.
+  , paramModes    :: [a]
+    -- ^ The modes the page offers, in the order of the row's links.
+    -- Can be a subset of the type's constructors.
+  , paramWord     :: a -> Text
+    -- ^ The URL word naming a mode, eg "gain". Each mode's must differ.
+  , paramRowLabel :: Translations -> Text
+    -- ^ The label before the row of links, eg "Calculate:".
+  , paramLabel    :: Translations -> a -> (Text, Text)
+    -- ^ A mode's link text and tooltip. The link text is also how the
+    -- closed options disclosure names the mode.
+  }
+
+-- | Read a parameter's value: one of its modes' words, or, when it is
+-- empty or absent, Nothing, for the page's default. An unknown word is
+-- returned on the Left.
+parseParam :: Param a -> Maybe Text -> Either Text (Maybe a)
+parseParam p = \case
+  Nothing -> Right Nothing
+  Just "" -> Right Nothing
+  Just w  -> maybe (Left w) (Right . Just) $ find ((== w) . paramWord p) (paramModes p)
+
+-- | A parameter's value in the request, if it names one of its modes.
+-- For pages that ignore an unknown value rather than report it.
+lookupParam :: MonadHandler m => Param a -> m (Maybe a)
+lookupParam p = either (const Nothing) id . parseParam p <$> lookupGetParam (paramName p)
+
+-- | The URL parameter selecting a mode.
+paramSetting :: Param a -> a -> (Text, Text)
+paramSetting p a = (paramName p, paramWord p a)
+
+-- | The URL parameter selecting a mode, if needed: not for the page's
+-- default mode, or a mode the parameter does not offer.
+paramSettings :: Eq a => Param a -> a -> a -> [(Text, Text)]
+paramSettings p dflt a = [paramSetting p a | a /= dflt, a `elem` paramModes p]
+
+-- | A parameter's row of links, one per mode, each replacing the
+-- parameter among the given ones; the page's default mode needs none.
+-- The mode being shown is marked. The row's class is the parameter's
+-- name, a hook for hledger.js's keyboard shortcuts.
+paramLinks :: Eq a => Param a -> Translations -> r -> [(Text, Text)] -> a -> a -> HtmlUrl r
+paramLinks p trs route kept dflt current =
+  linksRowClass (paramName p) (paramRowLabel p trs)
+    [ (label, title, (route, kept' ++ paramSettings p dflt a), a == current)
+    | a <- paramModes p, let (label, title) = paramLabel p trs a ]
+  where kept' = filter ((/= paramName p) . fst) kept
+
+-- | The link text of the mode a URL word names, if it names one: how
+-- the closed options disclosure lists it.
+paramPhrase :: Param a -> Translations -> Text -> Maybe Text
+paramPhrase p trs w = fst . paramLabel p trs <$> find ((== w) . paramWord p) (paramModes p)
diff --git a/Hledger/Web/ReportPage.hs b/Hledger/Web/ReportPage.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/ReportPage.hs
@@ -0,0 +1,867 @@
+{-|
+What hledger-web's report pages share: resolving their parameters into
+report options, translating the startup options into url state, and
+rendering a report's cells as the page's table.
+-}
+
+{-# LANGUAGE LambdaCase        #-}
+{-# LANGUAGE NamedFieldPuns    #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE RecordWildCards   #-}
+
+module Hledger.Web.ReportPage (
+  ReportParams(..),
+  ReportParamError(..),
+  reportParams,
+  startupUrlState,
+  intervalPeriodExpr,
+  autoInterval,
+  paramSwitch,
+  paramError,
+  reportProbe,
+  pctError,
+  AmountMode(..),
+  parseValue,
+  readParam,
+  accumParam,
+  calcParam,
+  chartParam,
+  listParam,
+  sortParam,
+  optionsSummary,
+  optionsSummaryWith,
+  withIntervalInEffect,
+  registerKeptParams,
+  valueWord,
+  amountModeOf,
+  setAmountMode,
+  valueParams,
+  addLinkParams,
+  labelAllAccounts,
+  nestUnderAll,
+  deepestDepth,
+  parseInterval,
+  depthParams,
+  columnHeading,
+  headingParams,
+  removeAttributes,
+  relinkDateHeaders,
+  reportLinks,
+  intervalLinks,
+  intervalLinksWith,
+  reportTable,
+  depthStepper,
+  chartReportSpec,
+  splitAccountNames,
+) where
+
+import Control.Exception qualified as E
+import Control.Monad (mfilter, unless)
+import Data.Foldable (find, for_, traverse_)
+import Data.List (elemIndex, mapAccumL, sortOn, stripPrefix)
+import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)
+import Data.Text.Encoding qualified as TE
+import Network.HTTP.Types.URI (urlEncode)
+import Safe (readMay)
+import Data.Text (Text)
+import Data.Text qualified as T
+import Data.Set qualified as Set
+import Text.Blaze.Html5 ((!))
+import Text.Blaze.Html5 qualified as H
+import Text.Blaze.Html5.Attributes qualified as A
+import Text.Megaparsec (eof)
+import Text.Megaparsec.Error (errorBundlePretty)
+
+import Yesod (HtmlUrl)
+
+import Hledger.Utils.I18n (Translations, tr, trc, trf)
+import Hledger
+import Hledger.Cli.Anchor (dateTerm, renderPeriodHeading)
+import Hledger.Web.Param (Param(..), linksRowClass, paramPhrase, paramSettings, parseParam)
+import Data.Time.Calendar (diffDays)
+import Hledger.Web.Widget.Common (AmountMode(..), depthParam, depthTitle, removeDates, valueWord)
+import Hledger.Query qualified as Query
+import Hledger.Write.Chart (BarLayout(..))
+import Hledger.Write.Html (Html, formatCell, nl)
+import Hledger.Write.Spreadsheet (Cell(..), Class(..), NumLines, textFromClass)
+
+-- | A report page's parameters, resolved.
+data ReportParams = ReportParams {
+    rpRopts    :: ReportOpts,
+      -- ^ The startup report options with the page's search, period, interval,
+      --   and zero-item setting applied, and links made relative. The
+      --   accumulation mode is left for the page to set.
+    rpRspec    :: ReportSpec,
+      -- ^ The startup report spec with those options and the page's query.
+    rpInterval :: Interval,
+      -- ^ The reporting interval: from the interval parameter, else none.
+    rpAccum    :: Maybe BalanceAccumulation,
+      -- ^ The accum parameter, if one was given.
+    rpValue    :: Maybe AmountMode,
+      -- ^ The value parameter, if one was given. rpRopts converts amounts
+      --   as it says.
+    rpChartLayout :: BarLayout
+      -- ^ The chart parameter: the bar layout of a chart with sections
+      --   (the statements'), diverging by default.
+}
+
+-- | A parameter the page cannot use, with what was given; or a
+-- combination of parameters that contradict each other.
+data ReportParamError
+  = BadInterval String | BadValue Text | BadParamValue Text Text
+  | ValuechangeNeedsEnd | GainNotCost | ValueThenUnsupported
+
+-- | Resolve a report page's parameters: the startup report spec, the search parameter and its parsed query and options, whether
+-- zero items are hidden, and a lookup for the page's other parameters:
+-- interval, accum, value, list, total, avg, sort, pct, and calc.
+--
+-- The interval parameter is a reporting interval as in a period
+-- expression ("monthly", "every 2 weeks"), with no dates: the report's
+-- dates are the search's date: terms (App.normaliseUrlState moves the
+-- intervals typed there to this parameter). "none" is no interval, said
+-- explicitly. Without the parameter (or a startup interval), the page
+-- picks one to suit the span it reports on, the search's dates within
+-- the given journal span (see autoInterval); it is not added to the
+-- page's links, so it follows the span as that changes.
+reportParams ::
+  ReportSpec -> DateSpan -> Text -> Query -> [QueryOpt] -> Bool -> [(Text, Text)] ->
+  Either ReportParamError ReportParams
+reportParams rspecOrig jspan qparam q qopts hideEmpty params = do
+  let roptsOrig = _rsReportOpts rspecOrig
+      param k = lookup k params
+  mivl <- case mfilter (not . T.null) (param "interval") of
+    Nothing -> Right Nothing
+    Just "none" -> Right (Just NoInterval)
+    Just t  -> either (Left . BadInterval . errorBundlePretty) (Right . Just) $ parseInterval t
+  rpAccum <- readParam accumParam (param $ paramName accumParam)
+  rpValue <- parseValue (param "value")
+  rpChartLayout <- fromMaybe Diverging <$> readParam chartParam (param $ paramName chartParam)
+  mlist   <- readParam listParam (param $ paramName listParam)
+  total   <- parseFlag "total" (param "total")
+  avg     <- parseFlag "avg" (param "avg")
+  sortAmt <- fromMaybe False <$> readParam sortParam (param $ paramName sortParam)
+  pct     <- parseFlag "pct" (param "pct")
+  calc    <- fromMaybe CalcChange <$> readParam calcParam (param $ paramName calcParam)
+  infer <- parseFlag "infer" (param "infer")
+  dat2  <- parseFlag "date2" (param "date2")
+  let ivl = case (mivl, interval_ roptsOrig) of
+        (Just i, _)           -> i
+        (Nothing, NoInterval) -> autoInterval $ spanIntersect jspan $ queryDateSpan dat2 q
+        (Nothing, startupivl) -> startupivl
+      rpInterval = fromMaybe ivl $ intervalFromQueryOpts qopts
+      ropts1 =
+        maybe id setAmountMode rpValue roptsOrig {
+          -- -E means the opposite in hledger-ui and hledger-web: hide
+          -- zero items, which are shown by default, as the sidebar does.
+          empty_ = not hideEmpty,
+          balance_base_url_ = Just "",
+          date2_ = date2_ roptsOrig || dat2,
+          infer_prices_ = infer_prices_ roptsOrig || infer,
+          querystring_ = filter (not . T.null) (Query.words'' queryprefixes qparam),
+          interval_ = rpInterval
+        }
+      tree = fromMaybe (accountlistmode_ roptsOrig) mlist == ALTree
+  -- The combinations the command line rejects too, judged on the
+  -- effective conversion: the value parameter, or startup's options.
+  let isEnd (AtEnd _) = True
+      isEnd _         = False
+      atCost = conversionop_ ropts1 == Just ToCost
+      offEnd = rpValue == Just AsRecorded || maybe False (not . isEnd) (value_ ropts1)
+  case calc of
+    CalcGain | atCost -> Left GainNotCost
+    _ | calc `elem` [CalcValueChange, CalcGain], atCost || offEnd -> Left ValuechangeNeedsEnd
+    _ -> Right ()
+  let
+      -- Value changes and gains are figured from period-end market
+      -- values; default to that valuation, as the commands do.
+      value' | calc `elem` [CalcValueChange, CalcGain], Nothing <- value_ ropts1 = Just $ AtEnd Nothing
+             | otherwise = value_ ropts1
+      rpRopts = ropts1 {
+          value_           = value',
+          accountlistmode_ = fromMaybe (accountlistmode_ roptsOrig) mlist,
+          depth_           = if tree then mempty else depth_ ropts1,
+          fold_depth_      = if folding then dsFlatDepth (queryDepth q) else Nothing,
+          row_total_       = total,
+          average_         = avg,
+          sort_amount_     = sortAmt,
+          percent_         = pct,
+          balancecalc_     = calc
+        }
+      -- Unlike the journal and register pages, keep any depth limit:
+      -- the report reads it from the query, and it is how a balance
+      -- report gets summarized (--depth at startup, or depth: in the
+      -- search). In tree mode the report is computed without the flat
+      -- depth limit instead, and the page folds it to that limit, with
+      -- each deeper group openable in place (see reportTable and
+      -- hledger.js); fold_depth_ keeps boring parents from being elided
+      -- across it. Per-account depth limits still clip, as on the
+      -- command line. Depth 0, a single total, has no account to fold
+      -- at, so its page puts the clipped report's one row above the
+      -- whole tree, folded under it (see nestUnderAll).
+      folding = tree
+      rpRspec =
+        rspecOrig {
+          _rsQuery = if folding then simplifyQuery $ filterQuery (not . queryIsFlatDepth) q else q,
+          _rsReportOpts = rpRopts
+        }
+  Right ReportParams{..}
+
+-- | The startup report options and query arguments, expressed as url
+-- state: the parameters for the url that browse mode opens and --serve
+-- prints. Query arguments and query-expressible options
+-- (periods, per-account depths, statuses, -R) become the q parameter's
+-- search terms; the other options the pages know, a flat --depth
+-- among them, become their parameters.
+-- Display preferences without a url spelling (the language, period
+-- title style, report titles) stay in the spec; report options the web
+-- ui has no vocabulary for (--invert, --transpose, ...) are dropped.
+startupUrlState :: ReportSpec -> ([(Text, Text)], ReportSpec)
+startupUrlState rspec@ReportSpec{_rsReportOpts = ropts} = (params, rspec')
+  where
+    params =
+      [("interval", p)        | Just p <- [intervalPeriodExpr $ interval_ ropts]] ++
+      [("depth", T.pack (show n)) | Just n <- [dsFlatDepth $ depth_ ropts]] ++
+      paramSettings accumParam PerPeriod (balanceaccum_ ropts) ++
+      [("value", valueWord m) | Just m <- [amountModeOf ropts], m /= AsRecorded] ++
+      paramSettings listParam ALFlat (accountlistmode_ ropts) ++
+      [("total", "1")         | row_total_ ropts] ++
+      [("avg", "1")           | average_ ropts] ++
+      paramSettings sortParam False (sort_amount_ ropts) ++
+      [("pct", "1")           | percent_ ropts] ++
+      paramSettings calcParam CalcChange (balancecalc_ ropts) ++
+      [("costs", "1")         | show_costs_ ropts] ++
+      [("infer", "1")         | infer_prices_ ropts] ++
+      [("date2", "1")         | date2_ ropts] ++
+      -- -E means the opposite here: hide the zero balances the web ui
+      -- shows by default (cf hideEmptyAccounts).
+      [("empty", "0")         | empty_ ropts] ++
+      [("q", T.unwords qterms) | not (null qterms)]
+    qterms =
+      map textQuoteIfNeeded (querystring_ ropts) ++
+      dateTerm (date2_ ropts) (periodAsDateSpan $ period_ ropts) ++
+      map statusTerm (statuses_ ropts) ++
+      ["real:1" | real_ ropts] ++
+      depthTerms (depth_ ropts)
+    statusTerm s = "status:" <> case s of
+      Unmarked -> ""
+      Pending  -> "!"
+      Cleared  -> "*"
+    depthTerms (DepthSpec _ regexps) =
+      -- quoted when the regexp has a space, like the query terms
+      [textQuoteIfNeeded $ "depth:" <> reString r <> "=" <> T.pack (show n) | (r, n) <- regexps]
+    rspec' = rspec{
+      _rsQuery = Any,
+      _rsQueryOpts = [],
+      _rsReportOpts = defreportopts{
+        -- startup display preferen
+        format_           = format_ ropts,
+        balance_base_url_ = balance_base_url_ ropts,
+        pretty_           = pretty_ ropts,
+        sortspec_         = sortspec_ ropts,
+        color_            = color_ ropts,
+        layout_           = layout_ ropts,
+        period_titles_    = period_titles_ ropts,
+        title_            = title_ ropts,
+        subreport_titles_ = subreport_titles_ ropts,
+        translations_     = translations_ ropts
+      }
+    }
+
+-- | Parse a reporting interval as in a period expression ("monthly",
+-- "every 2 weeks"), with nothing else.
+parseInterval :: Text -> Either HledgerParseErrors Interval
+parseInterval = parsewith (skipNonNewlineSpaces *> reportingintervalp <* skipNonNewlineSpaces <* eof) . T.toLower
+
+-- | The reporting interval a report page uses when none is chosen, to
+-- suit the span it reports on: monthly for up to two years, quarterly
+-- for up to six, yearly beyond, which keeps the table to about two dozen
+-- columns. Monthly when the span is unknown.
+autoInterval :: DateSpan -> Interval
+autoInterval spn = case (spanStart spn, spanEnd spn) of
+  (Just b, Just e)
+    | days > 6 * 366 -> Years 1
+    | days > 2 * 366 -> Quarters 1
+    where days = diffDays e b
+  _ -> Months 1
+
+-- | A parameter's modes as a compact inline switch, eg "List | Tree"
+-- beside a report table's account heading: paramLinks' links, given a
+-- url maker and the parameters to keep, with the mode shown marked.
+paramSwitch :: Eq a => Param a -> Translations -> ([(Text, Text)] -> Text) -> [(Text, Text)] -> a -> a -> Html
+paramSwitch p trs url kept dflt current =
+  H.span ! A.class_ (H.textValue $ "param-switch " <> paramName p <> "-switch") $
+    for_ (paramModes p) $ \a ->
+      let (label, title) = paramLabel p trs a
+      in if a == current
+           then H.span ! A.class_ "current" $ H.toHtml label
+           else H.a ! A.href (H.textValue $ url $ kept' ++ paramSettings p dflt a) ! A.title (H.textValue title) $ H.toHtml label
+  where kept' = filter ((/= paramName p) . fst) kept
+
+-- | A period expression naming the given reporting interval, none for
+-- NoInterval: the inverse of parseInterval.
+intervalPeriodExpr :: Interval -> Maybe Text
+intervalPeriodExpr = \case
+  NoInterval -> Nothing
+  Days 1     -> Just "daily"
+  Weeks 1    -> Just "weekly"
+  Months 1   -> Just "monthly"
+  Quarters 1 -> Just "quarterly"
+  Years 1    -> Just "yearly"
+  Days n     -> Just $ every n "days"
+  Weeks n    -> Just $ every n "weeks"
+  Months n   -> Just $ every n "months"
+  Quarters n -> Just $ every n "quarters"
+  Years n    -> Just $ every n "years"
+  MonthDay n             -> Just $ "every " <> ordinal n <> " day of month"
+  NthWeekdayOfMonth n wd -> (\name -> "every " <> ordinal n <> " " <> name <> " of month") <$> weekdayName wd
+  MonthAndDay m d        -> Just $ "every " <> T.pack (show m) <> "/" <> T.pack (show d)
+  DaysOfWeek [1,2,3,4,5] -> Just "every weekday"
+  DaysOfWeek [6,7]       -> Just "every weekendday"
+  DaysOfWeek []          -> Nothing
+  DaysOfWeek ds          -> ("every " <>) . T.intercalate "," <$> traverse weekdayName ds
+  where
+    every n unit = "every " <> T.pack (show n) <> " " <> unit
+    ordinal n = T.pack (show n) <> suffix
+      where
+        suffix | n `mod` 100 `elem` [11, 12, 13] = "th"
+               | otherwise = case n `mod` 10 of 1 -> "st"; 2 -> "nd"; 3 -> "rd"; _ -> "th"
+    -- The period parser accepts any day number in "every Nth day of
+    -- week", so days outside 1-7 arrive here: they have no name, and
+    -- their interval yields no period expression.
+    weekdayName d = lookup d $ zip [1..] ["monday","tuesday","wednesday","thursday","friday","saturday","sunday"]
+
+-- | Links to the report pages, given as route, label, and title, keeping
+-- the given parameters; the page being shown is marked. Unlike the other
+-- rows of links, this one needs no label: it is the pages' navigation.
+reportLinks :: Eq r => Translations -> r -> [(Text, Text)] -> [(r, Text, Text)] -> HtmlUrl r
+reportLinks trs here kept items =
+  linksRowClass "reports" ""
+    [ (tr trs label, tr trs title, (route, kept), route == here) | (route, label, title) <- items ]
+
+-- | Links to the same report page for each reporting interval, keeping
+-- the search (and its dates) and the given parameters; the interval
+-- being shown is marked.
+intervalLinks :: Translations -> r -> [(Text, Text)] -> Text -> Interval -> HtmlUrl r
+intervalLinks = intervalLinksWith "interval"
+
+-- | 'intervalLinks' setting this parameter, eg the holdings page's own
+-- interval (hinterval).
+intervalLinksWith :: Text -> Translations -> r -> [(Text, Text)] -> Text -> Interval -> HtmlUrl r
+intervalLinksWith ivlparam trs route kept qparam current =
+  -- The D, W, M, Q, and Y keys follow these links, by their order
+  -- here (hledger.js).
+  -- TRANSLATORS: the label before a report's interval links.
+  linksRowClass "interval" (tr trs "Interval:")
+    [ (label, title, link mword, ivl == current) | (label, title, mword, ivl) <- intervals ]
+  where
+    -- TRANSLATORS: the interval links above a report: each link's text, and its tooltip.
+    intervals :: [(Text, Text, Maybe Text, Interval)]
+    intervals =
+      [ (trc trs "interval" "None", tr trs "Show one column for the whole period", Just "none",      NoInterval)
+      , (tr trs "Yearly",    tr trs "Show a column per year",               Just "yearly",    Years 1)
+      , (tr trs "Quarterly", tr trs "Show a column per quarter",            Just "quarterly", Quarters 1)
+      , (tr trs "Monthly",   tr trs "Show a column per month",              Just "monthly",   Months 1)
+      , (tr trs "Weekly",    tr trs "Show a column per week",               Just "weekly",    Weeks 1)
+      , (tr trs "Daily",     tr trs "Show a column per day",                Just "daily",     Days 1)
+      ]
+    link mword =
+      (route, [("q", qparam) | not (T.null qparam)] ++ kept ++ [(ivlparam, w) | Just w <- [mword]])
+
+-- | A parameter that turns something on: "1", or "0" or nothing for off.
+parseFlag :: Text -> Maybe Text -> Either ReportParamError Bool
+parseFlag name = \case
+  Nothing    -> Right False
+  Just ""    -> Right False
+  Just "0"   -> Right False
+  Just "1"   -> Right True
+  Just other -> Left $ BadParamValue name other
+
+-- | Read a multiple-choice parameter's value (see 'parseParam'),
+-- naming the parameter if the value is unknown.
+readParam :: Param a -> Maybe Text -> Either ReportParamError (Maybe a)
+readParam p = either (Left . BadParamValue (paramName p)) Right . parseParam p
+
+-- | The accum parameter: whether a report shows balance changes, ending
+-- balances, or cumulative totals; absent for the page's own default.
+-- The links follow the command line's order: --change, --cumulative,
+-- --historical. The H key toggles Ending balances, the last link (hledger.js).
+accumParam :: Param BalanceAccumulation
+accumParam = Param
+  { paramName  = "accum"
+  , paramModes = [PerPeriod, Cumulative, Historical]
+  , paramWord  = \case
+      PerPeriod  -> "change"
+      Cumulative -> "cumulative"
+      Historical -> "historical"
+  -- TRANSLATORS: the label before a report's accumulation mode links, and the links' text and tooltips.
+  , paramRowLabel = \trs -> tr trs "Show:"
+  , paramLabel = \trs -> \case
+      PerPeriod  -> (tr trs "Balance changes", tr trs "Show how much each balance changed in each period")
+      Cumulative -> (tr trs "Cumulative totals", tr trs "Show each balance's change since the start of the report (--cumulative)")
+      Historical -> (tr trs "Ending balances", tr trs "Show each balance at the end of each period, including everything before it")
+  }
+
+-- | The calc parameter: what a report's cells calculate, as the balance
+-- commands' --valuechange, --gain, and --count flags choose.
+calcParam :: Param BalanceCalculation
+calcParam = Param
+  { paramName  = "calc"
+  , paramModes = [CalcChange, CalcValueChange, CalcGain, CalcPostingsCount]
+  , paramWord  = \case
+      CalcChange        -> "change"
+      CalcValueChange   -> "valuechange"
+      CalcGain          -> "gain"
+      CalcPostingsCount -> "count"
+      -- Not offered (not in paramModes), so never in a url.
+      _                 -> ""
+  -- TRANSLATORS: the label before a report's calculation links, and the links' text and tooltips.
+  , paramRowLabel = \trs -> tr trs "Calculate:"
+  , paramLabel = \trs -> \case
+      CalcChange        -> (trc trs "calculation" "Sums", tr trs "Show sums of postings")
+      CalcValueChange   -> (tr trs "Value change", tr trs "Show how period-end market values changed (--valuechange)")
+      CalcGain          -> (tr trs "Unrealized gain", tr trs "Show unrealized capital gains: market value minus cost (--gain)")
+      CalcPostingsCount -> (tr trs "Posting counts", tr trs "Count the postings instead of summing them (--count)")
+      _                 -> ("", "")
+  }
+
+-- | The list parameter: show accounts as a flat list or a tree; absent
+-- for the page's default, the startup one. The t key toggles them
+-- (hledger.js).
+listParam :: Param AccountListMode
+listParam = Param
+  { paramName  = "list"
+  , paramModes = [ALFlat, ALTree]
+  , paramWord  = \case
+      ALFlat -> "flat"
+      ALTree -> "tree"
+  -- TRANSLATORS: the label before a report's list/tree links, and the links' text and tooltips.
+  , paramRowLabel = \trs -> tr trs "Accounts:"
+  , paramLabel = \trs -> \case
+      ALFlat -> (trc trs "accounts" "List", tr trs "Show accounts as a flat list (--flat)")
+      ALTree -> (trc trs "accounts" "Tree", tr trs "Show accounts as a tree (--tree)")
+  }
+
+-- | The sort parameter: whether rows are sorted by amount, rather than
+-- by account display order (declaration order, otherwise name).
+-- The S key toggles By amount, the second link (hledger.js).
+sortParam :: Param Bool
+sortParam = Param
+  { paramName  = "sort"
+  , paramModes = [False, True]
+  , paramWord  = \case
+      False -> "account"
+      True  -> "amount"
+  -- TRANSLATORS: the label before a report's sort links, and the links' text and tooltips.
+  , paramRowLabel = \trs -> tr trs "Sort:"
+  , paramLabel = \trs -> \case
+      False -> (tr trs "By account", tr trs "Sort rows by account display order")
+      True  -> (tr trs "By amount", tr trs "Sort rows by their amounts, largest first (-S)")
+  }
+
+-- | The chart parameter: how a report's chart lays out each period's amounts:
+-- all in one bar above and below zero (the default), or a bar per account type
+-- (a statement's sections), side by side.
+chartParam :: Param BarLayout
+chartParam = Param
+  { paramName  = "chart"
+  , paramModes = [Diverging, Grouped]
+  , paramWord  = \case
+      Diverging -> "diverging"
+      Grouped   -> "grouped"
+  -- TRANSLATORS: the label before a report's chart layout links, and the links' text and tooltips.
+  , paramRowLabel = \trs -> tr trs "Chart:"
+  , paramLabel = \trs -> \case
+      Diverging -> (tr trs "Diverging", tr trs "Chart each period's amounts in one bar, above and below zero (--chart=diverging)")
+      Grouped   -> (tr trs "Grouped", tr trs "Chart each period's account types in bars side by side (--chart=grouped)")
+  }
+
+-- | Of the parameters the page links keep, those the sidebar's register
+-- links keep: the states the register reads, ie the depth limit (which
+-- clips its sidebar), the amounts mode, the accounts mode, inferred
+-- prices, zero balances, and lot detail. Each such link rewrites the
+-- search itself.
+registerKeptParams :: [(Text, Text)] -> [(Text, Text)]
+registerKeptParams ps = [p | p@(k, _) <- ps, k `elem` ["depth", "value", paramName listParam, "infer", "empty", "lots"]]
+
+-- | The report options a page's parameters set, as short phrases for the
+-- closed controls disclosure: the controls' own words where those stand
+-- alone ("Monthly", "Tree"), a phrase where a control's word would not
+-- ("Shown"). The pages' links carry only the options not at their
+-- defaults, so these are the options in effect, listed in the order of
+-- the controls' rows. The filters are not here: they are search terms,
+-- shown in the search box. The depth is the exception, always listed,
+-- since nothing else on the page says it: no depth limit, or one at or
+-- beyond the given deepest account's depth, as "Depth all".
+optionsSummary :: Translations -> Int -> [(Text, Text)] -> [Text]
+optionsSummary = optionsSummaryWith accumParam
+
+-- | Parameters for 'optionsSummary': the given ones, and the interval in
+-- effect if none was chosen, ie the one picked to suit the report's span
+-- (see 'autoInterval'), which the interval links show marked, so that
+-- the summary lists it too.
+withIntervalInEffect :: Interval -> [(Text, Text)] -> [(Text, Text)]
+withIntervalInEffect ivl ps
+  | any ((== "interval") . fst) ps = ps
+  | otherwise = ps ++ [("interval", w) | Just w <- [intervalPeriodExpr ivl]]
+
+-- | 'optionsSummary' for a page whose accum parameter's links have
+-- their own labels (the holdings page's gains), given by this Param.
+optionsSummaryWith :: Param BalanceAccumulation -> Translations -> Int -> [(Text, Text)] -> [Text]
+optionsSummaryWith accumP trs deepest = mapMaybe phrase . sortOn (rowOrder . fst)
+  where
+    -- TRANSLATORS: the depth limit, in the list of options in effect; {depth} is a number, or "all" (translated separately) for no limit.
+    depthPhrase n = trf trs "Depth {depth}" [("depth", n)]
+    -- TRANSLATORS: no depth limit, as {depth} in "Depth {depth}" in the list of options in effect.
+    depthAll = depthPhrase $ trc trs "depth" "all"
+
+    rowOrder k = fromMaybe maxBound $ elemIndex k
+      ["equity", "interval", paramName accumParam, "depth", paramName listParam, "value", "infer", "empty", "lots", "closed",
+       "total", "avg", "costs", paramName sortParam, "pct", paramName calcParam, "date2", paramName chartParam]
+    phrase = \case
+      ("interval", "none") -> Nothing
+      ("interval", w)     -> Just $ fromMaybe w $ lookup w
+        [ ("yearly", tr trs "Yearly"), ("quarterly", tr trs "Quarterly"), ("monthly", tr trs "Monthly")
+        , ("weekly", tr trs "Weekly"), ("daily", tr trs "Daily") ]
+      -- The depth is always listed, the default too: this is where the
+      -- page says what depth it shows. No limit is all, or a depth at or
+      -- beyond the deepest.
+      ("depth", "all")    -> Just depthAll
+      ("depth", n)        -> do
+        d <- readMay (T.unpack n) :: Maybe Int
+        Just $ if d >= deepest then depthAll else depthPhrase n
+      (k, w) | k == paramName accumP -> paramPhrase accumP trs w
+      ("value", "none")   -> Just $ tr trs "As recorded"
+      ("value", "cost")   -> Just $ trc trs "amounts" "Cost"
+      ("value", _)        -> Just $ trc trs "amounts" "Value"
+      (k, w) | k == paramName listParam -> paramPhrase listParam trs w
+      (k, w) | k == paramName sortParam -> paramPhrase sortParam trs w
+      ("pct", "1")        -> Just $ tr trs "Percentages"
+      -- TRANSLATORS: the grouped chart layout, in the list of options in effect.
+      ("chart", "grouped") -> Just $ tr trs "Grouped chart"
+      (k, w) | k == paramName calcParam -> paramPhrase calcParam trs w
+      -- TRANSLATORS: options in effect, listed on the closed options disclosure.
+      ("total", "1")      -> Just $ trc trs "column" "Total"
+      ("avg", "1")        -> Just $ trc trs "column" "Average"
+      ("infer", "1")      -> Just $ tr trs "Inferred prices"
+      ("empty", "0")      -> Just $ tr trs "Zero balances hidden"
+      ("empty", "1")      -> Just $ tr trs "Zero balances shown"
+      ("lots", "1")       -> Just $ tr trs "Lots shown"
+      ("costs", "1")      -> Just $ tr trs "Costs shown"
+      ("closed", "1")     -> Just $ tr trs "Closed positions shown"
+      ("closed", "0")     -> Just $ tr trs "Closed positions hidden"
+      ("date2", "1")      -> Just $ tr trs "Secondary dates"
+      ("equity", "1")     -> Just $ tr trs "Equity shown"
+      _                   -> Nothing
+
+-- | The value parameter, mirroring --value's WHEN[,COMM] syntax:
+-- "none", "cost", or a valuation "end", "then", "now", or a date, each
+-- optionally with a commodity to convert to (end,EUR = -X EUR). None
+-- for the startup options' conversion.
+parseValue :: Maybe Text -> Either ReportParamError (Maybe AmountMode)
+parseValue = \case
+  Nothing -> Right Nothing
+  Just "" -> Right Nothing
+  Just v ->
+    let (w, c) = T.break (== ',') v
+        mc = mfilter (not . T.null) $ Just $ T.drop 1 c
+        ok = Right . Just
+    in case (w, mc) of
+      ("none", Nothing) -> ok AsRecorded
+      ("cost", Nothing) -> ok AtCost
+      ("end",  _)       -> ok $ AtVal $ AtEnd mc
+      ("then", _)       -> ok $ AtVal $ AtThen mc
+      ("now",  _)       -> ok $ AtVal $ AtNow mc
+      _ | Just d <- parsedate (T.unpack w) -> ok $ AtVal $ AtDate d mc
+      _ -> Left $ BadValue v
+
+-- | Which amount mode report options convert amounts by, if any: only
+-- cost combined with a valuation, or conversion to transacted cost, are
+-- none of them.
+amountModeOf :: ReportOpts -> Maybe AmountMode
+amountModeOf ropts =
+  case (conversionop_ ropts, value_ ropts) of
+    (Just ToCost,           Nothing) -> Just AtCost
+    (Just ToCost,           _)       -> Nothing
+    (Just ToTransactedCost, _)       -> Nothing
+    (_,                     Nothing) -> Just AsRecorded
+    (_,                     Just vt) -> Just $ AtVal vt
+
+-- | Report options converting amounts by the given mode, and no other way.
+setAmountMode :: AmountMode -> ReportOpts -> ReportOpts
+setAmountMode mode ropts =
+  case mode of
+    AsRecorded -> ropts{conversionop_ = Just NoConversionOp, value_ = Nothing}
+    AtCost     -> ropts{conversionop_ = Just ToCost,         value_ = Nothing}
+    AtVal vt   -> ropts{conversionop_ = Just NoConversionOp, value_ = Just vt}
+
+-- | The value parameter that links staying on a page keep: the mode
+-- given, unless it is the startup options' own.
+valueParams :: ReportOpts -> Maybe AmountMode -> [(Text, Text)]
+valueParams roptsOrig mmode =
+  [("value", valueWord m) | Just m <- [mmode], Just m /= amountModeOf roptsOrig]
+
+-- | Add query parameters to a cell's link, if it has one. The values
+-- are url-encoded (interval words like "every 2 weeks", and value
+-- parameters carrying a commodity, are not url-safe); the keys are our
+-- own constant names.
+addLinkParams :: [(Text, Text)] -> Cell b Text -> Cell b Text
+addLinkParams [] c = c
+addLinkParams params c
+  | T.null (cellAnchor c) = c
+  | otherwise = c {cellAnchor = cellAnchor c <> sep <> T.intercalate "&" [k <> "=" <> enc v | (k, v) <- params]}
+  where
+    enc = TE.decodeUtf8 . urlEncode True . TE.encodeUtf8
+    sep = if "?" `T.isInfixOf` cellAnchor c then "&" else "?"
+
+-- | Label a depth 0 report's "..." row, all accounts in one, with the
+-- given word, as hledger-ui does.
+labelAllAccounts :: Text -> Cell b Text -> Cell b Text
+labelAllAccounts lbl c
+  | "account" `elem` T.words (textFromClass (cellClass c))
+  , T.dropWhile (== '\160') (cellContent c) == "..." = c {cellContent = lbl}
+  | otherwise = c
+
+-- | A tree-mode table section folded at depth 0: the depth 0 report's
+-- rows (its one row, all accounts in one) for that section, then the
+-- full tree's rows, each indented one level more, beneath it. The
+-- table then folds them all away under that row, whose caret opens
+-- them (see reportTable and hledger.js).
+nestUnderAll :: [[Cell b Text]] -> [[Cell b Text]] -> [[Cell b Text]]
+nestUnderAll allRows rows = allRows ++ map (map deeper) rows
+  where
+    deeper c = c{cellClass = Class $ T.unwords $ map deeperWord $ T.words $ textFromClass $ cellClass c}
+    deeperWord w
+      | Just n <- readMay . T.unpack =<< T.stripPrefix "indent-" w = "indent-" <> T.pack (show (n + 1 :: Int))
+      | otherwise = w
+
+-- | Force a report enough to surface the error a percentage report
+-- raises when its amounts span commodities: that depends on the data,
+-- not the parameters, so reportParams cannot catch it. Nothing when
+-- the report calculates.
+reportProbe :: Show r => r -> IO (Maybe String)
+reportProbe r =
+  E.handle (\(E.ErrorCall e) -> pure $ Just e) $
+    Nothing <$ E.evaluate (length $ show r)
+
+-- | Explain percentages falling back to plain amounts, showing the
+-- report's own message.
+pctError :: Translations -> String -> Html
+pctError trs e =
+  H.div ! A.class_ "alert alert-danger" $ do
+    H.toHtml $ tr trs "Could not calculate percentages:"
+    H.pre $ H.toHtml $ fromMaybe e $ stripPrefix "Error: " e
+
+-- | Explain a parameter the page could not use.
+paramError :: Translations -> ReportParamError -> Html
+paramError trs = \case
+  BadInterval err ->
+    H.div ! A.class_ "alert alert-danger" $ do
+      H.toHtml $ tr trs "Could not parse the reporting interval:"
+      H.pre $ H.toHtml err
+  BadValue v ->
+    H.div ! A.class_ "alert alert-danger" $ do
+      H.toHtml $ tr trs "Unknown amount conversion:"
+      H.pre $ H.toHtml v
+  BadParamValue name v ->
+    H.div ! A.class_ "alert alert-danger" $ do
+      H.toHtml $ trf trs "The {name} parameter has a value this page does not know:" [("name", name)]
+      H.pre $ H.toHtml v
+  ValuechangeNeedsEnd ->
+    H.div ! A.class_ "alert alert-danger" $
+      H.toHtml $ tr trs "Value changes and gains are figured from period-end market values: leave the value parameter off, or use value=end."
+  GainNotCost ->
+    H.div ! A.class_ "alert alert-danger" $
+      H.toHtml $ tr trs "Gains compare market value against cost, so they do not combine with value=cost."
+  ValueThenUnsupported ->
+    H.div ! A.class_ "alert alert-danger" $
+      H.toHtml $ tr trs "This report is at a single date, so value=then does not apply: use value=end, value=now, or a date."
+
+-- | The depth parameter for the query's depth limit, for links keeping
+-- it: depth=all when it has none, since no parameter means the default
+-- depth (see App.getViewData). (Only a depth:REGEX=N term can be in the
+-- search, which keeps it there: see App.setDepthFromSearch.)
+depthParams :: Query -> [(Text, Text)]
+depthParams q = [("depth", maybe "all" (T.pack . show) $ dsFlatDepth $ queryDepth q)]
+
+-- | The deepest account depth a report page can show: that of the
+-- journal's deepest account. The journal as displayed with lots shown
+-- includes the lot subaccounts, which are ordinary accounts here, so
+-- the Depth row extends to them, as in hledger-ui.
+deepestDepth :: Journal -> Int
+deepestDepth j = maximum (0 : map accountNameLevel (journalAccountNames j))
+
+-- | A column's heading: its period, or for ending balances and
+-- cumulative totals the period's end date, which is what those are at.
+columnHeading :: ReportOpts -> [DateSpan] -> DateSpan -> Text
+columnHeading ropts colspans spn =
+  case balanceaccum_ ropts of
+    PerPeriod -> renderPeriodHeading (period_titles_ ropts) spn
+    _         -> reportPeriodName ropts colspans spn
+
+-- A column heading opens this report for that column's period, in
+-- place of any date terms in the search, which the column narrows
+-- anyway. A chosen interval is kept (the drilled view is one column of
+-- it), so the report's subdivision survives navigating on from there.
+headingParams :: Text -> [(Text, Text)] -> DateSpan -> [(Text, Text)]
+headingParams qparam params spn =
+  [("q", T.unwords qt) |
+      let qt = dateTerm False spn ++ removeDates qparam,
+      not (null qt)] ++
+  removeAttributes ["q"] params
+
+removeAttributes :: [Text] -> [(Text, Text)] -> [(Text, Text)]
+removeAttributes attrs =
+  let attrSet = Set.fromList attrs
+  in filter (flip Set.notMember attrSet . fst)
+
+-- | Give a report's heading row this page's column headings and links:
+-- the cells that link (the columns' periods) get the given heading text
+-- and link for their span.
+relinkDateHeaders ::
+  Translations -> (DateSpan -> Text) -> (DateSpan -> Text) -> [DateSpan] -> [Cell NumLines Text] -> [Cell NumLines Text]
+relinkDateHeaders trs heading link = go
+  where
+    go (spn:spns) (c:cs)
+      | not (T.null $ cellAnchor c) =
+          c {cellContent = heading spn, cellAnchor = link spn, cellTitle = tr trs "Show this report for this period"} : go spns cs
+    go spns (c:cs) = c : go spns cs
+    go _ [] = []
+
+-- | In a flat report's body rows, strip what the account names share
+-- above their leaf names, and mark the account cells for path-dimmed
+-- rendering (acct-split; see reportTable and .acct-path in hledger.css):
+-- the least interesting parents stop repeating down the page. The
+-- register links keep the full names, which also head each cell's
+-- tooltip. Returns the shared prefix, for showing once in a heading.
+splitAccountNames :: [[Cell b Text]] -> (Maybe AccountName, [[Cell b Text]])
+splitAccountNames rws = (mprefix, map (map split) rws)
+  where
+    isAcct c = textFromClass (cellClass c) == "account"
+    names = [cellContent c | r <- rws, c <- r, isAcct c]
+    prefix = case map accountNameComponents names of
+      []    -> []
+      comps -> foldl1 commonPrefix (map init comps)  -- init: each leaf stays in its row
+    commonPrefix (x:xs) (y:ys) | x == y = x : commonPrefix xs ys
+    commonPrefix _ _ = []
+    mprefix = if null prefix then Nothing else Just (accountNameFromComponents prefix)
+    split c
+      | isAcct c = c
+          { cellContent = accountNameFromComponents $ drop (length prefix) $ accountNameComponents $ cellContent c
+          , cellClass = Class "account acct-split"
+          , cellTitle = cellContent c <> "\n" <> cellTitle c
+          }
+      | otherwise = c
+
+-- | A small control beside a report table's account heading, stepping
+-- the depth limit one level down or up as the - and + keys do: the Depth
+-- row's links, which are tucked away among the options, where the eye is
+-- when reading the table. Given a url maker, the parameters the links
+-- keep (the search and the page's own, any depth among them), and the
+-- deepest account depth, at which there is no limit. It stops at 0 and
+-- at the deepest; each step's tooltip says the depth it leads to. In
+-- tree mode, where the limit is the depth the tree is folded to, the
+-- steps fold or open a level of the whole tree.
+depthStepper :: Translations -> ([(Text, Text)] -> Text) -> [(Text, Text)] -> Int -> Html
+depthStepper trs url kept deepest =
+  H.span ! A.class_ "depth-stepper" $ do
+    step (current - 1) "\x2212"
+    step (current + 1) "+"
+  where
+    current = maybe deepest (min deepest) $ readMay . T.unpack =<< lookup "depth" kept
+    step n glyph
+      | n < 0 || n > deepest = H.span ! A.class_ "depth-step disabled" $ glyph
+      | otherwise =
+          H.a ! A.class_ "depth-step" ! A.title (H.textValue $ depthTitle trs deepest n)
+              ! A.href (H.textValue $ url $ filter ((/= "depth") . fst) kept ++ [depthParam deepest n]) $
+            glyph
+
+-- | Where a report page folds its tree at the depth limit (see
+-- reportParams), the report spec for its chart, given the page's search:
+-- one clipping the tree there instead, as the command line does, since a
+-- chart can't fold. Otherwise the chart's report is the page's own.
+chartReportSpec :: Query -> ReportSpec -> Maybe ReportSpec
+chartReportSpec q rspec@ReportSpec{_rsReportOpts = ropts} =
+  rspec{_rsQuery = q, _rsReportOpts = ropts{fold_depth_ = Nothing}} <$ fold_depth_ ropts
+
+-- | A report as a table in the page's own style: the heading rows, then
+-- a table section per report section (a titled row, its rows, then its
+-- subtotal rows), then the total rows as the table's footer. It scrolls
+-- sideways within the page when it is wider (see .report-table in
+-- hledger.css; bootstrap's .table-responsive does that only on a phone).
+-- In tree mode the rows carry indent and depth classes, the indent
+-- becomes css padding so hledger.js can put a fold caret at each group,
+-- and the table says what depth to fold to initially, if any.
+-- The given html is shown beside the account column's heading (eg
+-- depthStepper).
+reportTable ::
+  Bool -> Maybe Int -> Html ->
+  [[Cell NumLines Text]] -> [(Maybe Text, [[Cell NumLines Text]], [[Cell NumLines Text]])] -> [[Cell NumLines Text]] -> Html
+reportTable isTree mfold headingExtra header sections footer =
+  H.div ! A.class_ "table-responsive report-table" $
+    maybe id (\n t -> t ! H.dataAttribute "depth-fold" (H.toValue n)) mfold
+      (H.table ! A.class_ "balancereport table table-condensed") $ do
+      H.thead $ case header of
+        (c:cs) : hs -> do
+          tr' Nothing $ do
+            formatCell (cellHtml c){cellContent = H.toHtml (cellContent c) <> headingExtra}
+            traverse_ (formatCell . cellHtml) cs
+          rows Nothing hs
+        _ -> rows Nothing header
+      traverse_ section sections
+      unless (null footer) $ H.tfoot $ rows Nothing footer
+  where
+    ncols = maybe 1 length $ listToMaybe header
+    section (mtitle, body, subtotals) =
+      H.tbody $ do
+        for_ mtitle $ \t ->
+          H.tr ! A.class_ "section" $
+            H.th ! A.colspan (H.toValue ncols) ! H.customAttribute "scope" "rowgroup" $ H.toHtml t
+        traverse_ (uncurry row) $ zip (foldClasses body) body
+        rows (Just "subtotal") subtotals
+    rows mcls = traverse_ (row mcls)
+    row mcls r = tr' mcls $ traverse_ (formatCell . cellHtml) (stripIndents r)
+    tr' mcls cells = maybe id (\c -> (! A.class_ c)) mcls H.tr cells <> nl
+    -- With a depth limit, the rows below it are served already folded,
+    -- so the table paints at its folded height and nothing moves after
+    -- paint; hledger.js's carets toggle the same class from there.
+    -- A row is folded when one of its ancestor rows (the nearest row at
+    -- each lesser indent-N) is an account at or below the limit (its
+    -- depth-N). The limit counts account name levels, not indents,
+    -- which differ where boring parents are elided into a row.
+    foldClasses body = case mfold of
+      Nothing -> map (const Nothing) body
+      Just d -> snd $ mapAccumL (foldStep d) [] body
+    -- The ancestors stack holds the (indent, level) of the current
+    -- row's ancestor rows, nearest first.
+    foldStep d ancestors r = case (rowClassNum "indent-" r, rowClassNum "depth-" r) of
+      (Just dep, Just lvl) ->
+        let ancestors' = dropWhile ((>= dep) . fst) ancestors
+        in ((dep, lvl) : ancestors', "tree-fold-hide" <$ find ((>= d) . snd) ancestors')
+      _ -> (ancestors, Nothing)
+    rowClassNum prefix r = listToMaybe
+      [ n | c <- r, cls <- T.words $ textFromClass $ cellClass c
+          , Just ns <- [T.stripPrefix prefix cls]
+          , ((n, "") : _) <- [reads (T.unpack ns) :: [(Int, String)]] ]
+    -- An account cell marked acct-split renders as two spans, the parent
+    -- path and the leaf name, so css can dim the path and shorten it from
+    -- the left (.acct-path in hledger.css). The inner span is a bidi
+    -- isolate there, keeping that css left-shortening trick
+    -- (direction: rtl) from reordering the name.
+    cellHtml c
+      | "acct-split" `elem` T.words (textFromClass (cellClass c))
+      , (path, leaf) <- T.breakOnEnd ":" (cellContent c)
+      , not (T.null path)
+      = (H.toHtml <$> c)
+          { cellContent =
+              (H.span ! A.class_ "acct-path") (H.span $ H.toHtml $ T.init path)
+              <> H.toHtml (":" :: Text)
+              <> (H.span ! A.class_ "acct-leaf") (H.toHtml leaf) }
+      | otherwise = H.toHtml <$> c
+    -- The nbsp indent the renderer gives tree-mode account names, as
+    -- padding instead (hledger.css indents by the depth class), so the
+    -- caret sits at the name.
+    stripIndents | isTree = map stripCell
+                 | otherwise = id
+    stripCell c
+      | "indent-" `T.isInfixOf` textFromClass (cellClass c) = c{cellContent = T.dropWhile (== '\160') (cellContent c)}
+      | otherwise = c
diff --git a/Hledger/Web/Settings.hs b/Hledger/Web/Settings.hs
--- a/Hledger/Web/Settings.hs
+++ b/Hledger/Web/Settings.hs
@@ -25,7 +25,7 @@
 import Yesod.Default.Config
 import Yesod.Default.Util
 
-import Hledger.Cli.Version (packagemajorversion)
+import Hledger.Cli.Version (webManualUrl)
 
 development :: Bool
 development =
@@ -38,11 +38,12 @@
 production :: Bool
 production = not development
 
-hledgerorgurl :: Text
-hledgerorgurl = "https://hledger.org"
-
-manualurl :: Text
-manualurl = hledgerorgurl <> "/" <> T.pack packagemajorversion <> "/hledger.html"
+-- | The hledger and hledger-web manuals' URLs on hledger.org, for this
+-- build's version (the dev manuals, for a dev build; see
+-- 'Hledger.Cli.Version.docVersion').
+manualurl, webmanualurl :: Text
+manualurl    = T.pack $ webManualUrl "hledger" Nothing
+webmanualurl = T.pack $ webManualUrl "hledger-web" Nothing
 
 -- | The default IP address to listen on. May be overridden with --host.
 defhost :: String
@@ -112,12 +113,10 @@
 
 data Extra = Extra
     { extraCopyright  :: Text
-    , extraAnalytics  :: Maybe Text -- ^ Google Analytics
     , extraStaticRoot :: Maybe Text
     } deriving Show
 
 parseExtra :: DefaultEnv -> Object -> Parser Extra
 parseExtra _ o = Extra
     <$> o .:  "copyright"
-    <*> o .:? "analytics"
     <*> o .:? "staticRoot"
diff --git a/Hledger/Web/Settings/StaticFiles.hs b/Hledger/Web/Settings/StaticFiles.hs
--- a/Hledger/Web/Settings/StaticFiles.hs
+++ b/Hledger/Web/Settings/StaticFiles.hs
@@ -7,7 +7,7 @@
 import Data.FileEmbed (embedDir)
 import Network.Wai.Application.Static (defaultFileServerSettings, embeddedSettings, staticApp)
 import System.IO (stdout, hFlush)
-import WaiAppStatic.Types (StaticSettings(..))
+import WaiAppStatic.Types (MaxAge(..), StaticSettings(..))
 import Yesod.Core (WaiSubsite(..))
 
 import Hledger.Web.Settings (staticDir, development, staticFileRoute)
@@ -27,24 +27,13 @@
      -- putStrLn "Using built-in web files" >> hFlush stdout
      return $ serve $ embeddedSettings $(embedDir staticDir)
   where
-    -- serve files with hash-based ETag headers, so browsers can cache them
-    serve settings = WaiSubsite $ staticApp settings{ssUseHash = True}
+    -- Serve files with hash-based ETag headers, and Cache-Control: no-cache,
+    -- so browsers keep them but check with us before each use (a cheap 304 if unchanged).
+    -- Otherwise a browser may keep using an old hledger.js after an upgrade or rebuild.
+    serve settings = WaiSubsite $ staticApp settings{ssUseHash = True, ssMaxAge = NoCache}
 
 -- Type-safe routes for the static files used by the app,
 -- verified to exist at compile time.
-css_bootstrap_min_css                       = $(staticFileRoute "css/bootstrap.min.css")
-css_bootstrap_datepicker_standalone_min_css = $(staticFileRoute "css/bootstrap-datepicker.standalone.min.css")
-js_bootstrap_min_js                         = $(staticFileRoute "js/bootstrap.min.js")
-js_bootstrap_datepicker_min_js              = $(staticFileRoute "js/bootstrap-datepicker.min.js")
-js_excanvas_min_js                          = $(staticFileRoute "js/excanvas.min.js")
-js_jquery_cookie_js                         = $(staticFileRoute "js/jquery.cookie.js")
-js_jquery_flot_min_js                       = $(staticFileRoute "js/jquery.flot.min.js")
-js_jquery_flot_selection_min_js             = $(staticFileRoute "js/jquery.flot.selection.min.js")
-js_jquery_flot_time_min_js                  = $(staticFileRoute "js/jquery.flot.time.min.js")
-js_jquery_flot_tooltip_min_js               = $(staticFileRoute "js/jquery.flot.tooltip.min.js")
-js_jquery_hotkeys_js                        = $(staticFileRoute "js/jquery.hotkeys.js")
-js_jquery_min_js                            = $(staticFileRoute "js/jquery.min.js")
-js_jquery_url_js                            = $(staticFileRoute "js/jquery.url.js")
-js_typeahead_bundle_min_js                  = $(staticFileRoute "js/typeahead.bundle.min.js")
-hledger_css                                 = $(staticFileRoute "hledger.css")
-hledger_js                                  = $(staticFileRoute "hledger.js")
+css_bootstrap_min_css           = $(staticFileRoute "css/bootstrap.min.css")
+hledger_css                     = $(staticFileRoute "hledger.css")
+hledger_js                      = $(staticFileRoute "hledger.js")
diff --git a/Hledger/Web/Test.hs b/Hledger/Web/Test.hs
--- a/Hledger/Web/Test.hs
+++ b/Hledger/Web/Test.hs
@@ -1,204 +1,3292 @@
 {-|
-Test suite for hledger-web.
-
-Dev notes:
-
-http://hspec.github.io/writing-specs.html
-
-https://hackage.haskell.org/package/yesod-test-1.6.10/docs/Yesod-Test.html
-
-"The best way to see an example project using yesod-test is to create a scaffolded Yesod project:
-stack new projectname yesodweb/sqlite
-(See https://github.com/commercialhaskell/stack-templates/wiki#yesod for the full list of Yesod templates)"
-
-
-These tests don't exactly match the production code path, eg these bits are missing:
-
-  withJournal copts (web wopts)  -- extra withJournal logic (journalTransform..)
-  ...
-  -- query logic, more options logic
-  let depthlessinitialq = filterQuery (not . queryIsDepth) . _rsQuery . reportspec_ $ cliopts_ wopts
-      j' = filterJournalTransactions depthlessinitialq j
-      h = host_ wopts
-      p = port_ wopts
-      u = base_url_ wopts
-      staticRoot = T.pack <$> file_url_ wopts
-      appconfig = AppConfig{appEnv = Development
-                           ,appHost = fromString h
-                           ,appPort = p
-                           ,appRoot = T.pack u
-                           ,appExtra = Extra "" Nothing staticRoot
-                           }
-
-The production code path, when called in this test context, which I guess is using
-yesod's dev mode, needs to read ./config/settings.yml and fails without it (loadConfig).
-
--}
-
-{-# LANGUAGE OverloadedStrings #-}
-
-module Hledger.Web.Test (
-  hledgerWebTest
-) where
-
-import Data.String (fromString)
-import Data.Function ((&))
-import Data.Text qualified as T
-import Test.Hspec (hspec)
-import Yesod.Default.Config
-import Yesod.Test
-
-import Hledger.Web.Application ( makeAppWith )
-import Hledger.Web.WebOptions  -- ( WebOpts(..), defwebopts, prognameandversion )
-import Hledger.Web.Import hiding (get, j)
-import Hledger.Cli hiding (prognameandversion)
-
-
--- | Given a tests description, zero or more raw option name/value pairs,
--- a journal and some hspec tests, parse the options and configure the
--- web app more or less as we normally would (see details above), then run the tests.
---
--- Raw option names are like the long flag without the --, eg "file" or "base-url".
---
--- The journal and raw options should correspond enough to not cause problems.
--- Be cautious - without a [("file", "somepath")], perhaps journalReload could load
--- the user's default journal.
---
-runTests :: String -> [(String,String)] -> Journal -> YesodSpec App -> IO ()
-runTests testsdesc rawopts j tests = do
-  wopts <- rawOptsToWebOpts $ mkRawOpts rawopts
-  let yconf = AppConfig{  -- :: AppConfig DefaultEnv Extra
-          appEnv = Testing
-        -- https://hackage.haskell.org/package/conduit-extra/docs/Data-Conduit-Network.html#t:HostPreference
-        -- ,appHost = "*4"  -- "any IPv4 or IPv6 hostname, IPv4 preferred"
-        -- ,appPort = 3000  -- force a port for tests ?
-        -- Test with the host and port from opts. XXX more fragile, can clash with a running instance ?
-        ,appHost = host_ wopts & fromString
-        ,appPort = port_ wopts
-        ,appRoot = base_url_ wopts & T.pack  -- XXX not sure this or extraStaticRoot get used
-        ,appExtra = Extra
-                    { extraCopyright  = ""
-                    , extraAnalytics  = Nothing
-                    , extraStaticRoot = T.pack <$> file_url_ wopts
-                    }
-        }
-  app <- makeAppWith j yconf wopts
-  hspec $ yesodSpec app $ ydescribe testsdesc tests    -- https://hackage.haskell.org/package/yesod-test/docs/Yesod-Test.html
-
--- | Run hledger-web's built-in tests using the hspec test runner.
-hledgerWebTest :: IO ()
-hledgerWebTest = do
-  putStrLn $ "Running tests for " ++ prognameandversion -- ++ " (--test --help for options)"
-  let d = fromGregorian 2000 1 1
-
-  runTests "hledger-web" [] nulljournal $ do
-
-    yit "serves a reasonable-looking journal page" $ do
-      get JournalR
-      statusIs 200
-      bodyContains "Add a transaction"
-
-    yit "serves a reasonable-looking register page" $ do
-      get RegisterR
-      statusIs 200
-      bodyContains "accounts"
-
-    yit "hyperlinks use a base url made from the default host and port" $ do
-      get JournalR
-      statusIs 200
-      let defaultbaseurl = defbaseurl defhost defport
-      bodyContains ("href=\"" ++ defaultbaseurl)
-      bodyContains ("src=\"" ++ defaultbaseurl)
-
-    -- WIP
-    -- yit "shows the add form" $ do
-    --   get JournalR
-    --   -- printBody
-    --   -- let addbutton = "button:contains('add')"
-    --   -- bodyContains addbutton
-    --   -- htmlAnyContain "button:visible" "add"
-    --   printMatches "div#addmodal:visible"
-    --   htmlCount "div#addmodal:visible" 0
-
-    --   -- clickOn "a#addformlink"
-    --   -- printBody
-    --   -- bodyContains addbutton
-
-    -- yit "can add transactions" $ do
-
-  usecolor <- useColorOnStdout
-  let
-    rawopts = [("forecast","")]
-    iopts = rawOptsToInputOpts d usecolor True $ mkRawOpts rawopts
-    f = "fake"  -- need a non-null filename so forecast transactions get index 0
-  pj <- readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
-    ["~ monthly"
-    ,"    assets    10"
-    ,"    income"
-    ])
-  j <- fmap (either error' id) . runExceptT $ journalFinalise iopts f "" pj  -- PARTIAL: journalFinalise should not fail
-  runTests "hledger-web with --forecast" rawopts j $ do
-
-    yit "shows forecasted transactions" $ do
-      get JournalR
-      statusIs 200
-      bodyContains "id=\"transaction-2-1\""
-      bodyContains "id=\"transaction-2-2\""
-
-  -- Submitting an unbalanced transaction produces an error message that
-  -- echoes the entry (account names, amounts). Those values must be rendered
-  -- as text, not raw html. Note this echo happens on the FormFailure path,
-  -- which yesod does not gate with the CSRF token, so no token is sent here -
-  -- the vector is reachable cross-origin.
-  aj <- fmap (either error' id) . runExceptT . journalFinalise iopts "add.journal" "" =<<
-          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
-            ["2025-01-01 opening"
-            ,"    assets:bank:checking   100"
-            ,"    equity:opening"])
-  runTests "hledger-web add form" [("allow","add")] aj $ do
-
-    yit "escapes submitted values in an add-form error message" $ do
-      get JournalR
-      statusIs 200
-      -- Payloads in the two fields that reach the excerpt: the account name,
-      -- and the (unvalidated) description. Distinct payloads so that escaping
-      -- one field but not the other is caught. The entry parses but does not
-      -- balance, so its excerpt - which includes both fields - is echoed.
-      -- (Date and amount are validated and cannot carry raw html into it.)
-      request $ do
-        setMethod "POST"
-        setUrl AddR
-        addPostParam "_formid" "identify-add"
-        addPostParam "date" "2025-02-02"
-        addPostParam "description" "d<img src=x onerror=alert(1)>"
-        addPostParam "account" "a<img src=x onerror=alert(2)>"
-        addPostParam "amount" "5"
-        addPostParam "account" "equity:opening"
-        addPostParam "amount" "-3"
-      bodyContains "d&lt;img src=x onerror=alert(1)&gt;"   -- description, escaped
-      bodyContains "a&lt;img src=x onerror=alert(2)&gt;"   -- account, escaped
-      bodyNotContains "<img src=x onerror"                 -- neither as raw html
-
-  -- #2127
-  -- XXX I'm pretty sure this test lies, ie does not match production behaviour.
-  -- (test with curl -s http://localhost:5000/journal | rg '(href)="[\w/].*?"' -o )
-  -- App root setup is a maze of twisty passages, all alike.
-  -- runTests "hledger-web with --base-url"
-  --   [("base-url","https://base")] nulljournal $ do
-  --   yit "hyperlinks respect --base-url" $ do
-  --     get JournalR
-  --     statusIs 200
-  --     bodyContains "href=\"https://base"
-  --     bodyContains "src=\"https://base"
-
-  -- #2139
-  -- XXX Not passing.
-  -- Static root setup is a maze of twisty passages, all different.
-  -- runTests "hledger-web with --base-url, --file-url"
-  --   [("base-url","https://base"), ("file-url","https://files")] nulljournal $ do
-  --   yit "static file hyperlinks respect --file-url, others respect --base-url" $ do
-  --     get JournalR
-  --     statusIs 200
-  --     bodyContains "href=\"https://base"
-  --     bodyContains "src=\"https://files"
-
+hledger-web's server tests. These check what the server sends, without a browser;
+hledger-web's browser tests are in test/browser/ (see doc/TESTS.md, "hledger-web's tests").
+
+Dev notes:
+
+http://hspec.github.io/writing-specs.html
+
+https://hackage.haskell.org/package/yesod-test-1.6.10/docs/Yesod-Test.html
+
+"The best way to see an example project using yesod-test is to create a scaffolded Yesod project:
+stack new projectname yesodweb/sqlite
+(See https://github.com/commercialhaskell/stack-templates/wiki#yesod for the full list of Yesod templates)"
+
+
+These tests don't exactly match the production code path, eg these bits are missing:
+
+  withJournal copts (web wopts)  -- extra withJournal logic (journalTransform..)
+  ...
+  let h = host_ wopts
+      p = port_ wopts
+      u = base_url_ wopts
+      staticRoot = T.pack <$> file_url_ wopts
+      appconfig = AppConfig{appEnv = Development
+                           ,appHost = fromString h
+                           ,appPort = p
+                           ,appRoot = T.pack u
+                           ,appExtra = Extra "" staticRoot
+                           }
+
+The production code path, when called in this test context, which I guess is using
+yesod's dev mode, needs to read ./config/settings.yml and fails without it (loadConfig).
+
+-}
+
+{-# LANGUAGE OverloadedStrings #-}
+
+module Hledger.Web.Test (
+  hledgerWebTest
+) where
+
+import Control.Exception (bracket, bracket_)
+import Data.Aeson (encode)
+import Data.ByteString qualified as BS
+import Data.String (fromString)
+import Data.Function ((&))
+import Data.List (nub)
+import Data.Text qualified as T
+import Data.Text.Encoding qualified as TE
+import Data.Text.IO qualified as TIO
+import Data.Text.Lazy qualified as TL
+import Data.Text.Lazy.Encoding qualified as TLE
+import Network.HTTP.Types (HeaderName)
+import Network.Wai.Test (SResponse(..))
+import System.Directory (createDirectoryIfMissing, getTemporaryDirectory, removeDirectoryRecursive)
+import System.Entropy (getEntropy)
+import System.Environment (lookupEnv, setEnv, unsetEnv)
+import System.FilePath ((</>))
+import Test.Hspec (describe, expectationFailure, hspec, it, shouldBe)
+import Text.Printf (printf)
+import Yesod.Default.Config
+import Yesod.Test
+import Web.Cookie (defaultSetCookie, setCookieName, setCookieValue)
+
+import Hledger.Web.Application ( makeAppWith )
+import Hledger.Utils.I18n (noTranslations)
+import Hledger.Web.Paging (pageNumbers)
+import Hledger.Web.Param (Param(..), parseParam)
+import Hledger.Web.ReportPage (accumParam, calcParam, intervalPeriodExpr, listParam, optionsSummary, sortParam, startupUrlState)
+import Hledger.Web.WebOptions  -- ( WebOpts(..), defwebopts, prognameandversion )
+import Hledger.Web.Import hiding (get, j)
+import Hledger.Web.Widget.Common (MovedOptions(..), normalisedSearch, splitPeriodExpr, transactionFragment)
+import Hledger.Cli hiding (prognameandversion)
+
+
+-- | Given a tests description, zero or more raw option name/value pairs,
+-- a journal and some hspec tests, parse the options and configure the
+-- web app more or less as we normally would (see details above), then run the tests.
+--
+-- Raw option names are like the long flag without the --, eg "file" or "base-url".
+--
+-- The journal and raw options should correspond enough to not cause problems.
+-- Be cautious - without a [("file", "somepath")], perhaps journalReload could load
+-- the user's default journal.
+--
+runTests :: String -> [(String,String)] -> Journal -> YesodSpec App -> IO ()
+runTests testsdesc rawopts j tests = do
+  wopts <- rawOptsToWebOpts $ mkRawOpts rawopts
+  let yconf = AppConfig{  -- :: AppConfig DefaultEnv Extra
+          appEnv = Testing
+        -- https://hackage.haskell.org/package/conduit-extra/docs/Data-Conduit-Network.html#t:HostPreference
+        -- ,appHost = "*4"  -- "any IPv4 or IPv6 hostname, IPv4 preferred"
+        -- ,appPort = 3000  -- force a port for tests ?
+        -- Test with the host and port from opts. XXX more fragile, can clash with a running instance ?
+        ,appHost = host_ wopts & fromString
+        ,appPort = port_ wopts
+        ,appRoot = base_url_ wopts & T.pack  -- XXX not sure this or extraStaticRoot get used
+        ,appExtra = Extra
+                    { extraCopyright  = ""
+                    , extraStaticRoot = T.pack <$> file_url_ wopts
+                    }
+        }
+  app <- makeAppWith j yconf wopts
+  hspec $ yesodSpec app $ ydescribe testsdesc tests    -- https://hackage.haskell.org/package/yesod-test/docs/Yesod-Test.html
+
+-- | Assert that a journal file on disk does not contain the given text,
+-- ie that a request which should have been refused did not write to it.
+-- | Request a report page as one period with no depth limit, as many of
+-- these tests expect (by default the pages choose an interval and show
+-- depth 1), with any other parameters. Its links carry these on.
+getWhole :: Route App -> [(T.Text, T.Text)] -> YesodExample App ()
+getWhole r ps = request $ do
+  setMethod "GET"
+  setUrl r
+  mapM_ (uncurry addGetParam) $ ps ++ [("interval", "none"), ("depth", "all")]
+
+journalFileLacks :: FilePath -> T.Text -> YesodExample App ()
+journalFileLacks f t = do
+  txt <- liftIO $ TIO.readFile f
+  assertEq (f ++ " should not contain " ++ T.unpack t) (T.isInfixOf t txt) False
+
+-- | The name of the edit form's textarea in the current page. The edit form
+-- does not name that field, so yesod generates one (eg "f1"); find it rather
+-- than hardcode it, or a post can silently do nothing.
+editFieldName :: YesodExample App T.Text
+editFieldName = attrOfFirst "textarea" "name"
+
+-- | The value of an attribute of the first element matching a selector in
+-- the current page, failing the test if there is none.
+attrOfFirst :: T.Text -> T.Text -> YesodExample App T.Text
+attrOfFirst selector attr = do
+  els <- htmlQuery selector
+  case els of
+    [] -> failing $ "no element matches " ++ T.unpack selector
+    (e:_) -> do
+      let needle = attr <> "=\""
+          html = TL.toStrict (TLE.decodeUtf8 e)
+          (_, fromneedle) = T.breakOn needle html
+      if T.null fromneedle
+        then failing $ "the first " ++ T.unpack selector ++ " has no " ++ T.unpack attr
+        else return $ T.takeWhile (/= '"') $ T.drop (T.length needle) fromneedle
+
+-- | The current response's Content-Security-Policy header, failing the test
+-- if there is none.
+cspHeaderValue :: YesodExample App T.Text
+cspHeaderValue = headerValue "Content-Security-Policy"
+
+-- | The values of all of the current response's headers with this name.
+headerValues :: HeaderName -> YesodExample App [T.Text]
+headerValues name = withResponse $ \res ->
+  return [TE.decodeUtf8 v | (n, v) <- simpleHeaders res, n == name]
+
+-- | The current response's headers with this name, joined; failing the
+-- test if there are none.
+headerValue :: HeaderName -> YesodExample App T.Text
+headerValue name = do
+  vs <- headerValues name
+  if null vs
+    then failing ("the response has no " ++ show name ++ " header")
+    else return $ T.intercalate ", " vs
+
+-- | Assert that the current page contains these texts, in this order.
+bodyContainsInOrder :: [T.Text] -> YesodExample App ()
+bodyContainsInOrder needles = withResponse $ \res -> go (TL.toStrict $ TLE.decodeUtf8 $ simpleBody res) needles
+  where
+    go _ [] = return ()
+    go html (n:ns) = case T.breakOn n html of
+      (_, rest) | T.null rest -> failing $ "the page lacks " ++ T.unpack n ++ ", or has it before the texts preceding it here"
+                | otherwise   -> go (T.drop (T.length n) rest) ns
+
+-- | The nonce in the current response's Content-Security-Policy, failing the
+-- test if the header or the nonce is missing.
+cspNonce :: YesodExample App T.Text
+cspNonce = do
+  csp <- cspHeaderValue
+  let (_, fromnonce) = T.breakOn "'nonce-" csp
+  if T.null fromnonce
+    then failing "the Content-Security-Policy has no nonce"
+    else return $ T.takeWhile (/= '\'') $ T.drop (T.length "'nonce-") fromnonce
+
+-- | Run an action with XDG_CONFIG_HOME pointing at a fresh directory, removed
+-- afterwards, so that catalogs written by a test never come from, or end up
+-- in, the developer's real config directory, and concurrent runs do not share one.
+withTempConfigDir :: (FilePath -> IO a) -> IO a
+withTempConfigDir act = do
+  tmp <- getTemporaryDirectory
+  bytes <- BS.unpack <$> getEntropy 6
+  let dir = tmp </> ("hledger-web-test-" ++ concatMap (printf "%02x") bytes)
+  bracket_ (createDirectoryIfMissing True dir >> setEnv "XDG_CONFIG_HOME" dir)
+           (unsetEnv "XDG_CONFIG_HOME" >> removeDirectoryRecursive dir)
+           (act dir)
+
+-- | Fail the current test with a message. (yesod-test's own version of this
+-- is not exported.)
+failing :: String -> YesodExample App a
+failing msg = liftIO (expectationFailure msg) >> error "unreachable: expectationFailure returned"
+
+-- | The name of one of hledger-web's UI state cookies, as a test app,
+-- on the default port, names it (App.uiCookie).
+uiCookieName :: String -> BS.ByteString
+uiCookieName name = fromString $ name <> "_" <> show defport
+
+-- | Have the sidebar show its balances, hidden by default, for the
+-- tests of its amounts.
+withSidebarBalances :: YesodExample site ()
+withSidebarBalances = testSetCookie defaultSetCookie{setCookieName = uiCookieName "showbalances", setCookieValue = "1"}
+
+-- | Run hledger-web's built-in tests using the hspec test runner.
+hledgerWebTest :: IO ()
+hledgerWebTest = do
+  putStrLn $ "Running tests for " ++ prognameandversion -- ++ " (--test --help for options)"
+  let d = fromGregorian 2000 1 1
+
+  -- The pager's window of page numbers: up to ten, sliding with the current page.
+  hspec $ describe "pageNumbers" $ do
+    it "shows every page when there are ten or fewer" $ do
+      pageNumbers 1 3 `shouldBe` [1, 2, 3]
+      pageNumbers 3 3 `shouldBe` [1, 2, 3]
+      pageNumbers 1 1 `shouldBe` [1]
+    it "shows the first ten pages until the current one is past the middle" $ do
+      pageNumbers 1 30 `shouldBe` [1 .. 10]
+      pageNumbers 5 30 `shouldBe` [1 .. 10]
+      pageNumbers 6 30 `shouldBe` [2 .. 11]
+    it "keeps the current page in the middle, and the last ten at the end" $ do
+      pageNumbers 12 17 `shouldBe` [8 .. 17]
+      pageNumbers 17 17 `shouldBe` [8 .. 17]
+      pageNumbers 15 30 `shouldBe` [11 .. 20]
+
+  -- Startup report options and query arguments become the url parameters
+  -- browse mode opens, and the server's own report spec is rebuilt to
+  -- stock defaults (#2771).
+  hspec $ describe "startupUrlState" $ do
+    it "renders options as page parameters, queries and query-like options as search terms, and rebuilds the spec to stock" $ do
+      let ropts = defreportopts
+            { period_ = YearPeriod 2026, interval_ = Months 1
+            , value_ = Just (AtEnd Nothing), accountlistmode_ = ALTree
+            , empty_ = True, statuses_ = [Cleared], real_ = True
+            , depth_ = DepthSpec (Just 3) [(toRegexCI' "assets", 2)]
+            , querystring_ = ["assets", "two words"]
+            , title_ = Just "My books"
+            }
+          (params, rspec') = startupUrlState defreportspec{_rsReportOpts = ropts}
+      lookup "interval" params `shouldBe` Just "monthly"
+      lookup "period" params `shouldBe` Nothing
+      lookup "value" params `shouldBe` Just "end"
+      lookup "list" params `shouldBe` Just "tree"
+      -- -E means the opposite in the web ui: hide the zero balances shown by default
+      lookup "empty" params `shouldBe` Just "0"
+      -- a flat depth is a parameter; a per-account one stays a search term
+      lookup "depth" params `shouldBe` Just "3"
+      lookup "q" params `shouldBe` Just "assets \"two words\" date:2026 status:* real:1 depth:assets=2"
+      _rsQuery rspec' `shouldBe` Any
+      period_ (_rsReportOpts rspec') `shouldBe` PeriodAll
+      interval_ (_rsReportOpts rspec') `shouldBe` NoInterval
+      value_ (_rsReportOpts rspec') `shouldBe` Nothing
+      empty_ (_rsReportOpts rspec') `shouldBe` False
+      -- a display preference with no url spelling stays in the spec
+      title_ (_rsReportOpts rspec') `shouldBe` Just "My books"
+    it "spells intervals as in period expressions and valuations as value words" $ do
+      let p ropts = fst $ startupUrlState defreportspec{_rsReportOpts = ropts}
+      lookup "interval" (p defreportopts{interval_ = Weeks 2}) `shouldBe` Just "every 2 weeks"
+      lookup "value" (p defreportopts{value_ = Just (AtEnd (Just "EUR"))}) `shouldBe` Just "end,EUR"
+      lookup "value" (p defreportopts{conversionop_ = Just ToCost}) `shouldBe` Just "cost"
+      -- a depth regexp with a space must arrive as one quoted term
+      lookup "q" (p defreportopts{depth_ = DepthSpec Nothing [(toRegex' "a b", 2)]}) `shouldBe` Just "\"depth:a b=2\""
+
+  -- Report options in the search, and the old period parameter, move to
+  -- their own parameters (App.normaliseUrlState).
+  hspec $ describe "normalisedSearch" $ do
+    let refday = fromGregorian 2026 10 23
+    it "moves a date term's interval out, keeping its span as written" $ do
+      normalisedSearch refday "assets \"date:monthly in thisyear\"" Nothing `shouldBe` Just (MovedOptions "assets \"date:in thisyear\"" Nothing (Just (Months 1)) Nothing)
+      normalisedSearch refday "date:weekly" Nothing `shouldBe` Just (MovedOptions "" Nothing (Just (Weeks 1)) Nothing)
+    it "moves the last flat depth out, keeping per-account depths" $ do
+      normalisedSearch refday "depth:2 depth:assets=3 depth:1" Nothing `shouldBe` Just (MovedOptions "depth:assets=3" (Just 1) Nothing Nothing)
+    it "splits the period parameter into a date term and an interval, the search's interval winning" $ do
+      normalisedSearch refday "expenses" (Just "quarterly in 2025") `shouldBe` Just (MovedOptions "\"date:in 2025\" expenses" Nothing (Just (Quarters 1)) Nothing)
+      normalisedSearch refday "date:monthly" (Just "quarterly 2025") `shouldBe` Just (MovedOptions "date:2025" Nothing (Just (Months 1)) Nothing)
+      normalisedSearch refday "" (Just "2025-02") `shouldBe` Just (MovedOptions "date:2025-02" Nothing Nothing Nothing)
+    it "moves the first account term out, as the account register's subject" $ do
+      normalisedSearch refday "inacctonly:assets:bank desc:x inacct:expenses" Nothing `shouldBe` Just (MovedOptions "desc:x" Nothing Nothing (Just ("assets:bank", False)))
+      normalisedSearch refday "inacct:'assets:bank account'" Nothing `shouldBe` Just (MovedOptions "" Nothing Nothing (Just ("assets:bank account", True)))
+    it "leaves a search with nothing to move" $ do
+      normalisedSearch refday "assets date:2025 depth:assets=2" Nothing `shouldBe` Nothing
+    it "splits only an interval followed by a date span" $ do
+      splitPeriodExpr refday "every 2 weeks from 2025-01-01" `shouldBe` Just (Weeks 2, "from 2025-01-01")
+      splitPeriodExpr refday "2025" `shouldBe` Nothing
+      splitPeriodExpr refday "monthly bogus" `shouldBe` Nothing
+
+  -- The multiple-choice parameters, whose parsers are made from their words.
+  hspec $ describe "Param" $ do
+    it "gives each mode its own word" $ do
+      let distinctWords p = let ws = map (paramWord p) (paramModes p) in length (nub ws) == length ws
+      distinctWords accumParam `shouldBe` True
+      distinctWords calcParam `shouldBe` True
+      distinctWords listParam `shouldBe` True
+      distinctWords sortParam `shouldBe` True
+    it "reads a mode's word, an empty or absent value as the default, and returns an unknown word" $ do
+      parseParam calcParam (Just "gain") `shouldBe` Right (Just CalcGain)
+      parseParam calcParam (Just "") `shouldBe` Right Nothing
+      parseParam calcParam Nothing `shouldBe` Right Nothing
+      parseParam calcParam (Just "budget") `shouldBe` Left "budget"
+
+  -- The options in effect, listed on the closed Options disclosure.
+  hspec $ describe "optionsSummary" $ do
+    it "lists the options in the controls' order, in their words, skipping other parameters" $
+      optionsSummary noTranslations 3 [("sort", "amount"), ("q", "assets"), ("depth", "2"), ("account", "assets"), ("interval", "monthly"), ("lots", "1")]
+        `shouldBe` ["Monthly", "Depth 2", "Lots shown", "By amount"]
+    it "shows an interval without a word of its own as written" $
+      optionsSummary noTranslations 3 [("interval", "every 2 weeks")] `shouldBe` ["every 2 weeks"]
+    it "lists the depth, the default too, and no limit, or one deeper than the deepest account, as all" $ do
+      optionsSummary noTranslations 3 [("depth", "1"), ("lots", "1")] `shouldBe` ["Depth 1", "Lots shown"]
+      optionsSummary noTranslations 3 [("depth", "9"), ("lots", "1")] `shouldBe` ["Depth all", "Lots shown"]
+      optionsSummary noTranslations 3 [("depth", "all")] `shouldBe` ["Depth all"]
+    it "names amount conversions and extra columns briefly" $ do
+      optionsSummary noTranslations 3 [("value", "cost"), ("total", "1"), ("avg", "1")] `shouldBe` ["Cost", "Total", "Average"]
+      optionsSummary noTranslations 3 [("value", "end")] `shouldBe` ["Value"]
+
+  runTests "hledger-web" [] nulljournal $ do
+
+    yit "serves a reasonable-looking journal page" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "Add a transaction"
+
+    yit "serves a reasonable-looking register page" $ do
+      get RegisterR
+      statusIs 200
+      bodyContains "accounts"
+
+    yit "serves the favicon and robots.txt" $ do
+      get FaviconR
+      statusIs 200
+      assertHeader "Content-Type" "image/x-icon"
+      get RobotsR
+      statusIs 200
+      bodyContains "Disallow: /"
+
+    yit "serves the chart stylesheet, with its shading, and its dark colors for the screen only" $ do
+      get ChartCssR
+      statusIs 200
+      assertHeader "Content-Type" "text/css; charset=utf-8"
+      bodyContains ".hledger-chart .shade.future{"
+      bodyContains "@media screen and (prefers-color-scheme:dark){"
+      bodyNotContains "@media (prefers-color-scheme:dark)"
+
+    yit "serves static files for browsers to check before reusing, so an upgrade's hledger.js is used" $ do
+      get $ StaticR hledger_js
+      statusIs 200
+      assertHeader "Cache-Control" "no-cache"
+
+    yit "hyperlinks use a base url made from the default host and port" $ do
+      get JournalR
+      statusIs 200
+      let defaultbaseurl = defbaseurl defhost defport
+      bodyContains ("href=\"" ++ defaultbaseurl)
+      bodyContains ("src=\"" ++ defaultbaseurl)
+
+    yit "links the help dialog to the hledger-web manual for this version" $ do
+      get JournalR
+      statusIs 200
+      bodyContains ("<a href=\"" ++ T.unpack webmanualurl ++ "\" target=\"hledgerhelp\">hledger-web user manual</a>")
+
+    -- The Content-Security-Policy (#2703). Every HTML page sends one, and the
+    -- page's own inline scripts carry its nonce, so they are the only inline
+    -- scripts a browser will run.
+    yit "sends a Content-Security-Policy whose nonce marks the page's inline scripts" $ do
+      get JournalR
+      statusIs 200
+      csp <- cspHeaderValue
+      assertEq "the policy should allow scripts from our origin only"
+        (T.isInfixOf "script-src 'self' 'nonce-" csp) True
+      nonce <- cspNonce
+      assertEq "the nonce should be 16 bytes, base64 encoded" (T.length nonce) 24
+      bodyContains ("<script nonce=\"" ++ T.unpack nonce ++ "\">")
+      bodyNotContains "<script>"
+
+    yit "uses a fresh nonce for each response" $ do
+      get JournalR
+      nonce1 <- cspNonce
+      get JournalR
+      nonce2 <- cspNonce
+      assertEq "two responses should not share a nonce" (nonce1 == nonce2) False
+
+    -- Error pages are rendered by yesod's errorHandler, in a handler state of
+    -- its own; they must carry the policy too, with their own nonce.
+    yit "sends the Content-Security-Policy with error pages too" $ do
+      get ("/nosuchpage" :: T.Text)
+      statusIs 404
+      _ <- cspNonce
+      return ()
+
+    -- No --serve or --serve-api means the default --serve-browse mode, where
+    -- each page pings the server while it is open so that it does not exit.
+    -- The page is told to by a marker on the body. (The pinging and the
+    -- server's answer are outside this harness; the browser suite's
+    -- browse-mode spec checks those.)
+    yit "marks the page for the browse-mode ping" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "<body data-browse-mode"
+
+  runTests "hledger-web with --serve" [("serve","")] nulljournal $ do
+
+    yit "does not mark the page for the browse-mode ping" $ do
+      get JournalR
+      statusIs 200
+      bodyNotContains "data-browse-mode"
+
+    -- WIP
+    -- yit "shows the add form" $ do
+    --   get JournalR
+    --   -- printBody
+    --   -- let addbutton = "button:contains('add')"
+    --   -- bodyContains addbutton
+    --   -- htmlAnyContain "button:visible" "add"
+    --   printMatches "div#addmodal:visible"
+    --   htmlCount "div#addmodal:visible" 0
+
+    --   -- clickOn "a#addformlink"
+    --   -- printBody
+    --   -- bodyContains addbutton
+
+    -- yit "can add transactions" $ do
+
+  usecolor <- useColorOnStdout
+  let
+    rawopts = [("forecast","")]
+    iopts = rawOptsToInputOpts d usecolor $ mkRawOpts rawopts
+    f = "fake"  -- need a non-null filename so forecast transactions get index 0
+  pj <- readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+    ["~ monthly"
+    ,"    assets    10"
+    ,"    income"
+    ])
+  j <- fmap (either error' id) . runExceptT $ journalFinalise iopts f "" pj  -- PARTIAL: journalFinalise should not fail
+  runTests "hledger-web with --forecast" rawopts j $ do
+
+    yit "shows forecasted transactions" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "id=\"transaction-2-1\""
+      bodyContains "id=\"transaction-2-2\""
+
+  -- A journal with lot tracking enabled: two open AAA lots (FIFO), and
+  -- a fully disposed BBB position whose realised gain is $3.
+  let liopts = rawOptsToInputOpts d usecolor $ mkRawOpts []
+  lj <- fmap (either error' id) . runExceptT . journalFinalise liopts "lots.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["commodity AAA  ; lots:"
+            ,"commodity BBB  ; lots:"
+            ,"P 2026-01-31 AAA $12.00"
+            ,""
+            ,"2025-12-30 opening"  -- a second year, so the years row shows
+            ,"    assets:cash    $100.00"
+            ,"    equity:opening"
+            ,""
+            ,"2026-01-01 buy aaa"
+            ,"    assets:broker    2 AAA @ $10.00"
+            ,"    assets:cash    $-20.00"
+            ,""
+            ,"2026-01-15 buy more aaa"
+            ,"    assets:broker    2 AAA @ $11.00"
+            ,"    assets:cash    $-22.00"
+            ,""
+            ,"2026-01-16 buy bbb"
+            ,"    assets:broker    1 BBB @ $5.00"
+            ,"    assets:cash     $-5.00"
+            ,""
+            ,"2026-01-20 sell one aaa"
+            ,"    assets:broker   -1 AAA @ $12.00"
+            ,"    assets:cash     $12.00"
+            ,""
+            ,"2026-01-21 sell all bbb"
+            ,"    assets:broker   -1 BBB @ $8.00"
+            ,"    assets:cash      $8.00"
+            ])
+  runTests "hledger-web holdings page" [] lj $ do
+
+    -- the sales book their gains to a gain account
+    yit "offers the gain account type when there are gains" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "Show only capital gain accounts (type:G)"
+
+    yit "shows the holdings report, hiding closed positions by default" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("depth", "all")])
+      statusIs 200
+      bodyContains "Holdings on 2026-12-31"
+      bodyContains ">Avg cost<"
+      bodyContains "$32.00"   -- total cost: 1@10 + 2@11
+      bodyContains "$36.00"   -- total value: 3 AAA at the $12 market price
+      bodyContains "12.5%"    -- UGain%: 4/32
+      bodyContains "$5.00"    -- total RGain includes the closed BBB position
+      bodyNotContains "0 BBB" -- but its row is hidden without closed=1
+                              -- (the commodity filter row still offers BBB)
+      -- a note says so, with a link showing it
+      bodyContains "RGain and XIRR totals include 1 closed position, not shown ("
+      bodyContains "closed=1\">show them</a>)"
+      bodyContains "Holdings</a>"  -- and the journal has lots, so the menu links here
+      -- the controls sit behind the disclosure, with the report pages'
+      -- rows: years (setting the report date), status, real, type,
+      -- commodity, and prices
+      bodyContains "<details class=\"report-controls\">"
+      bodyContains "Years:"
+      bodyContains "Status:"
+      bodyNotContains "Type:"  -- holdings are of lot-tracked accounts already
+      bodyContains "Commodity:"
+      bodyContains "Prices:"
+      -- the account names' shared prefix is a group heading, rows show the rest
+      bodyContains "scope=\"rowgroup\">assets</th>"
+      bodyContains ">broker</a>"
+      -- a position's register link filters to its commodity
+      bodyContains "/register?q=date%3A2026%20cur%3AAAA&amp;account=assets%3Abroker&amp;depth=all\""
+      -- with lots hidden, the Depth row reaches the deepest real account
+      bodyContains "title=\"Show accounts at every depth\">2</a>"
+
+    yit "charts the holdings between the heading and the table, as holdings --chart does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("depth", "all")])
+      statusIs 200
+      bodyContains "</h2><div class=\"part-toggle-row chart-toggle-row\"><button type=\"button\" class=\"part-toggle\" data-report-part=\"chart\" title=\"Show or hide the chart (c)\">Chart</button></div><div class=\"report-chart\"><svg"
+      -- a bar per holding, its cost and gain, labelled with the gain percent
+      bodyContains ">assets:broker AAA</text>"
+      bodyContains ">Unrealised gain</text>"
+      bodyContains ">+12.5%</text>"
+      -- with no interval chosen, it picks none, and offers no gains row
+      bodyContains "report-links interval"
+      bodyNotContains "Gains:"
+
+    yit "with an interval, shows the holdings' totals at each period's end, as holdings -M does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026-01-01..2026-03-01"), ("hinterval", "monthly")])
+      statusIs 200
+      bodyContains "Monthly holdings, 2026-01-31..2026-02-28"
+      bodyContains ">Avg cost<"
+      bodyContains "$36.00"   -- total value: 3 AAA at the $12 market price
+      bodyContains "Gains:"
+      -- each date links to the holdings on that date, with gains since
+      -- acquisition, keeping the page's depth, by default 1
+      bodyContains "/holdings?q=date%3A..2026-02-01&amp;depth=1\" title=\"Show the holdings on this date\">2026-01-31</a>"
+      -- the chart has a bar per period end
+      bodyContains ">2026-02-28</text>"
+
+    yit "with an interval and accum=change, shows the gains in each period" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026-01-01..2026-03-01"), ("hinterval", "monthly"), ("accum", "change")])
+      statusIs 200
+      bodyContains "Monthly holdings, 2026-01-31..2026-02-28, gains in each period"
+      -- each date links to the holdings on that date, with gains in that period
+      bodyContains "/holdings?q=date%3A2026-02&amp;depth=1\" title=\"Show the holdings on this date\">2026-02-28</a>"
+      -- and the closed options summary says so in the gains row's words
+      bodyContains "Monthly · In each period"
+      -- the chart shows those gains, realised and unrealised
+      bodyContains ">Realised gain</text>"
+      bodyContains ">Unrealised gain</text>"
+      bodyNotContains ">Cost</text>"
+
+    yit "has an interval of its own, carrying the other pages' interval along for them" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("interval", "monthly")])
+      statusIs 200
+      bodyNotContains "Monthly holdings"
+      -- its interval links set its own interval, keeping the other pages'
+      bodyContains "/holdings?interval=monthly&amp;depth=1&amp;hinterval=yearly\""
+      -- an interval typed in its search becomes its own
+      request $ do
+        setMethod "GET"
+        setUrl HoldingsR
+        addGetParam "q" "date:monthly"
+      statusIs 303
+      loc <- headerValue "Location"
+      assertEq "the interval moves to the holdings interval" loc (T.pack (defbaseurl defhost defport) <> "/holdings?hinterval=monthly")
+
+    yit "keeps its interval while other pages are visited" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (BalanceR, [("hinterval", "monthly")])
+      statusIs 200
+      -- the balance page's own links, and the links to other pages, carry it
+      bodyContains "/balance?hinterval=monthly&amp;depth=1&amp;interval=yearly\""
+      bodyContains "/holdings?hinterval=monthly"
+
+  runTests "hledger-web holdings page with a startup interval" [("monthly", "")] lj $ do
+
+    yit "starts without an interval, the startup one being the other report pages'" $ do
+      get HoldingsR
+      statusIs 200
+      bodyNotContains "Monthly holdings"
+
+    yit "shows one row per lot with lots=1" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("lots", "1"), ("depth", "all")])
+      statusIs 200
+      bodyContains ">Unit cost<"
+      bodyContains "{2026-01-01, $10.00}"
+      bodyContains "class=\"account acct-split lot\""
+      -- with every lot under one account, that account is the group heading
+      bodyContains "scope=\"rowgroup\">assets:broker</th>"
+      -- lot subaccounts are ordinary accounts to the Depth row, which
+      -- now reaches one level deeper, as in hledger-ui
+      bodyContains "&amp;depth=2\" title=\"Show accounts down to depth 2\">2</a>"
+      bodyContains "title=\"Show accounts at every depth\">3</a>"
+
+    yit "shows closed positions with closed=1" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("closed", "1")])
+      statusIs 200
+      bodyContains "0 BBB"
+      bodyContains "$3.00"
+      bodyNotContains "closed position, not shown"
+      -- the page also has the usual zero-balances control, which the
+      -- empty parameter drives, so the z key keeps working here
+      bodyContains "Zero balances:"
+
+    yit "tree mode shows a single-commodity account as one combined row" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("list", "tree"), ("depth", "all")])
+      statusIs 200
+      -- the boring root is squashed into the one account, which holds one
+      -- commodity and so is a row, not a heading over a commodity row
+      bodyContains "class=\"account indent-0\""
+      bodyContains ">assets:broker</a>"
+      bodyNotContains "acctheading"
+
+    yit "tree mode clips to a depth limit, as the cli does, rather than folding" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("list", "tree"), ("depth", "1")])
+      statusIs 200
+      -- the positions are merged under the clipped account; folding the
+      -- full tree could only have shown assets:broker
+      bodyContains "<table class=\"balancereport table table-condensed\">"
+      bodyContains "account=assets&amp;list=tree&amp;depth=1\""
+      bodyNotContains "account=assets%3Abroker&amp;list=tree"  -- (the sidebar's links put depth first)
+
+    yit "tree mode groups several commodities under an account heading" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026"), ("list", "tree"), ("closed", "1"), ("depth", "all")])
+      statusIs 200
+      -- with the closed BBB position shown, the account holds two
+      -- commodities: a heading row subtotaling the dollar columns, then
+      -- a position row per commodity
+      bodyContains "class=\"account indent-0 acctheading\""
+      bodyContains ">assets:broker</a>"
+      bodyContains "class=\"account indent-1 commodity\""
+      bodyContains ">AAA</a>"
+      bodyContains ">BBB</a>"
+      -- each commodity row's register link filters to its own commodity
+      bodyContains "/register?q=date%3A2026%20cur%3ABBB&amp;account=assets%3Abroker&amp;list=tree&amp;depth=all\""
+      -- the heading's RGain subtotals both commodities' realized gains
+      bodyContains "$5.00"
+
+    yit "rejects value=then" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("value", "then")])
+      statusIs 200
+      bodyContains "value=then does not apply"
+
+  -- Two holdings, one of them (BBB) with no market price.
+  unpj <- fmap (either error' id) . runExceptT . journalFinalise liopts "unpriced.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["commodity AAA  ; lots:"
+            ,"commodity BBB  ; lots:"
+            ,"P 2026-01-31 AAA $12.00"
+            ,""
+            ,"2026-01-01 buy aaa"
+            ,"    assets:broker    2 AAA @ $10.00"
+            ,"    assets:cash"
+            ,""
+            ,"2026-01-10 buy bbb"
+            ,"    assets:broker    1 BBB @ $5.00"
+            ,"    assets:cash"
+            ])
+  runTests "hledger-web holdings page with an unpriced holding" [] unpj $ do
+
+    yit "totals the priced holdings' value and gains, with a note naming those left out" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026-01")])
+      statusIs 200
+      bodyContains "$24.00"   -- the total value: 2 AAA at $12
+      bodyContains "<p class=\"report-note\">Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: BBB</p>"
+
+    yit "with an interval, stars the periods whose totals leave some out" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (HoldingsR, [("q", "date:2026-01"), ("hinterval", "monthly")])
+      statusIs 200
+      bodyContains ">2026-01-31*</a>"
+      bodyContains "<p class=\"report-note\">* Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: BBB</p>"
+
+  runTests "hledger-web holdings page without lots" [] nulljournal $ do
+
+    yit "hides the Holdings link, but the page still answers" $ do
+      get JournalR
+      statusIs 200
+      bodyNotContains "Holdings</a>"
+      get HoldingsR
+      statusIs 200
+
+  -- A sale taking from two lots (FIFO): the 5 AAA left cost $100, and
+  -- are worth $200.
+  msj <- fmap (either error' id) . runExceptT . journalFinalise liopts "lotsale.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["commodity AAA  ; lots:"
+            ,"P 2026-04-01 AAA $40"
+            ,""
+            ,"2026-01-01 buy"
+            ,"    assets:broker    10 AAA @ $10"
+            ,"    assets:cash"
+            ,""
+            ,"2026-02-01 buy"
+            ,"    assets:broker    10 AAA @ $20"
+            ,"    assets:cash"
+            ,""
+            ,"2026-03-01 sell"
+            ,"    assets:broker   -15 AAA @ $30"
+            ,"    assets:cash      $450"
+            ])
+  runTests "hledger-web lots collapsed" [] msj $ do
+
+    -- At the sale's $30 price instead, the broker would show $-150 at
+    -- cost, and a $350 gain.
+    yit "converts a sale from several lots at the lots' cost, at cost and for gains" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "value" "cost"
+        addGetParam "depth" "all"
+      statusIs 200
+      htmlAnyContain "#main-content tbody td.amount" "$100"
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "calc" "gain"
+        addGetParam "depth" "all"
+      statusIs 200
+      htmlAnyContain "#main-content tbody td.amount" "$100"
+
+  -- Submitting an unbalanced transaction produces an error message that
+  -- echoes the entry (account names, amounts). Those values must be rendered
+  -- as text, not raw html. Note this echo happens on the FormFailure path,
+  -- which yesod does not gate with the CSRF token, so no token is sent here -
+  -- the vector is reachable cross-origin.
+  aj <- fmap (either error' id) . runExceptT . journalFinalise iopts "add.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["2025-01-01 opening"
+            ,"    assets:bank:checking   100"
+            ,"    equity:opening"])
+  runTests "hledger-web add form" [("allow","add")] aj $ do
+
+    yit "escapes submitted values in an add-form error message" $ do
+      get JournalR
+      statusIs 200
+      -- Payloads in the two fields that reach the excerpt: the account name,
+      -- and the (unvalidated) description. Distinct payloads so that escaping
+      -- one field but not the other is caught. The entry parses but does not
+      -- balance, so its excerpt - which includes both fields - is echoed.
+      -- (Date and amount are validated and cannot carry raw html into it.)
+      request $ do
+        setMethod "POST"
+        setUrl AddR
+        addPostParam "_formid" "identify-add"
+        addPostParam "date" "2025-02-02"
+        addPostParam "description" "d<img src=x onerror=alert(1)>"
+        addPostParam "account" "a<img src=x onerror=alert(2)>"
+        addPostParam "amount" "5"
+        addPostParam "account" "equity:opening"
+        addPostParam "amount" "-3"
+      bodyContains "d&lt;img src=x onerror=alert(1)&gt;"   -- description, escaped
+      bodyContains "a&lt;img src=x onerror=alert(2)&gt;"   -- account, escaped
+      bodyNotContains "<img src=x onerror"                 -- neither as raw html
+
+    yit "shows add-form validation messages in the viewer's language" $ do
+      request $ do
+        setMethod "POST"
+        setUrl AddR
+        addRequestHeader ("Accept-Language", "de")
+        addPostParam "_formid" "identify-add"
+        addPostParam "date" "not a date"
+        addPostParam "description" "d"
+        -- two accounts without amounts: only the last posting may omit its amount
+        addPostParam "account" "a"
+        addPostParam "amount" ""
+        addPostParam "account" "b"
+        addPostParam "amount" ""
+      bodyContains "Ungültiges Datumsformat"
+      bodyContains "Betrag fehlt"
+
+  runTests "hledger-web language selection" [] nulljournal $ do
+
+    yit "serves English by default" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "lang=\"en\""
+      bodyContains "Add a transaction"
+
+    yit "follows Accept-Language, trying each preference with its subtags dropped" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addRequestHeader ("Accept-Language", "de-CH,en;q=0.9")
+      statusIs 200
+      bodyContains "lang=\"de\""
+      bodyContains "Buchung hinzufügen"
+      bodyNotContains "Add a transaction"
+      vary <- headerValue "Vary"
+      assertEq "the page says it varies by language" (T.isInfixOf "Accept-Language" vary) True
+
+    yit "remembers an explicit _LANG choice in a cookie, when it names an available catalog" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (JournalR, [("_LANG", "de")])
+      statusIs 200
+      bodyContains "Buchung hinzufügen"
+      cookie <- headerValue "Set-Cookie"
+      assertEq "the language cookie is set" (T.isInfixOf "_LANG=de;" cookie) True
+      assertEq "the language cookie is SameSite" (T.isInfixOf "SameSite=Lax" cookie) True
+
+    yit "ignores a _LANG value that is not an available catalog, without setting a cookie" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (JournalR, [("_LANG", "../../etc/passwd")])
+      statusIs 200
+      bodyContains "Add a transaction"
+      cookies <- headerValues "Set-Cookie"
+      assertEq "no language cookie" (any (T.isInfixOf "_LANG=") cookies) False
+
+    yit "reads the language from the _LANG cookie on later requests" $ do
+      -- yesod-test keeps the cookies a response sets and sends them back
+      request $ do
+        setMethod "GET"
+        setUrl (JournalR, [("_LANG", "de")])
+      statusIs 200
+      get RegisterR
+      statusIs 200
+      bodyContains "lang=\"de\""
+      bodyContains "alle Konten"
+      bodyContains "Von/Nach Konto"
+
+    yit "shows the balance page in the viewer's language" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addRequestHeader ("Accept-Language", "de")
+      statusIs 200
+      bodyContains "<title>Salden - hledger-web</title>"
+      bodyContains "<h2>Saldoänderungen"
+      bodyContains "Intervall:"
+      bodyContains "title=\"Eine Spalte pro Monat anzeigen\">Monatlich</a>"
+
+  runTests "hledger-web with --lang" [("lang","de")] nulljournal $ do
+
+    yit "uses the --lang language whatever the viewer asks for, setting no language cookie" $ do
+      request $ do
+        setMethod "GET"
+        setUrl (JournalR, [("_LANG", "en")])
+        addRequestHeader ("Accept-Language", "en")
+      statusIs 200
+      bodyContains "lang=\"de\""
+      bodyContains "Buchung hinzufügen"
+      cookies <- headerValues "Set-Cookie"
+      assertEq "no language cookie" (any (T.isInfixOf "_LANG=") cookies) False
+
+  -- With --lang=auto the environment's language is only the fallback,
+  -- here English (LC_ALL=C), so that it can't be mistaken for the viewer's.
+  bracket (lookupEnv "LC_ALL" <* setEnv "LC_ALL" "C") (maybe (unsetEnv "LC_ALL") (setEnv "LC_ALL")) $ \_ ->
+    runTests "hledger-web with --lang=auto" [("lang","auto")] nulljournal $ do
+
+      yit "leaves the language to the viewer" $ do
+        request $ do
+          setMethod "GET"
+          setUrl JournalR
+          addRequestHeader ("Accept-Language", "de")
+        statusIs 200
+        bodyContains "lang=\"de\""
+        bodyContains "Buchung hinzufügen"
+
+  -- A translation is viewer-controlled text: it must be rendered as text
+  -- wherever it lands, including inside attributes.
+  withTempConfigDir $ \xdg -> do
+    createDirectoryIfMissing True (xdg </> "hledger" </> "locale")
+    TIO.writeFile (xdg </> "hledger" </> "locale" </> "xx.po") $ T.unlines
+      [ "msgid \"\""
+      , "msgstr \"Content-Type: text/plain; charset=UTF-8\\n\""
+      , ""
+      , "msgid \"Add a transaction\""
+      , "msgstr \"<img src=x onerror=alert(1)>\""
+      , ""
+      , "msgid \"Show search and general help\""
+      , "msgstr \"x\\\" onmouseover=\\\"alert(2)\""
+      ]
+    runTests "hledger-web with a user translation catalog" [] nulljournal $ do
+
+      yit "renders translations as text, in content and in attributes" $ do
+        request $ do
+          setMethod "GET"
+          setUrl JournalR
+          addRequestHeader ("Accept-Language", "xx")
+        statusIs 200
+        bodyContains "lang=\"xx\""
+        bodyContains "&lt;img src=x onerror=alert(1)&gt;"
+        bodyNotContains "<img src=x onerror"
+        bodyContains "x&quot; onmouseover=&quot;alert(2)"
+        bodyNotContains "onmouseover=\"alert(2)"
+
+  -- The balance page: the balance report, or with an interval,
+  -- the multi-period one, rendered without inline styles (the CSP).
+  let biopts = rawOptsToInputOpts d usecolor $ mkRawOpts []
+  bj <- fmap (either error' id) . runExceptT . journalFinalise biopts "balance.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["2025-01-05 pay"
+            ,"    assets:bank:checking   100"
+            ,"    income:salary"
+            ,"2025-02-05 lunch"
+            ,"    expenses:food           10"
+            ,"    assets:bank:checking"])
+  runTests "hledger-web balance page" [] bj $ do
+
+    -- With two transactions in one year there is nothing to page or to
+    -- move between, and the pages say nothing about it.
+    yit "shows no paging and no years row for a small journal" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "lunch</td>"
+      bodyNotContains "Showing "
+      bodyNotContains "Years:"
+      get RegisterR
+      statusIs 200
+      bodyContains "lunch</td>"
+      bodyNotContains "Showing "
+      bodyNotContains "Years:"
+
+    yit "serves the balance report, linking accounts to their register" $ do
+      get BalanceR
+      statusIs 200
+      -- by default, monthly, at depth 1
+      bodyContains "<h2>Balance changes in 2025-01-01..2025-02-28</h2>"
+      bodyContains "href=\"register?account=assets&amp;depth=1\""
+      bodyContains "<tfoot>"
+      bodyContains "class=\"amount negative\""
+
+    yit "lists the journal and reports, then All accounts, in one group" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains ">Cashflow statement</a><a class=\"current\""
+      bodyContains ">All accounts</a></p>"
+      bodyNotContains "group-start"
+
+    yit "charts the report between its heading and its table, as balance --chart does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "none"
+        addGetParam "depth" "all"
+      statusIs 200
+      bodyContains "<h2>All accounts</h2><div class=\"part-toggle-row chart-toggle-row\"><button type=\"button\" class=\"part-toggle\" data-report-part=\"chart\" title=\"Show or hide the chart (c)\">Chart</button></div><div class=\"report-chart\"><svg"
+      bodyContains "aria-label=\"All accounts\""
+      bodyContains "</svg></div><div class=\"part-toggle-row table-toggle-row\"><button type=\"button\" class=\"part-toggle\" data-report-part=\"table\" title=\"Show or hide the data (d)\">Data</button></div><div class=\"table-responsive report-table\">"
+      -- a bar per account, and the chart's styles from the stylesheet
+      bodyContains ">assets:bank:checking</text>"
+      bodyContains "/chart.css"
+      -- with an interval (by default, monthly), the accounts over time, and their total, as with balance --chart:
+      -- also for all accounts here, though it is zero in every month
+      get BalanceR
+      statusIs 200
+      bodyContains ">expenses</text>"
+      bodyContains ">Total</text>"
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "assets expenses"
+      statusIs 200
+      bodyContains ">Total</text>"
+
+    yit "charts a bar per account type with chart=grouped, as balance --chart=grouped does, which the links keep" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "<p class=\"report-links chart\"><span class=\"row-label\">Chart:</span>"
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "chart" "grouped"
+      statusIs 200
+      bodyContains "Grouped chart</span>"
+      bodyContains "chart=grouped\""
+      -- with no interval too: the whole period as one, its accounts stacked by type, not a bar per account
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "none"
+        addGetParam "depth" "all"
+        addGetParam "chart" "grouped"
+      statusIs 200
+      bodyContains "<title>assets:bank:checking · 90"
+      bodyNotContains "assets:bank:checking · Balance · 90"
+
+    yit "hides the chart or the table as the c and d keys left them" $ do
+      get BalanceR
+      statusIs 200
+      bodyNotContains "chart-hidden"
+      bodyNotContains "table-hidden"
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "showchart", setCookieValue = "0"}
+      get BalanceR
+      statusIs 200
+      bodyContains "chart-hidden"
+      bodyNotContains "table-hidden"
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "showchart", setCookieValue = "1"}
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "showtable", setCookieValue = "0"}
+      get BalanceR
+      statusIs 200
+      bodyNotContains "chart-hidden"
+      bodyContains "table-hidden"
+
+    yit "hides the charts' total lines until the N key shows them" $ do
+      get BalanceR
+      statusIs 200
+      bodyNotContains "net-shown"
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "shownet", setCookieValue = "1"}
+      get BalanceR
+      statusIs 200
+      bodyContains "net-shown"
+
+    yit "includes the add form on the report pages too, for the a key" $ do
+      forM_ [BalanceR, BalancesheetR, IncomestatementR] $ \r -> do
+        get r
+        statusIs 200
+        bodyContains "<dialog id=\"addmodal\""
+
+    yit "offers each page in the g key's menu, with its key" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "<div id=\"gomenu\" hidden"
+      bodyContains "data-gokey=\"j\""
+      bodyContains "<code>b</code> Balance sheet</a>"
+      bodyContains "<code>a</code> All accounts</a>"
+      bodyNotContains "data-gokey=\"e\""
+
+    yit "links the next and previous pages for the n and p keys, in the g key's menu's order, going round" $ do
+      let base = defbaseurl defhost defport
+      get BalanceR
+      statusIs 200
+      -- All accounts, the last, follows the cashflow statement (this
+      -- journal has no lots, so no Holdings page), and the journal, the
+      -- first, follows it
+      bodyContains ("<a href=\"" ++ base ++ "/journal\" data-stepkey=\"n\">")
+      bodyContains ("<a href=\"" ++ base ++ "/cashflow\" data-stepkey=\"p\">")
+      -- but they are not in the menu
+      bodyNotContains "data-gokey=\"n\""
+      get JournalR
+      statusIs 200
+      bodyContains ("<a href=\"" ++ base ++ "/balance\" data-stepkey=\"p\">")
+
+    yit "styles the report through the stylesheet, not inline styles" $ do
+      get BalanceR
+      statusIs 200
+      bodyNotContains "<style"
+      bodyNotContains "style=\""
+
+    yit "serves the multi-period report for an interval" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "monthly"
+      statusIs 200
+      bodyContains "Balance changes in 2025-01-01..2025-02-28"
+      bodyContains ">2025-01<"
+      bodyContains ">2025-02<"
+      -- the search form keeps the period, and marks the current report
+      bodyContains "<input type=\"hidden\" name=\"interval\" value=\"monthly\">"
+      bodyContains "class=\"current\""
+
+    yit "restricts the report to the search's date span" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-01"
+      statusIs 200
+      -- the report's own account links are relative (the sidebar's are not),
+      -- and carry the search's dates, so the register they open is restricted too
+      bodyContains "href=\"register?q=date:2025-01&amp;account=assets&amp;depth=1\""
+      -- (expenses, first posted to in February, is only in the sidebar, which lists every account)
+      bodyNotContains "href=\"register?q=date:2025-01&amp;account=expenses"
+
+    yit "honors a depth limit in the search" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "depth" "1"
+      statusIs 200
+      bodyContains "href=\"register?account=assets&amp;depth=1\""
+      bodyNotContains "account=assets:bank:checking"
+
+    yit "moves a depth term in the search to the depth parameter, keeping per-account depths in the search" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "assets depth:2 depth:assets:bank=3 depth:1"
+        addGetParam "list" "tree"
+      statusIs 303
+      -- the last depth term wins, as in the search
+      loc <- headerValue "Location"
+      assertEq "the page is reloaded with the depth as a parameter" loc
+        (T.pack (defbaseurl defhost defport) <> "/balance?q=assets%20depth%3Aassets%3Abank%3D3&list=tree&depth=1")
+
+    yit "lists the options in effect on the closed Options disclosure, and does not call a depth limit a filter" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "monthly"
+        addGetParam "depth" "2"
+      statusIs 200
+      bodyContains "<span class=\"options-summary\">Monthly · Depth 2</span>"
+      bodyNotContains ", filtered</h2>"
+      -- including the interval picked to suit the report's span, when none is chosen
+      get BalanceR
+      statusIs 200
+      bodyContains "<span class=\"options-summary\">Monthly · Depth 1</span>"
+
+    yit "keeps the depth in the search form" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "depth" "2"
+      statusIs 200
+      bodyContains "<input type=\"hidden\" name=\"depth\" value=\"2\">"
+
+    yit "links to each depth from 0, setting the depth parameter and keeping the search; the deepest sets all" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "assets"
+        addGetParam "depth" "1"
+      statusIs 200
+      let base = defbaseurl defhost defport
+      bodyContains ("href=\"" ++ base ++ "/balance?q=assets&amp;depth=0\" title=\"Show only the total (depth 0)\">0</a>")
+      bodyContains ("class=\"current\" href=\"" ++ base ++ "/balance?q=assets&amp;depth=1\"")
+      bodyContains ("href=\"" ++ base ++ "/balance?q=assets&amp;depth=2\"")
+      -- assets:bank:checking is at depth 3, so its link sets no limit
+      -- (depth=all, since no depth parameter means depth 1), as hledger-ui
+      -- does with a depth at or beyond the deepest
+      bodyContains ("href=\"" ++ base ++ "/balance?q=assets&amp;depth=all\" title=\"Show accounts at every depth\">3</a>")
+      bodyNotContains "&amp;depth=3\""
+      bodyNotContains "depth=4"
+
+    yit "squashes boring parents in tree mode, as the cli does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "list" "tree"
+        addGetParam "depth" "all"
+      statusIs 200
+      -- every account chain here is boring, so each is one indent-0 row
+      bodyContains ">assets:bank:checking</a>"
+      bodyContains "class=\"account indent-0 depth-3\""
+      bodyNotContains "class=\"account indent-1"
+
+    yit "in tree mode with a depth limit, gives boring parents at the limit their own rows, so it folds to the cli's rows" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "list" "tree"
+        addGetParam "depth" "1"
+      statusIs 200
+      bodyContains "data-depth-fold=\"1\""
+      -- the top-level accounts are the rows left showing, as --depth 1 shows them
+      bodyContains "<tr><td class=\"account indent-0 depth-1\"><a href=\"register?account=assets&amp;list=tree&amp;depth=1\""
+      -- the rest of each chain is a row beneath, served folded
+      bodyContains "<tr class=\"tree-fold-hide\"><td class=\"account indent-1 depth-3\"><a href=\"register?account=assets:bank:checking&amp;list=tree&amp;depth=1\""
+      bodyContains ">bank:checking</a>"
+      -- the sidebar's tree has every level as a row of its own, for its own folding
+      bodyContains "<tr data-indent=\"0\" data-acct=\"assets\">"
+      bodyContains "<tr data-indent=\"1\" data-acct=\"assets:bank\">"
+      bodyContains "<tr data-indent=\"2\" data-acct=\"assets:bank:checking\">"
+
+    yit "offers the depth links on the journal page, which leave the sidebar whole" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "depth" "1"
+      statusIs 200
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/journal?depth=2\"")
+      -- the sidebar's accounts are all served, for its own folding; the entries are not clipped either
+      bodyContains "account=assets%3Abank%3Achecking"
+      bodyContains "lunch</td>"
+
+    yit "serves the whole sidebar, not marked for folding to the page's depth, which it does not follow" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "list" "tree"
+        addGetParam "depth" "1"
+      statusIs 200
+      -- the journal page has no report table, so nothing is marked for folding
+      bodyNotContains "data-depth-fold"
+      bodyContains "account=assets%3Abank%3Achecking"
+      -- the - and + that fold or open the sidebar a level, in place
+      bodyContains "<button class=\"depth-step\" type=\"button\" data-step=\"-1\""
+
+    yit "reports an interval it cannot parse" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "bogus"
+      statusIs 200
+      bodyContains "Could not parse the reporting interval"
+      bodyNotContains "<tfoot>"
+
+    yit "takes an interval typed in the search, as the cli does, moving it to the interval parameter" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:monthly"
+      statusIs 303
+      loc <- headerValue "Location"
+      assertEq "the page is reloaded with the interval as a parameter" loc (T.pack (defbaseurl defhost defport) <> "/balance?interval=monthly")
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "monthly"
+      statusIs 200
+      bodyContains ">2025-01<"
+      bodyContains ">2025-02<"
+
+    yit "prefers an interval typed in the search to the interval parameter" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "yearly"
+        addGetParam "q" "date:monthly"
+      statusIs 303
+      loc <- headerValue "Location"
+      assertEq "the search's interval replaces the parameter" loc (T.pack (defbaseurl defhost defport) <> "/balance?interval=monthly")
+
+    yit "marks the report being shown for the interval" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "yearly"
+      statusIs 200
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?interval=yearly\"")
+
+    yit "keeps the search's dates in the interval links" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025"
+        addGetParam "interval" "monthly"
+      statusIs 200
+      bodyContains "balance?q=date%3A2025&amp;depth=1&amp;interval=yearly\""
+
+    yit "shows the accounts' shared prefix once, dimming remaining paths" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "assets"
+        addGetParam "depth" "all"
+      statusIs 200
+      -- the one asset account's parents become a group heading over its leaf
+      bodyContains "scope=\"rowgroup\">assets:bank</th>"
+      bodyContains ">checking</a>"
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "depth" "all"
+      statusIs 200
+      -- no shared prefix across all accounts: full names, parent paths dimmed
+      bodyContains "<span class=\"acct-path\"><span>assets:bank</span></span>:<span class=\"acct-leaf\">checking</span>"
+
+    yit "keeps the report controls behind a disclosure" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "<details class=\"report-controls\">"
+      bodyContains ">Options<span class=\"options-summary\">"
+      -- a single-commodity journal gets no commodity row (positive
+      -- control: the amount conversion group's multi-commodity journal)
+      bodyNotContains ">Commodity:"
+      get JournalR
+      statusIs 200
+      bodyContains "<details class=\"report-controls\">"
+
+    -- The open state travels in a cookie, written by the browser when
+    -- the disclosure is toggled, so the page is born as it was left
+    -- and nothing moves after paint.
+    yit "renders the controls open when the showcontrols cookie says so" $ do
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "showcontrols", setCookieValue = "1"}
+      get JournalR
+      statusIs 200
+      bodyContains "<details class=\"report-controls\" open>"
+
+    -- Cookies are shared by all servers on a host, so the names end with
+    -- the port, and another hledger-web's cookie does not apply.
+    yit "ignores the showcontrols cookie of an hledger-web on another port" $ do
+      testSetCookie defaultSetCookie{setCookieName = fromString ("showcontrols_" <> show (defport + 1)), setCookieValue = "1"}
+      get JournalR
+      statusIs 200
+      bodyContains "<details class=\"report-controls\">"
+
+    yit "marks each type a type: term selects, as a shift-click builds them" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "type:AL"
+      statusIs 200
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=type%3AA&amp;depth=1\" title=\"Show only asset accounts (type:A)\"")
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=type%3AL&amp;depth=1\" title=\"Show only liability accounts (type:L)\"")
+      bodyContains ("<a href=\"" ++ defbaseurl defhost defport ++ "/balance?depth=1\" title=\"Show accounts of every type\"")
+      bodyContains "Shift-click selects several types."
+
+    -- assets:bank:checking is a cash account; nothing is a conversion,
+    -- gain, or imbalance account
+    yit "offers the account subtypes the journal's accounts have" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "Show only cash accounts (type:C)"
+      bodyNotContains "(type:V)"
+      bodyNotContains "(type:G)"
+      bodyNotContains "(type:M)"
+
+    yit "offers a subtype the search selects, though no account has it" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "type:G"
+      statusIs 200
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=type%3AG&amp;depth=1\" title=\"Show only capital gain accounts (type:G)\"")
+
+    yit "survives an interval whose weekday is out of range" $ do
+      -- the period parser accepts this; naming the ninth weekday used
+      -- to crash the page (#2771 review)
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "every 9th day of week"
+      statusIs 200
+
+    -- intervalPeriodExpr is the period parser's interval syntax in
+    -- reverse; parsing back what it emits keeps them from drifting.
+    yit "emits period expressions the period parser reads back" $ do
+      let readBack i = case intervalPeriodExpr i of
+            Nothing -> Left ("no period expression for " ++ show i)
+            Just t -> case parsePeriodExpr (fromGregorian 2026 1 1) t of
+              Left _ -> Left (show i ++ " emitted unparseable " ++ T.unpack t)
+              Right (i', _) -> Right i'
+      mapM_ (\i -> assertEq "the interval round-trips" (Right i) (readBack i))
+        [ Days 1, Days 2, Weeks 1, Weeks 3, Months 1, Months 6, Quarters 1, Years 1, Years 2
+        , MonthDay 1, MonthDay 22, NthWeekdayOfMonth 2 3, MonthAndDay 6 15
+        , DaysOfWeek [1,2,3,4,5], DaysOfWeek [6,7], DaysOfWeek [2,4] ]
+      -- weekdays the parser accepts but the week lacks have no names:
+      -- no period expression, rather than a crash
+      assertEq "no ninth weekday" Nothing (intervalPeriodExpr (DaysOfWeek [9]))
+      assertEq "no empty weekday list" Nothing (intervalPeriodExpr (DaysOfWeek []))
+
+    yit "uses --title for the heading, unaltered" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "none"
+      statusIs 200
+      bodyContains "<h2>All accounts</h2>"
+
+    yit "escapes account names and search terms in the page" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "<img src=x onerror=alert(1)>"
+      statusIs 200
+      bodyNotContains "<img src=x onerror"
+
+    yit "titles the multi-period report in the viewer's language too" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "monthly"
+        addRequestHeader ("Accept-Language", "de")
+      statusIs 200
+      bodyContains "<h2>Saldoänderungen in 2025-01-01..2025-02-28</h2>"
+
+    yit "shows and passes the report state through the journal and register" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "interval" "monthly"
+        addGetParam "total" "1"
+      statusIs 200
+      -- kept by the search form, and carried on by the sidebar's report links
+      bodyContains "<input type=\"hidden\" name=\"interval\" value=\"monthly\">"
+      bodyContains "/balancesheet?interval=monthly&amp;total=1"
+      -- and shown, dimmed: these controls take effect on the report pages
+      bodyContains "controls-inert"
+      bodyContains ">Interval:"
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "interval" "monthly"
+      statusIs 200
+      bodyContains "<input type=\"hidden\" name=\"interval\" value=\"monthly\">"
+      bodyContains "controls-inert"
+
+    yit "shows balance changes for a period, and says so" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-02"
+      statusIs 200
+      bodyContains "<h2>Balance changes in 2025-02</h2>"
+      -- the report's own links are relative (the sidebar's are not)
+      bodyNotContains "account=income:salary"
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=date%3A2025-02&amp;depth=1\" title=\"Show how much")
+
+    yit "shows ending balances with accum=historical, asking their registers for the same" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-02"
+        addGetParam "accum" "historical"
+      statusIs 200
+      bodyContains "<h2>Ending balances (historical) in 2025-02</h2>"
+      -- no February postings, but a balance, whose register must start from before February
+      bodyContains "href=\"register?q=date:2025-02&amp;account=income&amp;accum=historical&amp;depth=1\""
+      -- the search form and the interval links keep the mode; the mode links mark it
+      bodyContains "<input type=\"hidden\" name=\"accum\" value=\"historical\">"
+      bodyContains "/balance?q=date%3A2025-02&amp;accum=historical&amp;depth=1&amp;interval=monthly\""
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=date%3A2025-02&amp;depth=1&amp;accum=historical\"")
+
+    yit "heads ending balance columns with their end dates, linking to this report for the period" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "monthly"
+        addGetParam "accum" "historical"
+      statusIs 200
+      bodyContains ">2025-01-31<"
+      bodyContains ">2025-02-28<"
+      -- the drilled view keeps the interval: one monthly column
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?q=date%3A2025-01&amp;accum=historical&amp;interval=monthly\" title=\"Show this report for this period\"")
+
+    yit "links a balance change column's heading to this report for the period" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "monthly"
+        addGetParam "q" "date:2025"
+      statusIs 200
+      bodyContains ">2025-01<"
+      -- the column's period replaces the search's date term; the interval is kept
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?q=date%3A2025-01&amp;interval=monthly\" title=\"Show this report for this period\"")
+
+    yit "reports an accumulation mode it does not know" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "accum" "bogus"
+      statusIs 200
+      bodyContains "The accum parameter has a value this page does not know"
+      bodyNotContains "<tfoot>"
+
+    yit "keeps the accumulation mode off the journal page's search form" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "accum" "historical"
+      statusIs 200
+      bodyNotContains "name=\"accum\""
+
+  runTests "hledger-web with --chart" [("chart", "net,1000")] bj $ do
+
+    yit "shows the charts' total lines at first, and fixes their scales, as the commands' --chart does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "none"
+      statusIs 200
+      bodyContains "net-shown"
+      -- the scale is 1000, not the largest bar's 100
+      bodyContains ">800</text>"
+      -- until the N key hides them
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "shownet", setCookieValue = "0"}
+      get BalanceR
+      statusIs 200
+      bodyNotContains "net-shown"
+
+  -- A journal whose accounts branch, so tree mode has real fold points
+  -- (bj's chains all squash to single rows).
+  fj <- fmap (either error' id) . runExceptT . journalFinalise biopts "branching.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["2025-01-05 pay"
+            ,"    assets:bank:checking   100"
+            ,"    income:salary"
+            ,"2025-02-05 save"
+            ,"    assets:bank:savings     50"
+            ,"    assets:bank:checking"])
+  runTests "hledger-web tree mode" [] fj $ do
+
+    yit "serves a tree-mode report at full depth, marked for folding to the search's depth" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "list" "tree"
+        addGetParam "depth" "1"
+      statusIs 200
+      bodyContains "data-depth-fold=\"1\""
+      bodyContains "<tr><td class=\"account indent-0 depth-1\">"
+      bodyContains ">assets</a>"
+      -- the rows below the fold are served too, for the page to unfold,
+      -- but already folded, so the table paints at its folded height
+      bodyContains "<tr class=\"tree-fold-hide\"><td class=\"account indent-1 depth-2\">"
+      bodyContains "<tr class=\"tree-fold-hide\"><td class=\"account indent-2 depth-3\">"
+      bodyContains ">checking</a>"
+      -- the chart can't fold, so it is clipped at the depth instead
+      bodyContains ">assets</text>"
+      bodyNotContains ">bank</text>"
+
+    yit "folds a tree-mode report by account depth, not indent, where boring parents are squashed" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "list" "tree"
+        addGetParam "depth" "2"
+      statusIs 200
+      -- assets is boring and squashed into its branching child, which
+      -- is at depth 2 though not indented; its subaccounts are below
+      -- the limit, so they are folded
+      bodyContains "<tr><td class=\"account indent-0 depth-2\">"
+      bodyContains ">assets:bank</a>"
+      bodyContains "<tr class=\"tree-fold-hide\"><td class=\"account indent-1 depth-3\">"
+      bodyNotContains "<tr><td class=\"account indent-1 depth-3\">"
+
+    yit "in tree mode, depth 0 shows one row of all accounts, with the whole tree folded under it" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "list" "tree"
+        addGetParam "depth" "0"
+      statusIs 200
+      bodyContains "data-depth-fold=\"0\""
+      -- the one row, labelled as in hledger-ui, links to everything's register
+      bodyContains "<tr><td class=\"account indent-0 depth-1\"><a href=\"register?list=tree&amp;depth=0\""
+      bodyContains ">All</a>"
+      -- the whole tree follows, one level deeper, folded
+      -- (with no fold point below the one row, boring parents squash as usual)
+      bodyContains "<tr class=\"tree-fold-hide\"><td class=\"account indent-1 depth-2\">"
+      bodyContains ">assets:bank</a>"
+      bodyContains "<tr class=\"tree-fold-hide\"><td class=\"account indent-2 depth-3\">"
+      bodyContains ">checking</a>"
+      -- not the sidebar, which has its own depth, at least 1
+      bodyNotContains "data-acct=\"...\""
+      bodyContains "<tr data-indent=\"0\" data-acct=\"assets\">"
+      -- the Depth row's 0 link is marked, not the deepest, which removes the limit
+      let base = defbaseurl defhost defport
+      bodyContains ("<a class=\"current\" href=\"" ++ base ++ "/balance?list=tree&amp;depth=0\" title=\"Show only the total (depth 0)\">0</a>")
+      bodyContains ("<a href=\"" ++ base ++ "/balance?list=tree&amp;depth=all\" title=\"Show accounts at every depth\">3</a>")
+
+    yit "in tree mode, a per-account depth limit clips its accounts, as the cli does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "list" "tree"
+        addGetParam "q" "depth:assets=2"
+        addGetParam "depth" "all"
+      statusIs 200
+      -- assets' subaccounts are clipped to depth 2 in the table, leaving
+      -- assets:bank with its subaccounts' total
+      bodyContains "<tr><td class=\"account indent-0 depth-2\"><a href=\"register?q=depth:assets%3d2&amp;account=assets:bank&amp;list=tree&amp;depth=all\""
+      bodyNotContains "href=\"register?q=depth:assets%3d2&amp;account=assets:bank:checking"
+      -- but not in the sidebar, which always lists every account
+      bodyContains "data-acct=\"assets:bank:checking\""
+
+  -- The journal, register, and sidebar link to one another: a date to that
+  -- day's journal entries, an account to its register, an amount to the
+  -- register that derives it, an entry to itself on either page.
+  let base = defbaseurl defhost defport
+      -- an entry's id (transaction-FILE-INDEX), as the pages compute it
+      frag desc = maybe (error' $ "no transaction " ++ desc) (transactionFragment bj) $
+        find ((== T.pack desc) . tdescription) (jtxns bj)
+      -- an entry's index, which an account link carries so that the
+      -- register opens on the page holding it
+      tix desc = maybe (error' $ "no transaction " ++ desc) (show . tindex) $
+        find ((== T.pack desc) . tdescription) (jtxns bj)
+  runTests "hledger-web journal, register, and sidebar links" [] bj $ do
+
+    yit "links a journal entry's date to that day's entries, and its accounts to their registers at the entry" $ do
+      get JournalR
+      statusIs 200
+      bodyContains ("href=\"" ++ base ++ "/journal?q=date%3A2025-01-05&amp;depth=1#" ++ frag "pay" ++ "\" title=\"Show the journal entries on this date\">")
+      bodyContains ("href=\"" ++ base ++ "/register?account=assets%3Abank%3Achecking&amp;txn=" ++ tix "lunch" ++ "&amp;depth=1#" ++ frag "lunch" ++ "\" title=\"assets:bank:checking\">")
+
+    yit "narrows the journal to a day" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:2025-02-05"
+      statusIs 200
+      bodyContains ("id=\"" ++ frag "lunch" ++ "\"")
+      bodyNotContains ("id=\"" ++ frag "pay" ++ "\"")
+
+    yit "gives register rows the journal's entry ids, and links dates to the entry on its day" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "depth" "all"
+      statusIs 200
+      bodyContains ("<tr id=\"" ++ frag "lunch" ++ "\"")
+      bodyContains ("href=\"" ++ base ++ "/journal?q=date%3A2025-02-05&amp;depth=all#" ++ frag "lunch" ++ "\" title=\"Show this entry and the other journal entries on its date\">")
+      bodyContains ("href=\"" ++ base ++ "/register?account=expenses%3Afood&amp;txn=" ++ tix "lunch" ++ "&amp;depth=all#" ++ frag "lunch" ++ "\" title=\"expenses:food\">")
+      -- the chart's points link to the rows, its styles are linked, and its base link is the register's
+      bodyContains ("<a href=\"#" ++ frag "lunch" ++ "\"")
+      bodyContains ("<link rel=\"stylesheet\" href=\"" ++ base ++ "/chart.css\">")
+      bodyContains ("data-baselink=\"" ++ base ++ "/register?account=assets%3Abank%3Achecking&amp;depth=all\"")
+
+    yit "replaces the search's date terms in a date link, and keeps its other terms" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date:2025-02 not:desc:\"x y\""
+      statusIs 200
+      bodyContains ("href=\"" ++ base ++ "/journal?q=date%3A2025-02-05%20%22not%3Adesc%3Ax%20y%22&amp;depth=1#" ++ frag "lunch" ++ "\"")
+      -- (the sidebar's Journal link keeps the search as typed; the date links are the ones with a fragment)
+      bodyNotContains "/journal?q=date%3A2025-02%20%22not%3Adesc%3Ax%20y%22#"
+
+    yit "links the sidebar's amounts where their account names go" $ do
+      withSidebarBalances
+      get JournalR
+      statusIs 200
+      -- (at the default depth 1, the top-level accounts)
+      bodyContains ("<a href=\"" ++ base ++ "/register?account=assets\" title=\"Show the transactions behind this balance\">")
+      -- an empty search adds no search to the account links
+      bodyNotContains "/register?q=&amp;account"
+      -- a balanced journal's total is zero, and does not link
+      bodyNotContains "Show the transactions behind this total"
+
+    yit "keeps the search, minus its account term, on the sidebar's Journal link" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date:2025"
+      statusIs 200
+      bodyContains ("<td class=\"top acct\" colspan=\"2\"><a href=\"" ++ base ++ "/journal?q=date%3A2025\" title=\"Show general journal entries, most recent first\">Journal</a>")
+      get JournalR
+      statusIs 200
+      bodyContains ("<td class=\"top acct\" colspan=\"2\"><a class=\"inacct\" href=\"" ++ base ++ "/journal\" title=\"Show general journal entries, most recent first\">Journal</a>")
+
+    yit "gives the journal links the same report state as the other page links" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "interval" "quarterly"
+        addGetParam "sort" "amount"
+      statusIs 200
+      -- in the sidebar, in the g menu, and in the row of page links
+      bodyContains ("<a href=\"" ++ base ++ "/journal?interval=quarterly&amp;sort=amount\" title=\"Show general journal entries, most recent first\">Journal</a>")
+      bodyContains ("<a href=\"" ++ base ++ "/journal?interval=quarterly&amp;sort=amount\" data-gokey=\"j\"")
+      bodyContains ("<p class=\"report-links reports\"><a href=\"" ++ base ++ "/journal?interval=quarterly&amp;sort=amount\"")
+
+    yit "starts each page with the report links, then the search, the options, and the heading" $ do
+      get BalancesheetR
+      statusIs 200
+      bodyContainsInOrder ["<p class=\"report-links reports\">", "searchform", "report-controls", "<h2>"]
+      -- the register, though no report, has them too
+      get RegisterR
+      statusIs 200
+      bodyContainsInOrder ["<p class=\"report-links reports\"><a href=\"" <> T.pack base <> "/journal\"", "searchform", "report-controls", "<h2>"]
+
+    yit "serves the sidebar without its balances by default, just the account names" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "<tr data-indent=\"0\" data-acct=\"assets\">"
+      -- no amounts, total row, or ledger-based muting
+      bodyNotContains "Show the transactions behind this balance"
+      bodyNotContains "<tr class=\"total\">"
+      bodyNotContains "class=\"acct empty\""
+      -- the heading, which reloads the page to show them
+      bodyContains "<button class=\"balances-toggle\" type=\"button\" data-reload=\"1\""
+
+    yit "lists every account in the sidebar, whatever the search, with their balances at the end of its dates" $ do
+      withSidebarBalances
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "expenses date:2025-01"
+      statusIs 200
+      -- assets and income too, and expenses, first posted to in February, at zero
+      bodyContains "<tr data-indent=\"0\" data-acct=\"assets\">"
+      bodyContains "<tr data-indent=\"0\" data-acct=\"income\">"
+      bodyContains "<tr data-indent=\"0\" data-acct=\"expenses\">"
+      -- the account names link to their registers with the search; the
+      -- balances, which only the search's dates decide, with just those
+      bodyContains ("<a class=\"acct-name\" href=\"" ++ base ++ "/register?q=expenses%20date%3A2025-01&amp;account=assets\"")
+      bodyContains ("<a href=\"" ++ base ++ "/register?q=date%3A2025-01&amp;account=assets\" title=\"Show the transactions behind this balance\">")
+
+    yit "dates the sidebar's balances: the journal's last date, or the search's last day" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "<span class=\"balances-date\""
+      bodyContains ">Balances on 2025-02-05</span>"
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:2025-01"
+      statusIs 200
+      bodyContains ">Balances on 2025-01-31</span>"
+
+  -- The register: a period's transactions, with a running total from zero,
+  -- or with accum=historical, the account's balance from before the period.
+  runTests "hledger-web register page" [] bj $ do
+
+    yit "headings name the search's dates, and say filtered for its other filters" $ do
+      get (JournalR, [("q", "date:2025")])
+      statusIs 200
+      bodyContains ">General Journal in 2025</h2>"
+      get (JournalR, [("q", "date:2025 lunch")])
+      statusIs 200
+      bodyContains ">General Journal in 2025, filtered</h2>"
+      get (RegisterR, [("account", "assets:bank:checking"), ("q", "date:2025")])
+      statusIs 200
+      bodyContains ">assets:bank:checking in 2025</h2>"
+
+    -- The register's table has a tbody; the sidebar, which shows the same
+    -- accounts, has none, so these assertions look only at the register.
+    yit "totals the period from zero by default" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date:2025-02"
+      statusIs 200
+      bodyContains ">Period Total</a>"
+      htmlAnyContain "#main-content tbody td.amount" "-10"
+      htmlNoneContain "#main-content tbody td.amount" "90"
+      bodyNotContains "Balance brought forward"
+      bodyNotContains "name=\"accum\""
+      -- the balance column's heading switches to historical mode
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/register?q=date%3A2025-02&amp;account=assets%3Abank%3Achecking&amp;depth=1&amp;accum=historical\" title=\"Click to show the running balance including everything before this period\">Period Total</a>")
+
+    yit "starts from the balance brought forward with accum=historical" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date:2025-02"
+        addGetParam "accum" "historical"
+        addGetParam "depth" "all"
+      statusIs 200
+      bodyContains ">Historical Total</a>"
+      htmlAnyContain "#main-content tbody td.amount" "90"
+      -- the oldest row is the balance brought forward, linking to the transactions before the period
+      htmlAnyContain "#main-content tbody tr.broughtforward td.amount" "100"
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/register?q=date%3A..2025-02-01&amp;account=assets%3Abank%3Achecking&amp;depth=all\" title=\"Show the transactions before this period\">")
+      -- the search form, the other-account links, and the chart's base link keep the mode
+      bodyContains "<input type=\"hidden\" name=\"accum\" value=\"historical\">"
+      bodyContains "&amp;accum=historical&amp;depth=all#"
+      bodyContains ("data-baselink=\"" ++ defbaseurl defhost defport ++ "/register?account=assets%3Abank%3Achecking&amp;accum=historical&amp;depth=all\"")
+      -- the heading switches back, dropping the mode
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/register?q=date%3A2025-02&amp;account=assets%3Abank%3Achecking&amp;depth=all\" title=\"Click to show the running balance from the start of this period\">Historical Total</a>")
+
+    yit "cuts the balance brought forward off by the kind of date the query has" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date2:2025-02"
+        addGetParam "accum" "historical"
+      statusIs 200
+      bodyContains "/register?q=date2%3A..2025-02-01&amp;account=assets%3Abank%3Achecking&amp;depth=1\" title=\"Show the transactions before this period\">"
+
+    yit "moves an account term in the search to the account parameter" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "q" "inacctonly:assets:bank:checking date:2025"
+      statusIs 303
+      loc <- headerValue "Location"
+      assertEq "the page is reloaded with the account as a parameter" loc
+        (T.pack (defbaseurl defhost defport) <> "/register?q=date%3A2025&account=assets%3Abank%3Achecking&subs=0")
+
+    yit "keeps the account when the search is cleared or changed" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date:2025"
+      statusIs 200
+      bodyContains ("<a class=\"btn btn-default\" id=\"search-clear\" href=\"" ++ defbaseurl defhost defport ++ "/register?account=assets%3Abank%3Achecking\" title=\"Clear search terms\"")
+      bodyContains "<input type=\"hidden\" name=\"account\" value=\"assets:bank:checking\">"
+
+    yit "names the other accounts of a type: search's transactions" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "q" "type:X date:2025-02"
+        addGetParam "depth" "all"
+      statusIs 200
+      bodyContains "title=\"expenses:food\">"
+
+  -- The financial statements: the balancesheet, balancesheetequity,
+  -- incomestatement, and cashflow commands' reports, with declared and
+  -- inferred account types, and each figure linked to its register.
+  tj <- fmap (either error' id) . runExceptT . journalFinalise biopts "statements.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["account liabilities:card  ; type:L"
+            ,"account equity:opening    ; type:E"
+            ,"2025-01-01 opening"
+            ,"    assets:bank:checking   1000"
+            ,"    equity:opening"
+            ,"2025-01-05 pay"
+            ,"    assets:bank:checking   100"
+            ,"    income:salary"
+            ,"2025-02-05 lunch"
+            ,"    expenses:food           10"
+            ,"    liabilities:card"
+            ,"2025-02-06 snack"
+            ,"    expenses:snacks<i>x      1"
+            ,"    liabilities:card"])
+  runTests "hledger-web financial statements" [] tj $ do
+
+    yit "serves the balance sheet, with ending balances, in sections" $ do
+      getWhole BalancesheetR []
+      statusIs 200
+      bodyContains "<h2>Balance Sheet 2025-02-06</h2>"
+      -- and charts it below the heading, with the net worth
+      bodyContains "<h2>Balance Sheet 2025-02-06</h2><div class=\"part-toggle-row chart-toggle-row\"><button type=\"button\" class=\"part-toggle\" data-report-part=\"chart\" title=\"Show or hide the chart (c)\">Chart</button></div><div class=\"report-chart\"><svg"
+      bodyContains ">Net</text>"
+      -- a section heading names a dropped shared prefix deeper than one
+      -- component; a single-component one stays implied by the title
+      bodyContains "<tr class=\"section\"><th colspan=\"2\" scope=\"rowgroup\">Assets — assets:bank</th></tr>"
+      bodyContains "<tr class=\"section\"><th colspan=\"2\" scope=\"rowgroup\">Liabilities</th></tr>"
+      bodyContains "<tr class=\"subtotal\">"
+      bodyContains "<tfoot>"
+      bodyContains "Net:"
+      -- figures link to registers in historical mode, restricted to the
+      -- section's account types; a liability's says its sign differs
+      bodyContains "href=\"register?q=type:A&amp;account=assets:bank:checking&amp;accum=historical&amp;interval=none&amp;depth=all\""
+      bodyContains "href=\"register?q=date:2025-01-01..2025-02-07+type:L&amp;account=liabilities:card&amp;accum=historical&amp;interval=none&amp;depth=all\" title=\"Show the transactions behind this balance, which the register shows with the opposite sign\">"
+      -- a section total links to the section's account types, the net total to all of them
+      bodyContains "href=\"register?q=type:L+date:2025-01-01..2025-02-07&amp;accum=historical&amp;interval=none&amp;depth=all\""
+      bodyContains "href=\"register?q=type:AL+date:2025-01-01..2025-02-07&amp;accum=historical&amp;interval=none&amp;depth=all\""
+      -- shown as positive amounts, and without inline styles
+      bodyNotContains "class=\"amount negative\""
+      bodyNotContains "style=\""
+
+    yit "serves the multi-period balance sheet, headed by end dates linking to this report" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "interval" "monthly"
+      statusIs 200
+      bodyContains "<h2>Monthly Balance Sheet 2025-01-31..2025-02-28</h2>"
+      bodyContains ">2025-01-31<"
+      bodyContains ">2025-02-28<"
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?q=date%3A2025-01&amp;interval=monthly\" title=\"Show this report for this period\"")
+      bodyContains "<input type=\"hidden\" name=\"interval\" value=\"monthly\">"
+
+    yit "shows balance changes instead when asked, and says so" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "accum" "change"
+      statusIs 200
+      bodyContains "<h2>Monthly Balance Sheet 2025-01-01..2025-02-28 (Balance Changes)</h2>"
+      bodyNotContains "accum=historical"
+      -- the search form and the interval links keep the override
+      bodyContains "<input type=\"hidden\" name=\"accum\" value=\"change\">"
+      bodyContains "/balancesheet?accum=change&amp;depth=1&amp;interval=monthly\""
+
+    yit "does not keep the balance sheet's own mode as a parameter" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "accum" "historical"
+      statusIs 200
+      bodyContains "<h2>Monthly Balance Sheet 2025-01-31..2025-02-28</h2>"
+      bodyNotContains "name=\"accum\""
+
+    yit "reports an accumulation mode it does not know" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "accum" "bogus"
+      statusIs 200
+      bodyContains "<h2>Balance Sheet</h2>"
+      bodyContains "The accum parameter has a value this page does not know"
+      bodyNotContains "<tfoot>"
+
+    yit "serves the income statement, with changes, revenues shown positive" $ do
+      getWhole IncomestatementR []
+      statusIs 200
+      bodyContains "<h2>Income Statement 2025-01-01..2025-02-06</h2>"
+      bodyContains ">Revenues</th>"
+      bodyContains ">Expenses</th>"
+      bodyContains "href=\"register?q=date:2025-01-01..2025-02-07+type:R&amp;account=income:salary&amp;interval=none&amp;depth=all\" title=\"Show the transactions that make up this amount, which the register shows with the opposite sign\">"
+      bodyContains "href=\"register?q=type:RX+date:2025-01-01..2025-02-07&amp;interval=none&amp;depth=all\" title=\"Show the transactions that make up this total, which the register shows with the opposite sign\">"
+      -- the page's own mode is never a parameter; the Show row's other modes are
+      bodyNotContains "accum=change"
+
+    yit "shows the income statement's ending balances when asked, and says so" $ do
+      getWhole IncomestatementR [("accum", "historical")]
+      statusIs 200
+      bodyContains "<h2>Income Statement 2025-02-06 (Historical Ending Balances)</h2>"
+      bodyContains "<input type=\"hidden\" name=\"accum\" value=\"historical\">"
+      bodyContains "href=\"register?q=type:R&amp;account=income:salary&amp;accum=historical&amp;interval=none&amp;depth=all\""
+
+    yit "serves the cashflow statement, with one section and no net total" $ do
+      getWhole CashflowR []
+      statusIs 200
+      bodyContains "<h2>Cashflow Statement 2025-01-01..2025-02-06</h2>"
+      bodyContains ">Cash flows — assets:bank</th>"
+      bodyNotContains "<tfoot>"
+
+    yit "lays out the chart's sections side by side with chart=grouped, which the links keep" $ do
+      get IncomestatementR
+      statusIs 200
+      bodyContains "<p class=\"report-links chart\"><span class=\"row-label\">Chart:</span>"
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/incomestatement?depth=1\" title=\"Chart each period&#39;s amounts in one bar")
+      request $ do
+        setMethod "GET"
+        setUrl IncomestatementR
+        addGetParam "chart" "grouped"
+      statusIs 200
+      bodyContains "<span class=\"options-summary\">Monthly · Depth 1 · Grouped chart</span>"
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/incomestatement?depth=1&amp;chart=grouped\"")
+      bodyContains "/balancesheet?chart=grouped\""
+      request $ do
+        setMethod "GET"
+        setUrl IncomestatementR
+        addGetParam "chart" "bogus"
+      statusIs 200
+      bodyContains "The chart parameter has a value this page does not know"
+
+    -- The balance sheet's Equity row shows balancesheetequity's report,
+    -- with an equity=1 parameter its own links keep, and its registers don't.
+    yit "serves the balance sheet with equity, for equity=1" $ do
+      get BalancesheetR
+      statusIs 200
+      bodyContains "<p class=\"report-links equity\"><span class=\"row-label\">Equity:</span>"
+      bodyNotContains ">Equity</th>"
+      getWhole BalancesheetR [("equity", "1")]
+      statusIs 200
+      bodyContains "<h2>Balance Sheet With Equity 2025-02-06</h2>"
+      bodyContains ">Equity</th>"
+      bodyContains "<span class=\"options-summary\">Equity shown · Depth all</span>"
+      bodyContains "/balancesheet?equity=1&amp;interval=none&amp;depth=all&amp;accum=change\""
+      bodyContains "href=\"register?q=type:ALE+date:2025-01-01..2025-02-07&amp;accum=historical&amp;interval=none&amp;depth=all\""
+      get IncomestatementR
+      statusIs 200
+      bodyNotContains "report-links equity"
+
+    -- The choice is remembered, for this hledger-web, in a cookie the
+    -- server sets when the equity parameter is given.
+    yit "remembers the balance sheet's equity choice" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "equity" "1"
+      statusIs 200
+      get BalancesheetR
+      statusIs 200
+      bodyContains ">Equity</th>"
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "equity" "0"
+      statusIs 200
+      bodyNotContains ">Equity</th>"
+      get BalancesheetR
+      statusIs 200
+      bodyNotContains ">Equity</th>"
+
+    yit "ignores the equity choice of an hledger-web on another port" $ do
+      testSetCookie defaultSetCookie{setCookieName = fromString ("showequity_" <> show (defport + 1)), setCookieValue = "1"}
+      get BalancesheetR
+      statusIs 200
+      bodyNotContains ">Equity</th>"
+
+    yit "redirects the old balance sheet with equity page to the balance sheet's equity=1" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetequityR
+        addGetParam "interval" "monthly"
+      statusIs 303
+      assertHeader "Location" (TE.encodeUtf8 $ T.pack (defbaseurl defhost defport) <> "/balancesheet?interval=monthly&equity=1")
+
+    yit "links the reports to one another, marking the one shown, and to All accounts" $ do
+      request $ do
+        setMethod "GET"
+        setUrl IncomestatementR
+        addGetParam "interval" "quarterly"
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "expenses"
+      statusIs 200
+      -- the links keep the period and the search minus its account term
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/incomestatement?interval=quarterly&amp;q=expenses\" title=\"Show revenues and expenses\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?interval=quarterly&amp;q=expenses\" title=\"Show assets, liabilities, and net worth\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?interval=quarterly&amp;q=expenses\" title=\"Show the balances of all accounts, by period, like the balance command\"")
+
+    yit "links All accounts to the statements too" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance\" title=\"Show the balances of all accounts, by period, like the balance command\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/incomestatement\" title=\"Show revenues and expenses\"")
+
+    yit "links the journal page to the reports too, keeping the search minus its account term" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "expenses"
+      statusIs 200
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?q=expenses\" title=\"Show assets, liabilities, and net worth\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?q=expenses\"")
+      -- the journal leads the row, marked as the page shown
+      bodyContains ("<p class=\"report-links reports\"><a class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/journal?q=expenses\" title=\"Show general journal entries, most recent first\">Journal</a>")
+
+    yit "links the report pages to the journal, first in their row of report links" $ do
+      get IncomestatementR
+      statusIs 200
+      bodyContains ("<p class=\"report-links reports\"><a href=\"" ++ defbaseurl defhost defport ++ "/journal\" title=\"Show general journal entries, most recent first\">Journal</a>")
+
+    yit "lists the balance sheet, income statement, and cashflow statement in the sidebar, marking the one shown" $ do
+      get BalancesheetR
+      statusIs 200
+      bodyContains ("<tr class=\"inacct\"><td class=\"top acct\" colspan=\"2\"><a class=\"inacct\" href=\"" ++ defbaseurl defhost defport ++ "/balancesheet\" title=\"Show assets, liabilities, and net worth\">Balance sheet</a>")
+      bodyContains ("<tr><td class=\"top acct\" colspan=\"2\"><a href=\"" ++ defbaseurl defhost defport ++ "/incomestatement\" title=\"Show revenues and expenses\">Income statement</a>")
+      bodyContains ("<a href=\"" ++ defbaseurl defhost defport ++ "/cashflow\" title=\"Show changes in liquid assets\">Cashflow statement</a>")
+      -- and All accounts, last
+      bodyContains ("<tr><td class=\"top acct\" colspan=\"2\"><a href=\"" ++ defbaseurl defhost defport ++ "/balance\" title=\"Show the balances of all accounts, by period, like the balance command\">All accounts</a>")
+
+    yit "gives the sidebar's report links the search minus its account term, and the period" $ do
+      request $ do
+        setMethod "GET"
+        setUrl IncomestatementR
+        addGetParam "interval" "quarterly"
+        addGetParam "accum" "historical"
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "expenses"
+      statusIs 200
+      -- the period is kept, the mode is not: it belongs to this report
+      bodyContains ("colspan=\"2\"><a href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?interval=quarterly&amp;q=expenses\" title=\"Show assets, liabilities, and net worth\">")
+      bodyNotContains "/balancesheet?interval=quarterly&amp;accum"
+
+    yit "links the sidebar's reports from the journal and register too" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:bank:checking"
+        addGetParam "q" "date:2025"
+      statusIs 200
+      bodyContains ("colspan=\"2\"><a href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?q=date%3A2025\" title=\"Show assets, liabilities, and net worth\">")
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:2025"
+      statusIs 200
+      bodyContains ("colspan=\"2\"><a href=\"" ++ defbaseurl defhost defport ++ "/incomestatement?q=date%3A2025\" title=\"Show revenues and expenses\">")
+
+    yit "drops each section's shared account prefix, dimming remaining paths" $ do
+      getWhole BalancesheetR []
+      statusIs 200
+      bodyContains "class=\"account acct-split\""
+      -- assets:bank:checking shows as its leaf; the full name heads the tooltip
+      bodyContains "title=\"assets:bank:checking"
+      bodyContains ">checking</a>"
+
+    yit "escapes account names and search terms in the statements" $ do
+      getWhole IncomestatementR []
+      statusIs 200
+      -- the full name heads the tooltip, and the stripped name is the link
+      bodyContains "title=\"expenses:snacks&lt;i&gt;x"
+      bodyContains ">snacks&lt;i&gt;x</a>"
+      bodyNotContains "snacks<i>x"
+      request $ do
+        setMethod "GET"
+        setUrl IncomestatementR
+        addGetParam "q" "<img src=x onerror=alert(1)>"
+      statusIs 200
+      bodyNotContains "<img src=x onerror"
+
+  -- Amounts as recorded, at cost, or at market value: a stock bought in
+  -- three months at three prices, and priced at each month's start.
+  vj <- fmap (either error' id) . runExceptT . journalFinalise biopts "valued.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["commodity $1,000.00"
+            ,"commodity 1000.00 \"AAA UU\""  -- a spaced symbol, for the commodity row
+            ,"P 2024-12-01 AAPL $80"
+            ,"P 2025-01-01 AAPL $100"
+            ,"P 2025-02-01 AAPL $120"
+            ,"2024-12-05 buy"
+            ,"    assets:broker   1 AAPL @ $80"
+            ,"    assets:bank"
+            ,"2025-01-05 buy"
+            ,"    assets:broker  10 AAPL @ $90"
+            ,"    assets:bank"
+            ,"2025-02-10 buy"
+            ,"    assets:broker   5 AAPL @ $110"
+            ,"    assets:bank"])
+  runTests "hledger-web amount conversion" [] vj $ do
+
+    yit "shows market values with value=end, asking the figures' registers for the same" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-01"
+        addGetParam "value" "end"
+        addGetParam "depth" "all"
+      statusIs 200
+      -- 10 AAPL at January's end
+      bodyContains "$1,000.00"
+      bodyContains "href=\"register?q=date:2025-01&amp;account=assets:broker&amp;value=end&amp;depth=all\""
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=date%3A2025-01&amp;depth=all&amp;value=end\"")
+      -- the other reports, and the search form, keep it
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?q=date%3A2025-01&amp;depth=all&amp;value=end\"")
+      bodyContains "<input type=\"hidden\" name=\"value\" value=\"end\">"
+
+    yit "shows costs with value=cost" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-01"
+        addGetParam "value" "cost"
+        addGetParam "depth" "all"
+      statusIs 200
+      bodyContains "$900.00"
+      bodyContains "href=\"register?q=date:2025-01&amp;account=assets:broker&amp;value=cost&amp;depth=all\""
+
+    -- The parameters appended to the figures' register links must be
+    -- url-encoded: interval words can carry spaces.
+    yit "url-encodes the parameters it adds to the figures' register links" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-01"
+        addGetParam "interval" "every 2 weeks"
+      statusIs 200
+      bodyContains "&amp;interval=every%202%20weeks"
+
+    -- Percentages need the amounts in one commodity, which depends on
+    -- the data: the page explains and shows plain amounts, instead of
+    -- the error page the report's error used to become (the url keeps
+    -- pct=1, so the links and the Numbers row keep the state).
+    yit "explains percentages it cannot calculate, showing amounts instead" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "pct" "1"
+      statusIs 200
+      bodyContains "Could not calculate percentages:"
+      -- the table's amounts (monthly changes), as the cli would show them
+      bodyContains "<span class=\"amount\">10 AAPL</span>"
+      bodyContains "pct=1"
+
+    yit "shows percentages when a conversion yields one commodity" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "pct" "1"
+        addGetParam "value" "end"
+      statusIs 200
+      bodyContains "100.0 %"
+      bodyNotContains "Could not calculate percentages"
+
+    yit "reports an amount conversion it does not know" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "value" "bogus"
+      statusIs 200
+      bodyContains "Unknown amount conversion"
+
+    yit "rejects gains over amounts as recorded, as the command line does" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "calc" "gain"
+        addGetParam "value" "none"
+      statusIs 200
+      bodyContains "figured from period-end market values"
+
+    yit "converts the register's amounts as the value parameter says, and its links keep its modes" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:broker"
+        addGetParam "accum" "historical"
+        addGetParam "value" "end"
+      statusIs 200
+      -- 16 AAPL at the journal's end
+      bodyContains "$1,920.00"
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/register?q=date%3A2025&amp;account=assets%3Abroker&amp;accum=historical&amp;value=end&amp;depth=1\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?value=end\"")
+
+    yit "offers the depth and amount links on the statements too, keeping an accumulation override" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "accum" "change"
+      statusIs 200
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?accum=change&amp;depth=1\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balancesheet?accum=change&amp;depth=1&amp;value=end\"")
+
+    yit "shows the sidebar's amounts the way the page's value parameter asks, naming its total row by the mode" $ do
+      withSidebarBalances
+      get JournalR
+      statusIs 200
+      bodyContains "Total:"
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "value" "cost"
+        addGetParam "depth" "all"
+      statusIs 200
+      -- 1 AAPL at $80, 10 at $90, 5 at $110, summed at cost
+      bodyContains "$1,530.00"
+      bodyContains "Total at cost:"
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "value" "end"
+      statusIs 200
+      bodyContains "Total at value:"
+      -- whatever the search, the total is of every account
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "assets"
+      statusIs 200
+      bodyContains "The sum of every account."
+
+    yit "offers the journal's commodities as filters, escaping their symbols" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains ">Commodity:"
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?q=cur%3AAAPL&amp;depth=1\" title=\"Show only amounts in AAPL\"")
+      bodyContains "q=cur%3A%5C%24&amp;depth=1\""
+      -- a spaced symbol's term is quoted whole, and its pattern is in its link's data
+      bodyContains "q=%22cur%3AAAA%20UU%22"
+      bodyContains "data-cur=\"AAA UU\""
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "cur:AAPL"
+      statusIs 200
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=cur%3AAAPL&amp;depth=1\"")
+
+    yit "marks each commodity a cur: alternation selects, as a shift-click builds them" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "cur:AAPL|\\$"
+      statusIs 200
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=cur%3AAAPL&amp;depth=1\"")
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?q=cur%3A%5C%24&amp;depth=1\"")
+      -- the search's other terms ride along for the script, pre-quoted
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "assets cur:AAPL"
+      statusIs 200
+      bodyContains "data-rest=\"assets\""
+
+  runTests "hledger-web amount conversion with -V" [("V","")] vj $ do
+
+    yit "shows amounts as recorded on a bare url, despite startup -V" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025-01"
+      statusIs 200
+      bodyContains "10 AAPL"
+      bodyNotContains "$1,000.00"
+
+  -- Many commodities: the row collapses to a line showing the selection.
+  cj <- fmap (either error' id) . runExceptT . journalFinalise biopts "commodities.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["commodity 1.00 CC" ++ [c] | c <- "ABCDEFG"])
+  runTests "hledger-web with many commodities" [] cj $ do
+
+    yit "collapses the commodity row to its selection, opening to the list" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "<summary title=\"List all the commodities\">"
+      bodyContains "class=\"sel\">All<"
+      bodyContains "data-cur=\"CCG\""
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "cur:CCA|CCC"
+      statusIs 200
+      bodyContains "class=\"sel\">CCA, CCC<"
+
+    -- Like the controls disclosure's open state, the list's travels in
+    -- a cookie the server reads, so it is born open, with no script
+    -- moving it after paint.
+    yit "renders the commodity list open when the showcommodities cookie says so" $ do
+      get BalanceR
+      statusIs 200
+      bodyNotContains "<details open=\"open\">"
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "showcommodities", setCookieValue = "1"}
+      get BalanceR
+      statusIs 200
+      bodyContains "<details open=\"open\">"
+
+  -- Registers of many commodities (#2784): a broker account whose balance
+  -- grows to four commodities, an account of eleven, one posted twice, and
+  -- one that buys five and then sells them one by one.
+  let closed = map (replicate 3) "ABCDE"
+  rj <- fmap (either error' id) . runExceptT . journalFinalise biopts "registers.journal" "" =<<
+          readJournal'' (T.pack $ unlines $  -- PARTIAL: readJournal'' should not fail
+            concat [ [ymd ++ " " ++ desc, "    assets:broker   " ++ amt, "    equity"]
+                   | (ymd, desc, amt) <- [ ("2025-01-01", "one",   "10 DDD")
+                                         , ("2025-01-02", "two",   "1 AAA")
+                                         , ("2025-01-03", "three", "2 BBB")
+                                         , ("2025-01-04", "four",  "3 CCC")
+                                         , ("2025-01-05", "five",  "4 DDD") ] ] ++
+            concat [ ["2025-02-01 many", "    assets:many   1 " ++ c, "    equity"]
+                   | c <- map (replicate 3) "ABCDEFGHIJK" ++ ["KKK"] ] ++
+            ["2025-03-01 buy"] ++ ["    assets:closed   1 " ++ c | c <- closed] ++ ["    equity"] ++
+            concat [ ["2025-03-02 sell " ++ c, "    assets:closed   -1 " ++ c, "    equity"]
+                   | c <- closed ])
+  -- the amount cells of an entry's register row
+  let rjamounts desc = maybe (error' $ "no transaction " ++ desc) (\t -> T.pack $ "#" ++ transactionFragment rj t ++ " td.amount") $
+        find ((== T.pack desc) . tdescription) (jtxns rj)
+  runTests "hledger-web registers of many commodities" [] rj $ do
+
+    yit "shows a running balance of up to three commodities in full, and of more only those its row posted (#2784)" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:broker"
+      statusIs 200
+      -- three: all of them, though the row posted one
+      htmlAnyContain (rjamounts "three") "10 DDD"
+      htmlNoneContain (rjamounts "three") "more"
+      -- four: the one the row posted, then how many more
+      htmlAnyContain (rjamounts "five") "14 DDD"
+      htmlAnyContain (rjamounts "five") "… and 3 more"
+      htmlNoneContain (rjamounts "five") "1 AAA"
+
+    yit "shows a commodity its row closed out, at zero, and elides a balance of zeros (#2784)" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:closed"
+      statusIs 200
+      -- buy posted all five: all of them, and no note of none more
+      htmlAnyContain (rjamounts "buy") "1 EEE"
+      htmlNoneContain (rjamounts "buy") "more"
+      -- sell AAA closed out AAA: it at zero, then the four left
+      htmlAnyContain (rjamounts "sell AAA") "0 AAA"
+      htmlAnyContain (rjamounts "sell AAA") "… and 4 more"
+      -- sell EEE left five zeros: its own, then the other four
+      htmlAnyContain (rjamounts "sell EEE") "0 EEE"
+      htmlAnyContain (rjamounts "sell EEE") "… and 4 more"
+      htmlNoneContain (rjamounts "sell EEE") "0 AAA"
+
+    yit "charts the ten commodities with the most transactions, noting the rest (#2784)" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:many"
+      statusIs 200
+      -- KKK, posted twice, comes first in the legend though last
+      -- alphabetically; of those posted once each, JJJ is left out
+      bodyContains "<label for=\"register-chart-0\">KKK</label>"
+      bodyContains "<label for=\"register-chart-9\">III</label>"
+      bodyNotContains ">JJJ</label>"
+      bodyContains "<p class=\"chart-note\">… and 1 more</p>"
+      -- four commodities are all charted, with no note
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:broker"
+      statusIs 200
+      bodyContains "<label for=\"register-chart-3\">"
+      bodyNotContains "chart-note"
+
+    yit "charts one commodity of a report at a time, chosen in a legend like the register's" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "assets:broker"
+        addGetParam "interval" "none"
+      statusIs 200
+      bodyContains "<div class=\"report-chart with-legend\"><span class=\"chart-legend-label\">Commodity:</span>"
+      bodyContains "<input type=\"radio\" name=\"report-chart\" id=\"report-chart-0\" checked=\"\">"
+      bodyContains "<label for=\"report-chart-3\">"
+      bodyNotContains "report-chart-4"
+      bodyContains "aria-label=\"All accounts, filtered: DDD\""
+
+    yit "draws the register chart as wide as the browser measured the page's main column" $ do
+      let broker = request $ do
+            setMethod "GET"
+            setUrl RegisterR
+            addGetParam "account" "assets:broker"
+      -- not measured yet, the chart's own width
+      broker
+      statusIs 200
+      bodyContains "class=\"hledger-chart\" width=\"880\""
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "chartwidth", setCookieValue = "1200"}
+      broker
+      bodyContains "class=\"hledger-chart\" width=\"1200\""
+      -- too narrow to draw in, it is widened
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "chartwidth", setCookieValue = "100"}
+      broker
+      bodyContains "class=\"hledger-chart\" width=\"320\""
+      -- with the column's widths with the sidebar shown and hidden, drawn at
+      -- both, for the page to show the one for the sidebar's state
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "chartwidths", setCookieValue = "800,1200"}
+      broker
+      bodyContainsInOrder
+        [ "<div class=\"chart-width\" data-sidebar=\"shown\">", "class=\"hledger-chart\" width=\"800\""
+        , "<div class=\"chart-width\" data-sidebar=\"hidden\">", "class=\"hledger-chart\" width=\"1200\"" ]
+      -- the same with the sidebar either way, eg on a narrow screen: drawn once, as it is
+      testSetCookie defaultSetCookie{setCookieName = uiCookieName "chartwidths", setCookieValue = "800,800"}
+      broker
+      bodyNotContains "chart-width"
+      bodyContains "class=\"hledger-chart\" width=\"320\""
+
+  -- A journal whose accounts have no recognizable types has empty statements.
+  uj <- fmap (either error' id) . runExceptT . journalFinalise biopts "untyped.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["2025-01-01 x"
+            ,"    aaa   1"
+            ,"    bbb"])
+  runTests "hledger-web financial statements without account types" [] uj $ do
+
+    yit "explains an empty statement, pointing to how account types are found" $ do
+      get BalancesheetR
+      statusIs 200
+      bodyContains "No accounts of the types this report shows were found"
+      bodyContains "hledger.html#account-types"
+      bodyNotContains "balancereport"
+      bodyNotContains "report-chart"
+
+    yit "says when a search matches nothing instead" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "q" "zzz"
+      statusIs 200
+      bodyContains "Nothing matches this search in this period."
+      bodyNotContains "account-types"
+
+  -- Typed accounts whose balances net to zero: hidden with -E, but there.
+  zj <- fmap (either error' id) . runExceptT . journalFinalise biopts "zeroed.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["account assets:bank      ; type:A"
+            ,"account liabilities:loan ; type:L"
+            ,"2025-01-01 borrow"
+            ,"    assets:bank        100"
+            ,"    liabilities:loan"
+            ,"2025-02-01 repay"
+            ,"    assets:bank       -100"
+            ,"    liabilities:loan"])
+  runTests "hledger-web financial statements with -E" [("empty","")] zj $ do
+
+    yit "shows the zero balances on a bare url, despite startup -E" $ do
+      get BalancesheetR
+      statusIs 200
+      bodyContains "assets:bank"
+      bodyNotContains "which are hidden"
+
+    yit "says when the accounts are all hidden zero balances" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalancesheetR
+        addGetParam "empty" "0"
+        -- one column: monthly, January's balances are not zero
+        addGetParam "interval" "none"
+      statusIs 200
+      bodyContains "All the accounts this report shows have zero balances, which are hidden."
+      bodyNotContains "account-types"
+
+  -- A commodity directive sets the display precision; the page must apply it,
+  -- as the sidebar beside it and the command line report do.
+  sj <- fmap (either error' id) . runExceptT . journalFinalise biopts "styled.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["commodity $1000.00"
+            ,"2025-01-05 rounding"
+            ,"    (assets:bank:checking)   $1.005"])
+  runTests "hledger-web balance page amount styles" [] sj $ do
+
+    yit "renders amounts in the journal's commodity style" $ do
+      get BalanceR
+      statusIs 200
+      bodyContains "$1.00"
+      bodyNotContains "$1.005"
+
+  -- Two accounts that net to zero, two that do not. -E means the opposite
+  -- here than on the command line: hide the zero ones.
+  ej <- fmap (either error' id) . runExceptT . journalFinalise biopts "empty.journal" "" =<<
+          readJournal'' (T.pack $ unlines  -- PARTIAL: readJournal'' should not fail
+            ["2025-01-01 out"
+            ,"    assets:zeroed    100"
+            ,"    income:zeroed   -100"
+            ,"2025-01-02 back"
+            ,"    assets:zeroed   -100"
+            ,"    income:zeroed    100"
+            ,"2025-01-03 kept"
+            ,"    assets:kept       50"
+            ,"    income:kept      -50"])
+  runTests "hledger-web balance page zero items" [] ej $ do
+
+    yit "shows zero items by default, as the sidebar does" $ do
+      withSidebarBalances
+      getWhole BalanceR []
+      statusIs 200
+      bodyContains "href=\"register?account=assets:zeroed&amp;interval=none&amp;depth=all\""
+      -- a zero sidebar amount has an empty register, and no link
+      bodyNotContains "account=assets%3Azeroed&amp;depth=all\" title=\"Show the transactions behind this balance\""
+      bodyContains "account=assets%3Akept&amp;depth=all\" title=\"Show the transactions behind this balance\""
+      -- and says so in the row of links; hiding them is the empty parameter
+      bodyContains ("class=\"current\" href=\"" ++ defbaseurl defhost defport ++ "/balance?interval=none&amp;depth=all\" title=\"Show accounts whose balances are zero\"")
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?interval=none&amp;depth=all&amp;empty=0\" title=\"Hide accounts whose balances are zero\"")
+
+    yit "hides them everywhere with empty=0, which links and the search form keep" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "empty" "0"
+        addGetParam "interval" "none"
+        addGetParam "depth" "all"
+      statusIs 200
+      -- the figures' registers keep the state too
+      bodyContains "href=\"register?account=assets:kept&amp;interval=none&amp;empty=0&amp;depth=all\""
+      bodyNotContains "account=assets:zeroed"
+      bodyContains "<input type=\"hidden\" name=\"empty\" value=\"0\">"
+      bodyContains "empty=0\" title=\"Show assets, liabilities, and net worth\""
+
+  runTests "hledger-web with -E" [("empty","")] ej $ do
+
+    yit "shows zero items on a bare url, despite startup -E, and empty=0 hides them" $ do
+      getWhole BalanceR []
+      statusIs 200
+      bodyContains "href=\"register?account=assets:zeroed&amp;interval=none&amp;depth=all\""
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?interval=none&amp;depth=all&amp;empty=0\" title=\"Hide accounts whose balances are zero\"")
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "empty" "0"
+        addGetParam "interval" "none"
+        addGetParam "depth" "all"
+      statusIs 200
+      bodyContains "href=\"register?account=assets:kept&amp;interval=none&amp;empty=0&amp;depth=all\""
+      bodyNotContains "account=assets:zeroed"
+      bodyContains ("href=\"" ++ defbaseurl defhost defport ++ "/balance?interval=none&amp;depth=all\" title=\"Show accounts whose balances are zero\"")
+
+  -- Startup report options are url state only: the server itself keeps
+  -- stock defaults (#2771).
+  runTests "hledger-web with --yearly" [("yearly","")] bj $ do
+
+    yit "serves the stock view on a bare url, despite startup options" $ do
+      -- the automatic interval, monthly here, not yearly
+      get BalanceR
+      statusIs 200
+      bodyContains ">2025-01</a>"
+      bodyNotContains ">2025</a>"
+
+    yit "takes the startup interval from the url instead" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "interval" "yearly"
+      statusIs 200
+      bodyContains ">2025</a>"
+      bodyNotContains ">2025-01</a>"
+
+    yit "shows a single-period report from a column heading's link" $ do
+      -- a heading link's target: the column's span as a date: search, with its interval
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2025"
+        addGetParam "interval" "yearly"
+      statusIs 200
+      bodyContains "Balance changes in 2025"
+      bodyContains ">2025</a>"
+      bodyNotContains ">2025-01</a>"
+
+  -- #2127
+  -- XXX I'm pretty sure this test lies, ie does not match production behaviour.
+  -- (test with curl -s http://localhost:5000/journal | rg '(href)="[\w/].*?"' -o )
+  -- App root setup is a maze of twisty passages, all alike.
+  -- runTests "hledger-web with --base-url"
+  --   [("base-url","https://base")] nulljournal $ do
+  --   yit "hyperlinks respect --base-url" $ do
+  --     get JournalR
+  --     statusIs 200
+  --     bodyContains "href=\"https://base"
+  --     bodyContains "src=\"https://base"
+
+  -- #2139
+  -- XXX Not passing.
+  -- Static root setup is a maze of twisty passages, all different.
+  -- runTests "hledger-web with --base-url, --file-url"
+  --   [("base-url","https://base"), ("file-url","https://files")] nulljournal $ do
+  --   yit "static file hyperlinks respect --file-url, others respect --base-url" $ do
+  --     get JournalR
+  --     statusIs 200
+  --     bodyContains "href=\"https://base"
+  --     bodyContains "src=\"https://files"
+
+  -- Tests for the write side: yesod's CSRF protection, and the restriction of
+  -- file access to the journal's own files. These use a journal in a temp file,
+  -- so that if one of these protections ever fails, the test writes there
+  -- rather than to the journal the developer happens to have configured.
+  tmpdir <- getTemporaryDirectory
+  let
+    jfile = tmpdir </> "hledger-web-test.journal"
+    jtext = T.pack $ unlines
+      ["2025-01-01 gift"
+      ,"    assets:bank:checking      10"
+      ,"    income:gifts"
+      ]
+    -- A path is only editable if it is one of the journal's own files, so
+    -- these must all be refused however they are spelled.
+    otherfiles =
+      ["/etc/passwd"
+      ,"../../../../etc/passwd"
+      ,"....//....//etc/passwd"
+      ,jfile ++ "/../../etc/passwd"
+      ]
+  TIO.writeFile jfile jtext
+  let wiopts = rawOptsToInputOpts d usecolor $ mkRawOpts [("file", jfile)]
+  wpj <- readJournal'' jtext
+  wj <- fmap (either error' id) . runExceptT $ journalFinalise wiopts jfile jtext wpj
+  runTests "hledger-web write requests" [("file", jfile), ("allow", "edit")] wj $ do
+
+    yit "puts a CSRF token in the add form" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "name=\"_token\""
+
+    -- These three post the same valid, balanced transaction, and differ only
+    -- in the CSRF token, so that the two failures can only be about the token.
+    -- The form is wrapped in identifyForm, so _formid must be sent too, or the
+    -- post is ignored as FormMissing and these would pass either way.
+    -- Both postings send an explicit amount: the form pairs the account and
+    -- amount params by position, and yesod-test before 1.7.0 sends repeated
+    -- params in reverse order, which would leave an account without its amount.
+    let postTransaction desc = do
+          setMethod "POST"
+          setUrl AddR
+          addPostParam "_formid" "identify-add"
+          addPostParam "date" "2025-02-02"
+          addPostParam "description" desc
+          addPostParam "account" "assets:bank:checking"
+          addPostParam "amount" "1"
+          addPostParam "account" "income:gifts"
+          addPostParam "amount" "-1"
+
+    yit "does not add a transaction when the CSRF token is missing" $ do
+      request $ postTransaction "CsrfNoToken"
+      bodyNotContains "Transaction added"
+      journalFileLacks jfile "CsrfNoToken"
+
+    yit "does not add a transaction when the CSRF token is wrong" $ do
+      request $ do
+        postTransaction "CsrfBadToken"
+        addPostParam "_token" "not-the-token"
+      bodyNotContains "Transaction added"
+      journalFileLacks jfile "CsrfBadToken"
+
+    -- The control for the two tests above: the same request, with a real
+    -- token, is accepted. Without this they could pass for the wrong reason.
+    yit "adds a transaction when the CSRF token is present" $ do
+      get JournalR
+      statusIs 200
+      request $ do
+        postTransaction "CsrfGoodToken"
+        addToken  -- from the page just fetched
+      statusIs 303  -- a successful add redirects to the journal
+      _ <- followRedirect
+      bodyContains "Transaction added"
+      txt <- liftIO $ TIO.readFile jfile
+      assertEq "journal should contain the added transaction"
+        (T.isInfixOf "CsrfGoodToken" txt) True
+
+    -- A newline in a field which is written verbatim (description, code,
+    -- account name) would split the entry across lines in the journal file,
+    -- injecting whatever follows as a directive - eg an include, which would
+    -- make hledger read another file. Newlines must be collapsed on the way
+    -- in, by both the add form and the JSON API.
+
+    yit "does not let the add form write a newline into the journal" $ do
+      get JournalR
+      statusIs 200
+      request $ do
+        postTransaction "AddFormNewline\ninclude /etc/passwd"
+        addToken  -- from the page just fetched
+      journalFileLacks jfile "\ninclude /etc/passwd"
+      txt <- liftIO $ TIO.readFile jfile
+      assertEq "the description should be written on one line"
+        (T.isInfixOf "AddFormNewline include /etc/passwd" txt) True
+
+    -- The JSON API does not go through the form, so it needs the same
+    -- treatment - and it has no CSRF token to stop a direct client.
+    yit "does not let the JSON API write a newline into the journal" $ do
+      let t = nulltransaction
+            { tdate = fromGregorian 2025 4 4
+            , tdescription = "JsonNewline\ninclude /etc/passwd"
+            , tpostings =
+              [ nullposting{paccount = "assets:bank:checking", pamount = mixedAmount (num 1)}
+              , nullposting{paccount = "income:gifts",         pamount = mixedAmount (num (-1))}
+              ]
+            }
+      request $ do
+        setMethod "PUT"
+        setUrl AddR
+        addRequestHeader ("Content-Type", "application/json")
+        setRequestBody $ encode t
+      journalFileLacks jfile "\ninclude /etc/passwd"
+      txt <- liftIO $ TIO.readFile jfile
+      assertEq "the description should be written on one line"
+        (T.isInfixOf "JsonNewline include /etc/passwd" txt) True
+
+    -- An entry the journal could not be read back with must be refused,
+    -- not written (#2864). (The test above is its accepted control.)
+    yit "rejects an unbalanced transaction sent to the JSON API, leaving the journal unchanged" $ do
+      let t = nulltransaction
+            { tdate = fromGregorian 2025 4 5
+            , tdescription = "JsonUnbalanced"
+            , tpostings =
+              [ nullposting{paccount = "assets:bank:checking", pamount = mixedAmount (num 2)}
+              , nullposting{paccount = "income:gifts",         pamount = mixedAmount (num (-1))}
+              ]
+            }
+      request $ do
+        setMethod "PUT"
+        setUrl AddR
+        addRequestHeader ("Content-Type", "application/json")
+        setRequestBody $ encode t
+      statusIs 400
+      bodyContains "unbalanced"
+      journalFileLacks jfile "JsonUnbalanced"
+
+    -- Likewise for the edit form: the same save, with and without the token.
+    let editJournal fld desc = do
+          setMethod "POST"
+          setUrl (EditR jfile)
+          addPostParam "_formid" "identify-edit"
+          addPostParam fld $
+            "2025-03-03 " <> desc <> "\n    assets:bank:checking  1\n    income:gifts\n"
+
+    yit "does not save the journal when the CSRF token is missing" $ do
+      get (EditR jfile)
+      statusIs 200
+      fld <- editFieldName
+      request $ editJournal fld "CsrfEdit"
+      bodyNotContains "Saved journal"
+      journalFileLacks jfile "CsrfEdit"
+
+    yit "saves the journal when the CSRF token is present" $ do
+      get (EditR jfile)
+      statusIs 200
+      fld <- editFieldName
+      request $ do
+        editJournal fld "CsrfEditOk"
+        addToken  -- from the page just fetched
+      txt <- liftIO $ TIO.readFile jfile
+      assertEq "journal should contain the saved text"
+        (T.isInfixOf "CsrfEditOk" txt) True
+
+    yit "serves its own journal file for editing" $ do
+      get (EditR jfile)
+      statusIs 200
+
+    forM_ otherfiles $ \otherfile -> do
+      yit ("refuses to edit " ++ otherfile) $ do
+        get (EditR otherfile)
+        statusIs 404
+      yit ("refuses to download " ++ otherfile) $ do
+        get (DownloadR otherfile)
+        statusIs 404
+
+  -- Checked writes (#2869): adds, edits and uploads are refused exactly when
+  -- the next read of the journal, with the server's options, would fail.
+  -- Each suite uses a journal in its own temp file, which its writes change.
+  let
+    -- Run some tests with a journal read from a new temp file, with the
+    -- file and these raw options (and the add and edit permissions).
+    -- The tests are given the file's path.
+    runTestsWithJournalFile desc name jtxt extraopts tests = do
+      let jf = tmpdir </> name
+          ropts = ("file", jf) : ("allow", "edit") : extraopts
+      TIO.writeFile jf jtxt
+      checksj <- fmap (either error' id) . runExceptT $  -- PARTIAL: the test journal should read
+              readJournalFiles (rawOptsToInputOpts d usecolor $ mkRawOpts ropts) [jf]
+      runTests desc ropts checksj (tests jf)
+    -- Send the transaction in this journal text to the JSON API's add route.
+    putTransactionText txt = do
+      ts <- liftIO $ jtxns <$> readJournal'' txt
+      case ts of
+        [t] -> request $ do
+          setMethod "PUT"
+          setUrl AddR
+          addRequestHeader ("Content-Type", "application/json")
+          setRequestBody $ encode t
+        _ -> failing "putTransactionText: expected one transaction"
+    -- Post this text from the edit form, with the CSRF token from the form page.
+    editJournalText cf txt = do
+      get (EditR cf)
+      statusIs 200
+      fld <- editFieldName
+      request $ do
+        setMethod "POST"
+        setUrl (EditR cf)
+        addPostParam "_formid" "identify-edit"
+        addPostParam fld txt
+        addToken
+    journalFileHas cf t = do
+      txt <- liftIO $ TIO.readFile cf
+      assertEq (cf ++ " should contain " ++ T.unpack t) (T.isInfixOf t txt) True
+
+  let lotsjtext = T.unlines
+        ["commodity AAPL  ; lots:"
+        ,"commodity $"
+        ,""
+        ,"2026-01-01 buy"
+        ,"    assets:broker:aapl     10 AAPL @ $100"
+        ,"    assets:cash"
+        ,""
+        ,"2026-06-01 check"
+        ,"    assets:cash             $0 = $-1000"
+        ]
+  runTestsWithJournalFile "hledger-web checked writes" "hledger-web-test-checks.journal" lotsjtext [] $ \cf -> do
+
+    yit "PUT /add refuses a sale of more lots than are held, leaving the journal unchanged" $ do
+      putTransactionText $ T.unlines
+        ["2026-07-01 OverSale"  -- after the assertion, so that only the lots are wrong
+        ,"    assets:broker:aapl    -20 AAPL @ $130"
+        ,"    assets:cash          $2600"
+        ,"    revenue:gains"
+        ]
+      statusIs 400
+      bodyContains "Insufficient lots"
+      journalFileLacks cf "OverSale"
+
+    yit "the add form refuses a transaction which breaks a later balance assertion" $ do
+      get JournalR
+      statusIs 200
+      request $ do
+        setMethod "POST"
+        setUrl AddR
+        addPostParam "_formid" "identify-add"
+        addPostParam "date" "2026-02-01"
+        addPostParam "description" "BreaksAssertion"
+        addPostParam "account" "expenses:food"
+        addPostParam "amount" "$5"
+        addPostParam "account" "assets:cash"
+        addPostParam "amount" "$-5"
+        addToken
+      bodyNotContains "Transaction added"
+      bodyContains "Balance assertion failed"
+      journalFileLacks cf "BreaksAssertion"
+
+    yit "PUT /add accepts a valid transaction, which the next request shows" $ do
+      putTransactionText $ T.unlines
+        ["2026-07-02 ValidAdd"
+        ,"    expenses:food           $1"
+        ,"    assets:cash"
+        ]
+      statusIs 201
+      journalFileHas cf "ValidAdd"
+      get TransactionsR
+      statusIs 200
+      bodyContains "ValidAdd"
+
+  let strictjtext = T.unlines
+        ["account assets:cash"
+        ,"account income:gifts"
+        ,"commodity $"
+        ,""
+        ,"2026-01-01 gift"
+        ,"    assets:cash             $10"
+        ,"    income:gifts"
+        ]
+  runTestsWithJournalFile "hledger-web checked writes with --strict" "hledger-web-test-strict.journal" strictjtext [("strict", "")] $ \cf -> do
+
+    yit "PUT /add refuses an undeclared account" $ do
+      putTransactionText $ T.unlines
+        ["2026-01-02 UndeclaredAdd"
+        ,"    assets:cash             $1"
+        ,"    income:typo"
+        ]
+      statusIs 400
+      bodyContains "has not been declared"
+      journalFileLacks cf "UndeclaredAdd"
+
+    yit "edit refuses text using an undeclared account" $ do
+      editJournalText cf $ strictjtext <> T.unlines
+        [""
+        ,"2026-01-03 UndeclaredEdit"
+        ,"    assets:cash             $1"
+        ,"    income:typo"
+        ]
+      bodyNotContains "Saved journal"
+      bodyContains "has not been declared"
+      journalFileLacks cf "UndeclaredEdit"
+
+  let failingassertionjtext = T.unlines
+        ["2026-01-01 gift"
+        ,"    assets:cash             10 = 999"
+        ,"    income:gifts"
+        ]
+  runTestsWithJournalFile "hledger-web checked writes with -I" "hledger-web-test-ignore-assertions.journal" failingassertionjtext [("ignore-assertions", "")] $ \cf -> do
+
+    yit "PUT /add accepts a transaction although a balance assertion fails" $ do
+      putTransactionText $ T.unlines
+        ["2026-01-02 IgnoredAssertionAdd"
+        ,"    assets:cash             1"
+        ,"    income:gifts"
+        ]
+      statusIs 201
+      journalFileHas cf "IgnoredAssertionAdd"
+
+    yit "edit saves text although a balance assertion fails" $ do
+      editJournalText cf $ failingassertionjtext <> T.unlines
+        [""
+        ,"2026-01-03 IgnoredAssertionEdit"
+        ,"    assets:cash             1"
+        ,"    income:gifts"
+        ]
+      statusIs 303
+      journalFileHas cf "IgnoredAssertionEdit"
+
+  -- Paging (#586): the journal and register pages show the newest pageSize
+  -- transactions and link to the older pages, so that a page stays small
+  -- however large the journal is; and a row of years links to each year the
+  -- search matches. 2300 transactions, one a day from 2023-01-01, each
+  -- moving 1 into assets:cash from income, or from expenses:food for every
+  -- third one, so a page holds 1000 rows and the cash register's running
+  -- balance after the n-th transaction is n.
+  let pagingtxns = 2300 :: Int
+      pagingentry i = unlines
+        [ show (addDays (fromIntegral i - 1) (fromGregorian 2023 1 1)) ++ " txn " ++ show i
+        , "    assets:cash    1"
+        , if i `mod` 3 == 0 then "    expenses:food" else "    income"
+        ]
+  pagingj <- fmap (either error' id) . runExceptT . journalFinalise biopts "paging.journal" "" =<<
+          readJournal'' (T.pack $ concatMap pagingentry [1..pagingtxns])  -- PARTIAL: readJournal'' should not fail
+  runTests "hledger-web paging" [] pagingj $ do
+
+    yit "shows the newest page of the journal, with a link to the older ones" $ do
+      get JournalR
+      statusIs 200
+      bodyContains "Showing 1 to 1,000 of 2,300 transactions"
+      bodyContains "txn 2300</td>"
+      bodyContains "txn 1301</td>"
+      bodyNotContains "txn 1300</td>"
+      bodyContains "/journal?depth=1&amp;page=2\" title=\"Show the older transactions\">Older"
+      bodyNotContains "Show the newer transactions"
+      -- the newer link's place is held, so the numbers do not shift on page 2
+      bodyContains "<span class=\"newer placeholder\" aria-hidden=\"true\">‹ Newer</span>"
+      -- the pages by number, the current one marked and not a link
+      bodyContains "<span class=\"current\" aria-current=\"page\">1</span>"
+      bodyContains "/journal?depth=1&amp;page=2\" title=\"Show page 2\" aria-label=\"Page 2\">2</a>"
+      bodyContains "/journal?depth=1&amp;page=3\" title=\"Show page 3\" aria-label=\"Page 3\">3</a>"
+      bodyNotContains "Show page 1\""
+
+    yit "shows the requested page, linking both ways" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "page" "2"
+      statusIs 200
+      bodyContains "Showing 1,001 to 2,000 of 2,300 transactions"
+      bodyContains "txn 1300</td>"
+      bodyContains "txn 301</td>"
+      bodyNotContains "txn 1301</td>"
+      bodyNotContains "txn 300</td>"
+      bodyContains "/journal?depth=1\" title=\"Show the newer transactions\">‹ Newer"
+      bodyContains "/journal?depth=1&amp;page=3\" title=\"Show the older transactions\">Older"
+      bodyContains "/journal?depth=1\" title=\"Show page 1\" aria-label=\"Page 1\">1</a>"
+      bodyContains "<span class=\"current\" aria-current=\"page\">2</span>"
+      bodyContains "/journal?depth=1&amp;page=3\" title=\"Show page 3\" aria-label=\"Page 3\">3</a>"
+
+    yit "brings a page number past the end back to the last page" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "page" "99"
+      statusIs 200
+      bodyContains "Showing 2,001 to 2,300 of 2,300 transactions"
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "page" "18446744073709551617"  -- past an Int, too
+      statusIs 200
+      bodyContains "Showing 2,001 to 2,300 of 2,300 transactions"
+      bodyContains "txn 1</td>"
+      bodyContains "/journal?depth=1&amp;page=2\" title=\"Show the newer transactions\">‹ Newer"
+      bodyNotContains "Show the older transactions"
+      bodyContains "<span class=\"older placeholder\" aria-hidden=\"true\">Older ›</span>"
+
+    yit "treats a page number that is not a positive integer as the first page" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "page" "x"
+      statusIs 200
+      bodyContains "Showing 1 to 1,000 of 2,300 transactions"
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "page" "0"
+      statusIs 200
+      bodyContains "Showing 1 to 1,000 of 2,300 transactions"
+
+    yit "pages only when there are more than pageSize transactions" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:..2025-09-27"  -- txn 1000 is on 2025-09-26
+      statusIs 200
+      bodyNotContains "Showing "
+      bodyContains "txn 1000</td>"
+      bodyContains "txn 1</td>"
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:..2025-09-28"
+      statusIs 200
+      bodyContains "Showing 1 to 1,000 of 1,001 transactions"
+      bodyNotContains "txn 1</td>"
+
+    yit "opens the page holding a linked transaction" $ do
+      -- A posting's account link names its transaction, so the register it
+      -- opens can show the page holding it and the browser can scroll to it. The transactions' indices depend on
+      -- how the journal was read, so take them from the pages.
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "page" "2"
+      statusIs 200
+      jid <- attrOfFirst "tr.title" "id"  -- transaction-F-N
+      let jtxn = T.takeWhileEnd (/= '-') jid
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "txn" jtxn
+      statusIs 200
+      bodyContains "Showing 1,001 to 2,000 of 2,300 transactions"
+      bodyContains ("id=\"" ++ T.unpack jid ++ "\"")
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "page" "3"
+      statusIs 200
+      rid <- attrOfFirst "#main-content tbody tr" "id"  -- transaction-F-N, as in the journal
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "txn" (T.takeWhileEnd (/= '-') rid)
+      statusIs 200
+      bodyContains "Showing 2,001 to 2,300 of 2,300 transactions"
+      bodyContains ("<tr id=\"" ++ T.unpack rid ++ "\"")
+      -- a transaction the search does not show gives the first page
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "income"
+        addGetParam "txn" "0"
+      statusIs 200
+      bodyContains "Showing 1 to 1,000 of 1,534 transactions"
+      -- The account links carry the transaction, on the journal and on the
+      -- register. (A register row's date link opens that day's journal
+      -- entries, which fit on one page.)
+      get JournalR
+      statusIs 200
+      jid1 <- attrOfFirst "tr.title" "id"
+      let jtxn1 = T.unpack $ T.takeWhileEnd (/= '-') jid1
+      bodyContains ("/register?account=assets%3Acash&amp;txn=" ++ jtxn1 ++ "&amp;depth=1#" ++ T.unpack jid1 ++ "\"")
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "page" "2"
+      statusIs 200
+      rid2 <- attrOfFirst "#main-content tbody tr" "id"
+      let rtxn2 = T.unpack $ T.takeWhileEnd (/= '-') rid2
+      bodyContains ("&amp;txn=" ++ rtxn2 ++ "&amp;depth=1#" ++ T.unpack rid2 ++ "\"")
+
+    yit "lists the years the search matches, each linking to that year" $ do
+      get JournalR
+      statusIs 200
+      bodyContains ">Years:</span>"
+      bodyContains "Shift-click selects a range of years."
+      bodyContains ("<a class=\"current\" href=\"" ++ base ++ "/journal?depth=1\" aria-current=\"page\" title=\"Show all years\">All</a>")
+      bodyContains "/journal?q=date%3A2023&amp;depth=1\" title=\"Show only 2023\">2023</a>"
+      bodyContains "/journal?q=date%3A2024&amp;depth=1\" title=\"Show only 2024\">2024</a>"
+      bodyContains "/journal?q=date%3A2029&amp;depth=1\" title=\"Show only 2029\">2029</a>"
+
+    yit "keeps every year in the row when the search is narrowed to one" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:2024"
+      statusIs 200
+      bodyNotContains "Showing "  -- 366 transactions fit on one page
+      bodyContains ("<a class=\"current\" href=\"" ++ base ++ "/journal?q=date%3A2024&amp;depth=1\" aria-current=\"page\" title=\"Show only 2024\">2024</a>")
+      bodyContains "/journal?q=date%3A2025&amp;depth=1\" title=\"Show only 2025\""
+      bodyContains ("<a href=\"" ++ base ++ "/journal?depth=1\" title=\"Show all years\">All</a>")
+
+    yit "carries the rest of the search in the year links" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "income date:2024"
+      statusIs 200
+      bodyContains "/journal?q=date%3A2025%20income&amp;depth=1\" title=\"Show only 2025\""
+      bodyContains ("<a class=\"current\" href=\"" ++ base ++ "/journal?q=date%3A2024%20income&amp;depth=1\" aria-current=\"page\" title=\"Show only 2024\"")
+      bodyContains ("<a href=\"" ++ base ++ "/journal?q=income&amp;depth=1\" title=\"Show all years\"")
+
+    yit "counts the years by the same matching as the rows" $ do
+      -- A search term that a posting can fail while its transaction matches:
+      -- the register admits the transaction on the matching posting, and so
+      -- must the years row, whether or not the search has a date term.
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "q" "not:acct:expenses date:2024"
+      statusIs 200
+      rows <- htmlQuery "#main-content tbody tr"
+      assertEq "the rows the years row counts" (length rows) 366
+      bodyNotContains "Showing "
+      bodyContains "title=\"Show only 2024\">2024</a>"
+      bodyContains "title=\"Show all years\">All</a>"
+
+    yit "counts the years by the search the year links make" $ do
+      -- A date term inside an expr: term is not one the year links replace,
+      -- so the years row counts what this search shows: one year, hence no row.
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "expr:\"date:2024 and desc:txn\""
+      statusIs 200
+      bodyContains "txn 731</td>"  -- 2024-01-01
+      bodyNotContains "Years:"
+
+    yit "shows the years row on the report pages too, the year links keeping the interval" $ do
+      request $ do
+        setMethod "GET"
+        setUrl BalanceR
+        addGetParam "q" "date:2024"
+        addGetParam "interval" "monthly"
+      statusIs 200
+      bodyContains ">Years:</span>"
+      bodyContains "/balance?q=date%3A2023&amp;interval=monthly&amp;depth=1\" title=\"Show only 2023\""
+      -- the search's date term marks its year
+      bodyContains "aria-current=\"page\" title=\"Show only 2024\""
+
+    yit "marks each year a range search covers, as a shift-click selects" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date:2023..2026"
+      statusIs 200
+      bodyContains "aria-current=\"page\" title=\"Show only 2023\""
+      bodyContains "aria-current=\"page\" title=\"Show only 2025\""
+      bodyNotContains "aria-current=\"page\" title=\"Show only 2026\""
+
+    -- Urls from before the interval parameter keep working.
+    yit "moves an old period parameter's dates to the search, and its interval to the interval parameter" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "period" "monthly in 2024"
+      statusIs 303
+      loc <- headerValue "Location"
+      assertEq "the page is reloaded without the period parameter" loc
+        (T.pack (defbaseurl defhost defport) <> "/journal?q=%22date%3Ain%202024%22&interval=monthly")
+
+    -- A search narrowing only by secondary date sets the shown span too.
+    yit "a date2: search marks its year" $ do
+      request $ do
+        setMethod "GET"
+        setUrl JournalR
+        addGetParam "q" "date2:2024"
+      statusIs 200
+      bodyContains "aria-current=\"page\" title=\"Show only 2024\""
+      bodyNotContains "aria-current=\"page\" title=\"Show all years\""
+
+    yit "pages the register, with the running balance carried across pages" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+      statusIs 200
+      bodyContains "Showing 1 to 1,000 of 2,300 transactions"
+      bodyContains "amount\">2300</span>"
+      bodyContains "amount\">1301</span>"
+      bodyNotContains "amount\">1300</span>"
+      bodyContains "/register?account=assets%3Acash&amp;depth=1&amp;page=2\" title=\"Show the older transactions\""
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "page" "2"
+      statusIs 200
+      bodyContains "Showing 1,001 to 2,000 of 2,300 transactions"
+      bodyContains "amount\">1300</span>"
+      bodyContains "amount\">301</span>"
+      bodyNotContains "amount\">1301</span>"
+      -- the chart covers every page's rows: its dates are all of theirs, and
+      -- a point on another page links to that page, opened at its row (the
+      -- newest point, last in its column, always has a link)
+      let txn i = fromMaybe (error' $ "no txn " ++ show i) $
+            find ((== T.pack ("txn " ++ show (i :: Int))) . tdescription) (jtxns pagingj)
+          rowfrag i = "#" ++ transactionFragment pagingj (txn i)
+      bodyContains ("data-d0=\"" ++ show (tdate $ txn 1) ++ "\" data-d1=\"" ++ show (tdate $ txn 2300) ++ "\"")
+      bodyContains ("<a href=\"" ++ base ++ "/register?account=assets%3Acash&amp;depth=1&amp;txn=" ++ show (tindex $ txn 2300) ++ rowfrag 2300 ++ "\"")
+      -- on its own page, a point links to its row there
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+      statusIs 200
+      bodyContains ("data-d0=\"" ++ show (tdate $ txn 1) ++ "\" data-d1=\"" ++ show (tdate $ txn 2300) ++ "\"")
+      bodyContains ("<a href=\"" ++ rowfrag 2300 ++ "\"")
+      -- the years row keeps the account
+      bodyContains "/register?q=date%3A2024&amp;account=assets%3Acash&amp;depth=1\" title=\"Show only 2024\">2024</a>"
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "q" "date:2024"
+      statusIs 200
+      bodyNotContains "Showing "
+      bodyContains ("<a class=\"current\" href=\"" ++ base ++ "/register?q=date%3A2024&amp;account=assets%3Acash&amp;depth=1\"")
+
+    yit "keeps the register's mode in its page and year links" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "accum" "historical"
+      statusIs 200
+      bodyContains "/register?account=assets%3Acash&amp;accum=historical&amp;depth=1&amp;page=2\" title=\"Show the older transactions\""
+      bodyContains "/register?q=date%3A2024&amp;account=assets%3Acash&amp;accum=historical&amp;depth=1\" title=\"Show only 2024\">2024</a>"
+
+  -- A startup depth limit does not apply to the register, nor to its years.
+  runTests "hledger-web paging with --depth" [("depth","1")] pagingj $ do
+
+    yit "counts the register's years without the depth limit" $ do
+      request $ do
+        setMethod "GET"
+        setUrl RegisterR
+        addGetParam "account" "assets:cash"
+        addGetParam "q" "date:2024"
+      statusIs 200
+      bodyContains "title=\"Show only 2024\">2024</a>"
+      bodyContains "title=\"Show all years\">All</a>"
+
+  -- More than twenty years are grouped by decade, a row each: 21 years here.
+  let decadesentry y = unlines
+        [ show y ++ "-06-15 txn " ++ show y
+        , "    assets:cash    1"
+        , "    income"
+        ]
+  decadesj <- fmap (either error' id) . runExceptT . journalFinalise biopts "decades.journal" "" =<<
+          readJournal'' (T.pack $ concatMap decadesentry [2005..2025 :: Int])  -- PARTIAL: readJournal'' should not fail
+  runTests "hledger-web years row" [] decadesj $ do
+
+    yit "groups more than twenty years by decade" $ do
+      get JournalR
+      statusIs 200
+      bodyContains ">All</a>"
+      rows <- map (TL.toStrict . TLE.decodeUtf8) <$> htmlQuery "p.years"
+      assertEq "the All row, then one row per decade" (length rows) 4
+      let row2010s = rows !! 2
+      assertEq "the 2010s row is labelled" (T.isInfixOf "<span class=\"row-label\">2010s:</span>" row2010s) True
+      assertEq "2010 opens the 2010s row" (T.isInfixOf "date%3A2010&amp;depth=1\"" row2010s) True
+      assertEq "2019 ends the 2010s row" (T.isInfixOf "date%3A2019&amp;depth=1\"" row2010s) True
+      assertEq "2009 is not in the 2010s row" (T.isInfixOf "date%3A2009&amp;depth=1\"" row2010s) False
+      assertEq "2020 is not in the 2010s row" (T.isInfixOf "date%3A2020\"" row2010s) False
diff --git a/Hledger/Web/WebOptions.hs b/Hledger/Web/WebOptions.hs
--- a/Hledger/Web/WebOptions.hs
+++ b/Hledger/Web/WebOptions.hs
@@ -1,6 +1,5 @@
 {-# LANGUAGE CPP #-}
 {-# LANGUAGE OverloadedStrings #-}
-{-# LANGUAGE TemplateHaskell #-}
 {-# LANGUAGE RecordWildCards #-}
 {-# LANGUAGE LambdaCase #-}
 
@@ -10,19 +9,22 @@
 import Data.ByteString.Char8 qualified as BC
 import Data.ByteString.UTF8 (fromString)
 import Data.Default (Default(def))
+import Data.Map qualified as M
 import Data.Maybe (fromMaybe)
 import Data.Text (Text)
-import GitHash (tGitInfoCwdTry)
 import System.Environment (getArgs)
 import Network.Wai as WAI
 import Network.Wai.Middleware.Cors
 import Safe (lastMay)
 
 import Hledger.Cli hiding (packageversion, progname, prognameandversion)
+import Hledger.Cli.Chart (ChartArg(..), chartArg, parseChartArg)
+import Hledger.Cli.GitInfo (gitInfo)
+import Hledger.Web.ReportPage (startupUrlState)
 import Hledger.Web.Settings (defhost, defport, defbaseurl)
 import Data.Text qualified as T
 import Data.Char (toLower)
-import Data.List (isPrefixOf)
+import Data.List (intercalate, isPrefixOf)
 import Data.Either (fromRight)
 
 -- cf Hledger.Cli.Version
@@ -40,11 +42,10 @@
 progname = "hledger-web"
 
 -- | Generate the version string for this program.
--- The template haskell call is here rather than in Hledger.Cli.Version to avoid wasteful recompilation.
 prognameandversion :: String
 prognameandversion =
   versionStringWith
-  $$tGitInfoCwdTry
+  gitInfo
 #ifdef GHCDEBUG
   True
 #else
@@ -61,7 +62,7 @@
   [ flagNone
       ["serve-browse"]
       (setboolopt "serve-browse")
-      (serveprefix ++ "serve the web UI and JSON API, and open a browser, and exit if inactive for 2m (default)")
+      (serveprefix ++ "serve the web UI and JSON API, and open a browser, and exit if inactive for 15m (default)")
   , flagNone
       ["serve"]
       (setboolopt "serve")
@@ -74,7 +75,8 @@
       ["allow"]
       (\s opts -> Right $ setopt "allow" s opts)
       "view|add|edit"
-      "set the user's access level for changing data (default: `add`). It also accepts `sandstorm` for use on that platform (reads permissions from the `X-Sandstorm-Permissions` request header)."
+      ("set the user's access level for changing data (default: `add` on a local-only address, `view` otherwise)." ++
+      " It also accepts `sandstorm` for that platform (reading from the `X-Sandstorm-Permissions` request header).")
   , flagReq
       ["cors"]
       (\s opts -> Right $ setopt "cors" s opts)
@@ -89,7 +91,7 @@
       ["port"]
       (\s opts -> Right $ setopt "port" s opts)
       "PORT"
-      ("listen on this TCP port (default: " ++ show defport ++ ")")
+      ("listen on this TCP port (default: " ++ show defport ++ "); 0 means a free port chosen by the OS")
   , flagReq
       ["socket"]
       (\s opts -> Right $ setopt "socket" s opts)
@@ -100,16 +102,27 @@
       (\s opts -> Right $ setopt "base-url" s opts)
       "BASEURL"
       "set the base url (default: http://IPADDR:PORT)"
+  , flagOpt "auto"
+      ["chart"]
+      (\s opts -> setopt "chart" s opts <$ parseChartArg M.empty s)
+      "KIND,net,SCALE"
+      ("set the charts' defaults, as the commands' --chart does. "
+        ++ "KIND: lay out the statements' charts with each period's sections in one bar, above and below zero (diverging, the default), or side by side (grouped). "
+        ++ "net: show the net total lines by default (the N key toggles them, and the browser remembers that). "
+        ++ "SCALE: the amount that fills the charts (eg 1000 or 1000 USD; one per commodity), for comparable charts.")
+  , flagReq
+      ["lang"]
+      (\s opts -> Right $ setopt "lang" s opts)
+      "LANG"
+      ("show the web UI in this language (" ++ intercalate ", " (map T.unpack builtinLanguageCodes) ++ ");"
+      ++ " or with auto, use each viewer's browser language if available, otherwise the server's."
+      ++ " (Default: the browser's language if available, otherwise en.)")
   -- XXX #2139
   -- , flagReq
   --     ["file-url"]
   --     (\s opts -> Right $ setopt "file-url" s opts)
   --     "FILEURL"
   --     "set a different base url for static files (default: `BASEURL/static/`)"
-  , flagNone
-      ["test"]
-      (setboolopt "test")
-      "run hledger-web's tests and exit. hspec test runner args may follow a --, eg: hledger-web --test -- --help"
   ]
   where
     serveprefix = "server mode: "
@@ -128,7 +141,8 @@
       , groupHidden = hiddenflags
           ++
           [flagNone ["server"] (setboolopt "serve") "old flag, use --serve instead"]
-      , groupNamed = mkgeneralflagsgroups1 helpflags
+      -- hledger-web's --lang (in webflags) works differently from the other tools'
+      , groupNamed = mkgeneralflagsgroups1 $ filter ((`notElem` [["lang"], ["write-lang"]]) . flagNames) helpflags
       }
   , modeHelpSuffix = []
   }
@@ -146,6 +160,11 @@
   , allow_              :: !AccessLevel
   , cliopts_            :: !CliOpts
   , socket_             :: !(Maybe String)
+  , startup_params_     :: ![(Text, Text)]
+      -- ^ the startup report options and query arguments as url
+      --   parameters, for the url browse mode opens and --serve prints.
+      --   The server itself keeps stock report options (see
+      --   'startupUrlState').
   } deriving (Show)
 
 defwebopts :: WebOpts
@@ -156,9 +175,10 @@
   , port_               = def
   , base_url_           = ""
   , file_url_           = Nothing
-  , allow_              = AddAccess
+  , allow_              = ViewAccess
   , cliopts_            = def
   , socket_             = Nothing
+  , startup_params_     = []
   }
 
 instance Default WebOpts where def = defwebopts
@@ -168,6 +188,11 @@
   checkWebOpts <$> do
     cliopts <- rawOptsToCliOpts rawopts
     let
+      -- Startup report options and query arguments become url state
+      -- (the url browse mode opens, --serve prints); the server itself
+      -- runs with stock report options, so that a url fully describes
+      -- its view and a bare url shows the stock view.
+      (startupparams, stockrspec) = startupUrlState $ reportspec_ cliopts
       h = fromMaybe defhost $ maybestringopt "host" rawopts
       p = fromMaybe defport $ maybeposintopt "port" rawopts
       -- Always set a base-url, constructing it from host and port if not specified.
@@ -176,9 +201,14 @@
       -- otherwise it will infer a better one from the request, which browsers prefer.
       b = maybe (defbaseurl h p) stripTrailingSlash $ maybestringopt "base-url" rawopts
       sock = stripTrailingSlash <$> maybestringopt "socket" rawopts
+      -- Is this a local-only listen address (loopback or unix socket) ?
+      -- If so, we'll allow add access by default.
+      isLocalOnly = case sock of
+        Just _  -> True
+        Nothing -> h `elem` ["127.0.0.1", "::1", "localhost"]
       access =
         case lastMay $ listofstringopt "allow" rawopts of
-          Nothing -> AddAccess
+          Nothing -> if isLocalOnly then AddAccess else ViewAccess
           Just t ->
             case parseAccessLevel t of
               Right al -> al
@@ -192,8 +222,9 @@
       , base_url_ = b
       , file_url_ = stripTrailingSlash <$> maybestringopt "file-url" rawopts
       , allow_ = access
-      , cliopts_ = cliopts
+      , cliopts_ = cliopts{reportspec_ = stockrspec}
       , socket_ = sock
+      , startup_params_ = startupparams ++ [("chart", "grouped") | caKind (chartArg M.empty cliopts) == "grouped"]
       }
   where
     stripTrailingSlash = reverse . dropWhile (== '/') . reverse -- yesod don't like it
diff --git a/Hledger/Web/Widget/AddForm.hs b/Hledger/Web/Widget/AddForm.hs
--- a/Hledger/Web/Widget/AddForm.hs
+++ b/Hledger/Web/Widget/AddForm.hs
@@ -1,4 +1,3 @@
-{-# LANGUAGE CPP #-}
 {-# LANGUAGE FlexibleContexts #-}
 {-# LANGUAGE GADTs #-}
 {-# LANGUAGE OverloadedStrings #-}
@@ -12,24 +11,21 @@
   ) where
 
 import Control.Monad.State.Strict (evalStateT)
-#if MIN_VERSION_base64(1,0,0)
-import Data.Base64.Types (extractBase64)
-#endif
 import Data.Bifunctor (first)
 import Data.Foldable (toList)
 import Data.List (dropWhileEnd, unfoldr)
 import Data.Maybe (isJust, fromMaybe)
 import Data.Set qualified as S
 import Data.Text (Text)
-import Data.Text.Encoding.Base64 (encodeBase64)
 import Data.Text qualified as T
 import Data.Time (Day)
-import Text.Blaze.Internal (Markup, preEscapedText)
+import Text.Blaze.Internal (Markup)
 import Text.Megaparsec (bundleErrors, eof, parseErrorTextPretty, runParser)
 import Yesod
 
+import Hledger.Utils.I18n (Translations, substitutePlaceholders, tr, trc, trf)
 import Hledger
-import Hledger.Web.App (App, Handler, Widget)
+import Hledger.Web.App (App, Handler, Widget, HMsg(..), requestTranslations)
 import Hledger.Web.Settings (widgetFile)
 import Data.Function ((&))
 import Control.Arrow (right)
@@ -38,39 +34,43 @@
 addModal addR j today = do
   (addView, addEnctype) <- handlerToWidget $ generateFormPost (addForm j today)
   [whamlet|
-<div .modal #addmodal tabindex="-1" role="dialog" aria-labelledby="addLabel" aria-hidden="true">
-  <div .modal-dialog .modal-lg>
-    <div .modal-content>
-      <div .modal-header>
-        <button type="button" .close data-dismiss="modal" aria-hidden="true">&times;
-        <h3 .modal-title #addLabel>Add a transaction
-      <div .modal-body>
-        <form#addform.form action=@{addR} method=POST enctype=#{addEnctype}>
-          ^{addView}
+<dialog #addmodal aria-labelledby="addLabel">
+  <div .modal-header>
+    <button type="button" .close data-dismiss="modal" aria-label=_{HMsg "Close"}>&times;
+    <h3 .modal-title #addLabel>_{HMsg "Add a transaction"}
+  <div .modal-body>
+    <form#addform.form action=@{addR} method=POST enctype=#{addEnctype}>
+      ^{addView}
 |]
 
 addForm :: Journal -> Day -> Markup -> MForm Handler (FormResult (Transaction,FilePath), Widget)
 addForm j today = identifyForm "add" $ \extra -> do
+  trs <- lift requestTranslations
   let  -- bindings used in add-form.hamlet
     descriptions = foldMap S.fromList [journalPayeesDeclaredOrUsed j, journalDescriptions j]
-    files = fst <$> jfiles j
+    files = journalFilePaths j
     deffile = journalFilePath j
+    accountPlaceholder = tr trs "Account {n}"
+    amountPlaceholder = tr trs "Amount {n}"
+    numbered template n = substitutePlaceholders [("n", T.pack (show n))] template
+    -- custom fields
+    dateField = textField & checkMMap (pure . right fromEFDay . validateDate) (T.pack . show)
+      where
+        validateDate s =
+          first (const (tr trs "Invalid date format")) $
+          fixSmartDateStrEither' today (T.strip s)
+    dateSettings = FieldSettings "date" Nothing Nothing (Just "date") [("class", "form-control input-lg"), ("placeholder", trc trs "placeholder" "Date")]
+    descSettings = FieldSettings "desc" Nothing Nothing (Just "description") [("class", "form-control input-lg"), ("placeholder", trc trs "placeholder" "Description"), ("size", "40"), ("list", "descriptionnames")]
   (dateRes, dateView) <- mreq dateField dateSettings Nothing
   (descRes, descView) <- mopt textField descSettings Nothing
   (acctsRes, _)       <- mreq listField acctSettings Nothing
   (amtsRes, _)        <- mreq listField amtSettings  Nothing
   (fileRes, fileView) <- mopt fileField' fileSettings Nothing
   let
-    (postingsRes, displayRows) = validatePostings acctsRes amtsRes
+    (postingsRes, displayRows) = validatePostings trs acctsRes amtsRes
     formRes = validateTransaction deffile dateRes descRes postingsRes fileRes
   return (formRes, $(widgetFile "add-form"))
   where
-    -- custom fields
-    dateField = textField & checkMMap (pure . right fromEFDay . validateDate) (T.pack . show)
-      where
-        validateDate s =
-          first (const ("Invalid date format" :: Text)) $
-          fixSmartDateStrEither' today (T.strip s)
     listField = Field
       { fieldParse = const . pure . Right . Just . dropWhileEnd T.null
       , fieldView = error' "listField should not be used for rendering"  -- PARTIAL:
@@ -85,8 +85,6 @@
           | f `elem` fs = Right f
           | otherwise = Left $ MsgInputNotFound $ T.pack f
     -- field settings
-    dateSettings = FieldSettings "date" Nothing Nothing (Just "date") [("class", "form-control input-lg"), ("placeholder", "Date")]
-    descSettings = FieldSettings "desc" Nothing Nothing (Just "description") [("class", "form-control input-lg typeahead"), ("placeholder", "Description"), ("size", "40")]
     acctSettings = FieldSettings "account" Nothing Nothing (Just "account") []
     amtSettings  = FieldSettings "amount" Nothing Nothing (Just "amount") []
     fileSettings = FieldSettings "file" Nothing Nothing (Just "file") [("class", "form-control input-lg")]
@@ -113,9 +111,11 @@
 -- | Parse a list of postings out of a list of accounts and a corresponding list
 -- of amounts
 validatePostings ::
-     FormResult [Text] -> FormResult [Text]
+     Translations -> FormResult [Text] -> FormResult [Text]
   -> (FormResult [Posting], [(Int, (Text, Text, Maybe Text, Maybe Text))])
-validatePostings acctsRes amtsRes = let
+validatePostings trs acctsRes amtsRes = let
+  missingamount = tr trs "Missing amount"
+  missingaccount = tr trs "Missing account"
 
   -- Zip accounts and amounts, fill in missing values and drop empty rows.
   rows :: [(Text, Text)]
@@ -127,22 +127,25 @@
   postings :: [(Text, Text, Either (Maybe Text, Maybe Text) Posting)]
   postings = unfoldr go (True, rows)
     where
-      go (True, (x, ""):y:xs) = Just ((x, "", zipRow (checkAccount x) (Left "Missing amount")), (True, y:xs))
+      go (True, (x, ""):y:xs) = Just ((x, "", zipRow (checkAccount x) (Left missingamount)), (True, y:xs))
       go (True, (x, ""):xs) = Just ((x, "", zipRow (checkAccount x) (Right missingamt)), (False, xs))
-      go (False, (x, ""):xs) = Just ((x, "", zipRow (checkAccount x) (Left "Missing amount")), (False, xs))
-      go (_, ("", y):xs) = Just (("", y, zipRow (Left "Missing account") (checkAmount y)), (False, xs))
+      go (False, (x, ""):xs) = Just ((x, "", zipRow (checkAccount x) (Left missingamount)), (False, xs))
+      go (_, ("", y):xs) = Just (("", y, zipRow (Left missingaccount) (checkAmount y)), (False, xs))
       go (_, (x, y):xs) = Just ((x, y, zipRow (checkAccount x) (checkAmount y)), (True, xs))
       go (_, []) = Nothing
 
   zipRow (Left e) (Left e') = Left (Just e, Just e')
   zipRow (Left e) (Right _) = Left (Just e, Nothing)
   zipRow (Right _) (Left e) = Left (Nothing, Just e)
-  zipRow (Right acct') (Right amt) = Right (nullposting {paccount = acct, ptype = atype, pamount = mixedAmount amt})
+  zipRow (Right acct') (Right amt) = Right (nullposting {paccount = acct, preal = atype, pamount = mixedAmount amt})
     where
       acct = accountNameWithoutPostingType acct'
       atype = accountNamePostingType acct'
 
-  errorToFormMsg = first (("Invalid value: " <>) . T.pack .
+  -- The parser's own message stays in English, inside a translated frame.
+  -- (The signature keeps this polymorphic under MonoLocalBinds, since it mentions trs.)
+  errorToFormMsg :: Either HledgerParseErrors a -> Either Text a
+  errorToFormMsg = first ((\e -> trf trs "Invalid value: {error}" [("error", e)]) . T.pack .
                           foldl (\s a -> s <> parseErrorTextPretty a) "" .
                           bundleErrors)
   checkAccount = errorToFormMsg . runParser (accountnamep <* eof) "" . T.strip
@@ -153,8 +156,8 @@
   result = case (acctsRes, amtsRes) of
     (FormMissing, FormMissing) -> postings
     _ -> case postings of
-      [] -> [ ("", "", Left (Just "Missing account", Just "Missing amount"))
-           , ("", "", Left (Just "Missing account", Nothing))
+      [] -> [ ("", "", Left (Just missingaccount, Just missingamount))
+           , ("", "", Left (Just missingaccount, Nothing))
            ]
       xs -> xs
 
@@ -167,40 +170,10 @@
 
   -- And finally prepare the final FormResult [Posting]
   formResult = case traverse (\(_, _, x) -> x) result of
-    Left _ -> FormFailure ["Postings validation failed"]
+    Left _ -> FormFailure [tr trs "Postings validation failed"]
     Right xs -> FormSuccess xs
 
   in (formResult, zip [(1 :: Int)..] display)
-
--- helper for add-form.hamlet
-toBloodhoundJson :: [Text] -> Markup
-toBloodhoundJson ts =
-  -- This used to work, but since 1.16, it seems like something changed.
-  -- toJSON ("a"::Text) gives String "a" instead of "a", etc.
-  -- preEscapedString . escapeJSSpecialChars . show . toJSON
-
-  preEscapedText $ T.concat [
-    "[",
-    T.intercalate "," $ map (
-      ("{\"value\":" <>).
-      (<> "}").
-      -- This will convert a value such as ``hledger!`` into
-      -- ``atob("aGxlZGdlciE=")``. When this gets evaluated on the client,
-      -- the resulting string is ``hledger!`` again. The same data is
-      -- passed, but the user-controlled bit of that string can only use
-      -- characters [a-zA-Z0-9+=/], making it impossible to break out of
-      -- string context.
-      b64wrap
-      ) ts,
-    "]"
-    ]
-  where
-    -- decodeBase64EncodedText is defined in add-form.hamlet
-    b64wrap = ("decodeBase64EncodedText(\""<>) . (<>"\")") .
-#if MIN_VERSION_base64(1,0,0)
-      extractBase64 .
-#endif
-      encodeBase64
 
 zipDefault :: a -> [a] -> [a] -> [(a, a)]
 zipDefault def (b:bs) (c:cs) = (b, c):(zipDefault def bs cs)
diff --git a/Hledger/Web/Widget/Chart.hs b/Hledger/Web/Widget/Chart.hs
new file mode 100644
--- /dev/null
+++ b/Hledger/Web/Widget/Chart.hs
@@ -0,0 +1,144 @@
+-- | The report pages' charts: hledger's SVG charts, as the commands'
+-- --chart draws them (see "Hledger.Cli.Chart"), drawn by the server and
+-- styled by /chart.css (ChartCssR), since the Content-Security-Policy
+-- allows no inline styles.
+
+{-# LANGUAGE OverloadedStrings #-}
+
+module Hledger.Web.Widget.Chart (
+  chartWidths,
+  chartAtWidths,
+  reportChart,
+  chartWithScales,
+  chartLegend,
+  chartToggle,
+  dataToggle,
+) where
+
+import Data.Text qualified as T
+import Safe (atMay, readMay)
+import Text.Blaze ((!), (!?))
+import Text.Blaze.Html5 qualified as H
+import Text.Blaze.Html5.Attributes qualified as A
+
+import Hledger.Data.Types (Amount(..))
+import Hledger.Cli.CliOptions (CliOpts)
+import Hledger.Cli.Chart (ChartArg(..), chartArgFor)
+import Hledger.Utils.I18n (Translations, tr)
+import Hledger.Write.Chart (Chart(..), Panel(..), setChartLayout, setChartScales)
+import Hledger.Write.Chart.Svg (SvgOptions(..), chartPanelsSvgMarkupWith, chartSvgMarkupWith, defaultSvgOptions)
+import Hledger.Web.Import
+import Hledger.Web.WebOptions (WebOpts(..))
+
+-- | The widths to draw a page's charts at: as wide as the page's main
+-- column, which the browser measures and keeps in cookies (hledger.js),
+-- from 320 to 2400 pixels, or by default 880. When the column's width
+-- with the sidebar shown and with it hidden differ (chartwidths), both,
+-- each with the sidebar state it is for, so that showing or hiding the
+-- sidebar needs no redraw (see 'chartAtWidths'); otherwise its width as
+-- it is (chartwidth).
+chartWidths :: Handler [(Maybe Text, Double)]
+chartWidths = do
+  mw <- (>>= width) <$> uiCookie "chartwidth"
+  mboth <- (>>= widthPair) <$> uiCookie "chartwidths"
+  return $ case mboth of
+    Just (shown, hidden) | shown /= hidden -> [(Just "shown", shown), (Just "hidden", hidden)]
+    _ -> [(Nothing, fromMaybe (svgWidth defaultSvgOptions) mw)]
+  where
+    width = fmap (fromIntegral . max 320 . min (2400 :: Int)) . readMay . T.unpack
+    widthPair t = case T.splitOn "," t of
+      [a, b] -> (,) <$> width a <*> width b
+      _      -> Nothing
+
+-- | A chart drawn at each of the given widths (see 'chartWidths'), by a
+-- function drawing it at a width, with its ids (see 'svgIds') ending in
+-- the given suffix, which differs for each width. At several widths, each
+-- is in an element that hledger.css shows only while the sidebar is in the
+-- state it is for.
+chartAtWidths :: [(Maybe Text, Double)] -> (Text -> Double -> Html) -> Html
+chartAtWidths ws draw = forM_ ws $ \(mstate, w) -> case mstate of
+  Nothing    -> draw "" w
+  Just state -> H.div ! A.class_ "chart-width" ! H.dataAttribute "sidebar" (H.toValue state) $ draw ("-" <> state) w
+
+-- | A report's chart, to go between its heading and its table: as wide
+-- as the page's main column, in the layout its report prefers, untitled,
+-- since the heading names it, and named for screen readers by the given
+-- label. Nothing when the chart has nothing to show. With several
+-- commodities, a legend chooses the one charted, as on the register
+-- (see 'chartLegend'). The c key hides it, and the d key the table
+-- (hledger.js, hledger.css), as do the buttons of 'chartToggle' and 'dataToggle'.
+reportChart :: Translations -> Text -> Chart -> Widget
+reportChart trs label chart = do
+  copts <- cliopts_ . appOpts <$> getYesod
+  -- without the title, which the page's heading shows, or the notes, which
+  -- the page shows below its table (and which each panel's svg would repeat)
+  let chart' = chartWithScales copts $ setChartLayout Nothing chart{chTitle = "", chNotes = []}
+      panels = chPanels chart'
+  unless (null panels) $ do
+    ws <- liftHandler chartWidths
+    addStylesheet ChartCssR
+    let opts sfx w = defaultSvgOptions{svgStyles = False, svgWidth = w, svgPlotHeight = 200, svgIds = "report-chart" <> sfx}
+        -- each panel's chart, at a width
+        panelsAt sfx w = chartPanelsSvgMarkupWith (opts sfx w) chart'
+    toWidget $ (\c -> chartToggle trs <> c <> dataToggle trs) $ case panels of
+      [_] -> H.div ! A.class_ "report-chart" $ chartAtWidths ws $ \sfx w ->
+               chartSvgMarkupWith (opts sfx w) chart' ! H.customAttribute "aria-label" (H.toValue label)
+      _   -> H.div ! A.class_ "report-chart with-legend" $
+               chartLegend "report-chart" legendlabel
+                 [ (name, chartAtWidths ws $ \sfx w ->
+                      forM_ (panelsAt sfx w `atMay` k) (! H.customAttribute "aria-label" (H.toValue $ label <> ": " <> name)))
+                 | (k, p) <- zip [0 ..] panels
+                 , let c = acommodity $ pnUnit p
+                 , let name = if T.null c then nosymbol else c
+                 ]
+  where
+    -- TRANSLATORS: in a report page's chart, before the commodities that can be charted.
+    legendlabel = tr trs "Commodity"
+    -- TRANSLATORS: a chart legend's entry for amounts written without a commodity symbol.
+    nosymbol = tr trs "no symbol"
+
+-- | A chart with the scales fixed by --chart's SCALE amounts at startup, if any,
+-- as the commands' --chart fixes them (read with the chart's commodity styles).
+chartWithScales :: CliOpts -> Chart -> Chart
+chartWithScales copts chart = setChartScales (caScales $ chartArgFor copts chart) chart
+
+-- | A legend choosing which of several charts is shown, with no javascript:
+-- its name, then for each chart, a radio button (named and numbered with
+-- the given prefix, which should be unique on the page), its label, and the
+-- chart, which /chart.css shows while its button is checked. The first is
+-- checked at first. It goes in an element of class with-legend.
+chartLegend :: Text -> Text -> [(Text, Html)] -> Html
+chartLegend prefix legendlabel charts = do
+  H.span ! A.class_ "chart-legend-label" $ H.toHtml legendlabel <> ":"
+  forM_ (zip [0 :: Int ..] charts) $ \(k, (name, chart)) -> do
+    let i = H.toValue $ prefix <> "-" <> T.pack (show k)
+    H.input ! A.type_ "radio" ! A.name (H.toValue prefix) ! A.id i !? (k == 0, A.checked "")
+    H.label ! A.for i $ H.toHtml name
+    H.div ! A.class_ "chart-panel" $ chart
+
+-- | The disclosure-like buttons showing or hiding a report's chart and its
+-- table, like the c and d keys: "Chart", to go right before the
+-- .report-chart element, and "Data", right after it, before the table.
+-- hledger.css puts them at the right margin, over the chart's top right
+-- corner and just above the table's, with a caret showing whether their
+-- part is shown, and while it is hidden, on a line of their own.
+chartToggle, dataToggle :: Translations -> Html
+chartToggle trs =
+  partToggle "chart"
+    -- TRANSLATORS: a tooltip; c is the keyboard shortcut, which is not translated.
+    (tr trs "Show or hide the chart (c)")
+    -- TRANSLATORS: a small disclosure button above a report page's chart, showing or hiding it.
+    (tr trs "Chart")
+dataToggle trs =
+  partToggle "table"
+    -- TRANSLATORS: a tooltip; d is the keyboard shortcut, which is not translated.
+    (tr trs "Show or hide the data (d)")
+    -- TRANSLATORS: a small disclosure button above a report page's data table, showing or hiding it.
+    (tr trs "Data")
+
+partToggle :: Text -> Text -> Text -> Html
+partToggle part title label =
+  H.div ! A.class_ (H.toValue $ "part-toggle-row " <> part <> "-toggle-row") $
+    H.button ! A.type_ "button" ! A.class_ "part-toggle" ! H.dataAttribute "report-part" (H.toValue part)
+      ! A.title (H.toValue title)
+      $ H.toHtml label
diff --git a/Hledger/Web/Widget/Common.hs b/Hledger/Web/Widget/Common.hs
--- a/Hledger/Web/Widget/Common.hs
+++ b/Hledger/Web/Widget/Common.hs
@@ -5,44 +5,82 @@
 {-# LANGUAGE TemplateHaskell   #-}
 
 module Hledger.Web.Widget.Common
-  ( accountQuery
-  , accountOnlyQuery
+  ( accountParams
+  , accountRegisterQuery
   , balanceReportAsHtml
+  , controlsHint
+  , controlsToggle
+  , searchHeading
+  , inertControls
+  , pricesLinks
+  , commodityLinks
+  , depthLinks
+  , depthTitle
+  , depthParam
+  , equityLinks
+  , amountLinks
+  , zeroBalanceLinks
+  , statusLinks
+  , realLinks
+  , columnsLinks
+  , percentLinks
+  , costsLinks
+  , lotsLinks
+  , closedLinks
+  , holdingsValueLinks
+  , typeLinks
+  , AmountMode(..)
+  , valueWord
+  , searchTerms
+  , MovedOptions(..)
+  , normalisedSearch
+  , splitPeriodExpr
   , helplink
   , mixedAmountAsHtml
+  , mixedAmountAsHtmlWith
+  , mixedAmountAsHtmlElided
+  , runningBalanceAsHtml
+  , moreCommodities
   , fromFormSuccess
-  , writeJournalTextIfValidAndChanged
   , journalFile404
   , transactionFragment
   , removeDates
-  , removeInacct
-  , replaceInacct
+  , journalDayQuery
   ) where
 
-import Control.Monad.Except (ExceptT, mapExceptT)
+import Control.Applicative ((<|>))
+import Control.Monad (when)
+import Data.Char (isDigit)
 import Data.Foldable (find, for_)
 import Data.List (elemIndex)
+import Data.Set qualified as Set
+import Data.Maybe (isJust, isNothing, listToMaybe, mapMaybe, maybeToList)
 import Data.Text (Text)
 import Data.Text qualified as T
+import Data.Time.Calendar (Day)
+import Safe (lastMay, readMay)
 import System.FilePath (takeFileName)
-import Text.Blaze ((!), textValue)
+import Text.Blaze ((!), (!?), textValue)
 import Text.Blaze.Html5 qualified as H
 import Text.Blaze.Html5.Attributes qualified as A
 import Text.Blaze.Internal (preEscapedString)
 import Text.Hamlet (hamletFile)
+import Text.Megaparsec (getInput)
 import Text.Printf (printf)
 import Yesod
 
+import Hledger.Utils.I18n (Translations, tr, trc, trf)
 import Hledger
-import Hledger.Cli.Utils (writeFileWithBackupIfChanged)
+import Hledger.Cli.Anchor qualified as Anchor
+import Hledger.Web.Param (linksRow, linksRowClass)
 import Hledger.Web.Settings (manualurl)
 import Hledger.Query qualified as Query
 
 
 journalFile404 :: FilePath -> Journal -> HandlerFor m (FilePath, Text)
 journalFile404 f j =
-  case find ((== f) . fst) (jfiles j) of
-    Just (_, txt) -> pure (takeFileName f, txt)
+  case find ((== f) . jfpath) (jfiles j) of
+    Just jf -> pure (takeFileName f, jftext jf)
     Nothing -> notFound
 
 fromFormSuccess :: Applicative m => m a -> FormResult a -> m a
@@ -50,53 +88,456 @@
 fromFormSuccess h (FormFailure _) = h
 fromFormSuccess _ (FormSuccess a) = pure a
 
--- | A helper for postEditR/postUploadR: check that the given text
--- parses as a Journal, and if so, write it to the given file, if the
--- text has changed. Or, return any error message encountered.
---
--- As a convenience for data received from web forms, which does not
--- have normalised line endings, line endings will be normalised (to \n)
--- before parsing.
---
--- The file will be written (if changed) with the current system's native
--- line endings (see writeFileWithBackupIfChanged).
---
-writeJournalTextIfValidAndChanged :: MonadHandler m => FilePath -> Text -> ExceptT String m ()
-writeJournalTextIfValidAndChanged f t = mapExceptT liftIO $ do
-  -- Ensure unix line endings, since both readJournal (cf
-  -- formatdirectivep, #1194) writeFileWithBackupIfChanged require them.
-  -- XXX klunky. Any equivalent of "hSetNewlineMode h universalNewlineMode" for form posts ?
-  let t' = T.replace "\r" "" t
-  j <- readJournal definputopts (Just f) =<< liftIO (textToHandle t')
-  _ <- liftIO $ j `seq` writeFileWithBackupIfChanged f t'  -- Only write backup if the journal didn't error
-  return ()
-
 -- | Link to a topic in the manual.
 helplink :: Text -> Text -> HtmlUrl r
 helplink topic label _ = H.a ! A.href u ! A.target "hledgerhelp" $ toHtml label
   where u = textValue $ manualurl <> if T.null topic then "" else T.cons '#' topic
 
--- | Render a "BalanceReport" as html.
-balanceReportAsHtml :: Eq r => (r, r) -> r -> Bool -> Journal -> Text -> [QueryOpt] -> BalanceReport -> HtmlUrl r
-balanceReportAsHtml (journalR, registerR) here hideEmpty j qparam qopts (items, total) =
+-- | Render a "BalanceReport" as the sidebar: the page links (each page's
+-- route, label, and title, with the parameters their links carry), then
+-- the accounts, linking to their registers with the given parameters
+-- (see 'Hledger.Web.ReportPage.registerKeptParams'). The current page's
+-- row is marked. Any given caption (the balances' date, with its tooltip)
+-- and, if asked, the - and + buttons that fold or open a level of the
+-- accounts (default-layout.hamlet's script) are shown above the
+-- accounts, in one row. Without balances (the sidebar's default), the
+-- report is just account names, with no amounts or total row.
+balanceReportAsHtml ::
+  Eq r => r -> r -> [(r, Text, Text)] -> [(Text, Text)] -> [(Text, Text)] -> Bool -> Text -> Text -> Maybe (Text, Text) -> Bool -> Bool -> Translations -> Journal -> Text -> Maybe (AccountName, Bool) -> BalanceReport -> HtmlUrl r
+balanceReportAsHtml registerR here reports reportParams kept hideEmpty totlabel tottitle mcaption stepper withBalances trs j qparam maccount (items, total) =
   $(hamletFile "templates/balance-report.hamlet")
   where
     l = ledgerFromJournal Any j
     indent a = preEscapedString $ concat $ replicate (2 + 2 * a) "&nbsp;"
-    hasSubAccounts acct = maybe True (not . null . asubs) $ ledgerAccount l acct
-    isInterestingAccount acct = maybe False isInteresting $ ledgerAccount l acct
-      where isInteresting a = not (all (mixedAmountLooksZero . bdexcludingsubs) . pdperiods $ adata a) || any isInteresting (asubs a)
-    matchesAcctSelector acct = Just True == ((`matchesAccount` acct) <$> inAccountQuery qopts)
+    -- Without balances, these are found from the names alone, not the
+    -- journal's ledger, whose balances would cost what hiding them saves;
+    -- and every account is shown, since which are zero is not known.
+    hasSubAccounts acct
+      | withBalances = maybe True (not . null . asubs) (ledgerAccount l acct)
+      | otherwise    = acct `Set.member` parents
+    parents = Set.fromList [parentAccountName a | (a, _, _, _) <- items]
+    isInterestingAccount acct
+      | withBalances = maybe False isInteresting (ledgerAccount l acct)
+      | otherwise    = True
+      -- Costs and cost bases are stripped before the zero test, since they
+      -- keep bought-and-fully-sold amounts from cancelling (eg a disposed
+      -- lot, +10 A @ one cost and -10 A at another), and the sidebar
+      -- displays such balances as zero.
+      where isInteresting a = not (all (mixedAmountLooksZero . mixedAmountStripCosts . bdexcludingsubs) . pdperiods $ adata a) || any isInteresting (asubs a)
+    matchesAcctSelector acct = maybe False ((`matchesAccount` acct) . accountRegisterQuery) maccount
+    qps = [("q", qparam) | not (T.null qparam)]
+    acctlink acct = (registerR, qps ++ accountParams True acct ++ kept)
+    acctonlylink acct = (registerR, qps ++ accountParams False acct ++ kept)
+    -- The amounts are every account's balances at the end of the search's
+    -- dates, whatever its other terms, so their links keep just the dates:
+    -- an account's register, and the register of everything.
+    dqps = [("q", t) | let t = T.unwords (onlyDates qparam), not (T.null t)]
+    amountlink acct = (registerR, dqps ++ accountParams True acct ++ kept)
+    totallink = (registerR, dqps ++ kept)
 
-accountQuery :: AccountName -> Text
-accountQuery = ("inacct:" <>) .  quoteIfSpaced
+-- | A page's rows of report controls behind a disclosure, closed by
+-- default so the page stays uncluttered. Opening it is remembered per
+-- browser in the showcontrols cookie (hledger.js), which the server
+-- reads (App.showControls), so each page is born the way the last one
+-- was left and nothing moves after paint.
+-- Closed, it lists the options in effect, so that the page's state is
+-- never hidden (see optionsSummary).
+controlsToggle :: Translations -> Bool -> [Text] -> HtmlUrl r -> HtmlUrl r
+controlsToggle trs open summary rows =
+  -- TRANSLATORS: the disclosure hiding each page's rows of report controls: its text, and its tooltip.
+  [hamlet|
+<details .report-controls :open:open>
+  <summary title=#{tr trs "Show the options that reshape this view"}>
+    #{tr trs "Options"}
+    $if not (null summary)
+      <span .options-summary>#{T.intercalate " · " summary}
+  ^{rows}
+|]
 
-accountOnlyQuery :: AccountName -> Text
-accountOnlyQuery = ("inacctonly:" <>) . quoteIfSpaced
+-- | A journal or register page's heading: the given title, then the
+-- search's dates, if it has any, shown as the balance pages show theirs
+-- (eg "General Journal in 2024"), then ", filtered" if it has other
+-- filters. A depth limit is not one.
+searchHeading :: Translations -> Bool -> Query -> Text -> Text
+searchHeading trs secondary q title = case (spn == nulldatespan, filtered) of
+  (True,  False) -> title
+  (True,  True)  -> trf trs "{title}, filtered" [("title", title)]
+  -- TRANSLATORS: a journal or register page's heading when the search has dates, eg "General Journal in 2024".
+  (False, False) -> trf trs "{title} in {dates}" [("title", title), ("dates", showDateSpan spn)]
+  (False, True)  -> trf trs "{title} in {dates}, filtered" [("title", title), ("dates", showDateSpan spn)]
+  where
+    spn = queryDateSpan secondary q
+    filtered = filterQuery (\t -> not (queryIsDepth t || queryIsDateOrDate2 t)) q /= Any
 
+-- | Rows of controls that take effect on other pages, their labels
+-- muted: they show and preserve the url's report state here too, so it
+-- is never invisible, and never lost by following a link.
+inertControls :: Translations -> HtmlUrl r -> HtmlUrl r
+inertControls trs rows =
+  -- TRANSLATORS: the tooltip on the muted control rows of the journal and register pages.
+  [hamlet|
+<div .controls-inert title=#{tr trs "These controls take effect on the report pages"}>
+  ^{rows}
+|]
+
+-- | A short usage hint below a row of controls, in muted small text.
+-- The text arrives already translated, so that the literal at the call
+-- site is what the extraction tool collects.
+controlsHint :: Text -> HtmlUrl r
+controlsHint t _ = H.p ! A.class_ "controls-hint" $ H.toHtml t
+
+-- | Links choosing where market prices come from: declared ones only,
+-- or inferred from transaction costs too, keeping the given parameters;
+-- the source being used is marked.
+pricesLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r
+pricesLinks trs route kept inferOn =
+  -- TRANSLATORS: the label before a page's market price source links, and the links' text and tooltips.
+  linksRow (tr trs "Prices:")
+    [ (tr trs "Declared", tr trs "Value amounts using declared market prices (P directives) only", (route, kept), not inferOn)
+    , (tr trs "Inferred too", tr trs "Infer market prices from transaction costs too (--infer-market-prices)", (route, kept ++ [("infer", "1")]), inferOn)
+    ]
+
+-- | How a page shows amounts: in the commodities they were recorded in,
+-- converted to cost (as with -B), or converted with one of the market
+-- valuations (as with -V, -X, and --value).
+data AmountMode = AsRecorded | AtCost | AtVal ValuationType
+  deriving (Eq, Show)
+
+-- | The value parameter naming an amount mode.
+valueWord :: AmountMode -> Text
+valueWord = \case
+  AsRecorded -> "none"
+  AtCost     -> "cost"
+  AtVal vt   -> case vt of
+    AtEnd  mc   -> "end"  <> comm mc
+    AtThen mc   -> "then" <> comm mc
+    AtNow  mc   -> "now"  <> comm mc
+    AtDate d mc -> showDate d <> comm mc
+  where comm = maybe "" ("," <>)
+
+-- | Links to the same report page limited to each account depth, from 0
+-- (only the total, as one row of all accounts, as --depth 0 shows) up
+-- to the given deepest one, which removes the limit, as hledger-ui
+-- does with a depth at or beyond the deepest. Each keeps the search and
+-- the given parameters; the depth being shown, the given parameters'
+-- depth, is marked, on the deepest link when there is no limit or it is
+-- at or beyond the deepest.
+-- The digit keys set a depth through the deepest link's url, and the -
+-- and + keys step through the links, going round (hledger.js).
+depthLinks :: Translations -> r -> [(Text, Text)] -> Text -> Int -> HtmlUrl r
+depthLinks trs route kept qparam deepest =
+  -- TRANSLATORS: the label before a report's depth links, and the links' text and tooltips.
+  linksRowClass "depth" (tr trs "Depth:")
+    [ (T.pack (show n), depthTitle trs deepest n, link n, marked n) | n <- [0 .. deepest] ]
+  where
+    current = readMay . T.unpack =<< lookup "depth" kept
+    marked n | n == deepest = maybe True (>= deepest) current
+             | otherwise    = current == Just n
+    link n =
+      (route, [("q", qparam) | not (T.null qparam)] ++ filter ((/= "depth") . fst) kept ++ [depthParam deepest n])
+
+-- | The depth parameter for a link to the given depth limit, given the
+-- deepest account depth: at or beyond it, depth=all, no limit (no
+-- parameter means the default depth).
+depthParam :: Int -> Int -> (Text, Text)
+depthParam deepest n = ("depth", if n < deepest then T.pack (show n) else "all")
+
+-- | The tooltip of a link to the given depth limit, given the deepest
+-- account depth (which removes the limit).
+depthTitle :: Translations -> Int -> Int -> Text
+depthTitle trs deepest n
+  -- TRANSLATORS: the tooltips of a report's depth links.
+  | n == 0       = tr trs "Show only the total (depth 0)"
+  | n >= deepest = tr trs "Show accounts at every depth"
+  | otherwise    = trf trs "Show accounts down to depth {depth}" [("depth", T.pack (show n))]
+
+-- | Links to the same report page showing amounts as recorded, at cost,
+-- or at market value, keeping the given parameters; the mode being
+-- shown, if it is one of these, is marked. The page's default mode, the
+-- startup one, needs no parameter. The V key toggles between the first
+-- link (as recorded) and the last (market value), and B the second, at
+-- cost (hledger.js).
+amountLinks :: Translations -> r -> [(Text, Text)] -> Maybe AmountMode -> Maybe AmountMode -> HtmlUrl r
+amountLinks trs route kept startup current =
+  -- TRANSLATORS: the label before a report's amount conversion links, and the links' text and tooltips.
+  linksRowClass "amounts" (tr trs "Amounts:")
+    [ (label, title, (route, kept ++ [("value", valueWord m) | Just m /= startup]), Just m == current)
+    | (label, title, m) <-
+        [ (tr trs "As recorded",     tr trs "Show amounts in the commodities they were recorded in", AsRecorded)
+        , (tr trs "At cost",         tr trs "Show amounts converted to their cost, as recorded in transactions (-B)", AtCost)
+        , (tr trs "At market value", tr trs "Show amounts converted to their market value at the end of each period, using market prices (-V)", AtVal (AtEnd Nothing))
+        ]
+    ]
+
+-- | Links that show or hide accounts with zero balances: each rewrites
+-- the empty parameter (1 shows them, 0 hides them, the direction of
+-- the command line's -E), keeping the given parameters; the state
+-- being shown is marked. The page's startup default needs no
+-- parameter. The z key follows the other link (hledger.js).
+zeroBalanceLinks :: Translations -> r -> [(Text, Text)] -> Bool -> Bool -> HtmlUrl r
+zeroBalanceLinks trs route kept dfltHidden hidden =
+  -- TRANSLATORS: the label before the links that show or hide zero balances, and the links' text and tooltips.
+  [hamlet|
+$newline never
+<p .report-links .zero-balances>
+  <span .row-label>#{tr trs "Zero balances:"}
+  <a href=@?{link True} :hidden:.current title=#{tr trs "Hide accounts whose balances are zero"}>#{tr trs "Hidden"}
+  <a href=@?{link False} :not hidden:.current title=#{tr trs "Show accounts whose balances are zero"}>#{tr trs "Shown"}
+|]
+  where link h = (route, kept ++ [("empty", if h then "0" else "1") | h /= dfltHidden])
+
+-- | On the balance sheet, links hiding or showing an equity section, as
+-- the balancesheet and balancesheetequity commands do, keeping the given
+-- parameters; the one in effect is marked. Both say which, overriding
+-- the remembered choice (StatementsR).
+equityLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r
+equityLinks trs route kept shown =
+  -- TRANSLATORS: the label before the balance sheet's links that hide or show equity, and the links' tooltips.
+  linksRowClass "equity" (tr trs "Equity:")
+    [ (tr trs "Hidden", tr trs "Show assets, liabilities, and net worth, as the balancesheet command does", link False, not shown)
+    , (tr trs "Shown",  tr trs "Show assets, liabilities, and equity, as the balancesheetequity command does", link True, shown)
+    ]
+  where link e = (route, kept ++ [("equity", if e then "1" else "0")])
+
+-- | A row of links that each rewrite one kind of search term: each link
+-- replaces the terms the row owns (those the predicate matches) with its
+-- own term, or removes them, keeping the search's other terms and the
+-- given parameters. The link whose term the search has is marked, or the
+-- removing link when it has none.
+queryTermRow :: r -> [(Text, Text)] -> Text -> (Text -> Bool) -> Text -> Text -> [(Text, Text, Maybe Text)] -> HtmlUrl r
+queryTermRow route kept qparam owns cls rowlabel items =
+  linksRowClass cls rowlabel [ (label, title, link mterm, current mterm) | (label, title, mterm) <- items ]
+  where
+    terms = searchTerms qparam
+    rest = map quoteIfSpaced $ filter (not . owns) terms
+    current mterm = filter owns terms == maybeToList mterm
+    link mterm =
+      (route, [("q", t) | let t = T.unwords $ rest ++ map quoteIfSpaced (maybeToList mterm), not (T.null t)] ++ kept)
+
+-- | Links filtering by transaction status, as hledger-ui's U, P, and C
+-- keys do: each rewrites the status: term in the search. The same keys
+-- follow them, by their order here (hledger.js).
+statusLinks :: Translations -> r -> [(Text, Text)] -> Text -> HtmlUrl r
+statusLinks trs route kept qparam =
+  -- TRANSLATORS: the label before a report's status filter links, and the links' text and tooltips.
+  queryTermRow route kept qparam (T.isPrefixOf "status:") "status" (tr trs "Status:")
+    [ (trc trs "status" "All", tr trs "Show transactions of any status", Nothing)
+    , (tr trs "Unmarked", tr trs "Show only unmarked transactions (status:)",     Just "status:")
+    , (tr trs "Pending",  tr trs "Show only pending transactions (status:!)",    Just "status:!")
+    , (tr trs "Cleared",  tr trs "Show only cleared transactions (status:*)",    Just "status:*")
+    ]
+
+-- | Links filtering to real or virtual postings: each rewrites the
+-- real: term in the search. The R key toggles Real, the second link
+-- (hledger.js).
+realLinks :: Translations -> r -> [(Text, Text)] -> Text -> HtmlUrl r
+realLinks trs route kept qparam =
+  -- TRANSLATORS: the label before a report's real/virtual filter links, and the links' text and tooltips.
+  queryTermRow route kept qparam (T.isPrefixOf "real:") "postings" (tr trs "Postings:")
+    [ (trc trs "postings" "All", tr trs "Show real and virtual postings", Nothing)
+    , (tr trs "Real",    tr trs "Show only real postings, as -R does (real:1)", Just "real:1")
+    , (tr trs "Virtual", tr trs "Show only virtual postings, the parenthesized ones (real:0)", Just "real:0")
+    ]
+
+-- | Toggles adding a row-total and a row-average column to a
+-- multi-period report, as -T and -A do; the columns shown are marked.
+-- The T and A keys follow these links, by their order here (hledger.js).
+columnsLinks :: Translations -> r -> [(Text, Text)] -> Bool -> Bool -> HtmlUrl r
+columnsLinks trs route kept total avg =
+  -- TRANSLATORS: the label before a report's extra-column toggles, and the toggles' text and tooltips.
+  linksRowClass "columns" (tr trs "Extra columns:")
+    [ (trc trs "column" "Total", tr trs "Add a column totaling each row (-T)",
+        (route, kept ++ [("avg", "1") | avg] ++ [("total", "1") | not total]), total)
+    , (trc trs "column" "Average", tr trs "Add a column averaging each row (-A)",
+        (route, kept ++ [("total", "1") | total] ++ [("avg", "1") | not avg]), avg)
+    ]
+
+-- | Links showing the report's numbers as amounts or as percentages of
+-- their column's total, keeping the given parameters.
+percentLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r
+percentLinks trs route kept pct =
+  -- TRANSLATORS: the label before a report's amounts/percentages links, and the links' text and tooltips.
+  linksRow (tr trs "Numbers:")
+    [ (trc trs "numbers" "Amounts", tr trs "Show the amounts", (route, kept), not pct)
+    , (tr trs "Percentages", tr trs "Show each amount as a percentage of its column's total (-%)", (route, kept ++ [("pct", "1")]), pct)
+    ]
+
+-- | Links showing or hiding the costs recorded with a register's
+-- amounts (10 AAPL @ $95), keeping the given parameters.
+costsLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r
+costsLinks trs route kept on =
+  -- TRANSLATORS: the label before the register's cost links, and the links' text and tooltips.
+  linksRow (tr trs "Costs:")
+    [ (trc trs "costs" "Hidden", tr trs "Show amounts without their costs", (route, kept), not on)
+    , (trc trs "costs" "Shown", tr trs "Show amounts with the costs recorded in the journal", (route, kept ++ [("costs", "1")]), on)
+    ]
+
+-- | Links that show or hide lot detail: each holding's individual lots,
+-- shown as lot subaccounts (the lots parameter; 1 shows them).
+-- The L key toggles between them (hledger.js).
+lotsLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r
+lotsLinks trs route kept on =
+  -- TRANSLATORS: the label before a report's lot detail links, and the links' text and tooltips.
+  linksRowClass "lots" (tr trs "Lots:")
+    [ (trc trs "lots" "Hidden", tr trs "Aggregate each account's lots", (route, kept), not on)
+    , (trc trs "lots" "Shown", tr trs "Show each lot separately (--lots)", (route, kept ++ [("lots", "1")]), on)
+    ]
+
+-- | Links that show or hide fully closed positions: commodities no
+-- longer held, with realized gains to show (the closed parameter;
+-- 1 shows them - the empty parameter keeps meaning zero balances).
+-- On this page the z key follows the other link (hledger.js).
+closedLinks :: Translations -> r -> [(Text, Text)] -> Bool -> Bool -> HtmlUrl r
+closedLinks trs route kept dfltHidden hidden =
+  -- TRANSLATORS: the label before the holdings page's closed-position links, and the links' text and tooltips.
+  linksRowClass "closed-positions" (tr trs "Closed positions:")
+    [ (trc trs "closed" "Hidden", tr trs "Show only open positions", link True, hidden)
+    , (trc trs "closed" "Shown", tr trs "Also show fully disposed positions and their realized gains (-E)", link False, not hidden)
+    ]
+  where link h = (route, kept ++ [("closed", if h then "0" else "1") | h /= dfltHidden])
+
+-- | Links choosing how the holdings page values holdings: each lot in
+-- its own cost commodity (the default), or all in the market valuation
+-- commodity, as -V does.
+holdingsValueLinks :: Translations -> r -> [(Text, Text)] -> Bool -> HtmlUrl r
+holdingsValueLinks trs route kept valued =
+  -- TRANSLATORS: the label before the holdings page's valuation links, and the links' text and tooltips.
+  linksRow (tr trs "Values:")
+    [ (tr trs "Per cost commodity", tr trs "Value each holding in its own cost commodity", (route, kept), not valued)
+    , (tr trs "At market value", tr trs "Convert values and costs to the market valuation commodity (-V)", (route, kept ++ [("value", "end")]), valued)
+    ]
+
+-- | Links filtering to accounts of one or more types: a link rewrites
+-- the type: term in the search to its own type, and shift-clicking adds
+-- or removes a type (hledger.js), the selection carried as one
+-- type:AL.. term, whose letters mark their links. The subtypes are
+-- offered only when the journal has accounts of them. Not for the
+-- statement pages, which choose their own types.
+typeLinks :: Translations -> r -> [(Text, Text)] -> Text -> Journal -> HtmlUrl r
+typeLinks trs route kept qparam j renderUrl =
+  H.div ! A.class_ "types" $ do
+    -- TRANSLATORS: the label before the account type filter links, and the links' text and tooltips.
+    linksRow (tr trs "Type:")
+      ( (trc trs "account type" "All", tr trs "Show accounts of every type", link Nothing, null selected)
+      : [ (label, title, link (Just letter), letter `elem` selected)
+        | (label, title, t) <- types, let letter = T.pack (show t), offered t letter ]) renderUrl
+  where
+    types =
+      [ (tr trs "Asset",      tr trs "Show only asset accounts (type:A)",      Asset)
+      , (tr trs "Liability",  tr trs "Show only liability accounts (type:L)",  Liability)
+      , (tr trs "Equity",     tr trs "Show only equity accounts (type:E)",     Equity)
+      , (tr trs "Revenue",    tr trs "Show only revenue accounts (type:R)",    Revenue)
+      , (tr trs "Expense",    tr trs "Show only expense accounts (type:X)",    Expense)
+      , (tr trs "Cash",       tr trs "Show only cash accounts (type:C)",       Cash)
+      , (tr trs "Conversion", tr trs "Show only conversion accounts (type:V)", Conversion)
+      , (tr trs "Gain",       tr trs "Show only capital gain accounts (type:G)", Gain)
+      , (tr trs "Imbalance",  tr trs "Show only imbalance accounts (type:M)",  Imbalance)
+      ]
+    -- The main types are always offered; the subtypes only when some
+    -- account has them (declared or inferred), or the search selects them.
+    offered t letter =
+      t `elem` [Asset, Liability, Equity, Revenue, Expense] || t `elem` jaccounttypes j || letter `elem` selected
+    terms = searchTerms qparam
+    rest = map quoteIfSpaced $ filter (not . T.isPrefixOf "type:") terms
+    -- the letters of the search's type: terms
+    selected = [T.singleton c | t <- terms, Just ls <- [T.stripPrefix "type:" t], c <- T.unpack (T.toUpper ls)]
+    link mletter =
+      (route, [("q", t) | let t = T.unwords $ rest ++ ["type:" <> l | Just l <- [mletter]], not (T.null t)] ++ kept)
+
+-- | Links filtering to one or more of the journal's commodities: a link
+-- rewrites the cur: term in the search to its own commodity, and
+-- shift-clicking adds or removes one (hledger.js), the selection
+-- carried as a single cur:A|B term, whose alternatives mark their
+-- links. The symbols are regex-escaped, since cur: matches whole
+-- symbols as regular expressions. Each link carries its pattern, and
+-- the row the search's other terms, as data attributes, so the script
+-- composes selections without parsing the search: any symbol works,
+-- spaces included, a composed term containing one being quoted whole.
+-- The given pre-translated hint renders below the row, and fewer than
+-- two commodities render nothing, hint included.
+-- The collapsed list's open state is remembered per browser in the
+-- showcommodities cookie (hledger.js), rendered here server side like
+-- the controls disclosure's.
+commodityLinks :: Translations -> r -> [(Text, Text)] -> Text -> Bool -> Text -> Journal -> HtmlUrl r
+commodityLinks trs route kept qparam open hint j renderUrl
+  | length syms < 2 = mempty
+  -- A few commodities are a row like any other; many collapse to a
+  -- line showing the selection, the full list opening on demand.
+  | length syms <= 6 =
+      (H.div ! A.class_ "commodities" ! H.dataAttribute "rest" (H.toValue restText) $
+        links True)
+      <> hinted
+  | otherwise =
+      (H.div ! A.class_ "commodities" ! H.dataAttribute "rest" (H.toValue restText) $
+        H.details !? (open, A.open "open") $ do
+          H.summary ! A.title (H.toValue $ tr trs "List all the commodities") $ do
+            -- TRANSLATORS: the label before a page's commodity filter links, and the links' text and tooltips.
+            H.span ! A.class_ "row-label" $ H.toHtml $ tr trs "Commodity:"
+            H.span ! A.class_ "sel" $ H.toHtml selectionText
+          links False)
+      <> hinted
+  where
+    hinted = controlsHint hint renderUrl
+    links withLabel =
+      H.p ! A.class_ "report-links" $ do
+        H.span ! A.class_ "row-label" $
+          if withLabel then H.toHtml $ tr trs "Commodity:" else mempty
+        H.a !? (null selected, A.class_ "current")
+            ! A.href (H.toValue $ uncurry renderUrl alllink)
+            ! A.title (H.toValue $ tr trs "Show amounts in every commodity") $
+          H.toHtml $ trc trs "commodity" "All"
+        for_ syms $ \sym -> do
+          let pat = regexEscape sym
+          H.a !? (pat `elem` selected, A.class_ "current")
+              ! A.href (H.toValue $ uncurry renderUrl $ symlink pat)
+              ! A.title (H.toValue $ trf trs "Show only amounts in {commodity}" [("commodity", sym)])
+              ! H.dataAttribute "cur" (H.toValue pat) $
+            H.toHtml sym
+    chosen = [sym | sym <- syms, regexEscape sym `elem` selected]
+    selectionText
+      | null chosen = trc trs "commodity" "All"
+      | otherwise = T.intercalate ", " chosen
+    syms = filter (not . T.null) $ Set.toAscList $ journalCommodities j
+    terms = searchTerms qparam
+    rest = map quoteIfSpaced $ filter (not . T.isPrefixOf "cur:") terms
+    restText = T.unwords rest
+    -- the alternatives of the search's cur: term(s), marking their links
+    selected = concatMap (splitAlternatives . T.drop 4) $ filter (T.isPrefixOf "cur:") terms
+    symlink pat = (route, ("q", T.unwords $ rest ++ [quoteIfSpaced $ "cur:" <> pat]) : kept)
+    alllink = (route, [("q", restText) | not (T.null restText)] ++ kept)
+    -- Split a cur: pattern on its unescaped |s, regex alternation.
+    splitAlternatives = map T.pack . go . T.unpack
+      where
+        go s = case break (== '|') s of
+          (a, '|':b)
+            | odd (length (takeWhile (== '\\') (reverse a))) ->
+                case go b of (c:cs) -> (a ++ "|" ++ c) : cs; [] -> [a ++ "|"]
+            | otherwise -> a : go b
+          (a, _) -> [a]
+
+-- | The parameters naming an account register's account: with its
+-- subaccounts, or with subs=0, without them. (An inacct: or inacctonly:
+-- term typed in the search becomes these; see App.normaliseUrlState.)
+accountParams :: Bool -> AccountName -> [(Text, Text)]
+accountParams = Anchor.accountParams
+
+-- | The query selecting an account register's account, with its
+-- subaccounts or without them (as inacct: and inacctonly: do).
+accountRegisterQuery :: (AccountName, Bool) -> Query
+accountRegisterQuery (a, subs) = Acct $ (if subs then accountNameToAccountRegex else accountNameToAccountOnlyRegex) a
+
 mixedAmountAsHtml :: MixedAmount -> HtmlUrl a
-mixedAmountAsHtml b _ =
-  for_ (lines (showMixedAmountWith noCostFmt{displayZeroCommodity=True} b)) $ \t -> do
+mixedAmountAsHtml = mixedAmountAsHtmlWith noCostFmt{displayZeroCommodity=True}
+
+-- | Like 'mixedAmountAsHtml' with a chosen display format, for a page
+-- showing amounts with their costs.
+mixedAmountAsHtmlWith :: AmountFormat -> MixedAmount -> HtmlUrl a
+mixedAmountAsHtmlWith fmt b _ = amountLinesHtml b $ lines (showMixedAmountWith fmt b)
+
+-- | An amount's lines, one per commodity, colored by the sign of the whole.
+amountLinesHtml :: MixedAmount -> [String] -> Html
+amountLinesHtml b ls =
+  for_ ls $ \t -> do
     H.span ! A.class_ c $ toHtml t
     H.br
   where
@@ -104,6 +545,60 @@
       Just True -> "negative amount"
       _ -> "positive amount"
 
+-- | How many commodities a balance shows in full. One of more shows
+-- fewer, then a line saying how many more there are.
+commoditiesShown :: Int
+commoditiesShown = 3
+
+-- | Like 'mixedAmountAsHtml', but showing at most 'commoditiesShown'
+-- commodities, then a line saying how many more there are: for the
+-- sidebar, where an account holding many commodities would otherwise
+-- be a wall of lines. Searching for a commodity (cur:) shows it alone.
+mixedAmountAsHtmlElided :: Translations -> MixedAmount -> HtmlUrl a
+mixedAmountAsHtmlElided trs b _ = do
+    amountLinesHtml b $ take commoditiesShown ls
+    when (length ls > commoditiesShown) $ moreCommoditiesHtml trs (length ls - commoditiesShown)
+  where
+    ls = lines (showMixedAmountWith noCostFmt{displayZeroCommodity=True} b)
+
+-- | Like 'mixedAmountAsHtml', for a register row's running balance, given
+-- the row's amount. A balance of more than 'commoditiesShown' commodities
+-- shows only those the amount has, at zero if the row closed one out,
+-- then a line saying how many more there are, so that what the row
+-- changed is not lost among the rest (which, row after row, would also be
+-- most of the page). Searching for a commodity (cur:) shows its balance
+-- alone.
+runningBalanceAsHtml :: Translations -> MixedAmount -> MixedAmount -> HtmlUrl a
+runningBalanceAsHtml trs amt bal render
+  | length bs <= commoditiesShown = mixedAmountAsHtml bal' render
+  | otherwise = do
+      amountLinesHtml (mixed shown) $ concatMap (\a -> lines $ showMixedAmountWith fmt $ mixed [a]) shown
+      when (hidden > 0) $ moreCommoditiesHtml trs hidden
+  where
+    fmt = noCostFmt{displayZeroCommodity=True}
+    bal' = mixedAmountStripCosts bal
+    -- its amounts as shown in full: the nonzero ones, or if none, every zero
+    bs = amountsPreservingZeros bal'
+    -- the commodities the row posted, including any netting to zero
+    cs = Set.fromList $ map acommodity $ amountsRaw amt
+    -- the balance in each, zeros included, each shown on its own so that
+    -- a zero beside the others is not dropped
+    shown = filter ((`Set.member` cs) . acommodity) $ amountsRaw bal'
+    hidden = length $ filter ((`Set.notMember` cs) . acommodity) bs
+
+-- | The line below an amount that shows fewer commodities than it has.
+moreCommoditiesHtml :: Translations -> Int -> Html
+moreCommoditiesHtml trs n = do
+  H.span ! A.class_ "more-commodities" $ toHtml $ moreCommodities trs n
+  H.br
+
+-- | The note saying how many more commodities there are than an amount,
+-- or the register chart, shows.
+moreCommodities :: Translations -> Int -> Text
+moreCommodities trs n =
+  -- TRANSLATORS: the note for a balance, or the register chart, showing fewer commodities than it has.
+  trf trs "… and {n} more" [("n", T.pack $ show n)]
+
 -- Make a slug to uniquely identify this transaction
 -- in hyperlinks (as far as possible).
 transactionFragment :: Journal -> Transaction -> String
@@ -114,19 +609,83 @@
     -- or 0 if this txn has no known file (eg a forecasted txn)
     tfileindex = maybe 0 (+1) $ elemIndex (sourceName $ fst tsourcepos) (journalFilePaths j)
 
+-- | The search's terms without its date terms, each quoted if it needs to be.
 removeDates :: Text -> [Text]
-removeDates =
-    map quoteIfSpaced .
-    filter (\term ->
-        not $ T.isPrefixOf "date:" term || T.isPrefixOf "date2:" term) .
-    Query.words'' queryprefixes
+removeDates = map quoteIfSpaced . Anchor.removeDates . searchTerms
 
-removeInacct :: Text -> [Text]
-removeInacct =
-    map quoteIfSpaced .
-    filter (\term ->
-        not $ T.isPrefixOf "inacct:" term || T.isPrefixOf "inacctonly:" term) .
-    Query.words'' queryprefixes
+-- | A search's date terms alone.
+onlyDates :: Text -> [Text]
+onlyDates = map quoteIfSpaced . filter (\t -> any (`T.isPrefixOf` t) ["date:", "date2:"]) . searchTerms
 
-replaceInacct :: Text -> Text -> Text
-replaceInacct q acct = T.unwords $ acct : removeInacct q
+-- | What 'normalisedSearch' moves out of a search: the search without
+-- it, and the options found.
+data MovedOptions = MovedOptions {
+    moSearch   :: Text,
+    moDepth    :: Maybe Int,
+    moInterval :: Maybe Interval,
+    moAccount  :: Maybe (AccountName, Bool)  -- ^ the account, and whether with subaccounts
+  } deriving (Eq, Show)
+
+-- | The report options in a search and in the old period parameter, which
+-- hledger-web keeps in their own parameters (see App.normaliseUrlState):
+-- the search without them, the depth of its last depth:N term, the
+-- interval of its last date:INTERVAL term, else of the period parameter,
+-- and the account of its first inacct: or inacctonly: term (the one an
+-- account register used). A date:INTERVAL term is reduced to its date
+-- span, if it has one, and the period parameter's date span joins the
+-- search as a date: term. A depth:REGEX=N term, limiting some accounts
+-- only, stays in the search. Nothing when there is nothing to move.
+normalisedSearch :: Day -> Text -> Maybe Text -> Maybe MovedOptions
+normalisedSearch today qparam mperiod
+  | isNothing mdepth && null termIntervals && isNothing macct && isNothing mperiod = Nothing
+  | otherwise = Just $ MovedOptions (T.unwords $ map quoteIfSpaced $ periodTerms ++ concatMap rest terms) mdepth mivl macct
+  where
+    terms = searchTerms qparam
+    mdepth = lastMay $ mapMaybe flatDepth terms
+    dateInterval t = T.stripPrefix "date:" t >>= splitPeriodExpr today
+    termIntervals = [i | t <- terms, Just (i, _) <- [dateInterval t]]
+    accountTerm t = (\a -> (a, False)) <$> T.stripPrefix "inacctonly:" t
+                <|> (\a -> (a, True))  <$> T.stripPrefix "inacct:" t
+    macct = listToMaybe $ mapMaybe accountTerm terms
+    rest t
+      | isJust (flatDepth t)           = []
+      | isJust (accountTerm t)         = []
+      | Just (_, sp) <- dateInterval t = ["date:" <> sp | not (T.null sp)]
+      | otherwise                      = [t]
+    -- A period that is not an interval and a span is a span only (or
+    -- unparseable, which its date: term then reports).
+    (periodInterval, periodTerms) = case mperiod of
+      Nothing -> (Nothing, [])
+      Just p  -> case splitPeriodExpr today p of
+        Just (i, sp) -> (Just i, ["date:" <> sp | not (T.null sp)])
+        Nothing      -> (Nothing, ["date:" <> p])
+    mivl = lastMay termIntervals <|> periodInterval
+
+-- | Split a period expression's reporting interval from its date span,
+-- keeping the span as written, eg "monthly in 2025" gives monthly and
+-- "in 2025". Nothing when it does not start with an interval, or what
+-- follows is not a date span.
+splitPeriodExpr :: Day -> Text -> Maybe (Interval, Text)
+splitPeriodExpr today s = do
+  (ivl, rest) <- either (const Nothing) Just $
+    parsewith ((,) <$> (skipNonNewlineSpaces *> reportingintervalp) <*> (skipNonNewlineSpaces *> getInput)) (T.toLower s)
+  let sp = T.strip rest
+  if T.null sp || either (const False) ((== NoInterval) . fst) (parsePeriodExpr today sp)
+    then Just (ivl, sp)
+    else Nothing
+
+-- | The depth a depth:N term limits all accounts to.
+flatDepth :: Text -> Maybe Int
+flatDepth t = do
+  n <- T.stripPrefix "depth:" t
+  if not (T.null n) && T.all isDigit n then readMay (T.unpack n) else Nothing
+
+-- | The search's terms; none for an empty search.
+searchTerms :: Text -> [Text]
+searchTerms = filter (not . T.null) . Query.words'' queryprefixes
+
+-- | The search for the journal page narrowed to a day: the day's date
+-- term in place of any date terms.
+journalDayQuery :: Text -> Day -> Text
+journalDayQuery qparam d =
+  T.unwords $ ("date:" <> showDate d) : removeDates qparam
diff --git a/config/favicon.ico b/config/favicon.ico
Binary files a/config/favicon.ico and b/config/favicon.ico differ
diff --git a/config/robots.txt b/config/robots.txt
--- a/config/robots.txt
+++ b/config/robots.txt
@@ -1,1 +1,2 @@
 User-agent: *
+Disallow: /
diff --git a/config/routes b/config/routes
--- a/config/routes
+++ b/config/routes
@@ -1,5 +1,6 @@
 /favicon.ico     FaviconR        GET
 /robots.txt      RobotsR         GET
+/chart.css       ChartCssR       GET
 /static          StaticR         WaiSubsite getStatic
 
 /openapi.json    OpenApiR        GET
@@ -7,6 +8,12 @@
 /                RootR           GET
 /journal         JournalR        GET
 /register        RegisterR       GET
+/balance         BalanceR        GET
+/holdings        HoldingsR       GET
+/balancesheet       BalancesheetR       GET
+/balancesheetequity BalancesheetequityR GET
+/incomestatement    IncomestatementR    GET
+/cashflow           CashflowR           GET
 /add             AddR            GET POST PUT
 
 /manage             ManageR         GET
diff --git a/config/settings.yml b/config/settings.yml
--- a/config/settings.yml
+++ b/config/settings.yml
@@ -3,7 +3,6 @@
   port: 3000
   approot: "http://localhost:3000"
   copyright: " "
-  #analytics: UA-YOURCODE
 
 Development:
   <<: *defaults
diff --git a/hledger-web.1 b/hledger-web.1
--- a/hledger-web.1
+++ b/hledger-web.1
@@ -1,5 +1,5 @@
 
-.TH "HLEDGER\-WEB" "1" "August 2026" "hledger-web-1.52.4 " "hledger User Manuals"
+.TH "HLEDGER\-WEB" "1" "December 2026" "hledger-web-2.0 " "hledger User Manuals"
 
 
 
@@ -17,7 +17,7 @@
 .PD
 \f[CR]hledger web [OPTS] [QUERY]\f[R]
 .SH DESCRIPTION
-This manual is for hledger\(aqs web interface, version 1.52.4.
+This manual is for hledger\(aqs web interface, version 2.0.
 See also the hledger manual for common concepts and file formats.
 .PP
 hledger is a robust, user\-friendly, cross\-platform set of programs for
@@ -26,20 +26,18 @@
 hledger is inspired by and largely compatible with ledger(1), and
 largely interconvertible with beancount(1).
 .PP
-hledger\-web is a simple web application for browsing and adding
-transactions.
-It provides a more user\-friendly UI than the hledger CLI or hledger\-ui
-TUI, showing more at once (accounts, the current account register,
-balance charts) and allowing history\-aware data entry, interactive
-searching, and bookmarking.
+hledger\-web is hledger\(aqs web interface.
+In a web browser, it shows the journal, account registers, and the main
+financial reports with their charts, and lets you search them, add
+transactions, and (if allowed) edit the journal files.
+It shows more at once than the hledger CLI or hledger\-ui (eg the
+accounts beside a register, or a report\(aqs chart above its table), and
+every view has its own url, so it can be bookmarked or shared.
 .PP
 hledger\-web also lets you share a journal with multiple users, or even
 the public web.
-There is no access control, so if you need that you should put it behind
-a suitable web proxy.
-As a small protection against data loss when running an unprotected
-instance, it writes a numbered backup of the main journal file (only) on
-every edit.
+There is no user authentication, so if you need that you should put it
+behind a suitable web proxy (see Permissions).
 .PP
 Like hledger, it reads from (and appends to) a journal file specified by
 the \f[CR]LEDGER_FILE\f[R] environment variable (defaulting to
@@ -53,8 +51,8 @@
 .IP \(bu 2
 \f[CR]\-\-serve\-browse\f[R] mode (the default): the app serves the web
 UI and JSON API, and opens your default web browser to show the app if
-possible, and exits automatically after two minutes of inactivity (with
-no requests received and no open browser windows viewing it).
+possible, and exits automatically once no browser window has shown it
+for fifteen minutes.
 .IP \(bu 2
 \f[CR]\-\-serve\f[R]: the app just serves the web UI and JSON API.
 .IP \(bu 2
@@ -63,42 +61,62 @@
 In all cases hledger\-web runs as a foreground process, logging requests
 to stdout.
 .SH OPTIONS
-hledger\-web provides the following options:
+hledger\-web provides the following command line options:
 .IP
 .EX
 Flags:
-     \-\-serve \-\-server       serve and log requests, don\(aqt browse or auto\-exit
-     \-\-serve\-api            like \-\-serve, but serve only the JSON web API,
-                            not the web UI
-     \-\-allow=view|add|edit  set the user\(aqs access level for changing data
-                            (default: \(gaadd\(ga). It also accepts \(gasandstorm\(ga for
-                            use on that platform (reads permissions from the
-                            \(gaX\-Sandstorm\-Permissions\(ga request header).
-     \-\-cors=ORIGIN          allow cross\-origin requests from the specified
-                            origin; setting ORIGIN to \(dq*\(dq allows requests from
-                            any origin
-     \-\-host=IPADDR          listen on this IP address (default: 127.0.0.1)
-     \-\-port=PORT            listen on this TCP port (default: 5000)
-     \-\-socket=SOCKET        listen on the given unix socket instead of an IP
-                            address and port (unix only; implies \-\-serve)
-     \-\-base\-url=BASEURL     set the base url (default: http://IPADDR:PORT)
-     \-\-test                 run hledger\-web\(aqs tests and exit. hspec test
-                            runner args may follow a \-\-, eg: hledger\-web \-\-test
-                            \-\-help
+     \-\-serve\-browse            server mode: serve the web UI and JSON API,
+                               and open a browser, and exit if inactive for 15m
+                               (default)
+     \-\-serve                   server mode: just serve the web UI and JSON
+                               API
+     \-\-serve\-api               server mode: just serve the JSON API
+     \-\-allow=view|add|edit     set the user\(aqs access level for changing data
+                               (default: \(gaadd\(ga on a local\-only address, \(gaview\(ga
+                               otherwise). It also accepts \(gasandstorm\(ga for that
+                               platform (reading from the
+                               \(gaX\-Sandstorm\-Permissions\(ga request header).
+     \-\-cors=ORIGIN             allow cross\-origin requests from the specified
+                               origin; setting ORIGIN to \(dq*\(dq allows requests
+                               from any origin
+     \-\-host=IPADDR             listen on this IP address (default: 127.0.0.1)
+     \-\-port=PORT               listen on this TCP port (default: 5000); 0
+                               means a free port chosen by the OS
+     \-\-socket=SOCKET           listen on the given unix socket instead of an
+                               IP address and port (only on unix)
+     \-\-base\-url=BASEURL        set the base url (default: http://IPADDR:PORT)
+     \-\-chart[=KIND,net,SCALE]  set the charts\(aq defaults, as the commands\(aq
+                               \-\-chart does. KIND: lay out the statements\(aq
+                               charts with each period\(aqs sections in one bar,
+                               above and below zero (diverging, the default),
+                               or side by side (grouped). net: show the net
+                               total lines by default (the N key toggles them,
+                               and the browser remembers that). SCALE: the
+                               amount that fills the charts (eg 1000 or 1000
+                               USD; one per commodity), for comparable charts.
+     \-\-lang=LANG               show the web UI in this language (en, de, es,
+                               ru, zh); or with auto, use each viewer\(aqs browser
+                               language if available, otherwise the server\(aqs.
+                               (Default: the browser\(aqs language if available,
+                               otherwise en.)
 .EE
 .PP
 By default hledger\-web listens only on IP address \f[CR]127.0.0.1\f[R],
-which be accessed only from the local machine.
+which can be accessed only from the local machine.
 .PP
 To allow access from elsewhere, use \f[CR]\-\-host\f[R] to specify an
-externally accessible address configured on this machine, The special
-address \f[CR]0.0.0.0\f[R] causes it to listen on all of this
-machine\(aqs addresses.
+externally accessible address configured on this machine.
+The special address \f[CR]0.0.0.0\f[R] causes it to listen on all of
+this machine\(aqs addresses.
 .PP
 Similarly, you can use \f[CR]\-\-port\f[R] to listen on a TCP port other
 than 5000.
 This is useful if you want to run multiple hledger\-web instances on a
 machine.
+\f[CR]\-\-port 0\f[R] makes the operating system choose a free port,
+which is reported in the startup message and in the default base url,
+and is where the browser is opened in \f[CR]\-\-serve\-browse\f[R] mode.
+This can be useful eg when scripting.
 .PP
 When \f[CR]\-\-socket\f[R] is used, hledger\-web creates and
 communicates via a socket file instead of a TCP port.
@@ -119,11 +137,15 @@
 hledger\-web also supports many of hledger\(aqs general options:
 .IP
 .EX
-General input/data transformation flags:
-  \-f \-\-file=[FMT:]FILE      Read data from FILE, or from stdin if FILE is \-,
-                            inferring format from extension or a FMT: prefix.
-                            Can be specified more than once. If not specified,
-                            reads from $LEDGER_FILE or $HOME/.hledger.journal.
+General input flags:
+  \-f \-\-file=[FMT:]FILE      Use this as the journal file (\- means stdin). If
+                            not specified, $LEDGER_FILE or \(ti/.hledger.journal
+                            will be used. If specified more than once, the
+                            files will be read in order. Each file\(aqs format
+                            (journal, csv, timeclock, timedot, rules..) is
+                            inferred from the file extension or a FMT: prefix.
+                            Some commands (add, import) write to the (first)
+                            file, and expect it to be in journal format.
      \-\-rules=RULESFILE      Use rules defined in this rules file for
                             converting subsequent CSV/SSV/TSV files. If not
                             specified, uses FILE.csv.rules for each FILE.csv.
@@ -138,27 +160,30 @@
                             will also be applied to these transactions. In
                             hledger\-ui, also make future\-dated transactions
                             visible at startup.
-  \-I \-\-ignore\-assertions    don\(aqt check balance assertions by default
-     \-\-txn\-balancing=...    how to check that transactions are balanced:
-                            \(aqold\(aq:   use global display precision
-                            \(aqexact\(aq: use transaction precision (default)
-     \-\-infer\-costs          infer conversion equity postings from costs
-     \-\-infer\-equity         infer costs from conversion equity postings
+     \-\-ignore\-assertions    don\(aqt check balance assertions by default
+     \-\-ignore\-lots          don\(aqt track lots: skip lot checks, inferred cost
+                            bases and gain postings
+  \-I                        shortcut for \-\-ignore\-assertions \-\-ignore\-lots
+     \-\-txn\-tolerance=...    how much imbalance to allow in transactions:
+                            \(aqentry\(aq:   \- the entry\(aqs precision (default)
+                            \(aqdisplay\(aq: \- display precision (legacy)
+     \-\-infer\-costs          infer costs from conversion equity postings
+     \-\-infer\-equity         infer conversion equity postings from costs
+     \-\-infer\-imbalance      add postings showing tolerated imbalances
      \-\-infer\-market\-prices  infer market prices from costs
      \-\-pivot=TAGNAME        use a different field or tag as account names
   \-s \-\-strict               do extra error checks (and override \-I)
-     \-\-verbose\-tags         add tags indicating generated/modified data
 
-General output/reporting flags (supported by some commands):
+General output flags (affecting some commands):
   \-b \-\-begin=DATE           include postings/transactions on/after this date
   \-e \-\-end=DATE             include postings/transactions before this date
                             (with a report interval, will be adjusted to
                             following subperiod end)
-  \-D \-\-daily                multiperiod report with 1 day interval
-  \-W \-\-weekly               multiperiod report with 1 week interval
-  \-M \-\-monthly              multiperiod report with 1 month interval
-  \-Q \-\-quarterly            multiperiod report with 1 quarter interval
-  \-Y \-\-yearly               multiperiod report with 1 year interval
+  \-D \-\-daily                set report interval: 1 day
+  \-W \-\-weekly               set report interval: 1 week
+  \-M \-\-monthly              set report interval: 1 month
+  \-Q \-\-quarterly            set report interval: 1 quarter
+  \-Y \-\-yearly               set report interval: 1 year
   \-p \-\-period=PERIODEXP     set begin date, end date, and/or report interval,
                             with more flexibility
      \-\-today=DATE           override today\(aqs date (affects relative dates)
@@ -173,65 +198,257 @@
      \-\-depth=DEPTHEXP       if a number (or \-NUM): show only top NUM levels
                             of accounts. If REGEXP=NUM, only apply limiting to
                             accounts matching the regular expression.
-  \-B \-\-cost                 show amounts converted to their cost/sale amount
-  \-V \-\-market               Show amounts converted to their value at period
-                            end(s) in their default valuation commodity.
-                            Equivalent to \-\-value=end.
-  \-X \-\-exchange=COMM        Show amounts converted to their value at period
-                            end(s) in the specified commodity.
-                            Equivalent to \-\-value=end,COMM.
-     \-\-value=WHEN[,COMM]    show amounts converted to their value on the
-                            specified date(s) in their default valuation
-                            commodity or a specified commodity. WHEN can be:
+  \-B \-\-cost                 convert amounts to their cost basis ({}), or else
+                            their cost/sale amount (\(at/\(at\(at)
+  \-V \-\-market               valuation mode: show amounts converted to market
+                            value at period end(s) in their default valuation
+                            commodity. Short for \-\-value=end.
+  \-X \-\-exchange=COMM        valuation mode: show amounts converted to market
+                            value at period end(s) in the specified commodity.
+                            Short for \-\-value=end,COMM.
+     \-\-value=WHEN[,COMM]    valuation mode: show amounts converted to market
+                            value on the specified date(s) in their default
+                            valuation commodity or a specified commodity. WHEN
+                            can be:
                             \(aqthen\(aq:     value on transaction dates
                             \(aqend\(aq:      value at period end(s)
                             \(aqnow\(aq:      value today
                             YYYY\-MM\-DD: value on given date
+                            \(aqcost\(aq:     cost basis, or else transacted cost
+                            (same as \-B)
+                            \(aqtransacted\(aq: transacted cost/sale amount (\(at/\(at\(at)
+                            only
+                            COMM may be written in double quotes; \(aq\(dq\(dq\(aq or an
+                            empty COMM means the no\-symbol commodity.
+     \-\-lots                 show lot subaccounts and other lot details
   \-c \-\-commodity\-style=S    Override a commodity\(aqs display style.
                             Eg: \-c \(aq.\(aq or \-c \(aq1.000,00 EUR\(aq
-     \-\-pretty[=YN]          Use box\-drawing characters in text output? Can be
-                            \(aqy\(aq/\(aqyes\(aq or \(aqn\(aq/\(aqno\(aq.
-                            If YN is specified, the equals is required.
+     \-\-pretty[=YN]          Use box\-drawing characters in text output? The
+                            optional \(aqy\(aq/\(aqyes\(aq or \(aqn\(aq/\(aqno\(aq arg requires =.
+     \-\-title=T              set or customise a report title
+     \-\-subreport\-titles=TS  customise subreport headings in compound reports
+                            (|\-separated)
+     \-\-period\-titles=OPT    customise headings in periodic reports:
+                            \(aqcompact\(aq: readable period names when possible
+                            \(aqdates\(aq:   exact dates/date ranges always
 
 General help flags:
-  \-h \-\-help                 show command line help
-     \-\-tldr                 show command examples with tldr
-     \-\-info                 show the manual with info
-     \-\-man                  show the manual with man
+  \-?                        show the hledger quick reference
+  \-h \-\-help                 show this command\(aqs usage help
+     \-\-info                 show this command\(aqs manual with info
+     \-\-man                  show this command\(aqs manual with man
+     \-\-webman               show this command\(aqs manual on the web
+     \-\-examples             show examples for this command
      \-\-version              show version information
+     \-\-test[=PATTERN]       run built\-in tests (those matching PATTERN) and
+                            exit
+     \-\-write\-lang=LANG      write LANG\(aqs PO file to the config directory, for
+                            editing translations, and exit
      \-\-debug=[1\-9]          show this much debug output (default: 1)
      \-\-pager=YN             use a pager when needed ? y/yes (default) or n/no
      \-\-color=YNA \-\-colour   use ANSI color ? y/yes, n/no, or auto (default)
 .EE
 .PP
+Some of these can be adjusted while hledger\-web is running, in the web
+UI\(aqs Options panel.
+.PP
 hledger\-web shows accounts with zero balances by default (like
-\f[CR]hledger\-ui\f[R], and unlike \f[CR]hledger\f[R]).
-Using the \f[CR]\-E/\-\-empty\f[R] flag will reverse this behaviour.
-If you see accounts which appear to have a zero balance, but cannot be
-hidden with \f[CR]\-E\f[R], it\(aqs because they have a mixed\-cost
-balance, which looks like zero when costs are hidden.
-(hledger\-web does not show costs.)
+\f[CR]hledger\-ui\f[R], and unlike \f[CR]hledger\f[R]);
+\f[CR]\-E/\-\-empty\f[R] starts it with them hidden instead.
+In the web UI, the Zero balances option or the \f[CR]z\f[R] key shows or
+hides them.
+(The holdings page differs: its closed positions are hidden by default,
+as in the \f[CR]holdings\f[R] command; \f[CR]\-E\f[R] starts it with
+them shown, and \f[CR]z\f[R] there shows or hides them.)
 .PP
-Reporting options and/or query arguments can be used to set an initial
-query, which although not shown in the UI, will restrict the data shown
-(in addition to any search query entered in the UI).
+Report options and a query given at startup set the view hledger\-web
+opens with, by putting them in its url (see URL parameters).
+Eg \f[CR]hledger\-web \-V \-M\f[R] opens
+\f[CR]/balancesheet?interval=monthly&value=end\f[R], and
+\f[CR]hledger\-web \-\-cleared \-3 assets\f[R] opens
+\f[CR]/balancesheet?q=assets status:*&depth=3\f[R].
+They are only a starting point: they can be changed in the web UI, and
+they don\(aqt affect other urls or the JSON API.
+Report options that hledger\-web has no equivalent for are ignored.
 .PP
+Note, a startup query doesn\(aqt restrict what hledger\-web serves; to
+do that, give it a file holding only the entries to serve (eg one
+written by \f[CR]hledger print QUERY\f[R]).
+.PP
 If you use the bash shell, you can auto\-complete flags by pressing TAB
 in the command line.
 If this is not working see Install > Shell completions.
-.SH PERMISSIONS
-By default, hledger\-web allows anyone who can reach it to view the
-journal and to add new transactions, but not to change existing data.
+.SH WEB UI
+hledger\-web\(aqs main views are:
+.IP \(bu 2
+the \f[B]journal view\f[R], showing journal entries, newest first, with
+their postings
+.IP \(bu 2
+the \f[B]report views\f[R], described below: the balance sheet, income
+statement, cashflow statement (and holdings, for journals using lots),
+and All accounts report
+.IP \(bu 2
+a \f[B]register view\f[R] for each account, reached by clicking an
+account name, showing the transactions affecting that account (and its
+subaccounts), with a running balance and a balance chart.
 .PP
-You can restrict who can reach it, by
+Every page has, from the top: links to the journal and the reports, the
+search form, the options, and then the view itself.
+The options are hidden until you open them (click Options, or press
+\f[CR]o\f[R]); while hidden, they list the ones in effect, eg
+\(dqMonthly · Depth 2 · Tree\(dq.
+.PP
+The journal and register show the newest 1000 matching transactions,
+with links to older and newer pages.
+When the transactions span more than one year, the options include a row
+of years, to narrow the view to one year; shift\-click a second year to
+select a range of years.
+.PP
+The register\(aqs chart shows the running balance over the page\(aqs
+transactions.
+With several commodities, use the legend, or the \f[CR][\f[R] and
+\f[CR]]\f[R] keys, to choose the one charted.
+Click a point to go to its transaction, or drag across the chart to see
+the transactions of those dates.
+The register\(aqs Costs option shows the costs recorded with its
+amounts.
+.PP
+The \f[B]sidebar\f[R] lists every account, and optionally their balances
+(parent balances include subaccounts).
+The search doesn\(aqt change it, except that its dates set the
+balances\(aq date.
+The balances are hidden at first, since on a large journal they take
+much of each page\(aqs time; click the \(dqBalances\(dq heading above
+the accounts to show them, or to hide them again.
+These are historical balances, as of the end of the report period set by
+date:, otherwise the latest (the heading shows the date).
+While the balances are hidden, all accounts are listed, even with Zero
+balances: Hidden.
+It is always a tree, with carets that fold and open each group, whether
+the Accounts option is List or Tree.
+The − and + above it fold or open a level of the whole tree, without
+changing the page; its depth is its own, apart from the page\(aqs depth
+limit.
+The browser remembers the sidebar\(aqs depth and the groups you open or
+close (until the next − or +).
+The button at the top left (or the \f[CR]s\f[R] key) shows or hides the
+sidebar, and it stays the way you left it from page to page.
+On a narrow screen, it slides the sidebar in or out.
+.PP
+Click an account name to see its register, with the search, or an amount
+to see the transactions it is made of.
+In the journal and register, click a date to see that day\(aqs journal
+entries.
+.PP
+The \f[B]search form\f[R] filters every view with hledger\(aqs query
+syntax, eg \f[CR]expenses date:thismonth\f[R]; the help dialog
+summarises the query types.
+The search and the options are part of the page\(aqs url (see URL
+parameters).
+.PP
+The \f[B]add form\f[R] (press \f[CR]a\f[R], or click \(dqAdd a
+transaction\(dq in the journal view) adds a transaction to the main
+journal file, if the access level allows it, and if the journal would
+still be readable with it added (see Editing, uploading, downloading).
+It autocompletes account names and descriptions from your existing
+entries.
+.PP
+The \f[B]help dialog\f[R] (press \f[CR]?\f[R], or click the question
+mark button) lists these keyboard shortcuts, which work when you are not
+typing in a field:
 .IP \(bu 2
+\f[CR]h\f[R] or \f[CR]?\f[R] \- show or hide the help dialog
+.IP \(bu 2
+\f[CR]g\f[R] \- go to another page: shows a menu of the pages, each with
+its key; then \f[CR]j\f[R] journal, \f[CR]b\f[R] balance sheet,
+\f[CR]i\f[R] income statement, \f[CR]c\f[R] cashflow statement,
+\f[CR]h\f[R] holdings (for journals using lots), \f[CR]a\f[R] all
+accounts (escape to cancel)
+.IP \(bu 2
+\f[CR]n\f[R] / \f[CR]p\f[R] \- go to the next / previous page, in the
+\f[CR]g\f[R] menu\(aqs order, wrapping round
+.IP \(bu 2
+\f[CR]a\f[R] \- add a transaction (escape to cancel)
+.IP \(bu 2
+\f[CR]s\f[R] \- show or hide the sidebar
+.IP \(bu 2
+shift with \f[CR]1\f[R]\-\f[CR]9\f[R] \- fold or open the sidebar\(aqs
+accounts to that depth, as its − and + do (by the digit keys\(aq place,
+whatever the layout; except where shift with one types a character that
+is a shortcut itself, eg a digit on AZERTY keyboards, or \f[CR]/\f[R] on
+German ones)
+.IP \(bu 2
+\f[CR]b\f[R] \- show or hide the sidebar\(aqs balances, as its Balances
+heading does (while the sidebar shows)
+.IP \(bu 2
+\f[CR]o\f[R] \- show or hide the report options
+.IP \(bu 2
+\f[CR]c\f[R] \- show or hide the report\(aqs chart (on pages with one)
+.IP \(bu 2
+\f[CR][\f[R] / \f[CR]]\f[R] \- chart the previous / next commodity (on
+pages whose chart has several, wrapping round)
+.IP \(bu 2
+\f[CR]N\f[R] \- show or hide the chart\(aqs net total line (on pages
+whose chart has one)
+.IP \(bu 2
+\f[CR]d\f[R] \- show or hide the report\(aqs data, its table (on pages
+with a chart)
+.IP \(bu 2
+\f[CR]f\f[R] \- full window: show only the report\(aqs heading and data,
+or everything (\f[CR]s\f[R], \f[CR]o\f[R] and \f[CR]/\f[R] leave it,
+showing what they ask for)
+.IP \(bu 2
+\f[CR]z\f[R] \- show or hide accounts with zero balances (on the
+holdings page: closed positions)
+.IP \(bu 2
+\f[CR]t\f[R] \- show accounts as a tree, or a list
+.IP \(bu 2
+\f[CR]H\f[R] \- show ending balances, or balance changes
+.IP \(bu 2
+\f[CR]L\f[R] \- show or hide lot detail
+.IP \(bu 2
+\f[CR]V\f[R] \- show amounts at market value, or as recorded
+.IP \(bu 2
+\f[CR]B\f[R] \- show amounts at cost, or as recorded
+.IP \(bu 2
+\f[CR]R\f[R] \- show only real postings, or all
+.IP \(bu 2
+\f[CR]U\f[R], \f[CR]P\f[R], \f[CR]C\f[R] \- show only unmarked, pending,
+or cleared transactions, or all
+.IP \(bu 2
+\f[CR]S\f[R] \- sort by amount, or by account
+.IP \(bu 2
+\f[CR]T\f[R], \f[CR]A\f[R] \- add or remove the row total and average
+columns (multi\-period reports)
+.IP \(bu 2
+\f[CR]D\f[R], \f[CR]W\f[R], \f[CR]M\f[R], \f[CR]Q\f[R], \f[CR]Y\f[R] \-
+set the report interval (daily, weekly, monthly, quarterly, yearly);
+pressed again, remove it
+.IP \(bu 2
+\f[CR]0\f[R]\-\f[CR]9\f[R], \f[CR]\-\f[R], \f[CR]+\f[R] \- set or adjust
+the account depth limit (\f[CR]\-\f[R] and \f[CR]+\f[R] step between 0
+and the deepest)
+.IP \(bu 2
+\f[CR]/\f[R] \- focus the search form, ready to add a term (escape to
+leave it)
+.IP \(bu 2
+\f[CR]Delete\f[R] or \f[CR]Backspace\f[R] \- clear the search, as its
+clear button does
+.PP
+The pages are light or dark, following your OS or browser\(aqs color
+scheme setting, and switch when it changes.
+.PP
+Editing, uploading and downloading journal files is described below.
+.SH PERMISSIONS
+You can restrict who can access hledger\-web by
+.IP \(bu 2
 setting the IP address it listens on (see \f[CR]\-\-host\f[R] above).
 By default it listens on 127.0.0.1, accessible to users on the local
 machine only.
 .IP \(bu 2
-putting it behind an authenticating proxy, such as caddy or apache
+or by putting it behind an authenticating proxy, such as caddy or apache
 .IP \(bu 2
-putting it behind a firewall
+or by putting it behind a firewall.
 .PP
 And you can restrict what the users reaching it can do, by specifying
 the \f[CR]\-\-allow=ACCESSLEVEL\f[R] option at startup.
@@ -249,28 +466,301 @@
 whichever of \f[CR]view\f[R], \f[CR]add\f[R], or \f[CR]edit\f[R] are
 specified in the \f[CR]X\-Sandstorm\-Permissions\f[R] HTTP header
 .PP
-The default access level is \f[CR]add\f[R].
+The default access level is \f[CR]add\f[R] when listening on a
+local\-only address (\f[CR]127.0.0.1\f[R], \f[CR]::1\f[R],
+\f[CR]localhost\f[R], or a unix socket), and \f[CR]view\f[R] otherwise.
+To allow more than the default access, start it with an explicit
+\f[CR]\-\-allow=add\f[R] or \f[CR]\-\-allow=edit\f[R] option.
 .SH EDITING, UPLOADING, DOWNLOADING
-If you enable the \f[CR]manage\f[R] capability mentioned above,
-you\(aqll see a new \(dqspanner\(dq button to the right of the search
-form.
+If you start hledger\-web with \f[CR]\-\-allow=edit\f[R], you\(aqll see
+a new \(dqspanner\(dq button to the right of the search form.
 Clicking this will let you edit, upload, or download the journal file or
 any files it includes.
 .PP
 Note, unlike any other hledger command, in this mode you (or any
 visitor) can alter or wipe the data files.
-.PP
-Normally whenever a file is changed in this way, hledger\-web saves a
-numbered backup (assuming file permissions allow it, the disk is not
-full, etc.)
+Before saving an edited or uploaded file, hledger\-web saves a numbered
+backup of it (eg \f[CR]main.journal.1\f[R], then
+\f[CR]main.journal.2\f[R]); if the backup can\(aqt be written, the file
+is not changed.
+(Adding a transaction appends it to the main journal file without making
+a backup.)
 hledger\-web is not aware of version control systems, currently; if you
-use one, you\(aqll have to arrange to commit the changes yourself (eg
-with a cron job or a file watcher like entr).
+use one, you\(aqll have to arrange to commit the changes yourself.
 .PP
-Changes which would leave the journal file(s) unparseable or non\-valid
-(eg with failing balance assertions) are prevented.
-(Probably.
-This needs re\-testing.)
+Changes which would leave the journal unreadable are refused, and the
+file is not changed.
+This applies to edits, uploads and added transactions.
+Each change is checked as the next read of the journal will check it, in
+the context of all the journal\(aqs files and with the options
+hledger\-web was started with: so transactions must balance, balance
+assertions must pass (unless started with \f[CR]\-I\f[R]), lots must be
+valid, and with \f[CR]\-\-strict\f[R], the strict checks must pass too.
+.SH REPORTS
+Besides the journal and the account registers, hledger\-web shows these
+reports.
+The sidebar and the links at the top of every page lead to each of them,
+and so does the \f[CR]g\f[R] key followed by the first letter of the
+report\(aqs name:
+.IP \(bu 2
+\f[B]Balance sheet\f[R] (\f[CR]b\f[R], \f[CR]/balancesheet\f[R]):
+assets, liabilities and net worth, like the balancesheet command.
+Its Equity option adds an equity section, like balancesheetequity.
+.IP \(bu 2
+\f[B]Income statement\f[R] (\f[CR]i\f[R], \f[CR]/incomestatement\f[R]):
+revenues, expenses and net income, like incomestatement.
+.IP \(bu 2
+\f[B]Cashflow\f[R] (\f[CR]c\f[R], \f[CR]/cashflow\f[R]): changes in cash
+accounts, like cashflow.
+.IP \(bu 2
+\f[B]Holdings\f[R] (\f[CR]h\f[R], \f[CR]/holdings\f[R]): investments and
+their performance, like holdings.
+Shown only for journals that use lots; see below.
+.IP \(bu 2
+\f[B]All accounts\f[R] (\f[CR]a\f[R], \f[CR]/balance\f[R]): all
+accounts, or those you search for, like balance.
+.PP
+Each report shows a chart and then a table (by default; both can be
+toggled).
+Click any amount to see the transactions it is made of.
+.SS Options
+A report\(aqs options (click Options, or press \f[CR]o\f[R]) change what
+it shows.
+These are similar to hledger\(aqs command\-line options and
+hledger\-ui\(aqs keys.
+The main ones, with their keyboard shortcuts:
+.IP \(bu 2
+\f[B]Interval\f[R] (\f[CR]D\f[R], \f[CR]W\f[R], \f[CR]M\f[R],
+\f[CR]Q\f[R], \f[CR]Y\f[R]): one column for the whole period, or one per
+day, week, month, quarter or year (see Report intervals).
+Until you choose one, the reports pick an interval to suit the period
+shown (except holdings, whose interval is its own; see Holdings):
+monthly for up to two years, quarterly for up to six, yearly beyond.
+Click a column\(aqs heading to see the report for just its dates.
+.IP \(bu 2
+\f[B]Show\f[R] (\f[CR]H\f[R]): balance changes in each period, or ending
+balances (which include everything before the period).
+The balance sheet shows ending balances by default and the other reports
+show changes, as their commands do; the report\(aqs heading says which
+it is showing.
+.IP \(bu 2
+\f[B]Depth\f[R] (\f[CR]0\f[R]\-\f[CR]9\f[R], \f[CR]\-\f[R],
+\f[CR]+\f[R]): how many levels of accounts to show (see Depth).
+Depth 0 shows only the totals.
+Until you choose one, the depth is 1, the top\-level accounts.
+The − and + beside the table\(aqs Account heading step it too.
+In tree mode they fold or open a level of the whole tree.
+(The sidebar has a depth of its own; see above.)
+.IP \(bu 2
+\f[B]Accounts\f[R] (\f[CR]t\f[R]): a list, or a tree with subtotals; the
+List and Tree links beside the table\(aqs Account heading switch too.
+In a tree, the accounts below the depth limit are folded, and their
+carets open them in place (at depth 0, all of them, under each
+section\(aqs total).
+.IP \(bu 2
+\f[B]Amounts\f[R] (\f[CR]B\f[R], \f[CR]V\f[R]): as recorded, at cost, or
+at market value at the end of each period (see Cost reporting and Value
+reporting).
+.IP \(bu 2
+\f[B]Zero balances\f[R] (\f[CR]z\f[R]): hide or show accounts whose
+balance is zero.
+(On the holdings page, \f[CR]z\f[R] toggles Closed positions instead;
+use this option\(aqs links there.)
+.IP \(bu 2
+\f[B]Equity\f[R] (balance sheet only): hide or show the equity section.
+The browser remembers this choice for each hledger\-web server.
+.IP \(bu 2
+\f[B]Status\f[R] (\f[CR]U\f[R], \f[CR]P\f[R], \f[CR]C\f[R]),
+\f[B]Postings\f[R] (\f[CR]R\f[R]), account types, and commodities: show
+only transactions with that status, only real postings, or only some
+account types or commodities.
+These rows edit the search, adding a term like \f[CR]status:*\f[R] or
+\f[CR]type:A\f[R].
+Shift\-click selects several types or commodities.
+.PP
+The options you choose stay in effect as you move to other pages, except
+Show, which each report sets to its own default.
+On the journal and register, the report options are shown muted, but are
+kept.
+.PP
+The search form filters reports as it does the other pages, and its
+\f[CR]date:\f[R] terms set the report\(aqs dates.
+An interval or depth typed in the search, like \f[CR]date:monthly\f[R]
+or \f[CR]depth:2\f[R], moves into the options when the page reloads.
+A depth limit for some accounts only, like \f[CR]depth:assets=3\f[R],
+stays in the search.
+.PP
+The options are also URL parameters, so you can bookmark a report with
+them.
+.PP
+(For more detail, see the hledger manual, eg CONCEPTS.)
+.SS Charts
+A report\(aqs chart is the one its command draws with
+\f[CR]\-\-chart\f[R]: eg a bar per account, or with an interval, each
+account over time, and for the statements, each section and the net
+total.
+In tree mode it shows the accounts down to the depth limit.
+With several commodities, use the legend, or the \f[CR][\f[R] and
+\f[CR]]\f[R] keys, to choose the one charted.
+The Balance page\(aqs and statements\(aq charts stack each period\(aqs
+accounts (or sections) in one bar, above and below zero; the Chart row
+in Options (or \f[CR]\-\-chart=grouped\f[R] at startup) shows a bar per
+account type (or section), side by side, instead (on the Balance page
+with no interval, for the whole period, as
+\f[CR]balance \-\-chart=grouped\f[R] does).
+\f[CR]\-\-chart\f[R] at startup takes the same value as the commands\(aq
+\f[CR]\-\-chart\f[R]; its SCALE amounts fix the scales of the report and
+register charts, so that they can be compared.
+Hover over a bar or a line (or on a touch screen, tap it) to see its
+period (or date, or account), its series and its amount.
+Charts are drawn as wide as the page shows them, and redrawn when that
+changes, eg when you hide or show the sidebar or resize the window.
+.PP
+The \f[CR]c\f[R] key hides or shows the chart, and \f[CR]d\f[R] the
+table (the report\(aqs data).
+You can also click the Chart and Data buttons at their top right
+corners, whose carets show whether they are shown.
+The \f[CR]N\f[R] key shows or hides the net total line (or marks), eg a
+statement\(aqs net, or holdings\(aq value or net gain; this is hidden at
+first, leaving the bars it totals (or with \f[CR]\-\-chart=net\f[R] at
+startup, shown at first).
+The browser remembers this for each hledger\-web server, and once you
+have chosen with \f[CR]N\f[R], your choice wins over
+\f[CR]\-\-chart=net\f[R].
+.SS From a report to its transactions
+Click an amount to see its account\(aqs register for that period: the
+transactions the amount is made of.
+An ending balance\(aqs register starts with the balance brought forward,
+so its final running balance is that amount.
+A section\(aqs total shows the register of all the section\(aqs
+accounts.
+An amount shown at cost or market value leads to a register showing its
+amounts the same way.
+.PP
+Some things can make the register look different from the report:
+.IP \(bu 2
+The statements show liabilities, equity and revenues as positive
+amounts, as their commands do, so their registers show the same amounts
+negated.
+The amount\(aqs tooltip says so.
+.IP \(bu 2
+When a posting has a date of its own, the report counts it on that date,
+but the register lists its whole transaction, on the transaction\(aqs
+date.
+.SS Holdings
+The holdings report shows one row for each commodity held in each
+account, with its cost basis, value and gains.
+Its chart has a bar for each one, showing its cost basis and unrealised
+gain or loss.
+Its own options can show:
+.IP \(bu 2
+each lot separately (\f[B]Lots\f[R], \f[CR]L\f[R]),
+.IP \(bu 2
+fully disposed positions and their realised gains (\f[B]Closed
+positions\f[R], \f[CR]z\f[R]),
+.IP \(bu 2
+all values in the market valuation commodity (\f[B]Values\f[R]).
+.PP
+Closed positions are hidden by default, as in the \f[CR]holdings\f[R]
+command, but the totals\(aq RGain and XIRR always include them; a note
+below the table says how many are hidden, with a link to show them.
+.PP
+Its depth limit doesn\(aqt fold accounts: as on the command line, it
+merges the deeper accounts\(aq positions, by commodity, into the
+accounts at the limit.
+.PP
+With an \f[B]Interval\f[R] chosen (it picks none by itself), it shows
+how your holdings changed, like holdings with a report interval: a row
+for each period\(aqs end, with the totals of all the holdings then, and
+a bar for each in the chart.
+Each row\(aqs date links to the holdings on that date.
+This page\(aqs interval is its own, since it makes a different report
+here: choosing one doesn\(aqt change the other reports\(aq interval, nor
+theirs this page\(aqs, and an interval given at startup (eg
+\f[CR]\-M\f[R]) is theirs.
+Its \f[B]Gains\f[R] option chooses what the gain columns cover: each
+period, the time since the report\(aqs start date, or the time since
+acquisition (the default).
+With the first two, the chart shows those gains: realised, and
+unrealised (hatched).
+\f[CR]H\f[R] toggles between gains since acquisition and gains in each
+period.
+.PP
+On journals that use lots, every page also has a Lots option, showing
+lot subaccounts and per\-lot postings.
+.SH URL PARAMETERS
+A page\(aqs url includes its search and options, so a bookmark or a
+shared link shows the same view.
+You can also write these urls yourself, eg
+\f[CR]/balancesheet?interval=monthly&depth=2\f[R] or
+\f[CR]/register?account=assets:bank\f[R].
+These are the parameters, most corresponding to hledger options:
+.IP \(bu 2
+\f[CR]q\f[R] \- the search
+.IP \(bu 2
+\f[CR]account\f[R] \- the account whose register to show (with its
+subaccounts, unless \f[CR]subs=0\f[R])
+.IP \(bu 2
+\f[CR]page\f[R] \- which page of transactions to show, in the journal
+and register (1 is the newest)
+.IP \(bu 2
+\f[CR]interval\f[R] \- \f[CR]daily\f[R], \f[CR]weekly\f[R],
+\f[CR]monthly\f[R], \f[CR]quarterly\f[R] or \f[CR]yearly\f[R] (like
+\f[CR]\-D\f[R], \f[CR]\-W\f[R], \f[CR]\-M\f[R], \f[CR]\-Q\f[R],
+\f[CR]\-Y\f[R]), or \f[CR]none\f[R] for one column; without it the
+reports pick one
+.IP \(bu 2
+\f[CR]hinterval\f[R] \- the holdings page\(aqs own interval, in the same
+words; without it, none
+.IP \(bu 2
+\f[CR]depth\f[R] \- a number (like \f[CR]\-\-depth\f[R]), or
+\f[CR]all\f[R] for no limit; without it, 1
+.IP \(bu 2
+\f[CR]accum\f[R] \- \f[CR]change\f[R], \f[CR]historical\f[R] or
+\f[CR]cumulative\f[R] (like \f[CR]\-\-change\f[R], \f[CR]\-H\f[R],
+\f[CR]\-\-cumulative\f[R]); on the holdings page, with an interval, what
+the gains cover
+.IP \(bu 2
+\f[CR]value\f[R] \- \f[CR]none\f[R], \f[CR]cost\f[R], or
+\f[CR]then\f[R], \f[CR]end\f[R], \f[CR]now\f[R] or a date, optionally
+followed by \f[CR],COMMODITY\f[R] (like \f[CR]\-\-value\f[R])
+.IP \(bu 2
+\f[CR]infer\f[R] \- \f[CR]1\f[R] to infer market prices from transaction
+costs too (like \f[CR]\-\-infer\-market\-prices\f[R])
+.IP \(bu 2
+\f[CR]empty\f[R] \- \f[CR]1\f[R] to show zero balances, \f[CR]0\f[R] to
+hide them (like \f[CR]\-E\f[R])
+.IP \(bu 2
+\f[CR]list\f[R] \- \f[CR]tree\f[R] or \f[CR]flat\f[R] (like
+\f[CR]\-\-tree\f[R], \f[CR]\-\-flat\f[R])
+.IP \(bu 2
+\f[CR]sort\f[R] \- \f[CR]amount\f[R] (like \f[CR]\-S\f[R])
+.IP \(bu 2
+\f[CR]total\f[R], \f[CR]avg\f[R], \f[CR]pct\f[R] \- \f[CR]1\f[R] to add
+totals, averages, or show percentages (like \f[CR]\-T\f[R],
+\f[CR]\-A\f[R], \f[CR]\-%\f[R])
+.IP \(bu 2
+\f[CR]calc\f[R] \- \f[CR]valuechange\f[R], \f[CR]gain\f[R] or
+\f[CR]count\f[R] (like \f[CR]\-\-valuechange\f[R], \f[CR]\-\-gain\f[R],
+\f[CR]\-\-count\f[R])
+.IP \(bu 2
+\f[CR]date2\f[R] \- \f[CR]1\f[R] to use secondary dates (like
+\f[CR]\-\-date2\f[R])
+.IP \(bu 2
+\f[CR]costs\f[R] \- \f[CR]1\f[R] to show costs, in the register
+.IP \(bu 2
+\f[CR]equity\f[R] \- \f[CR]1\f[R] or \f[CR]0\f[R], on the balance sheet
+(the old \f[CR]/balancesheetequity\f[R] address leads to
+\f[CR]equity=1\f[R])
+.IP \(bu 2
+\f[CR]lots\f[R] \- \f[CR]1\f[R] to show lots (like \f[CR]\-\-lots\f[R])
+.IP \(bu 2
+\f[CR]closed\f[R] \- \f[CR]1\f[R], on the holdings page, to show closed
+positions, \f[CR]0\f[R] to hide them
+.IP \(bu 2
+\f[CR]chart\f[R] \- \f[CR]grouped\f[R], on the Balance and statement
+pages, to chart each period\(aqs account types (or sections) side by
+side (like \f[CR]\-\-chart=grouped\f[R])
 .SH RELOADING
 hledger\-web detects changes made to the files by other means (eg if you
 edit it directly, outside of hledger\-web), and it will show the new
@@ -278,8 +768,8 @@
 If a change makes a file unparseable, hledger\-web will display an error
 message until the file has been fixed.
 .PP
-(Note: if you are viewing files mounted from another machine, make sure
-that both machine clocks are roughly in step.)
+(If you are viewing files mounted from another machine, make sure that
+both machines have roughly the same idea of what time it is.)
 .SH JSON API
 In addition to the web UI, hledger\-web also serves a JSON API that can
 be used to get data or add new transactions.
@@ -302,6 +792,7 @@
 /commodities
 /accounts
 /accounttransactions/ACCOUNTNAME
+/openapi.json
 .EE
 .PP
 Eg, all account names in the journal (similar to the accounts command).
@@ -309,7 +800,7 @@
 prettify it):
 .IP
 .EX
-$ curl \-s http://127.0.0.1:5000/accountnames | python \-m json.tool
+$ curl \-s http://127.0.0.1:5000/accountnames | python3 \-m json.tool
 [
     \(dqassets\(dq,
     \(dqassets:bank\(dq,
@@ -330,7 +821,7 @@
 Or all transactions:
 .IP
 .EX
-$ curl \-s http://127.0.0.1:5000/transactions | python \-m json.tool
+$ curl \-s http://127.0.0.1:5000/transactions | python3 \-m json.tool
 [
     {
         \(dqtcode\(dq: \(dq\(dq,
@@ -345,8 +836,8 @@
                 \(dqpamount\(dq: [
                     {
                         \(dqacommodity\(dq: \(dq$\(dq,
-                        \(dqaismultiplier\(dq: false,
-                        \(dqaprice\(dq: null,
+                        \(dqacost\(dq: null,
+                        \(dqacostbasis\(dq: null,
 \&...
 .EE
 .PP
@@ -354,132 +845,135 @@
 what the fields mean, see the Hledger.Data.Json haddock docs and click
 on the various data types, eg Transaction.
 And for a higher level understanding, see the journal docs.
-There is also a basic OpenAPI specification.
+There is also a basic OpenAPI specification, also served at
+\f[CR]/openapi.json\f[R].
 .PP
-In some cases there is outer JSON corresponding to a \(dqReport\(dq
-type.
-To understand that, go to the Hledger.Web.Handler.MiscR haddock and look
-at the source for the appropriate handler to see what it returns.
-Eg for \f[CR]/accounttransactions\f[R] it\(aqs getAccounttransactionsR,
-returning a \(dq\f[CR]accountTransactionsReport ...\f[R]\(dq.
-Looking up the haddock for that we can see that /accounttransactions
-returns an AccountTransactionsReport, which consists of a report title
-and a list of AccountTransactionsReportItem (etc).
+Some routes return a report type wrapping the data; eg
+\f[CR]/accounttransactions\f[R] returns an AccountTransactionsReport, a
+report title and a list of items.
+The handlers in Hledger.Web.Handler.MiscR show what each route returns.
 .PP
 You can add a new transaction to the journal with a PUT request to
-\f[CR]/add\f[R], if hledger\-web was started with the \f[CR]add\f[R]
-capability (enabled by default).
+\f[CR]/add\f[R], if hledger\-web was started with
+\f[CR]\-\-allow=add\f[R] (the default when listening on a local\-only
+address).
 The payload must be the full, exact JSON representation of a hledger
 transaction (partial data won\(aqt do).
+The journal must still be readable with the transaction added, with
+hledger\-web\(aqs startup options (see Editing, uploading, downloading);
+if not, the response has status 400 and the error message, and the
+journal is not changed.
 You can get sample JSON from hledger\-web\(aqs \f[CR]/transactions\f[R]
-or \f[CR]/accounttransactions\f[R], or you can export it with
-hledger\-lib, eg like so:
+or \f[CR]/accounttransactions\f[R], or from hledger\(aqs print command.
+Eg, this saves the first transaction of the sample journal to
+\f[CR]txn.json\f[R]:
 .IP
 .EX
-\&.../hledger$ stack ghci hledger\-lib
->>> writeJsonFile \(dqtxn.json\(dq (head $ jtxns samplejournal)
->>> :q
+$ hledger \-f examples/sample.journal print \-O json | python3 \-c \(aqimport json,sys; json.dump(json.load(sys.stdin)[0], sys.stdout, indent=4)\(aq > txn.json
 .EE
 .PP
-Here\(aqs how it looks as of hledger\-1.17 (remember, this JSON
-corresponds to hledger\(aqs Transaction and related data types):
+Here\(aqs how it looks (remember, this JSON corresponds to hledger\(aqs
+Transaction and related data types):
 .IP
 .EX
 {
+    \(dqtcode\(dq: \(dq\(dq,
     \(dqtcomment\(dq: \(dq\(dq,
+    \(dqtdate\(dq: \(dq2008\-01\-01\(dq,
+    \(dqtdate2\(dq: \f[B]null\f[R],
+    \(dqtdescription\(dq: \(dqincome\(dq,
+    \(dqtindex\(dq: 1,
     \(dqtpostings\(dq: [
         {
-            \(dqpbalanceassertion\(dq: \f[B]null\f[R],
-            \(dqpstatus\(dq: \(dqUnmarked\(dq,
+            \(dqpaccount\(dq: \(dqassets:bank:checking\(dq,
             \(dqpamount\(dq: [
                 {
-                    \(dqaprice\(dq: \f[B]null\f[R],
                     \(dqacommodity\(dq: \(dq$\(dq,
+                    \(dqacost\(dq: \f[B]null\f[R],
+                    \(dqacostbasis\(dq: \f[B]null\f[R],
                     \(dqaquantity\(dq: {
-                        \(dqfloatingPoint\(dq: 1,
-                        \(dqdecimalPlaces\(dq: 10,
-                        \(dqdecimalMantissa\(dq: 10000000000
+                        \(dqdecimalMantissa\(dq: 1,
+                        \(dqdecimalPlaces\(dq: 0,
+                        \(dqfloatingPoint\(dq: 1
                     },
-                    \(dqaismultiplier\(dq: \f[B]false\f[R],
                     \(dqastyle\(dq: {
                         \(dqascommodityside\(dq: \(dqL\(dq,
-                        \(dqasdigitgroups\(dq: \f[B]null\f[R],
                         \(dqascommodityspaced\(dq: \f[B]false\f[R],
-                        \(dqasprecision\(dq: 2,
-                        \(dqasdecimalpoint\(dq: \(dq.\(dq
+                        \(dqasdecimalmark\(dq: \(dq.\(dq,
+                        \(dqasdigitgroups\(dq: \f[B]null\f[R],
+                        \(dqasprecision\(dq: 0,
+                        \(dqasrounding\(dq: \(dqNoRounding\(dq
                     }
                 }
             ],
-            \(dqptransaction_\(dq: \(dq1\(dq,
-            \(dqpaccount\(dq: \(dqassets:bank:checking\(dq,
-            \(dqpdate\(dq: \f[B]null\f[R],
-            \(dqptype\(dq: \(dqRegularPosting\(dq,
+            \(dqpbalanceassertion\(dq: \f[B]null\f[R],
             \(dqpcomment\(dq: \(dq\(dq,
+            \(dqpdate\(dq: \f[B]null\f[R],
             \(dqpdate2\(dq: \f[B]null\f[R],
+            \(dqporiginal\(dq: \f[B]null\f[R],
+            \(dqpreal\(dq: \(dqRealPosting\(dq,
+            \(dqpstatus\(dq: \(dqUnmarked\(dq,
             \(dqptags\(dq: [],
-            \(dqporiginal\(dq: \f[B]null\f[R]
+            \(dqptransaction_\(dq: \(dq1\(dq
         },
         {
-            \(dqpbalanceassertion\(dq: \f[B]null\f[R],
-            \(dqpstatus\(dq: \(dqUnmarked\(dq,
+            \(dqpaccount\(dq: \(dqincome:salary\(dq,
             \(dqpamount\(dq: [
                 {
-                    \(dqaprice\(dq: \f[B]null\f[R],
                     \(dqacommodity\(dq: \(dq$\(dq,
+                    \(dqacost\(dq: \f[B]null\f[R],
+                    \(dqacostbasis\(dq: \f[B]null\f[R],
                     \(dqaquantity\(dq: {
-                        \(dqfloatingPoint\(dq: \-1,
-                        \(dqdecimalPlaces\(dq: 10,
-                        \(dqdecimalMantissa\(dq: \-10000000000
+                        \(dqdecimalMantissa\(dq: \-1,
+                        \(dqdecimalPlaces\(dq: 0,
+                        \(dqfloatingPoint\(dq: \-1
                     },
-                    \(dqaismultiplier\(dq: \f[B]false\f[R],
                     \(dqastyle\(dq: {
                         \(dqascommodityside\(dq: \(dqL\(dq,
-                        \(dqasdigitgroups\(dq: \f[B]null\f[R],
                         \(dqascommodityspaced\(dq: \f[B]false\f[R],
-                        \(dqasprecision\(dq: 2,
-                        \(dqasdecimalpoint\(dq: \(dq.\(dq
+                        \(dqasdecimalmark\(dq: \(dq.\(dq,
+                        \(dqasdigitgroups\(dq: \f[B]null\f[R],
+                        \(dqasprecision\(dq: 0,
+                        \(dqasrounding\(dq: \(dqNoRounding\(dq
                     }
                 }
             ],
-            \(dqptransaction_\(dq: \(dq1\(dq,
-            \(dqpaccount\(dq: \(dqincome:salary\(dq,
-            \(dqpdate\(dq: \f[B]null\f[R],
-            \(dqptype\(dq: \(dqRegularPosting\(dq,
+            \(dqpbalanceassertion\(dq: \f[B]null\f[R],
             \(dqpcomment\(dq: \(dq\(dq,
+            \(dqpdate\(dq: \f[B]null\f[R],
             \(dqpdate2\(dq: \f[B]null\f[R],
+            \(dqporiginal\(dq: \f[B]null\f[R],
+            \(dqpreal\(dq: \(dqRealPosting\(dq,
+            \(dqpstatus\(dq: \(dqUnmarked\(dq,
             \(dqptags\(dq: [],
-            \(dqporiginal\(dq: \f[B]null\f[R]
+            \(dqptransaction_\(dq: \(dq1\(dq
         }
     ],
-    \(dqttags\(dq: [],
-    \(dqtsourcepos\(dq: {
-        \(dqtag\(dq: \(dqJournalSourcePos\(dq,
-        \(dqcontents\(dq: [
-            \(dq\(dq,
-            [
-                1,
-                1
-            ]
-        ]
-    },
-    \(dqtdate\(dq: \(dq2008\-01\-01\(dq,
-    \(dqtcode\(dq: \(dq\(dq,
-    \(dqtindex\(dq: 1,
     \(dqtprecedingcomment\(dq: \(dq\(dq,
-    \(dqtdate2\(dq: \f[B]null\f[R],
-    \(dqtdescription\(dq: \(dqincome\(dq,
-    \(dqtstatus\(dq: \(dqUnmarked\(dq
+    \(dqtsourcepos\(dq: [
+        {
+            \(dqsourceColumn\(dq: 1,
+            \(dqsourceLine\(dq: 31,
+            \(dqsourceName\(dq: \(dq/home/user/hledger/examples/sample.journal\(dq
+        },
+        {
+            \(dqsourceColumn\(dq: 1,
+            \(dqsourceLine\(dq: 34,
+            \(dqsourceName\(dq: \(dq/home/user/hledger/examples/sample.journal\(dq
+        }
+    ],
+    \(dqtstatus\(dq: \(dqUnmarked\(dq,
+    \(dqttags\(dq: []
 }
 .EE
 .PP
-And here\(aqs how to test adding it with curl.
-This should add a new entry to your journal:
+And here\(aqs how to add it with curl.
+This should append a new entry to your journal file:
 .IP
 .EX
 $ curl http://127.0.0.1:5000/add \-X PUT \-H \(aqContent\-Type: application/json\(aq \-\-data\-binary \(attxn.json
 .EE
 .SH DEBUG OUTPUT
-.SS Debug output
 You can add \f[CR]\-\-debug[=N]\f[R] to the command line to log debug
 output.
 N ranges from 1 (least output, the default) to 9 (maximum output).
@@ -493,6 +987,33 @@
 .P
 .PD
 \f[CR]hledger\-web \-\-debug=3 2>hledger\-web.log\f[R].
+.SH LANGUAGE
+hledger\-web\(aqs pages can be shown in another language when a
+translation catalog is available (see Languages in the hledger manual).
+.PP
+When hledger\-web is started with \f[CR]\-\-lang LANG\f[R], eg
+\f[CR]\-\-lang de\f[R], every page is in that language, whatever the
+browser asks for.
+So you can use hledger\-web in a language other than your browser\(aqs,
+or give every user of a shared server the same language.
+.PP
+Otherwise the language is chosen per request, and the first of these
+naming an available translation wins:
+.IP "1." 3
+a \f[CR]_LANG\f[R] query parameter, eg \f[CR]?_LANG=de\f[R].
+This choice is remembered in a \f[CR]_LANG\f[R] cookie.
+.IP "2." 3
+the \f[CR]_LANG\f[R] cookie
+.IP "3." 3
+the browser\(aqs \f[CR]Accept\-Language\f[R] header, ie the browser\(aqs
+or system\(aqs language settings
+.PP
+If none does, pages are in English, or with \f[CR]\-\-lang auto\f[R], in
+the language of hledger\-web\(aqs environment.
+So viewers usually get their browser\(aqs language automatically, if
+hledger\-web has it.
+Catalogs, including any in the config directory, are loaded when
+hledger\-web starts.
 .SH ENVIRONMENT
 \f[B]LEDGER_FILE\f[R] The main journal file to use when not specified
 with \f[CR]\-f/\-\-file\f[R].
@@ -504,7 +1025,9 @@
 .PP
 Some known issues:
 .PP
-Does not work well on small screens, or in text\-mode browsers.
+Without JavaScript (eg in text\-mode browsers), pages can be viewed and
+their links followed, but the add form, help dialog, keyboard shortcuts,
+sidebar toggle and folding don\(aqt work.
 
 
 .SH AUTHORS
diff --git a/hledger-web.cabal b/hledger-web.cabal
--- a/hledger-web.cabal
+++ b/hledger-web.cabal
@@ -5,7 +5,7 @@
 -- see: https://github.com/sol/hpack
 
 name:           hledger-web
-version:        1.52.4
+version:        2.0
 synopsis:       Web user interface for the hledger accounting system
 description:    A simple web user interface for the hledger accounting system,
                 providing a more modern UI than the command-line or terminal interfaces.
@@ -28,7 +28,7 @@
 license-file:   LICENSE
 build-type:     Simple
 tested-with:
-    ghc==9.6.7, ghc==9.8.4, ghc==9.10.2, ghc==9.12.4
+    ghc==9.6.7, ghc==9.8.4, ghc==9.10.3, ghc==9.12.4, ghc==9.14.1
 extra-source-files:
     CHANGES.md
     README.md
@@ -38,7 +38,6 @@
     config/robots.txt
     config/routes
     config/settings.yml
-    static/css/bootstrap-datepicker.standalone.min.css
     static/css/bootstrap-theme.css
     static/css/bootstrap-theme.min.css
     static/css/bootstrap.css
@@ -51,50 +50,6 @@
     static/fonts/glyphicons-halflings-regular.woff
     static/hledger.css
     static/hledger.js
-    static/js/bootstrap-datepicker.min.js
-    static/js/bootstrap.js
-    static/js/bootstrap.min.js
-    static/js/excanvas.js
-    static/js/excanvas.min.js
-    static/js/jquery.cookie.js
-    static/js/jquery.flot.canvas.js
-    static/js/jquery.flot.canvas.min.js
-    static/js/jquery.flot.categories.js
-    static/js/jquery.flot.categories.min.js
-    static/js/jquery.flot.crosshair.js
-    static/js/jquery.flot.crosshair.min.js
-    static/js/jquery.flot.errorbars.js
-    static/js/jquery.flot.errorbars.min.js
-    static/js/jquery.flot.fillbetween.js
-    static/js/jquery.flot.fillbetween.min.js
-    static/js/jquery.flot.image.js
-    static/js/jquery.flot.image.min.js
-    static/js/jquery.flot.js
-    static/js/jquery.flot.min.js
-    static/js/jquery.flot.navigate.js
-    static/js/jquery.flot.navigate.min.js
-    static/js/jquery.flot.pie.js
-    static/js/jquery.flot.pie.min.js
-    static/js/jquery.flot.resize.js
-    static/js/jquery.flot.resize.min.js
-    static/js/jquery.flot.selection.js
-    static/js/jquery.flot.selection.min.js
-    static/js/jquery.flot.stack.js
-    static/js/jquery.flot.stack.min.js
-    static/js/jquery.flot.symbol.js
-    static/js/jquery.flot.symbol.min.js
-    static/js/jquery.flot.threshold.js
-    static/js/jquery.flot.threshold.min.js
-    static/js/jquery.flot.time.js
-    static/js/jquery.flot.time.min.js
-    static/js/jquery.flot.tooltip.js
-    static/js/jquery.flot.tooltip.min.js
-    static/js/jquery.hotkeys.js
-    static/js/jquery.js
-    static/js/jquery.min.js
-    static/js/jquery.url.js
-    static/js/typeahead.bundle.js
-    static/js/typeahead.bundle.min.js
     templates/add-form.hamlet
     templates/balance-report.hamlet
     templates/chart.hamlet
@@ -103,15 +58,17 @@
     templates/edit-form.hamlet
     templates/journal.hamlet
     templates/manage.hamlet
+    templates/paging.hamlet
     templates/register.hamlet
     templates/upload-form.hamlet
+    templates/years.hamlet
     hledger-web.1
     hledger-web.txt
     hledger-web.info
 
 source-repository head
   type: git
-  location: https://github.com/simonmichael/hledger
+  location: https://github.com/hledgerorg/hledger
 
 flag debug
   description: Build with GHC 9.10+ stack traces enabled
@@ -134,18 +91,25 @@
       Hledger.Web.App
       Hledger.Web.Application
       Hledger.Web.Handler.AddR
+      Hledger.Web.Handler.BalanceR
       Hledger.Web.Handler.EditR
+      Hledger.Web.Handler.HoldingsR
       Hledger.Web.Handler.JournalR
       Hledger.Web.Handler.MiscR
       Hledger.Web.Handler.RegisterR
+      Hledger.Web.Handler.StatementsR
       Hledger.Web.Handler.UploadR
       Hledger.Web.Import
       Hledger.Web.Main
+      Hledger.Web.Paging
+      Hledger.Web.Param
+      Hledger.Web.ReportPage
       Hledger.Web.Settings
       Hledger.Web.Settings.StaticFiles
       Hledger.Web.Test
       Hledger.Web.WebOptions
       Hledger.Web.Widget.AddForm
+      Hledger.Web.Widget.Chart
       Hledger.Web.Widget.Common
   other-modules:
       Paths_hledger_web
@@ -154,12 +118,13 @@
   hs-source-dirs:
       ./
   ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -threaded
-  cpp-options: -DVERSION="1.52.4"
+  cpp-options: -DVERSION="2.0"
   build-depends:
       Decimal >=0.5.1
     , aeson >=2.2.5.1 && <2.4
+    , async
     , base >=4.18 && <4.23
-    , base64
+    , base64-bytestring
     , blaze-html
     , blaze-markup
     , bytestring
@@ -169,14 +134,15 @@
     , conduit
     , conduit-extra >=1.1
     , containers >=0.5.9
+    , cookie
     , data-default
     , directory >=1.2.3.0
+    , entropy
     , extra >=1.7.11
     , file-embed >=0.0.16.0
     , filepath
-    , githash >=0.1.6.2
-    , hledger >=1.52.4 && <1.53
-    , hledger-lib >=1.52.4 && <1.53
+    , hledger ==2.0.*
+    , hledger-lib ==2.0.*
     , hspec
     , http-client
     , http-conduit
@@ -186,6 +152,7 @@
     , network
     , safe >=0.3.20
     , shakespeare >=2.0.2.2
+    , streaming-commons
     , template-haskell
     , text >=1.2.4.1
     , time >=1.5
@@ -194,15 +161,14 @@
     , unordered-containers
     , utf8-string
     , wai
-    , wai-app-static >=3.1
+    , wai-app-static >=3.1.9
     , wai-cors
     , wai-extra
-    , wai-handler-launch >=3.0.3
     , warp
     , yaml
     , yesod >=1.4 && <1.7
     , yesod-core >=1.4 && <1.8
-    , yesod-form >=1.4 && <1.8
+    , yesod-form >=1.4.12 && <1.8
     , yesod-test
   default-language: GHC2021
   if (flag(dev)) || (flag(library-only))
@@ -220,8 +186,8 @@
       Paths_hledger_web
   hs-source-dirs:
       app
-  ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -threaded
-  cpp-options: -DVERSION="1.52.4"
+  ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -threaded -rtsopts
+  cpp-options: -DVERSION="2.0"
   build-depends:
       base >=4.18 && <4.23
     , hledger-web
@@ -241,7 +207,7 @@
   hs-source-dirs:
       test
   ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -threaded
-  cpp-options: -DVERSION="1.52.4"
+  cpp-options: -DVERSION="2.0"
   build-depends:
       base >=4.18 && <4.23
     , hledger-web
diff --git a/hledger-web.info b/hledger-web.info
--- a/hledger-web.info
+++ b/hledger-web.info
@@ -18,7 +18,7 @@
 or
 'hledger web [OPTS] [QUERY]'
 
-   This manual is for hledger's web interface, version 1.52.4.  See also
+   This manual is for hledger's web interface, version 2.0.  See also
 the hledger manual for common concepts and file formats.
 
    hledger is a robust, user-friendly, cross-platform set of programs
@@ -27,17 +27,17 @@
 and largely compatible with ledger(1), and largely interconvertible with
 beancount(1).
 
-   hledger-web is a simple web application for browsing and adding
-transactions.  It provides a more user-friendly UI than the hledger CLI
-or hledger-ui TUI, showing more at once (accounts, the current account
-register, balance charts) and allowing history-aware data entry,
-interactive searching, and bookmarking.
+   hledger-web is hledger's web interface.  In a web browser, it shows
+the journal, account registers, and the main financial reports with
+their charts, and lets you search them, add transactions, and (if
+allowed) edit the journal files.  It shows more at once than the hledger
+CLI or hledger-ui (eg the accounts beside a register, or a report's
+chart above its table), and every view has its own url, so it can be
+bookmarked or shared.
 
    hledger-web also lets you share a journal with multiple users, or
-even the public web.  There is no access control, so if you need that
-you should put it behind a suitable web proxy.  As a small protection
-against data loss when running an unprotected instance, it writes a
-numbered backup of the main journal file (only) on every edit.
+even the public web.  There is no user authentication, so if you need
+that you should put it behind a suitable web proxy (see Permissions).
 
    Like hledger, it reads from (and appends to) a journal file specified
 by the 'LEDGER_FILE' environment variable (defaulting to
@@ -49,8 +49,8 @@
 
    * '--serve-browse' mode (the default): the app serves the web UI and
      JSON API, and opens your default web browser to show the app if
-     possible, and exits automatically after two minutes of inactivity
-     (with no requests received and no open browser windows viewing it).
+     possible, and exits automatically once no browser window has shown
+     it for fifteen minutes.
 
    * '--serve': the app just serves the web UI and JSON API.
 
@@ -62,52 +62,75 @@
 * Menu:
 
 * OPTIONS::
+* WEB UI::
 * PERMISSIONS::
 * EDITING UPLOADING DOWNLOADING::
+* REPORTS::
+* URL PARAMETERS::
 * RELOADING::
 * JSON API::
 * DEBUG OUTPUT::
+* LANGUAGE::
 * ENVIRONMENT::
 * BUGS::
 
 
-File: hledger-web.info,  Node: OPTIONS,  Next: PERMISSIONS,  Prev: Top,  Up: Top
+File: hledger-web.info,  Node: OPTIONS,  Next: WEB UI,  Prev: Top,  Up: Top
 
 1 OPTIONS
 *********
 
-hledger-web provides the following options:
+hledger-web provides the following command line options:
 
 Flags:
-     --serve --server       serve and log requests, don't browse or auto-exit
-     --serve-api            like --serve, but serve only the JSON web API,
-                            not the web UI
-     --allow=view|add|edit  set the user's access level for changing data
-                            (default: `add`). It also accepts `sandstorm` for
-                            use on that platform (reads permissions from the
-                            `X-Sandstorm-Permissions` request header).
-     --cors=ORIGIN          allow cross-origin requests from the specified
-                            origin; setting ORIGIN to "*" allows requests from
-                            any origin
-     --host=IPADDR          listen on this IP address (default: 127.0.0.1)
-     --port=PORT            listen on this TCP port (default: 5000)
-     --socket=SOCKET        listen on the given unix socket instead of an IP
-                            address and port (unix only; implies --serve)
-     --base-url=BASEURL     set the base url (default: http://IPADDR:PORT)
-     --test                 run hledger-web's tests and exit. hspec test
-                            runner args may follow a --, eg: hledger-web --test
-                            --help
+     --serve-browse            server mode: serve the web UI and JSON API,
+                               and open a browser, and exit if inactive for 15m
+                               (default)
+     --serve                   server mode: just serve the web UI and JSON
+                               API
+     --serve-api               server mode: just serve the JSON API
+     --allow=view|add|edit     set the user's access level for changing data
+                               (default: `add` on a local-only address, `view`
+                               otherwise). It also accepts `sandstorm` for that
+                               platform (reading from the
+                               `X-Sandstorm-Permissions` request header).
+     --cors=ORIGIN             allow cross-origin requests from the specified
+                               origin; setting ORIGIN to "*" allows requests
+                               from any origin
+     --host=IPADDR             listen on this IP address (default: 127.0.0.1)
+     --port=PORT               listen on this TCP port (default: 5000); 0
+                               means a free port chosen by the OS
+     --socket=SOCKET           listen on the given unix socket instead of an
+                               IP address and port (only on unix)
+     --base-url=BASEURL        set the base url (default: http://IPADDR:PORT)
+     --chart[=KIND,net,SCALE]  set the charts' defaults, as the commands'
+                               --chart does. KIND: lay out the statements'
+                               charts with each period's sections in one bar,
+                               above and below zero (diverging, the default),
+                               or side by side (grouped). net: show the net
+                               total lines by default (the N key toggles them,
+                               and the browser remembers that). SCALE: the
+                               amount that fills the charts (eg 1000 or 1000
+                               USD; one per commodity), for comparable charts.
+     --lang=LANG               show the web UI in this language (en, de, es,
+                               ru, zh); or with auto, use each viewer's browser
+                               language if available, otherwise the server's.
+                               (Default: the browser's language if available,
+                               otherwise en.)
 
    By default hledger-web listens only on IP address '127.0.0.1', which
-be accessed only from the local machine.
+can be accessed only from the local machine.
 
    To allow access from elsewhere, use '--host' to specify an externally
-accessible address configured on this machine, The special address
+accessible address configured on this machine.  The special address
 '0.0.0.0' causes it to listen on all of this machine's addresses.
 
    Similarly, you can use '--port' to listen on a TCP port other than
 5000.  This is useful if you want to run multiple hledger-web instances
-on a machine.
+on a machine.  '--port 0' makes the operating system choose a free port,
+which is reported in the startup message and in the default base url,
+and is where the browser is opened in '--serve-browse' mode.  This can
+be useful eg when scripting.
 
    When '--socket' is used, hledger-web creates and communicates via a
 socket file instead of a TCP port.  This can be more secure, respects
@@ -124,11 +147,15 @@
 
    hledger-web also supports many of hledger's general options:
 
-General input/data transformation flags:
-  -f --file=[FMT:]FILE      Read data from FILE, or from stdin if FILE is -,
-                            inferring format from extension or a FMT: prefix.
-                            Can be specified more than once. If not specified,
-                            reads from $LEDGER_FILE or $HOME/.hledger.journal.
+General input flags:
+  -f --file=[FMT:]FILE      Use this as the journal file (- means stdin). If
+                            not specified, $LEDGER_FILE or ~/.hledger.journal
+                            will be used. If specified more than once, the
+                            files will be read in order. Each file's format
+                            (journal, csv, timeclock, timedot, rules..) is
+                            inferred from the file extension or a FMT: prefix.
+                            Some commands (add, import) write to the (first)
+                            file, and expect it to be in journal format.
      --rules=RULESFILE      Use rules defined in this rules file for
                             converting subsequent CSV/SSV/TSV files. If not
                             specified, uses FILE.csv.rules for each FILE.csv.
@@ -143,27 +170,30 @@
                             will also be applied to these transactions. In
                             hledger-ui, also make future-dated transactions
                             visible at startup.
-  -I --ignore-assertions    don't check balance assertions by default
-     --txn-balancing=...    how to check that transactions are balanced:
-                            'old':   use global display precision
-                            'exact': use transaction precision (default)
-     --infer-costs          infer conversion equity postings from costs
-     --infer-equity         infer costs from conversion equity postings
+     --ignore-assertions    don't check balance assertions by default
+     --ignore-lots          don't track lots: skip lot checks, inferred cost
+                            bases and gain postings
+  -I                        shortcut for --ignore-assertions --ignore-lots
+     --txn-tolerance=...    how much imbalance to allow in transactions:
+                            'entry':   - the entry's precision (default)
+                            'display': - display precision (legacy)
+     --infer-costs          infer costs from conversion equity postings
+     --infer-equity         infer conversion equity postings from costs
+     --infer-imbalance      add postings showing tolerated imbalances
      --infer-market-prices  infer market prices from costs
      --pivot=TAGNAME        use a different field or tag as account names
   -s --strict               do extra error checks (and override -I)
-     --verbose-tags         add tags indicating generated/modified data
 
-General output/reporting flags (supported by some commands):
+General output flags (affecting some commands):
   -b --begin=DATE           include postings/transactions on/after this date
   -e --end=DATE             include postings/transactions before this date
                             (with a report interval, will be adjusted to
                             following subperiod end)
-  -D --daily                multiperiod report with 1 day interval
-  -W --weekly               multiperiod report with 1 week interval
-  -M --monthly              multiperiod report with 1 month interval
-  -Q --quarterly            multiperiod report with 1 quarter interval
-  -Y --yearly               multiperiod report with 1 year interval
+  -D --daily                set report interval: 1 day
+  -W --weekly               set report interval: 1 week
+  -M --monthly              set report interval: 1 month
+  -Q --quarterly            set report interval: 1 quarter
+  -Y --yearly               set report interval: 1 year
   -p --period=PERIODEXP     set begin date, end date, and/or report interval,
                             with more flexibility
      --today=DATE           override today's date (affects relative dates)
@@ -178,67 +208,219 @@
      --depth=DEPTHEXP       if a number (or -NUM): show only top NUM levels
                             of accounts. If REGEXP=NUM, only apply limiting to
                             accounts matching the regular expression.
-  -B --cost                 show amounts converted to their cost/sale amount
-  -V --market               Show amounts converted to their value at period
-                            end(s) in their default valuation commodity.
-                            Equivalent to --value=end.
-  -X --exchange=COMM        Show amounts converted to their value at period
-                            end(s) in the specified commodity.
-                            Equivalent to --value=end,COMM.
-     --value=WHEN[,COMM]    show amounts converted to their value on the
-                            specified date(s) in their default valuation
-                            commodity or a specified commodity. WHEN can be:
+  -B --cost                 convert amounts to their cost basis ({}), or else
+                            their cost/sale amount (@/@@)
+  -V --market               valuation mode: show amounts converted to market
+                            value at period end(s) in their default valuation
+                            commodity. Short for --value=end.
+  -X --exchange=COMM        valuation mode: show amounts converted to market
+                            value at period end(s) in the specified commodity.
+                            Short for --value=end,COMM.
+     --value=WHEN[,COMM]    valuation mode: show amounts converted to market
+                            value on the specified date(s) in their default
+                            valuation commodity or a specified commodity. WHEN
+                            can be:
                             'then':     value on transaction dates
                             'end':      value at period end(s)
                             'now':      value today
                             YYYY-MM-DD: value on given date
+                            'cost':     cost basis, or else transacted cost
+                            (same as -B)
+                            'transacted': transacted cost/sale amount (@/@@)
+                            only
+                            COMM may be written in double quotes; '""' or an
+                            empty COMM means the no-symbol commodity.
+     --lots                 show lot subaccounts and other lot details
   -c --commodity-style=S    Override a commodity's display style.
                             Eg: -c '.' or -c '1.000,00 EUR'
-     --pretty[=YN]          Use box-drawing characters in text output? Can be
-                            'y'/'yes' or 'n'/'no'.
-                            If YN is specified, the equals is required.
+     --pretty[=YN]          Use box-drawing characters in text output? The
+                            optional 'y'/'yes' or 'n'/'no' arg requires =.
+     --title=T              set or customise a report title
+     --subreport-titles=TS  customise subreport headings in compound reports
+                            (|-separated)
+     --period-titles=OPT    customise headings in periodic reports:
+                            'compact': readable period names when possible
+                            'dates':   exact dates/date ranges always
 
 General help flags:
-  -h --help                 show command line help
-     --tldr                 show command examples with tldr
-     --info                 show the manual with info
-     --man                  show the manual with man
+  -?                        show the hledger quick reference
+  -h --help                 show this command's usage help
+     --info                 show this command's manual with info
+     --man                  show this command's manual with man
+     --webman               show this command's manual on the web
+     --examples             show examples for this command
      --version              show version information
+     --test[=PATTERN]       run built-in tests (those matching PATTERN) and
+                            exit
+     --write-lang=LANG      write LANG's PO file to the config directory, for
+                            editing translations, and exit
      --debug=[1-9]          show this much debug output (default: 1)
      --pager=YN             use a pager when needed ? y/yes (default) or n/no
      --color=YNA --colour   use ANSI color ? y/yes, n/no, or auto (default)
 
+   Some of these can be adjusted while hledger-web is running, in the
+web UI's Options panel.
+
    hledger-web shows accounts with zero balances by default (like
-'hledger-ui', and unlike 'hledger').  Using the '-E/--empty' flag will
-reverse this behaviour.  If you see accounts which appear to have a zero
-balance, but cannot be hidden with '-E', it's because they have a
-mixed-cost balance, which looks like zero when costs are hidden.
-(hledger-web does not show costs.)
+'hledger-ui', and unlike 'hledger'); '-E/--empty' starts it with them
+hidden instead.  In the web UI, the Zero balances option or the 'z' key
+shows or hides them.  (The holdings page differs: its closed positions
+are hidden by default, as in the 'holdings' command; '-E' starts it with
+them shown, and 'z' there shows or hides them.)
 
-   Reporting options and/or query arguments can be used to set an
-initial query, which although not shown in the UI, will restrict the
-data shown (in addition to any search query entered in the UI).
+   Report options and a query given at startup set the view hledger-web
+opens with, by putting them in its url (see URL parameters).  Eg
+'hledger-web -V -M' opens '/balancesheet?interval=monthly&value=end',
+and 'hledger-web --cleared -3 assets' opens '/balancesheet?q=assets
+status:*&depth=3'.  They are only a starting point: they can be changed
+in the web UI, and they don't affect other urls or the JSON API. Report
+options that hledger-web has no equivalent for are ignored.
 
+   Note, a startup query doesn't restrict what hledger-web serves; to do
+that, give it a file holding only the entries to serve (eg one written
+by 'hledger print QUERY').
+
    If you use the bash shell, you can auto-complete flags by pressing
 TAB in the command line.  If this is not working see Install > Shell
 completions.
 
 
-File: hledger-web.info,  Node: PERMISSIONS,  Next: EDITING UPLOADING DOWNLOADING,  Prev: OPTIONS,  Up: Top
+File: hledger-web.info,  Node: WEB UI,  Next: PERMISSIONS,  Prev: OPTIONS,  Up: Top
 
-2 PERMISSIONS
-*************
+2 WEB UI
+********
 
-By default, hledger-web allows anyone who can reach it to view the
-journal and to add new transactions, but not to change existing data.
+hledger-web's main views are:
 
-   You can restrict who can reach it, by
+   * the *journal view*, showing journal entries, newest first, with
+     their postings
+   * the *report views*, described below: the balance sheet, income
+     statement, cashflow statement (and holdings, for journals using
+     lots), and All accounts report
+   * a *register view* for each account, reached by clicking an account
+     name, showing the transactions affecting that account (and its
+     subaccounts), with a running balance and a balance chart.
 
+   Every page has, from the top: links to the journal and the reports,
+the search form, the options, and then the view itself.  The options are
+hidden until you open them (click Options, or press 'o'); while hidden,
+they list the ones in effect, eg "Monthly · Depth 2 · Tree".
+
+   The journal and register show the newest 1000 matching transactions,
+with links to older and newer pages.  When the transactions span more
+than one year, the options include a row of years, to narrow the view to
+one year; shift-click a second year to select a range of years.
+
+   The register's chart shows the running balance over the page's
+transactions.  With several commodities, use the legend, or the '[' and
+']' keys, to choose the one charted.  Click a point to go to its
+transaction, or drag across the chart to see the transactions of those
+dates.  The register's Costs option shows the costs recorded with its
+amounts.
+
+   The *sidebar* lists every account, and optionally their balances
+(parent balances include subaccounts).  The search doesn't change it,
+except that its dates set the balances' date.  The balances are hidden
+at first, since on a large journal they take much of each page's time;
+click the "Balances" heading above the accounts to show them, or to hide
+them again.  These are historical balances, as of the end of the report
+period set by date:, otherwise the latest (the heading shows the date).
+While the balances are hidden, all accounts are listed, even with Zero
+balances: Hidden.  It is always a tree, with carets that fold and open
+each group, whether the Accounts option is List or Tree.  The − and +
+above it fold or open a level of the whole tree, without changing the
+page; its depth is its own, apart from the page's depth limit.  The
+browser remembers the sidebar's depth and the groups you open or close
+(until the next − or +).  The button at the top left (or the 's' key)
+shows or hides the sidebar, and it stays the way you left it from page
+to page.  On a narrow screen, it slides the sidebar in or out.
+
+   Click an account name to see its register, with the search, or an
+amount to see the transactions it is made of.  In the journal and
+register, click a date to see that day's journal entries.
+
+   The *search form* filters every view with hledger's query syntax, eg
+'expenses date:thismonth'; the help dialog summarises the query types.
+The search and the options are part of the page's url (see URL
+parameters).
+
+   The *add form* (press 'a', or click "Add a transaction" in the
+journal view) adds a transaction to the main journal file, if the access
+level allows it, and if the journal would still be readable with it
+added (see Editing, uploading, downloading).  It autocompletes account
+names and descriptions from your existing entries.
+
+   The *help dialog* (press '?', or click the question mark button)
+lists these keyboard shortcuts, which work when you are not typing in a
+field:
+
+   * 'h' or '?' - show or hide the help dialog
+   * 'g' - go to another page: shows a menu of the pages, each with its
+     key; then 'j' journal, 'b' balance sheet, 'i' income statement, 'c'
+     cashflow statement, 'h' holdings (for journals using lots), 'a' all
+     accounts (escape to cancel)
+   * 'n' / 'p' - go to the next / previous page, in the 'g' menu's
+     order, wrapping round
+   * 'a' - add a transaction (escape to cancel)
+   * 's' - show or hide the sidebar
+   * shift with '1'-'9' - fold or open the sidebar's accounts to that
+     depth, as its − and + do (by the digit keys' place, whatever the
+     layout; except where shift with one types a character that is a
+     shortcut itself, eg a digit on AZERTY keyboards, or '/' on German
+     ones)
+   * 'b' - show or hide the sidebar's balances, as its Balances heading
+     does (while the sidebar shows)
+   * 'o' - show or hide the report options
+   * 'c' - show or hide the report's chart (on pages with one)
+   * '[' / ']' - chart the previous / next commodity (on pages whose
+     chart has several, wrapping round)
+   * 'N' - show or hide the chart's net total line (on pages whose chart
+     has one)
+   * 'd' - show or hide the report's data, its table (on pages with a
+     chart)
+   * 'f' - full window: show only the report's heading and data, or
+     everything ('s', 'o' and '/' leave it, showing what they ask for)
+   * 'z' - show or hide accounts with zero balances (on the holdings
+     page: closed positions)
+   * 't' - show accounts as a tree, or a list
+   * 'H' - show ending balances, or balance changes
+   * 'L' - show or hide lot detail
+   * 'V' - show amounts at market value, or as recorded
+   * 'B' - show amounts at cost, or as recorded
+   * 'R' - show only real postings, or all
+   * 'U', 'P', 'C' - show only unmarked, pending, or cleared
+     transactions, or all
+   * 'S' - sort by amount, or by account
+   * 'T', 'A' - add or remove the row total and average columns
+     (multi-period reports)
+   * 'D', 'W', 'M', 'Q', 'Y' - set the report interval (daily, weekly,
+     monthly, quarterly, yearly); pressed again, remove it
+   * '0'-'9', '-', '+' - set or adjust the account depth limit ('-' and
+     '+' step between 0 and the deepest)
+   * '/' - focus the search form, ready to add a term (escape to leave
+     it)
+   * 'Delete' or 'Backspace' - clear the search, as its clear button
+     does
+
+   The pages are light or dark, following your OS or browser's color
+scheme setting, and switch when it changes.
+
+   Editing, uploading and downloading journal files is described below.
+
+
+File: hledger-web.info,  Node: PERMISSIONS,  Next: EDITING UPLOADING DOWNLOADING,  Prev: WEB UI,  Up: Top
+
+3 PERMISSIONS
+*************
+
+You can restrict who can access hledger-web by
+
    * setting the IP address it listens on (see '--host' above).  By
      default it listens on 127.0.0.1, accessible to users on the local
      machine only.
-   * putting it behind an authenticating proxy, such as caddy or apache
-   * putting it behind a firewall
+   * or by putting it behind an authenticating proxy, such as caddy or
+     apache
+   * or by putting it behind a firewall.
 
    And you can restrict what the users reaching it can do, by specifying
 the '--allow=ACCESSLEVEL' option at startup.  ACCESSLEVEL is one of:
@@ -252,36 +434,279 @@
      of 'view', 'add', or 'edit' are specified in the
      'X-Sandstorm-Permissions' HTTP header
 
-   The default access level is 'add'.
+   The default access level is 'add' when listening on a local-only
+address ('127.0.0.1', '::1', 'localhost', or a unix socket), and 'view'
+otherwise.  To allow more than the default access, start it with an
+explicit '--allow=add' or '--allow=edit' option.
 
 
-File: hledger-web.info,  Node: EDITING UPLOADING DOWNLOADING,  Next: RELOADING,  Prev: PERMISSIONS,  Up: Top
+File: hledger-web.info,  Node: EDITING UPLOADING DOWNLOADING,  Next: REPORTS,  Prev: PERMISSIONS,  Up: Top
 
-3 EDITING, UPLOADING, DOWNLOADING
+4 EDITING, UPLOADING, DOWNLOADING
 *********************************
 
-If you enable the 'manage' capability mentioned above, you'll see a new
-"spanner" button to the right of the search form.  Clicking this will
-let you edit, upload, or download the journal file or any files it
-includes.
+If you start hledger-web with '--allow=edit', you'll see a new "spanner"
+button to the right of the search form.  Clicking this will let you
+edit, upload, or download the journal file or any files it includes.
 
    Note, unlike any other hledger command, in this mode you (or any
-visitor) can alter or wipe the data files.
+visitor) can alter or wipe the data files.  Before saving an edited or
+uploaded file, hledger-web saves a numbered backup of it (eg
+'main.journal.1', then 'main.journal.2'); if the backup can't be
+written, the file is not changed.  (Adding a transaction appends it to
+the main journal file without making a backup.)  hledger-web is not
+aware of version control systems, currently; if you use one, you'll have
+to arrange to commit the changes yourself.
 
-   Normally whenever a file is changed in this way, hledger-web saves a
-numbered backup (assuming file permissions allow it, the disk is not
-full, etc.)  hledger-web is not aware of version control systems,
-currently; if you use one, you'll have to arrange to commit the changes
-yourself (eg with a cron job or a file watcher like entr).
+   Changes which would leave the journal unreadable are refused, and the
+file is not changed.  This applies to edits, uploads and added
+transactions.  Each change is checked as the next read of the journal
+will check it, in the context of all the journal's files and with the
+options hledger-web was started with: so transactions must balance,
+balance assertions must pass (unless started with '-I'), lots must be
+valid, and with '--strict', the strict checks must pass too.
 
-   Changes which would leave the journal file(s) unparseable or
-non-valid (eg with failing balance assertions) are prevented.
-(Probably.  This needs re-testing.)
+
+File: hledger-web.info,  Node: REPORTS,  Next: URL PARAMETERS,  Prev: EDITING UPLOADING DOWNLOADING,  Up: Top
 
+5 REPORTS
+*********
+
+Besides the journal and the account registers, hledger-web shows these
+reports.  The sidebar and the links at the top of every page lead to
+each of them, and so does the 'g' key followed by the first letter of
+the report's name:
+
+   * *Balance sheet* ('b', '/balancesheet'): assets, liabilities and net
+     worth, like the balancesheet command.  Its Equity option adds an
+     equity section, like balancesheetequity.
+   * *Income statement* ('i', '/incomestatement'): revenues, expenses
+     and net income, like incomestatement.
+   * *Cashflow* ('c', '/cashflow'): changes in cash accounts, like
+     cashflow.
+   * *Holdings* ('h', '/holdings'): investments and their performance,
+     like holdings.  Shown only for journals that use lots; see below.
+   * *All accounts* ('a', '/balance'): all accounts, or those you search
+     for, like balance.
+
+   Each report shows a chart and then a table (by default; both can be
+toggled).  Click any amount to see the transactions it is made of.
+
+* Menu:
+
+* Options::
+* Charts::
+* From a report to its transactions::
+* Holdings::
+
 
-File: hledger-web.info,  Node: RELOADING,  Next: JSON API,  Prev: EDITING UPLOADING DOWNLOADING,  Up: Top
+File: hledger-web.info,  Node: Options,  Next: Charts,  Up: REPORTS
 
-4 RELOADING
+5.1 Options
+===========
+
+A report's options (click Options, or press 'o') change what it shows.
+These are similar to hledger's command-line options and hledger-ui's
+keys.  The main ones, with their keyboard shortcuts:
+
+   * *Interval* ('D', 'W', 'M', 'Q', 'Y'): one column for the whole
+     period, or one per day, week, month, quarter or year (see Report
+     intervals).  Until you choose one, the reports pick an interval to
+     suit the period shown (except holdings, whose interval is its own;
+     see Holdings): monthly for up to two years, quarterly for up to
+     six, yearly beyond.  Click a column's heading to see the report for
+     just its dates.
+   * *Show* ('H'): balance changes in each period, or ending balances
+     (which include everything before the period).  The balance sheet
+     shows ending balances by default and the other reports show
+     changes, as their commands do; the report's heading says which it
+     is showing.
+   * *Depth* ('0'-'9', '-', '+'): how many levels of accounts to show
+     (see Depth).  Depth 0 shows only the totals.  Until you choose one,
+     the depth is 1, the top-level accounts.  The − and + beside the
+     table's Account heading step it too.  In tree mode they fold or
+     open a level of the whole tree.  (The sidebar has a depth of its
+     own; see above.)
+   * *Accounts* ('t'): a list, or a tree with subtotals; the List and
+     Tree links beside the table's Account heading switch too.  In a
+     tree, the accounts below the depth limit are folded, and their
+     carets open them in place (at depth 0, all of them, under each
+     section's total).
+   * *Amounts* ('B', 'V'): as recorded, at cost, or at market value at
+     the end of each period (see Cost reporting and Value reporting).
+   * *Zero balances* ('z'): hide or show accounts whose balance is zero.
+     (On the holdings page, 'z' toggles Closed positions instead; use
+     this option's links there.)
+   * *Equity* (balance sheet only): hide or show the equity section.
+     The browser remembers this choice for each hledger-web server.
+   * *Status* ('U', 'P', 'C'), *Postings* ('R'), account types, and
+     commodities: show only transactions with that status, only real
+     postings, or only some account types or commodities.  These rows
+     edit the search, adding a term like 'status:*' or 'type:A'.
+     Shift-click selects several types or commodities.
+
+   The options you choose stay in effect as you move to other pages,
+except Show, which each report sets to its own default.  On the journal
+and register, the report options are shown muted, but are kept.
+
+   The search form filters reports as it does the other pages, and its
+'date:' terms set the report's dates.  An interval or depth typed in the
+search, like 'date:monthly' or 'depth:2', moves into the options when
+the page reloads.  A depth limit for some accounts only, like
+'depth:assets=3', stays in the search.
+
+   The options are also URL parameters, so you can bookmark a report
+with them.
+
+   (For more detail, see the hledger manual, eg CONCEPTS.)
+
+
+File: hledger-web.info,  Node: Charts,  Next: From a report to its transactions,  Prev: Options,  Up: REPORTS
+
+5.2 Charts
+==========
+
+A report's chart is the one its command draws with '--chart': eg a bar
+per account, or with an interval, each account over time, and for the
+statements, each section and the net total.  In tree mode it shows the
+accounts down to the depth limit.  With several commodities, use the
+legend, or the '[' and ']' keys, to choose the one charted.  The Balance
+page's and statements' charts stack each period's accounts (or sections)
+in one bar, above and below zero; the Chart row in Options (or
+'--chart=grouped' at startup) shows a bar per account type (or section),
+side by side, instead (on the Balance page with no interval, for the
+whole period, as 'balance --chart=grouped' does).  '--chart' at startup
+takes the same value as the commands' '--chart'; its SCALE amounts fix
+the scales of the report and register charts, so that they can be
+compared.  Hover over a bar or a line (or on a touch screen, tap it) to
+see its period (or date, or account), its series and its amount.  Charts
+are drawn as wide as the page shows them, and redrawn when that changes,
+eg when you hide or show the sidebar or resize the window.
+
+   The 'c' key hides or shows the chart, and 'd' the table (the report's
+data).  You can also click the Chart and Data buttons at their top right
+corners, whose carets show whether they are shown.  The 'N' key shows or
+hides the net total line (or marks), eg a statement's net, or holdings'
+value or net gain; this is hidden at first, leaving the bars it totals
+(or with '--chart=net' at startup, shown at first).  The browser
+remembers this for each hledger-web server, and once you have chosen
+with 'N', your choice wins over '--chart=net'.
+
+
+File: hledger-web.info,  Node: From a report to its transactions,  Next: Holdings,  Prev: Charts,  Up: REPORTS
+
+5.3 From a report to its transactions
+=====================================
+
+Click an amount to see its account's register for that period: the
+transactions the amount is made of.  An ending balance's register starts
+with the balance brought forward, so its final running balance is that
+amount.  A section's total shows the register of all the section's
+accounts.  An amount shown at cost or market value leads to a register
+showing its amounts the same way.
+
+   Some things can make the register look different from the report:
+
+   * The statements show liabilities, equity and revenues as positive
+     amounts, as their commands do, so their registers show the same
+     amounts negated.  The amount's tooltip says so.
+   * When a posting has a date of its own, the report counts it on that
+     date, but the register lists its whole transaction, on the
+     transaction's date.
+
+
+File: hledger-web.info,  Node: Holdings,  Prev: From a report to its transactions,  Up: REPORTS
+
+5.4 Holdings
+============
+
+The holdings report shows one row for each commodity held in each
+account, with its cost basis, value and gains.  Its chart has a bar for
+each one, showing its cost basis and unrealised gain or loss.  Its own
+options can show:
+
+   * each lot separately (*Lots*, 'L'),
+   * fully disposed positions and their realised gains (*Closed
+     positions*, 'z'),
+   * all values in the market valuation commodity (*Values*).
+
+   Closed positions are hidden by default, as in the 'holdings' command,
+but the totals' RGain and XIRR always include them; a note below the
+table says how many are hidden, with a link to show them.
+
+   Its depth limit doesn't fold accounts: as on the command line, it
+merges the deeper accounts' positions, by commodity, into the accounts
+at the limit.
+
+   With an *Interval* chosen (it picks none by itself), it shows how
+your holdings changed, like holdings with a report interval: a row for
+each period's end, with the totals of all the holdings then, and a bar
+for each in the chart.  Each row's date links to the holdings on that
+date.  This page's interval is its own, since it makes a different
+report here: choosing one doesn't change the other reports' interval,
+nor theirs this page's, and an interval given at startup (eg '-M') is
+theirs.  Its *Gains* option chooses what the gain columns cover: each
+period, the time since the report's start date, or the time since
+acquisition (the default).  With the first two, the chart shows those
+gains: realised, and unrealised (hatched).  'H' toggles between gains
+since acquisition and gains in each period.
+
+   On journals that use lots, every page also has a Lots option, showing
+lot subaccounts and per-lot postings.
+
+
+File: hledger-web.info,  Node: URL PARAMETERS,  Next: RELOADING,  Prev: REPORTS,  Up: Top
+
+6 URL PARAMETERS
+****************
+
+A page's url includes its search and options, so a bookmark or a shared
+link shows the same view.  You can also write these urls yourself, eg
+'/balancesheet?interval=monthly&depth=2' or
+'/register?account=assets:bank'.  These are the parameters, most
+corresponding to hledger options:
+
+   * 'q' - the search
+   * 'account' - the account whose register to show (with its
+     subaccounts, unless 'subs=0')
+   * 'page' - which page of transactions to show, in the journal and
+     register (1 is the newest)
+   * 'interval' - 'daily', 'weekly', 'monthly', 'quarterly' or 'yearly'
+     (like '-D', '-W', '-M', '-Q', '-Y'), or 'none' for one column;
+     without it the reports pick one
+   * 'hinterval' - the holdings page's own interval, in the same words;
+     without it, none
+   * 'depth' - a number (like '--depth'), or 'all' for no limit; without
+     it, 1
+   * 'accum' - 'change', 'historical' or 'cumulative' (like '--change',
+     '-H', '--cumulative'); on the holdings page, with an interval, what
+     the gains cover
+   * 'value' - 'none', 'cost', or 'then', 'end', 'now' or a date,
+     optionally followed by ',COMMODITY' (like '--value')
+   * 'infer' - '1' to infer market prices from transaction costs too
+     (like '--infer-market-prices')
+   * 'empty' - '1' to show zero balances, '0' to hide them (like '-E')
+   * 'list' - 'tree' or 'flat' (like '--tree', '--flat')
+   * 'sort' - 'amount' (like '-S')
+   * 'total', 'avg', 'pct' - '1' to add totals, averages, or show
+     percentages (like '-T', '-A', '-%')
+   * 'calc' - 'valuechange', 'gain' or 'count' (like '--valuechange',
+     '--gain', '--count')
+   * 'date2' - '1' to use secondary dates (like '--date2')
+   * 'costs' - '1' to show costs, in the register
+   * 'equity' - '1' or '0', on the balance sheet (the old
+     '/balancesheetequity' address leads to 'equity=1')
+   * 'lots' - '1' to show lots (like '--lots')
+   * 'closed' - '1', on the holdings page, to show closed positions, '0'
+     to hide them
+   * 'chart' - 'grouped', on the Balance and statement pages, to chart
+     each period's account types (or sections) side by side (like
+     '--chart=grouped')
+
+
+File: hledger-web.info,  Node: RELOADING,  Next: JSON API,  Prev: URL PARAMETERS,  Up: Top
+
+7 RELOADING
 ***********
 
 hledger-web detects changes made to the files by other means (eg if you
@@ -290,13 +715,13 @@
 file unparseable, hledger-web will display an error message until the
 file has been fixed.
 
-   (Note: if you are viewing files mounted from another machine, make
-sure that both machine clocks are roughly in step.)
+   (If you are viewing files mounted from another machine, make sure
+that both machines have roughly the same idea of what time it is.)
 
 
 File: hledger-web.info,  Node: JSON API,  Next: DEBUG OUTPUT,  Prev: RELOADING,  Up: Top
 
-5 JSON API
+8 JSON API
 **********
 
 In addition to the web UI, hledger-web also serves a JSON API that can
@@ -315,12 +740,13 @@
 /commodities
 /accounts
 /accounttransactions/ACCOUNTNAME
+/openapi.json
 
    Eg, all account names in the journal (similar to the accounts
 command).  (hledger-web's JSON does not include newlines, here we use
 python to prettify it):
 
-$ curl -s http://127.0.0.1:5000/accountnames | python -m json.tool
+$ curl -s http://127.0.0.1:5000/accountnames | python3 -m json.tool
 [
     "assets",
     "assets:bank",
@@ -339,7 +765,7 @@
 
    Or all transactions:
 
-$ curl -s http://127.0.0.1:5000/transactions | python -m json.tool
+$ curl -s http://127.0.0.1:5000/transactions | python3 -m json.tool
 [
     {
         "tcode": "",
@@ -354,146 +780,139 @@
                 "pamount": [
                     {
                         "acommodity": "$",
-                        "aismultiplier": false,
-                        "aprice": null,
+                        "acost": null,
+                        "acostbasis": null,
 ...
 
    Most of the JSON corresponds to hledger's data types; for details of
 what the fields mean, see the Hledger.Data.Json haddock docs and click
 on the various data types, eg Transaction.  And for a higher level
 understanding, see the journal docs.  There is also a basic OpenAPI
-specification.
+specification, also served at '/openapi.json'.
 
-   In some cases there is outer JSON corresponding to a "Report" type.
-To understand that, go to the Hledger.Web.Handler.MiscR haddock and look
-at the source for the appropriate handler to see what it returns.  Eg
-for '/accounttransactions' it's getAccounttransactionsR, returning a
-"'accountTransactionsReport ...'".  Looking up the haddock for that we
-can see that /accounttransactions returns an AccountTransactionsReport,
-which consists of a report title and a list of
-AccountTransactionsReportItem (etc).
+   Some routes return a report type wrapping the data; eg
+'/accounttransactions' returns an AccountTransactionsReport, a report
+title and a list of items.  The handlers in Hledger.Web.Handler.MiscR
+show what each route returns.
 
    You can add a new transaction to the journal with a PUT request to
-'/add', if hledger-web was started with the 'add' capability (enabled by
-default).  The payload must be the full, exact JSON representation of a
-hledger transaction (partial data won't do).  You can get sample JSON
-from hledger-web's '/transactions' or '/accounttransactions', or you can
-export it with hledger-lib, eg like so:
+'/add', if hledger-web was started with '--allow=add' (the default when
+listening on a local-only address).  The payload must be the full, exact
+JSON representation of a hledger transaction (partial data won't do).
+The journal must still be readable with the transaction added, with
+hledger-web's startup options (see Editing, uploading, downloading); if
+not, the response has status 400 and the error message, and the journal
+is not changed.  You can get sample JSON from hledger-web's
+'/transactions' or '/accounttransactions', or from hledger's print
+command.  Eg, this saves the first transaction of the sample journal to
+'txn.json':
 
-.../hledger$ stack ghci hledger-lib
->>> writeJsonFile "txn.json" (head $ jtxns samplejournal)
->>> :q
+$ hledger -f examples/sample.journal print -O json | python3 -c 'import json,sys; json.dump(json.load(sys.stdin)[0], sys.stdout, indent=4)' > txn.json
 
-   Here's how it looks as of hledger-1.17 (remember, this JSON
-corresponds to hledger's Transaction and related data types):
+   Here's how it looks (remember, this JSON corresponds to hledger's
+Transaction and related data types):
 
 {
+    "tcode": "",
     "tcomment": "",
+    "tdate": "2008-01-01",
+    "tdate2": null,
+    "tdescription": "income",
+    "tindex": 1,
     "tpostings": [
         {
-            "pbalanceassertion": null,
-            "pstatus": "Unmarked",
+            "paccount": "assets:bank:checking",
             "pamount": [
                 {
-                    "aprice": null,
                     "acommodity": "$",
+                    "acost": null,
+                    "acostbasis": null,
                     "aquantity": {
-                        "floatingPoint": 1,
-                        "decimalPlaces": 10,
-                        "decimalMantissa": 10000000000
+                        "decimalMantissa": 1,
+                        "decimalPlaces": 0,
+                        "floatingPoint": 1
                     },
-                    "aismultiplier": false,
                     "astyle": {
                         "ascommodityside": "L",
-                        "asdigitgroups": null,
                         "ascommodityspaced": false,
-                        "asprecision": 2,
-                        "asdecimalpoint": "."
+                        "asdecimalmark": ".",
+                        "asdigitgroups": null,
+                        "asprecision": 0,
+                        "asrounding": "NoRounding"
                     }
                 }
             ],
-            "ptransaction_": "1",
-            "paccount": "assets:bank:checking",
-            "pdate": null,
-            "ptype": "RegularPosting",
+            "pbalanceassertion": null,
             "pcomment": "",
+            "pdate": null,
             "pdate2": null,
+            "poriginal": null,
+            "preal": "RealPosting",
+            "pstatus": "Unmarked",
             "ptags": [],
-            "poriginal": null
+            "ptransaction_": "1"
         },
         {
-            "pbalanceassertion": null,
-            "pstatus": "Unmarked",
+            "paccount": "income:salary",
             "pamount": [
                 {
-                    "aprice": null,
                     "acommodity": "$",
+                    "acost": null,
+                    "acostbasis": null,
                     "aquantity": {
-                        "floatingPoint": -1,
-                        "decimalPlaces": 10,
-                        "decimalMantissa": -10000000000
+                        "decimalMantissa": -1,
+                        "decimalPlaces": 0,
+                        "floatingPoint": -1
                     },
-                    "aismultiplier": false,
                     "astyle": {
                         "ascommodityside": "L",
-                        "asdigitgroups": null,
                         "ascommodityspaced": false,
-                        "asprecision": 2,
-                        "asdecimalpoint": "."
+                        "asdecimalmark": ".",
+                        "asdigitgroups": null,
+                        "asprecision": 0,
+                        "asrounding": "NoRounding"
                     }
                 }
             ],
-            "ptransaction_": "1",
-            "paccount": "income:salary",
-            "pdate": null,
-            "ptype": "RegularPosting",
+            "pbalanceassertion": null,
             "pcomment": "",
+            "pdate": null,
             "pdate2": null,
+            "poriginal": null,
+            "preal": "RealPosting",
+            "pstatus": "Unmarked",
             "ptags": [],
-            "poriginal": null
+            "ptransaction_": "1"
         }
     ],
-    "ttags": [],
-    "tsourcepos": {
-        "tag": "JournalSourcePos",
-        "contents": [
-            "",
-            [
-                1,
-                1
-            ]
-        ]
-    },
-    "tdate": "2008-01-01",
-    "tcode": "",
-    "tindex": 1,
     "tprecedingcomment": "",
-    "tdate2": null,
-    "tdescription": "income",
-    "tstatus": "Unmarked"
+    "tsourcepos": [
+        {
+            "sourceColumn": 1,
+            "sourceLine": 31,
+            "sourceName": "/home/user/hledger/examples/sample.journal"
+        },
+        {
+            "sourceColumn": 1,
+            "sourceLine": 34,
+            "sourceName": "/home/user/hledger/examples/sample.journal"
+        }
+    ],
+    "tstatus": "Unmarked",
+    "ttags": []
 }
 
-   And here's how to test adding it with curl.  This should add a new
-entry to your journal:
+   And here's how to add it with curl.  This should append a new entry
+to your journal file:
 
 $ curl http://127.0.0.1:5000/add -X PUT -H 'Content-Type: application/json' --data-binary @txn.json
 
 
-File: hledger-web.info,  Node: DEBUG OUTPUT,  Next: ENVIRONMENT,  Prev: JSON API,  Up: Top
+File: hledger-web.info,  Node: DEBUG OUTPUT,  Next: LANGUAGE,  Prev: JSON API,  Up: Top
 
-6 DEBUG OUTPUT
+9 DEBUG OUTPUT
 **************
 
-* Menu:
-
-* Debug output::
-
-
-File: hledger-web.info,  Node: Debug output,  Up: DEBUG OUTPUT
-
-6.1 Debug output
-================
-
 You can add '--debug[=N]' to the command line to log debug output.  N
 ranges from 1 (least output, the default) to 9 (maximum output).
 Typically you would start with 1 and increase until you are seeing
@@ -503,19 +922,48 @@
 'hledger-web --debug=3 2>hledger-web.log'.
 
 
-File: hledger-web.info,  Node: ENVIRONMENT,  Next: BUGS,  Prev: DEBUG OUTPUT,  Up: Top
+File: hledger-web.info,  Node: LANGUAGE,  Next: ENVIRONMENT,  Prev: DEBUG OUTPUT,  Up: Top
 
-7 ENVIRONMENT
-*************
+10 LANGUAGE
+***********
 
+hledger-web's pages can be shown in another language when a translation
+catalog is available (see Languages in the hledger manual).
+
+   When hledger-web is started with '--lang LANG', eg '--lang de', every
+page is in that language, whatever the browser asks for.  So you can use
+hledger-web in a language other than your browser's, or give every user
+of a shared server the same language.
+
+   Otherwise the language is chosen per request, and the first of these
+naming an available translation wins:
+
+  1. a '_LANG' query parameter, eg '?_LANG=de'.  This choice is
+     remembered in a '_LANG' cookie.
+  2. the '_LANG' cookie
+  3. the browser's 'Accept-Language' header, ie the browser's or
+     system's language settings
+
+   If none does, pages are in English, or with '--lang auto', in the
+language of hledger-web's environment.  So viewers usually get their
+browser's language automatically, if hledger-web has it.  Catalogs,
+including any in the config directory, are loaded when hledger-web
+starts.
+
+
+File: hledger-web.info,  Node: ENVIRONMENT,  Next: BUGS,  Prev: LANGUAGE,  Up: Top
+
+11 ENVIRONMENT
+**************
+
 *LEDGER_FILE* The main journal file to use when not specified with
 '-f/--file'.  Default: '$HOME/.hledger.journal'.
 
 
 File: hledger-web.info,  Node: BUGS,  Prev: ENVIRONMENT,  Up: Top
 
-8 BUGS
-******
+12 BUGS
+*******
 
 We welcome bug reports in the hledger issue tracker
 (https://bugs.hledger.org), or on the hledger chat or mail list
@@ -523,20 +971,29 @@
 
    Some known issues:
 
-   Does not work well on small screens, or in text-mode browsers.
+   Without JavaScript (eg in text-mode browsers), pages can be viewed
+and their links followed, but the add form, help dialog, keyboard
+shortcuts, sidebar toggle and folding don't work.
 
 
 Tag Table:
 Node: Top223
 Node: OPTIONS2577
-Node: PERMISSIONS11475
-Node: EDITING UPLOADING DOWNLOADING12625
-Node: RELOADING13640
-Node: JSON API14207
-Node: DEBUG OUTPUT19856
-Node: Debug output20008
-Node: ENVIRONMENT20526
-Node: BUGS20762
+Node: WEB UI15201
+Node: PERMISSIONS21325
+Node: EDITING UPLOADING DOWNLOADING22579
+Node: REPORTS23966
+Node: Options25177
+Node: Charts28323
+Node: From a report to its transactions30122
+Node: Holdings31121
+Node: URL PARAMETERS32942
+Node: RELOADING35215
+Node: JSON API35781
+Node: DEBUG OUTPUT41753
+Node: LANGUAGE42292
+Node: ENVIRONMENT43417
+Node: BUGS43651
 
 End Tag Table
 
diff --git a/hledger-web.txt b/hledger-web.txt
--- a/hledger-web.txt
+++ b/hledger-web.txt
@@ -11,7 +11,7 @@
      hledger web [OPTS] [QUERY]
 
 DESCRIPTION
-     This manual is for hledger's web interface, version 1.52.4.  See  also  the
+     This manual is for hledger's web interface,  version  2.0.   See  also  the
      hledger manual for common concepts and file formats.
 
      hledger  is  a  robust,  user-friendly,  cross-platform set of programs for
@@ -19,30 +19,30 @@
      and a simple, editable file format.  hledger is  inspired  by  and  largely
      compatible with ledger(1), and largely interconvertible with beancount(1).
 
-     hledger-web  is  a  simple web application for browsing and adding transac-
-     tions.  It provides a  more  user-friendly  UI  than  the  hledger  CLI  or
-     hledger-ui  TUI, showing more at once (accounts, the current account regis-
-     ter, balance charts) and allowing  history-aware  data  entry,  interactive
-     searching, and bookmarking.
+     hledger-web  is  hledger's  web  interface.  In a web browser, it shows the
+     journal, account registers, and  the  main  financial  reports  with  their
+     charts,  and  lets you search them, add transactions, and (if allowed) edit
+     the journal files.   It  shows  more  at  once  than  the  hledger  CLI  or
+     hledger-ui  (eg  the  accounts beside a register, or a report's chart above
+     its table), and every view has its own url, so  it  can  be  bookmarked  or
+     shared.
 
      hledger-web  also lets you share a journal with multiple users, or even the
-     public web.  There is no access control, so if you need that you should put
-     it behind a suitable web proxy.  As a small protection  against  data  loss
-     when  running  an  unprotected instance, it writes a numbered backup of the
-     main journal file (only) on every edit.
+     public web.  There is no user authentication,  so  if  you  need  that  you
+     should put it behind a suitable web proxy (see Permissions).
 
-     Like hledger, it reads from (and appends to) a journal  file  specified  by
-     the  LEDGER_FILE  environment  variable (defaulting to $HOME/.hledger.jour-
+     Like  hledger,  it  reads from (and appends to) a journal file specified by
+     the LEDGER_FILE environment variable  (defaulting  to  $HOME/.hledger.jour-
      nal); or you can specify files with -f options.  It can also read timeclock
-     files, timedot files, or any CSV/SSV/TSV file  with  a  date  field.   (See
+     files,  timedot  files,  or  any  CSV/SSV/TSV file with a date field.  (See
      hledger(1) -> Input for details.)
 
      hledger-web can be run in three modes:
 
-     * --serve-browse  mode  (the  default):  the app serves the web UI and JSON
-       API, and opens your default web browser to show the app if possible,  and
-       exits automatically after two minutes of inactivity (with no requests re-
-       ceived and no open browser windows viewing it).
+     * --serve-browse mode (the default): the app serves the  web  UI  and  JSON
+       API,  and opens your default web browser to show the app if possible, and
+       exits automatically once no browser window has shown it for fifteen  min-
+       utes.
 
      * --serve: the app just serves the web UI and JSON API.
 
@@ -52,58 +52,81 @@
      stdout.
 
 OPTIONS
-     hledger-web provides the following options:
+     hledger-web provides the following command line options:
 
             Flags:
-                 --serve --server       serve and log requests, don't browse or auto-exit
-                 --serve-api            like --serve, but serve only the JSON web API,
-                                        not the web UI
-                 --allow=view|add|edit  set the user's access level for changing data
-                                        (default: `add`). It also accepts `sandstorm` for
-                                        use on that platform (reads permissions from the
-                                        `X-Sandstorm-Permissions` request header).
-                 --cors=ORIGIN          allow cross-origin requests from the specified
-                                        origin; setting ORIGIN to "*" allows requests from
-                                        any origin
-                 --host=IPADDR          listen on this IP address (default: 127.0.0.1)
-                 --port=PORT            listen on this TCP port (default: 5000)
-                 --socket=SOCKET        listen on the given unix socket instead of an IP
-                                        address and port (unix only; implies --serve)
-                 --base-url=BASEURL     set the base url (default: http://IPADDR:PORT)
-                 --test                 run hledger-web's tests and exit. hspec test
-                                        runner args may follow a --, eg: hledger-web --test
-                                        --help
+                 --serve-browse            server mode: serve the web UI and JSON API,
+                                           and open a browser, and exit if inactive for 15m
+                                           (default)
+                 --serve                   server mode: just serve the web UI and JSON
+                                           API
+                 --serve-api               server mode: just serve the JSON API
+                 --allow=view|add|edit     set the user's access level for changing data
+                                           (default: `add` on a local-only address, `view`
+                                           otherwise). It also accepts `sandstorm` for that
+                                           platform (reading from the
+                                           `X-Sandstorm-Permissions` request header).
+                 --cors=ORIGIN             allow cross-origin requests from the specified
+                                           origin; setting ORIGIN to "*" allows requests
+                                           from any origin
+                 --host=IPADDR             listen on this IP address (default: 127.0.0.1)
+                 --port=PORT               listen on this TCP port (default: 5000); 0
+                                           means a free port chosen by the OS
+                 --socket=SOCKET           listen on the given unix socket instead of an
+                                           IP address and port (only on unix)
+                 --base-url=BASEURL        set the base url (default: http://IPADDR:PORT)
+                 --chart[=KIND,net,SCALE]  set the charts' defaults, as the commands'
+                                           --chart does. KIND: lay out the statements'
+                                           charts with each period's sections in one bar,
+                                           above and below zero (diverging, the default),
+                                           or side by side (grouped). net: show the net
+                                           total lines by default (the N key toggles them,
+                                           and the browser remembers that). SCALE: the
+                                           amount that fills the charts (eg 1000 or 1000
+                                           USD; one per commodity), for comparable charts.
+                 --lang=LANG               show the web UI in this language (en, de, es,
+                                           ru, zh); or with auto, use each viewer's browser
+                                           language if available, otherwise the server's.
+                                           (Default: the browser's language if available,
+                                           otherwise en.)
 
-     By default hledger-web listens only on IP address 127.0.0.1, which  be  ac-
-     cessed only from the local machine.
+     By default hledger-web listens only on IP address 127.0.0.1, which  can  be
+     accessed only from the local machine.
 
      To  allow access from elsewhere, use --host to specify an externally acces-
-     sible address configured on  this  machine,  The  special  address  0.0.0.0
+     sible address configured on this  machine.   The  special  address  0.0.0.0
      causes it to listen on all of this machine's addresses.
 
      Similarly,  you  can  use  --port  to listen on a TCP port other than 5000.
      This is useful if you want to run multiple hledger-web instances on  a  ma-
-     chine.
+     chine.   --port  0  makes the operating system choose a free port, which is
+     reported in the startup message and in the default base url, and  is  where
+     the  browser  is opened in --serve-browse mode.  This can be useful eg when
+     scripting.
 
-     When  --socket  is  used, hledger-web creates and communicates via a socket
-     file instead of a TCP port.  This can be more secure,  respects  unix  file
-     permissions,  and  makes certain use cases easier, such as running per-user
-     instances   behind   an   nginx    reverse    proxy.     (Eg:    proxy_pass
+     When --socket is used, hledger-web creates and communicates  via  a  socket
+     file  instead  of  a TCP port.  This can be more secure, respects unix file
+     permissions, and makes certain use cases easier, such as  running  per-user
+     instances    behind    an    nginx    reverse   proxy.    (Eg:   proxy_pass
      http://unix:/tmp/hledger/${remote_user}.socket;.)
 
      You can use --base-url to change the protocol, hostname, port and path that
-     appear  in  hledger-web's  hyperlinks.   This is useful eg when integrating
-     hledger-web within a larger website.  The default is http://HOST:PORT/  us-
-     ing  the  server's  configured host address and TCP port (or http://HOST if
+     appear in hledger-web's hyperlinks.  This is  useful  eg  when  integrating
+     hledger-web  within a larger website.  The default is http://HOST:PORT/ us-
+     ing the server's configured host address and TCP port  (or  http://HOST  if
      PORT is 80).  Note this affects url generation but not route parsing.
 
      hledger-web also supports many of hledger's general options:
 
-            General input/data transformation flags:
-              -f --file=[FMT:]FILE      Read data from FILE, or from stdin if FILE is -,
-                                        inferring format from extension or a FMT: prefix.
-                                        Can be specified more than once. If not specified,
-                                        reads from $LEDGER_FILE or $HOME/.hledger.journal.
+            General input flags:
+              -f --file=[FMT:]FILE      Use this as the journal file (- means stdin). If
+                                        not specified, $LEDGER_FILE or ~/.hledger.journal
+                                        will be used. If specified more than once, the
+                                        files will be read in order. Each file's format
+                                        (journal, csv, timeclock, timedot, rules..) is
+                                        inferred from the file extension or a FMT: prefix.
+                                        Some commands (add, import) write to the (first)
+                                        file, and expect it to be in journal format.
                  --rules=RULESFILE      Use rules defined in this rules file for
                                         converting subsequent CSV/SSV/TSV files. If not
                                         specified, uses FILE.csv.rules for each FILE.csv.
@@ -118,27 +141,30 @@
                                         will also be applied to these transactions. In
                                         hledger-ui, also make future-dated transactions
                                         visible at startup.
-              -I --ignore-assertions    don't check balance assertions by default
-                 --txn-balancing=...    how to check that transactions are balanced:
-                                        'old':   use global display precision
-                                        'exact': use transaction precision (default)
-                 --infer-costs          infer conversion equity postings from costs
-                 --infer-equity         infer costs from conversion equity postings
+                 --ignore-assertions    don't check balance assertions by default
+                 --ignore-lots          don't track lots: skip lot checks, inferred cost
+                                        bases and gain postings
+              -I                        shortcut for --ignore-assertions --ignore-lots
+                 --txn-tolerance=...    how much imbalance to allow in transactions:
+                                        'entry':   - the entry's precision (default)
+                                        'display': - display precision (legacy)
+                 --infer-costs          infer costs from conversion equity postings
+                 --infer-equity         infer conversion equity postings from costs
+                 --infer-imbalance      add postings showing tolerated imbalances
                  --infer-market-prices  infer market prices from costs
                  --pivot=TAGNAME        use a different field or tag as account names
               -s --strict               do extra error checks (and override -I)
-                 --verbose-tags         add tags indicating generated/modified data
 
-            General output/reporting flags (supported by some commands):
+            General output flags (affecting some commands):
               -b --begin=DATE           include postings/transactions on/after this date
               -e --end=DATE             include postings/transactions before this date
                                         (with a report interval, will be adjusted to
                                         following subperiod end)
-              -D --daily                multiperiod report with 1 day interval
-              -W --weekly               multiperiod report with 1 week interval
-              -M --monthly              multiperiod report with 1 month interval
-              -Q --quarterly            multiperiod report with 1 quarter interval
-              -Y --yearly               multiperiod report with 1 year interval
+              -D --daily                set report interval: 1 day
+              -W --weekly               set report interval: 1 week
+              -M --monthly              set report interval: 1 month
+              -Q --quarterly            set report interval: 1 quarter
+              -Y --yearly               set report interval: 1 year
               -p --period=PERIODEXP     set begin date, end date, and/or report interval,
                                         with more flexibility
                  --today=DATE           override today's date (affects relative dates)
@@ -153,63 +179,230 @@
                  --depth=DEPTHEXP       if a number (or -NUM): show only top NUM levels
                                         of accounts. If REGEXP=NUM, only apply limiting to
                                         accounts matching the regular expression.
-              -B --cost                 show amounts converted to their cost/sale amount
-              -V --market               Show amounts converted to their value at period
-                                        end(s) in their default valuation commodity.
-                                        Equivalent to --value=end.
-              -X --exchange=COMM        Show amounts converted to their value at period
-                                        end(s) in the specified commodity.
-                                        Equivalent to --value=end,COMM.
-                 --value=WHEN[,COMM]    show amounts converted to their value on the
-                                        specified date(s) in their default valuation
-                                        commodity or a specified commodity. WHEN can be:
+              -B --cost                 convert amounts to their cost basis ({}), or else
+                                        their cost/sale amount (@/@@)
+              -V --market               valuation mode: show amounts converted to market
+                                        value at period end(s) in their default valuation
+                                        commodity. Short for --value=end.
+              -X --exchange=COMM        valuation mode: show amounts converted to market
+                                        value at period end(s) in the specified commodity.
+                                        Short for --value=end,COMM.
+                 --value=WHEN[,COMM]    valuation mode: show amounts converted to market
+                                        value on the specified date(s) in their default
+                                        valuation commodity or a specified commodity. WHEN
+                                        can be:
                                         'then':     value on transaction dates
                                         'end':      value at period end(s)
                                         'now':      value today
                                         YYYY-MM-DD: value on given date
+                                        'cost':     cost basis, or else transacted cost
+                                        (same as -B)
+                                        'transacted': transacted cost/sale amount (@/@@)
+                                        only
+                                        COMM may be written in double quotes; '""' or an
+                                        empty COMM means the no-symbol commodity.
+                 --lots                 show lot subaccounts and other lot details
               -c --commodity-style=S    Override a commodity's display style.
                                         Eg: -c '.' or -c '1.000,00 EUR'
-                 --pretty[=YN]          Use box-drawing characters in text output? Can be
-                                        'y'/'yes' or 'n'/'no'.
-                                        If YN is specified, the equals is required.
+                 --pretty[=YN]          Use box-drawing characters in text output? The
+                                        optional 'y'/'yes' or 'n'/'no' arg requires =.
+                 --title=T              set or customise a report title
+                 --subreport-titles=TS  customise subreport headings in compound reports
+                                        (|-separated)
+                 --period-titles=OPT    customise headings in periodic reports:
+                                        'compact': readable period names when possible
+                                        'dates':   exact dates/date ranges always
 
             General help flags:
-              -h --help                 show command line help
-                 --tldr                 show command examples with tldr
-                 --info                 show the manual with info
-                 --man                  show the manual with man
+              -?                        show the hledger quick reference
+              -h --help                 show this command's usage help
+                 --info                 show this command's manual with info
+                 --man                  show this command's manual with man
+                 --webman               show this command's manual on the web
+                 --examples             show examples for this command
                  --version              show version information
+                 --test[=PATTERN]       run built-in tests (those matching PATTERN) and
+                                        exit
+                 --write-lang=LANG      write LANG's PO file to the config directory, for
+                                        editing translations, and exit
                  --debug=[1-9]          show this much debug output (default: 1)
                  --pager=YN             use a pager when needed ? y/yes (default) or n/no
                  --color=YNA --colour   use ANSI color ? y/yes, n/no, or auto (default)
 
-     hledger-web shows accounts with zero balances by default (like  hledger-ui,
-     and  unlike  hledger).   Using the -E/--empty flag will reverse this behav-
-     iour.  If you see accounts which appear to have a zero balance, but  cannot
-     be hidden with -E, it's because they have a mixed-cost balance, which looks
-     like zero when costs are hidden.  (hledger-web does not show costs.)
+     Some of these can be adjusted while hledger-web is running, in the web UI's
+     Options panel.
 
-     Reporting  options  and/or  query  arguments  can be used to set an initial
-     query, which although not shown in the UI, will restrict the data shown (in
-     addition to any search query entered in the UI).
+     hledger-web  shows accounts with zero balances by default (like hledger-ui,
+     and unlike hledger); -E/--empty starts it with them hidden instead.  In the
+     web UI, the Zero balances option or the z key shows or  hides  them.   (The
+     holdings  page  differs:  its closed positions are hidden by default, as in
+     the holdings command; -E starts it with them shown, and z  there  shows  or
+     hides them.)
 
-     If you use the bash shell, you can auto-complete flags by pressing  TAB  in
+     Report  options and a query given at startup set the view hledger-web opens
+     with, by putting them in its url (see URL parameters).  Eg  hledger-web  -V
+     -M    opens   /balancesheet?interval=monthly&value=end,   and   hledger-web
+     --cleared -3 assets opens  /balancesheet?q=assets  status:*&depth=3.   They
+     are  only  a  starting  point:  they can be changed in the web UI, and they
+     don't affect other urls or the JSON API.  Report options  that  hledger-web
+     has no equivalent for are ignored.
+
+     Note, a startup query doesn't restrict what hledger-web serves; to do that,
+     give it a file holding only the entries to serve (eg one written by hledger
+     print QUERY).
+
+     If  you  use the bash shell, you can auto-complete flags by pressing TAB in
      the command line.  If this is not working see Install > Shell completions.
 
-PERMISSIONS
-     By  default, hledger-web allows anyone who can reach it to view the journal
-     and to add new transactions, but not to change existing data.
+WEB UI
+     hledger-web's main views are:
 
-     You can restrict who can reach it, by
+     * the journal view, showing journal entries, newest first, with their post-
+       ings
 
-     * setting the IP address it listens on (see --host above).  By  default  it
+     * the report views, described below: the balance sheet,  income  statement,
+       cashflow  statement  (and holdings, for journals using lots), and All ac-
+       counts report
+
+     * a register view for each account, reached by clicking  an  account  name,
+       showing  the  transactions  affecting that account (and its subaccounts),
+       with a running balance and a balance chart.
+
+     Every page has, from the top: links to the journal  and  the  reports,  the
+     search form, the options, and then the view itself.  The options are hidden
+     until  you  open  them (click Options, or press o); while hidden, they list
+     the ones in effect, eg "Monthly A Depth 2 A Tree".
+
+     The journal and register show the newest 1000 matching  transactions,  with
+     links  to  older and newer pages.  When the transactions span more than one
+     year, the options include a row of years, to narrow the view to  one  year;
+     shift-click a second year to select a range of years.
+
+     The  register's  chart  shows  the running balance over the page's transac-
+     tions.  With several commodities, use the legend, or the [ and ]  keys,  to
+     choose  the  one  charted.  Click a point to go to its transaction, or drag
+     across the chart to see the transactions of those  dates.   The  register's
+     Costs option shows the costs recorded with its amounts.
+
+     The sidebar lists every account, and optionally their balances (parent bal-
+     ances  include subaccounts).  The search doesn't change it, except that its
+     dates set the balances' date.  The balances are hidden at first, since on a
+     large journal they take much of each  page's  time;  click  the  "Balances"
+     heading  above the accounts to show them, or to hide them again.  These are
+     historical balances, as of the end of the report period set by date:,  oth-
+     erwise  the  latest  (the  heading shows the date).  While the balances are
+     hidden, all accounts are listed, even with Zero balances:  Hidden.   It  is
+     always  a  tree, with carets that fold and open each group, whether the Ac-
+     counts option is List or Tree.  The a and + above it fold or open  a  level
+     of  the  whole tree, without changing the page; its depth is its own, apart
+     from the page's depth limit.  The browser remembers the sidebar's depth and
+     the groups you open or close (until the next a or +).  The  button  at  the
+     top  left  (or  the s key) shows or hides the sidebar, and it stays the way
+     you left it from page to page.  On a narrow screen, it slides  the  sidebar
+     in or out.
+
+     Click an account name to see its register, with the search, or an amount to
+     see  the  transactions it is made of.  In the journal and register, click a
+     date to see that day's journal entries.
+
+     The search form filters every view with hledger's query syntax, eg expenses
+     date:thismonth; the help dialog summarises the query types.  The search and
+     the options are part of the page's url (see URL parameters).
+
+     The add form (press a, or click "Add a transaction" in  the  journal  view)
+     adds a transaction to the main journal file, if the access level allows it,
+     and  if the journal would still be readable with it added (see Editing, up-
+     loading, downloading).  It autocompletes  account  names  and  descriptions
+     from your existing entries.
+
+     The  help  dialog  (press ?, or click the question mark button) lists these
+     keyboard shortcuts, which work when you are not typing in a field:
+
+     * h or ? - show or hide the help dialog
+
+     * g - go to another page: shows a menu of the pages,  each  with  its  key;
+       then  j  journal,  b balance sheet, i income statement, c cashflow state-
+       ment, h holdings (for journals using lots), a  all  accounts  (escape  to
+       cancel)
+
+     * n  /  p - go to the next / previous page, in the g menu's order, wrapping
+       round
+
+     * a - add a transaction (escape to cancel)
+
+     * s - show or hide the sidebar
+
+     * shift with 1-9 - fold or open the sidebar's accounts to  that  depth,  as
+       its  a  and  +  do (by the digit keys' place, whatever the layout; except
+       where shift with one types a character that is a shortcut  itself,  eg  a
+       digit on AZERTY keyboards, or / on German ones)
+
+     * b  -  show  or  hide the sidebar's balances, as its Balances heading does
+       (while the sidebar shows)
+
+     * o - show or hide the report options
+
+     * c - show or hide the report's chart (on pages with one)
+
+     * [ / ] - chart the previous / next commodity (on  pages  whose  chart  has
+       several, wrapping round)
+
+     * N  -  show  or  hide the chart's net total line (on pages whose chart has
+       one)
+
+     * d - show or hide the report's data, its table (on pages with a chart)
+
+     * f - full window: show only the report's heading and data,  or  everything
+       (s, o and / leave it, showing what they ask for)
+
+     * z  -  show  or  hide  accounts  with zero balances (on the holdings page:
+       closed positions)
+
+     * t - show accounts as a tree, or a list
+
+     * H - show ending balances, or balance changes
+
+     * L - show or hide lot detail
+
+     * V - show amounts at market value, or as recorded
+
+     * B - show amounts at cost, or as recorded
+
+     * R - show only real postings, or all
+
+     * U, P, C - show only unmarked, pending, or cleared transactions, or all
+
+     * S - sort by amount, or by account
+
+     * T, A - add or remove the row total and average columns (multi-period  re-
+       ports)
+
+     * D,  W,  M,  Q, Y - set the report interval (daily, weekly, monthly, quar-
+       terly, yearly); pressed again, remove it
+
+     * 0-9, -, + - set or adjust the account depth limit (- and + step between 0
+       and the deepest)
+
+     * / - focus the search form, ready to add a term (escape to leave it)
+
+     * Delete or Backspace - clear the search, as its clear button does
+
+     The pages are light or dark, following your OS or  browser's  color  scheme
+     setting, and switch when it changes.
+
+     Editing, uploading and downloading journal files is described below.
+
+PERMISSIONS
+     You can restrict who can access hledger-web by
+
+     * setting  the  IP address it listens on (see --host above).  By default it
        listens on 127.0.0.1, accessible to users on the local machine only.
 
-     * putting it behind an authenticating proxy, such as caddy or apache
+     * or by putting it behind an authenticating proxy, such as caddy or apache
 
-     * putting it behind a firewall
+     * or by putting it behind a firewall.
 
-     And  you  can restrict what the users reaching it can do, by specifying the
+     And you can restrict what the users reaching it can do, by  specifying  the
      --allow=ACCESSLEVEL option at startup.  ACCESSLEVEL is one of:
 
      * view - allows viewing the journal file(s)
@@ -218,39 +411,263 @@
 
      * edit - also allows editing, uploading or downloading the journal file(s)
 
-     * sandstorm - (for the hledger-web  Sandstorm  app:)  allows  whichever  of
-       view,  add,  or  edit  are  specified in the X-Sandstorm-Permissions HTTP
+     * sandstorm  -  (for  the  hledger-web  Sandstorm app:) allows whichever of
+       view, add, or edit are  specified  in  the  X-Sandstorm-Permissions  HTTP
        header
 
-     The default access level is add.
+     The  default  access  level  is  add when listening on a local-only address
+     (127.0.0.1, ::1, localhost, or a unix socket), and view otherwise.  To  al-
+     low  more than the default access, start it with an explicit --allow=add or
+     --allow=edit option.
 
 EDITING, UPLOADING, DOWNLOADING
-     If you enable the manage capability  mentioned  above,  you'll  see  a  new
-     "spanner"  button  to the right of the search form.  Clicking this will let
-     you edit, upload, or download the journal file or any files it includes.
+     If you start hledger-web with --allow=edit, you'll see a new "spanner" but-
+     ton to the right of the search form.  Clicking this will let you edit,  up-
+     load, or download the journal file or any files it includes.
 
-     Note, unlike any other hledger command, in this mode you (or  any  visitor)
-     can alter or wipe the data files.
+     Note,  unlike  any other hledger command, in this mode you (or any visitor)
+     can alter or wipe the data files.  Before  saving  an  edited  or  uploaded
+     file,  hledger-web  saves  a numbered backup of it (eg main.journal.1, then
+     main.journal.2); if the backup can't be written, the file is  not  changed.
+     (Adding  a transaction appends it to the main journal file without making a
+     backup.)  hledger-web is not aware of version control  systems,  currently;
+     if you use one, you'll have to arrange to commit the changes yourself.
 
-     Normally  whenever  a file is changed in this way, hledger-web saves a num-
-     bered backup (assuming file permissions allow it, the  disk  is  not  full,
-     etc.)   hledger-web  is not aware of version control systems, currently; if
-     you use one, you'll have to arrange to commit the changes yourself (eg with
-     a cron job or a file watcher like entr).
+     Changes  which would leave the journal unreadable are refused, and the file
+     is not changed.  This applies to edits,  uploads  and  added  transactions.
+     Each  change  is  checked as the next read of the journal will check it, in
+     the context of all the journal's files and with the options hledger-web was
+     started with: so transactions must balance, balance  assertions  must  pass
+     (unless started with -I), lots must be valid, and with --strict, the strict
+     checks must pass too.
 
-     Changes which would leave the journal file(s) unparseable or non-valid  (eg
-     with  failing  balance  assertions)  are prevented.  (Probably.  This needs
-     re-testing.)
+REPORTS
+     Besides  the journal and the account registers, hledger-web shows these re-
+     ports.  The sidebar and the links at the top of every page lead to each  of
+     them,  and  so  does the g key followed by the first letter of the report's
+     name:
 
+     * Balance sheet (b, /balancesheet): assets, liabilities and net worth, like
+       the balancesheet command.  Its Equity option adds an equity section, like
+       balancesheetequity.
+
+     * Income statement (i, /incomestatement): revenues, expenses  and  net  in-
+       come, like incomestatement.
+
+     * Cashflow (c, /cashflow): changes in cash accounts, like cashflow.
+
+     * Holdings  (h,  /holdings):  investments and their performance, like hold-
+       ings.  Shown only for journals that use lots; see below.
+
+     * All accounts (a, /balance): all accounts, or those you search  for,  like
+       balance.
+
+     Each  report  shows  a chart and then a table (by default; both can be tog-
+     gled).  Click any amount to see the transactions it is made of.
+
+   Options
+     A report's options (click Options, or press o) change what it shows.  These
+     are similar to hledger's command-line options and hledger-ui's  keys.   The
+     main ones, with their keyboard shortcuts:
+
+     * Interval  (D,  W,  M,  Q, Y): one column for the whole period, or one per
+       day, week, month, quarter or year  (see  Report  intervals).   Until  you
+       choose one, the reports pick an interval to suit the period shown (except
+       holdings, whose interval is its own; see Holdings): monthly for up to two
+       years,  quarterly for up to six, yearly beyond.  Click a column's heading
+       to see the report for just its dates.
+
+     * Show (H): balance changes in each period, or ending balances  (which  in-
+       clude everything before the period).  The balance sheet shows ending bal-
+       ances  by  default  and the other reports show changes, as their commands
+       do; the report's heading says which it is showing.
+
+     * Depth (0-9, -, +): how many levels  of  accounts  to  show  (see  Depth).
+       Depth 0 shows only the totals.  Until you choose one, the depth is 1, the
+       top-level  accounts.  The a and + beside the table's Account heading step
+       it too.  In tree mode they fold or open a level of the whole tree.   (The
+       sidebar has a depth of its own; see above.)
+
+     * Accounts  (t):  a list, or a tree with subtotals; the List and Tree links
+       beside the table's Account heading switch too.  In a tree,  the  accounts
+       below the depth limit are folded, and their carets open them in place (at
+       depth 0, all of them, under each section's total).
+
+     * Amounts  (B,  V):  as recorded, at cost, or at market value at the end of
+       each period (see Cost reporting and Value reporting).
+
+     * Zero balances (z): hide or show accounts whose balance is zero.  (On  the
+       holdings  page,  z  toggles  Closed  positions instead; use this option's
+       links there.)
+
+     * Equity (balance sheet only):  hide  or  show  the  equity  section.   The
+       browser remembers this choice for each hledger-web server.
+
+     * Status (U, P, C), Postings (R), account types, and commodities: show only
+       transactions  with  that status, only real postings, or only some account
+       types or commodities.  These rows edit the search,  adding  a  term  like
+       status:* or type:A.  Shift-click selects several types or commodities.
+
+     The  options  you  choose stay in effect as you move to other pages, except
+     Show, which each report sets to its own default.  On the journal and regis-
+     ter, the report options are shown muted, but are kept.
+
+     The search form filters reports as it does the other pages, and  its  date:
+     terms  set  the  report's dates.  An interval or depth typed in the search,
+     like date:monthly or depth:2, moves into the options when the page reloads.
+     A depth limit for some accounts only, like  depth:assets=3,  stays  in  the
+     search.
+
+     The  options  are  also  URL  parameters, so you can bookmark a report with
+     them.
+
+     (For more detail, see the hledger manual, eg CONCEPTS.)
+
+   Charts
+     A report's chart is the one its command draws with --chart: eg  a  bar  per
+     account,  or  with  an interval, each account over time, and for the state-
+     ments, each section and the net total.  In tree mode it shows the  accounts
+     down  to the depth limit.  With several commodities, use the legend, or the
+     [ and ] keys, to choose the one charted.  The  Balance  page's  and  state-
+     ments'  charts stack each period's accounts (or sections) in one bar, above
+     and below zero; the Chart row in Options (or  --chart=grouped  at  startup)
+     shows  a  bar  per account type (or section), side by side, instead (on the
+     Balance  page  with  no  interval,  for  the  whole  period,   as   balance
+     --chart=grouped does).  --chart at startup takes the same value as the com-
+     mands' --chart; its SCALE amounts fix the scales of the report and register
+     charts,  so that they can be compared.  Hover over a bar or a line (or on a
+     touch screen, tap it) to see its period (or date, or account),  its  series
+     and  its  amount.  Charts are drawn as wide as the page shows them, and re-
+     drawn when that changes, eg when you hide or show the sidebar or resize the
+     window.
+
+     The c key hides or shows the chart, and d the table  (the  report's  data).
+     You  can  also click the Chart and Data buttons at their top right corners,
+     whose carets show whether they are shown.  The N key shows or hides the net
+     total line (or marks), eg a statement's net,  or  holdings'  value  or  net
+     gain;  this  is  hidden  at  first,  leaving  the  bars  it totals (or with
+     --chart=net at startup, shown at first).  The browser  remembers  this  for
+     each  hledger-web server, and once you have chosen with N, your choice wins
+     over --chart=net.
+
+   From a report to its transactions
+     Click an amount to see its account's register for that period: the transac-
+     tions the amount is made of.  An ending balance's register starts with  the
+     balance  brought  forward,  so its final running balance is that amount.  A
+     section's total shows the register  of  all  the  section's  accounts.   An
+     amount  shown  at  cost  or  market  value  leads to a register showing its
+     amounts the same way.
+
+     Some things can make the register look different from the report:
+
+     * The statements show liabilities, equity and revenues as positive amounts,
+       as their commands do, so their registers show the same  amounts  negated.
+       The amount's tooltip says so.
+
+     * When  a posting has a date of its own, the report counts it on that date,
+       but the register lists its whole transaction, on the transaction's date.
+
+   Holdings
+     The holdings report shows one row for each commodity held in each  account,
+     with  its  cost  basis, value and gains.  Its chart has a bar for each one,
+     showing its cost basis and unrealised gain or loss.  Its  own  options  can
+     show:
+
+     * each lot separately (Lots, L),
+
+     * fully disposed positions and their realised gains (Closed positions, z),
+
+     * all values in the market valuation commodity (Values).
+
+     Closed positions are hidden by default, as in the holdings command, but the
+     totals' RGain and XIRR always include them; a note below the table says how
+     many are hidden, with a link to show them.
+
+     Its  depth  limit  doesn't fold accounts: as on the command line, it merges
+     the deeper accounts' positions, by commodity,  into  the  accounts  at  the
+     limit.
+
+     With  an Interval chosen (it picks none by itself), it shows how your hold-
+     ings changed, like holdings with a report interval: a row for each period's
+     end, with the totals of all the holdings then, and a bar for  each  in  the
+     chart.   Each  row's  date links to the holdings on that date.  This page's
+     interval is its own, since it makes a different report here:  choosing  one
+     doesn't  change the other reports' interval, nor theirs this page's, and an
+     interval given at startup (eg -M) is theirs.  Its Gains option chooses what
+     the gain columns cover: each period, the  time  since  the  report's  start
+     date, or the time since acquisition (the default).  With the first two, the
+     chart shows those gains: realised, and unrealised (hatched).  H toggles be-
+     tween gains since acquisition and gains in each period.
+
+     On  journals  that use lots, every page also has a Lots option, showing lot
+     subaccounts and per-lot postings.
+
+URL PARAMETERS
+     A page's url includes its search and options, so a  bookmark  or  a  shared
+     link shows the same view.  You can also write these urls yourself, eg /bal-
+     ancesheet?interval=monthly&depth=2 or /register?account=assets:bank.  These
+     are the parameters, most corresponding to hledger options:
+
+     * q - the search
+
+     * account  -  the account whose register to show (with its subaccounts, un-
+       less subs=0)
+
+     * page - which page of transactions to show, in the journal and register (1
+       is the newest)
+
+     * interval - daily, weekly, monthly, quarterly or yearly (like -D, -W,  -M,
+       -Q, -Y), or none for one column; without it the reports pick one
+
+     * hinterval  - the holdings page's own interval, in the same words; without
+       it, none
+
+     * depth - a number (like --depth), or all for no limit; without it, 1
+
+     * accum - change, historical or cumulative (like  --change,  -H,  --cumula-
+       tive); on the holdings page, with an interval, what the gains cover
+
+     * value  -  none, cost, or then, end, now or a date, optionally followed by
+       ,COMMODITY (like --value)
+
+     * infer - 1 to infer market prices from transaction costs too  (like  --in-
+       fer-market-prices)
+
+     * empty - 1 to show zero balances, 0 to hide them (like -E)
+
+     * list - tree or flat (like --tree, --flat)
+
+     * sort - amount (like -S)
+
+     * total,  avg,  pct  - 1 to add totals, averages, or show percentages (like
+       -T, -A, -%)
+
+     * calc - valuechange, gain or count (like --valuechange, --gain, --count)
+
+     * date2 - 1 to use secondary dates (like --date2)
+
+     * costs - 1 to show costs, in the register
+
+     * equity - 1 or 0, on the balance sheet (the  old  /balancesheetequity  ad-
+       dress leads to equity=1)
+
+     * lots - 1 to show lots (like --lots)
+
+     * closed  -  1,  on  the holdings page, to show closed positions, 0 to hide
+       them
+
+     * chart - grouped, on the Balance and statement pages, to  chart  each  pe-
+       riod's account types (or sections) side by side (like --chart=grouped)
+
 RELOADING
-     hledger-web detects changes made to the files by other  means  (eg  if  you
-     edit  it  directly,  outside of hledger-web), and it will show the new data
-     when you reload the page or navigate to a new page.  If a  change  makes  a
-     file  unparseable, hledger-web will display an error message until the file
+     hledger-web  detects  changes  made  to the files by other means (eg if you
+     edit it directly, outside of hledger-web), and it will show  the  new  data
+     when  you  reload  the page or navigate to a new page.  If a change makes a
+     file unparseable, hledger-web will display an error message until the  file
      has been fixed.
 
-     (Note: if you are viewing files mounted from  another  machine,  make  sure
-     that both machine clocks are roughly in step.)
+     (If you are viewing files mounted from another machine, make sure that both
+     machines have roughly the same idea of what time it is.)
 
 JSON API
      In  addition  to the web UI, hledger-web also serves a JSON API that can be
@@ -269,12 +686,13 @@
             /commodities
             /accounts
             /accounttransactions/ACCOUNTNAME
+            /openapi.json
 
      Eg,  all  account  names  in the journal (similar to the accounts command).
      (hledger-web's JSON does not include newlines, here we use python to  pret-
      tify it):
 
-            $ curl -s http://127.0.0.1:5000/accountnames | python -m json.tool
+            $ curl -s http://127.0.0.1:5000/accountnames | python3 -m json.tool
             [
                 "assets",
                 "assets:bank",
@@ -293,7 +711,7 @@
 
      Or all transactions:
 
-            $ curl -s http://127.0.0.1:5000/transactions | python -m json.tool
+            $ curl -s http://127.0.0.1:5000/transactions | python3 -m json.tool
             [
                 {
                     "tcode": "",
@@ -308,130 +726,132 @@
                             "pamount": [
                                 {
                                     "acommodity": "$",
-                                    "aismultiplier": false,
-                                    "aprice": null,
+                                    "acost": null,
+                                    "acostbasis": null,
             ...
 
      Most  of  the JSON corresponds to hledger's data types; for details of what
      the fields mean, see the Hledger.Data.Json haddock docs and  click  on  the
      various  data types, eg Transaction.  And for a higher level understanding,
-     see the journal docs.  There is also a basic OpenAPI specification.
+     see the journal docs.  There is also a basic  OpenAPI  specification,  also
+     served at /openapi.json.
 
-     In some cases there is outer JSON corresponding to a "Report" type.  To un-
-     derstand that, go to the Hledger.Web.Handler.MiscR haddock and look at  the
-     source  for  the  appropriate  handler to see what it returns.  Eg for /ac-
-     counttransactions it's getAccounttransactionsR, returning a  "accountTrans-
-     actionsReport  ...".   Looking up the haddock for that we can see that /ac-
-     counttransactions returns an AccountTransactionsReport, which consists of a
-     report title and a list of AccountTransactionsReportItem (etc).
+     Some routes return a report type wrapping the data; eg /accounttransactions
+     returns  an  AccountTransactionsReport, a report title and a list of items.
+     The handlers in Hledger.Web.Handler.MiscR show what each route returns.
 
      You can add a new transaction to the journal with a PUT request to /add, if
-     hledger-web was started with the add capability (enabled by default).   The
-     payload  must  be the full, exact JSON representation of a hledger transac-
-     tion (partial data won't do).  You can get sample JSON  from  hledger-web's
-     /transactions   or   /accounttransactions,   or  you  can  export  it  with
-     hledger-lib, eg like so:
+     hledger-web was started with --allow=add (the default when listening  on  a
+     local-only  address).  The payload must be the full, exact JSON representa-
+     tion of a hledger transaction (partial data won't do).   The  journal  must
+     still  be  readable  with the transaction added, with hledger-web's startup
+     options (see Editing, uploading, downloading); if  not,  the  response  has
+     status  400 and the error message, and the journal is not changed.  You can
+     get sample JSON from hledger-web's /transactions  or  /accounttransactions,
+     or  from  hledger's print command.  Eg, this saves the first transaction of
+     the sample journal to txn.json:
 
-            .../hledger$ stack ghci hledger-lib
-            >>> writeJsonFile "txn.json" (head $ jtxns samplejournal)
-            >>> :q
+            $ hledger -f examples/sample.journal print -O json | python3 -c 'import json,sys; json.dump(json.load(sys.stdin)[0], sys.stdout, indent=4)' > txn.json
 
-     Here's how it looks as of hledger-1.17 (remember, this JSON corresponds  to
-     hledger's Transaction and related data types):
+     Here's how it looks (remember, this JSON corresponds to hledger's  Transac-
+     tion and related data types):
 
             {
+                "tcode": "",
                 "tcomment": "",
+                "tdate": "2008-01-01",
+                "tdate2": null,
+                "tdescription": "income",
+                "tindex": 1,
                 "tpostings": [
                     {
-                        "pbalanceassertion": null,
-                        "pstatus": "Unmarked",
+                        "paccount": "assets:bank:checking",
                         "pamount": [
                             {
-                                "aprice": null,
                                 "acommodity": "$",
+                                "acost": null,
+                                "acostbasis": null,
                                 "aquantity": {
-                                    "floatingPoint": 1,
-                                    "decimalPlaces": 10,
-                                    "decimalMantissa": 10000000000
+                                    "decimalMantissa": 1,
+                                    "decimalPlaces": 0,
+                                    "floatingPoint": 1
                                 },
-                                "aismultiplier": false,
                                 "astyle": {
                                     "ascommodityside": "L",
-                                    "asdigitgroups": null,
                                     "ascommodityspaced": false,
-                                    "asprecision": 2,
-                                    "asdecimalpoint": "."
+                                    "asdecimalmark": ".",
+                                    "asdigitgroups": null,
+                                    "asprecision": 0,
+                                    "asrounding": "NoRounding"
                                 }
                             }
                         ],
-                        "ptransaction_": "1",
-                        "paccount": "assets:bank:checking",
-                        "pdate": null,
-                        "ptype": "RegularPosting",
+                        "pbalanceassertion": null,
                         "pcomment": "",
+                        "pdate": null,
                         "pdate2": null,
+                        "poriginal": null,
+                        "preal": "RealPosting",
+                        "pstatus": "Unmarked",
                         "ptags": [],
-                        "poriginal": null
+                        "ptransaction_": "1"
                     },
                     {
-                        "pbalanceassertion": null,
-                        "pstatus": "Unmarked",
+                        "paccount": "income:salary",
                         "pamount": [
                             {
-                                "aprice": null,
                                 "acommodity": "$",
+                                "acost": null,
+                                "acostbasis": null,
                                 "aquantity": {
-                                    "floatingPoint": -1,
-                                    "decimalPlaces": 10,
-                                    "decimalMantissa": -10000000000
+                                    "decimalMantissa": -1,
+                                    "decimalPlaces": 0,
+                                    "floatingPoint": -1
                                 },
-                                "aismultiplier": false,
                                 "astyle": {
                                     "ascommodityside": "L",
-                                    "asdigitgroups": null,
                                     "ascommodityspaced": false,
-                                    "asprecision": 2,
-                                    "asdecimalpoint": "."
+                                    "asdecimalmark": ".",
+                                    "asdigitgroups": null,
+                                    "asprecision": 0,
+                                    "asrounding": "NoRounding"
                                 }
                             }
                         ],
-                        "ptransaction_": "1",
-                        "paccount": "income:salary",
-                        "pdate": null,
-                        "ptype": "RegularPosting",
+                        "pbalanceassertion": null,
                         "pcomment": "",
+                        "pdate": null,
                         "pdate2": null,
+                        "poriginal": null,
+                        "preal": "RealPosting",
+                        "pstatus": "Unmarked",
                         "ptags": [],
-                        "poriginal": null
+                        "ptransaction_": "1"
                     }
                 ],
-                "ttags": [],
-                "tsourcepos": {
-                    "tag": "JournalSourcePos",
-                    "contents": [
-                        "",
-                        [
-                            1,
-                            1
-                        ]
-                    ]
-                },
-                "tdate": "2008-01-01",
-                "tcode": "",
-                "tindex": 1,
                 "tprecedingcomment": "",
-                "tdate2": null,
-                "tdescription": "income",
-                "tstatus": "Unmarked"
+                "tsourcepos": [
+                    {
+                        "sourceColumn": 1,
+                        "sourceLine": 31,
+                        "sourceName": "/home/user/hledger/examples/sample.journal"
+                    },
+                    {
+                        "sourceColumn": 1,
+                        "sourceLine": 34,
+                        "sourceName": "/home/user/hledger/examples/sample.journal"
+                    }
+                ],
+                "tstatus": "Unmarked",
+                "ttags": []
             }
 
-     And here's how to test adding it with curl.  This should add a new entry to
-     your journal:
+     And here's how to add it with curl.  This should append a new entry to your
+     journal file:
 
             $ curl http://127.0.0.1:5000/add -X PUT -H 'Content-Type: application/json' --data-binary @txn.json
 
 DEBUG OUTPUT
-   Debug output
      You  can add --debug[=N] to the command line to log debug output.  N ranges
      from 1 (least output, the default) to 9 (maximum  output).   Typically  you
      would  start with 1 and increase until you are seeing enough.  Debug output
@@ -439,18 +859,45 @@
      debug output in a log file instead, you can usually redirect stderr, eg:
      hledger-web --debug=3 2>hledger-web.log.
 
+LANGUAGE
+     hledger-web's pages can be shown in another  language  when  a  translation
+     catalog is available (see Languages in the hledger manual).
+
+     When  hledger-web  is started with --lang LANG, eg --lang de, every page is
+     in  that  language,  whatever  the  browser  asks  for.   So  you  can  use
+     hledger-web  in a language other than your browser's, or give every user of
+     a shared server the same language.
+
+     Otherwise the language is chosen per request, and the first of these naming
+     an available translation wins:
+
+     1. a _LANG query parameter, eg ?_LANG=de.  This choice is remembered  in  a
+        _LANG cookie.
+
+     2. the _LANG cookie
+
+     3. the  browser's Accept-Language header, ie the browser's or system's lan-
+        guage settings
+
+     If none does, pages are in English, or with --lang auto, in the language of
+     hledger-web's environment.  So viewers usually get their browser's language
+     automatically, if hledger-web has it.  Catalogs, including any in the  con-
+     fig directory, are loaded when hledger-web starts.
+
 ENVIRONMENT
      LEDGER_FILE The main journal file to use when not specified with -f/--file.
      Default: $HOME/.hledger.journal.
 
 BUGS
      We    welcome    bug    reports    in    the    hledger    issue    tracker
-     (https://bugs.hledger.org),   or   on   the   hledger  chat  or  mail  list
+     (https://bugs.hledger.org),  or  on  the  hledger   chat   or   mail   list
      (https://hledger.org/support).
 
      Some known issues:
 
-     Does not work well on small screens, or in text-mode browsers.
+     Without  JavaScript  (eg  in  text-mode  browsers), pages can be viewed and
+     their links followed, but the add form, help  dialog,  keyboard  shortcuts,
+     sidebar toggle and folding don't work.
 
 
 
@@ -470,4 +917,4 @@
 SEE ALSO
      hledger(1), hledger-ui(1), hledger-web(1), ledger(1)
 
-hledger-web-1.52.4                 August 2026                    HLEDGER-WEB(1)
+hledger-web-2.0                   December 2026                   HLEDGER-WEB(1)
diff --git a/static/css/bootstrap-datepicker.standalone.min.css b/static/css/bootstrap-datepicker.standalone.min.css
deleted file mode 100644
--- a/static/css/bootstrap-datepicker.standalone.min.css
+++ /dev/null
@@ -1,7 +0,0 @@
-/*!
- * Datepicker for Bootstrap v1.7.1 (https://github.com/uxsolutions/bootstrap-datepicker)
- *
- * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- */
-
-.datepicker{padding:4px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;direction:ltr}.datepicker-inline{width:220px}.datepicker-rtl{direction:rtl}.datepicker-rtl.dropdown-menu{left:auto}.datepicker-rtl table tr td span{float:right}.datepicker-dropdown{top:0;left:0}.datepicker-dropdown:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #999;border-top:0;border-bottom-color:rgba(0,0,0,.2);position:absolute}.datepicker-dropdown:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid #fff;border-top:0;position:absolute}.datepicker-dropdown.datepicker-orient-left:before{left:6px}.datepicker-dropdown.datepicker-orient-left:after{left:7px}.datepicker-dropdown.datepicker-orient-right:before{right:6px}.datepicker-dropdown.datepicker-orient-right:after{right:7px}.datepicker-dropdown.datepicker-orient-bottom:before{top:-7px}.datepicker-dropdown.datepicker-orient-bottom:after{top:-6px}.datepicker-dropdown.datepicker-orient-top:before{bottom:-7px;border-bottom:0;border-top:7px solid #999}.datepicker-dropdown.datepicker-orient-top:after{bottom:-6px;border-bottom:0;border-top:6px solid #fff}.datepicker table{margin:0;-webkit-touch-callout:none;-webkit-user-select:none;-khtml-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.datepicker td,.datepicker th{text-align:center;width:20px;height:20px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;border:none}.table-striped .datepicker table tr td,.table-striped .datepicker table tr th{background-color:transparent}.datepicker table tr td.day.focused,.datepicker table tr td.day:hover{background:#eee;cursor:pointer}.datepicker table tr td.new,.datepicker table tr td.old{color:#999}.datepicker table tr td.disabled,.datepicker table tr td.disabled:hover{background:0 0;color:#999;cursor:default}.datepicker table tr td.highlighted{background:#d9edf7;border-radius:0}.datepicker table tr td.today,.datepicker table tr td.today.disabled,.datepicker table tr td.today.disabled:hover,.datepicker table tr td.today:hover{background-color:#fde19a;background-image:-moz-linear-gradient(to bottom,#fdd49a,#fdf59a);background-image:-ms-linear-gradient(to bottom,#fdd49a,#fdf59a);background-image:-webkit-gradient(linear,0 0,0 100%,from(#fdd49a),to(#fdf59a));background-image:-webkit-linear-gradient(to bottom,#fdd49a,#fdf59a);background-image:-o-linear-gradient(to bottom,#fdd49a,#fdf59a);background-image:linear-gradient(to bottom,#fdd49a,#fdf59a);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fdd49a', endColorstr='#fdf59a', GradientType=0);border-color:#fdf59a #fdf59a #fbed50;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);color:#000}.datepicker table tr td.today.active,.datepicker table tr td.today.disabled,.datepicker table tr td.today.disabled.active,.datepicker table tr td.today.disabled.disabled,.datepicker table tr td.today.disabled:active,.datepicker table tr td.today.disabled:hover,.datepicker table tr td.today.disabled:hover.active,.datepicker table tr td.today.disabled:hover.disabled,.datepicker table tr td.today.disabled:hover:active,.datepicker table tr td.today.disabled:hover:hover,.datepicker table tr td.today.disabled:hover[disabled],.datepicker table tr td.today.disabled[disabled],.datepicker table tr td.today:active,.datepicker table tr td.today:hover,.datepicker table tr td.today:hover.active,.datepicker table tr td.today:hover.disabled,.datepicker table tr td.today:hover:active,.datepicker table tr td.today:hover:hover,.datepicker table tr td.today:hover[disabled],.datepicker table tr td.today[disabled]{background-color:#fdf59a}.datepicker table tr td.today.active,.datepicker table tr td.today.disabled.active,.datepicker table tr td.today.disabled:active,.datepicker table tr td.today.disabled:hover.active,.datepicker table tr td.today.disabled:hover:active,.datepicker table tr td.today:active,.datepicker table tr td.today:hover.active,.datepicker table tr td.today:hover:active{background-color:#fbf069\9}.datepicker table tr td.today:hover:hover{color:#000}.datepicker table tr td.today.active:hover{color:#fff}.datepicker table tr td.range,.datepicker table tr td.range.disabled,.datepicker table tr td.range.disabled:hover,.datepicker table tr td.range:hover{background:#eee;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.datepicker table tr td.range.today,.datepicker table tr td.range.today.disabled,.datepicker table tr td.range.today.disabled:hover,.datepicker table tr td.range.today:hover{background-color:#f3d17a;background-image:-moz-linear-gradient(to bottom,#f3c17a,#f3e97a);background-image:-ms-linear-gradient(to bottom,#f3c17a,#f3e97a);background-image:-webkit-gradient(linear,0 0,0 100%,from(#f3c17a),to(#f3e97a));background-image:-webkit-linear-gradient(to bottom,#f3c17a,#f3e97a);background-image:-o-linear-gradient(to bottom,#f3c17a,#f3e97a);background-image:linear-gradient(to bottom,#f3c17a,#f3e97a);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#f3c17a', endColorstr='#f3e97a', GradientType=0);border-color:#f3e97a #f3e97a #edde34;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);-webkit-border-radius:0;-moz-border-radius:0;border-radius:0}.datepicker table tr td.range.today.active,.datepicker table tr td.range.today.disabled,.datepicker table tr td.range.today.disabled.active,.datepicker table tr td.range.today.disabled.disabled,.datepicker table tr td.range.today.disabled:active,.datepicker table tr td.range.today.disabled:hover,.datepicker table tr td.range.today.disabled:hover.active,.datepicker table tr td.range.today.disabled:hover.disabled,.datepicker table tr td.range.today.disabled:hover:active,.datepicker table tr td.range.today.disabled:hover:hover,.datepicker table tr td.range.today.disabled:hover[disabled],.datepicker table tr td.range.today.disabled[disabled],.datepicker table tr td.range.today:active,.datepicker table tr td.range.today:hover,.datepicker table tr td.range.today:hover.active,.datepicker table tr td.range.today:hover.disabled,.datepicker table tr td.range.today:hover:active,.datepicker table tr td.range.today:hover:hover,.datepicker table tr td.range.today:hover[disabled],.datepicker table tr td.range.today[disabled]{background-color:#f3e97a}.datepicker table tr td.range.today.active,.datepicker table tr td.range.today.disabled.active,.datepicker table tr td.range.today.disabled:active,.datepicker table tr td.range.today.disabled:hover.active,.datepicker table tr td.range.today.disabled:hover:active,.datepicker table tr td.range.today:active,.datepicker table tr td.range.today:hover.active,.datepicker table tr td.range.today:hover:active{background-color:#efe24b\9}.datepicker table tr td.selected,.datepicker table tr td.selected.disabled,.datepicker table tr td.selected.disabled:hover,.datepicker table tr td.selected:hover{background-color:#9e9e9e;background-image:-moz-linear-gradient(to bottom,#b3b3b3,grey);background-image:-ms-linear-gradient(to bottom,#b3b3b3,grey);background-image:-webkit-gradient(linear,0 0,0 100%,from(#b3b3b3),to(grey));background-image:-webkit-linear-gradient(to bottom,#b3b3b3,grey);background-image:-o-linear-gradient(to bottom,#b3b3b3,grey);background-image:linear-gradient(to bottom,#b3b3b3,grey);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#b3b3b3', endColorstr='#808080', GradientType=0);border-color:grey grey #595959;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25)}.datepicker table tr td.selected.active,.datepicker table tr td.selected.disabled,.datepicker table tr td.selected.disabled.active,.datepicker table tr td.selected.disabled.disabled,.datepicker table tr td.selected.disabled:active,.datepicker table tr td.selected.disabled:hover,.datepicker table tr td.selected.disabled:hover.active,.datepicker table tr td.selected.disabled:hover.disabled,.datepicker table tr td.selected.disabled:hover:active,.datepicker table tr td.selected.disabled:hover:hover,.datepicker table tr td.selected.disabled:hover[disabled],.datepicker table tr td.selected.disabled[disabled],.datepicker table tr td.selected:active,.datepicker table tr td.selected:hover,.datepicker table tr td.selected:hover.active,.datepicker table tr td.selected:hover.disabled,.datepicker table tr td.selected:hover:active,.datepicker table tr td.selected:hover:hover,.datepicker table tr td.selected:hover[disabled],.datepicker table tr td.selected[disabled]{background-color:grey}.datepicker table tr td.selected.active,.datepicker table tr td.selected.disabled.active,.datepicker table tr td.selected.disabled:active,.datepicker table tr td.selected.disabled:hover.active,.datepicker table tr td.selected.disabled:hover:active,.datepicker table tr td.selected:active,.datepicker table tr td.selected:hover.active,.datepicker table tr td.selected:hover:active{background-color:#666\9}.datepicker table tr td.active,.datepicker table tr td.active.disabled,.datepicker table tr td.active.disabled:hover,.datepicker table tr td.active:hover{background-color:#006dcc;background-image:-moz-linear-gradient(to bottom,#08c,#04c);background-image:-ms-linear-gradient(to bottom,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(to bottom,#08c,#04c);background-image:-o-linear-gradient(to bottom,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#08c', endColorstr='#0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25)}.datepicker table tr td.active.active,.datepicker table tr td.active.disabled,.datepicker table tr td.active.disabled.active,.datepicker table tr td.active.disabled.disabled,.datepicker table tr td.active.disabled:active,.datepicker table tr td.active.disabled:hover,.datepicker table tr td.active.disabled:hover.active,.datepicker table tr td.active.disabled:hover.disabled,.datepicker table tr td.active.disabled:hover:active,.datepicker table tr td.active.disabled:hover:hover,.datepicker table tr td.active.disabled:hover[disabled],.datepicker table tr td.active.disabled[disabled],.datepicker table tr td.active:active,.datepicker table tr td.active:hover,.datepicker table tr td.active:hover.active,.datepicker table tr td.active:hover.disabled,.datepicker table tr td.active:hover:active,.datepicker table tr td.active:hover:hover,.datepicker table tr td.active:hover[disabled],.datepicker table tr td.active[disabled]{background-color:#04c}.datepicker table tr td.active.active,.datepicker table tr td.active.disabled.active,.datepicker table tr td.active.disabled:active,.datepicker table tr td.active.disabled:hover.active,.datepicker table tr td.active.disabled:hover:active,.datepicker table tr td.active:active,.datepicker table tr td.active:hover.active,.datepicker table tr td.active:hover:active{background-color:#039\9}.datepicker table tr td span{display:block;width:23%;height:54px;line-height:54px;float:left;margin:1%;cursor:pointer;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px}.datepicker table tr td span.focused,.datepicker table tr td span:hover{background:#eee}.datepicker table tr td span.disabled,.datepicker table tr td span.disabled:hover{background:0 0;color:#999;cursor:default}.datepicker table tr td span.active,.datepicker table tr td span.active.disabled,.datepicker table tr td span.active.disabled:hover,.datepicker table tr td span.active:hover{background-color:#006dcc;background-image:-moz-linear-gradient(to bottom,#08c,#04c);background-image:-ms-linear-gradient(to bottom,#08c,#04c);background-image:-webkit-gradient(linear,0 0,0 100%,from(#08c),to(#04c));background-image:-webkit-linear-gradient(to bottom,#08c,#04c);background-image:-o-linear-gradient(to bottom,#08c,#04c);background-image:linear-gradient(to bottom,#08c,#04c);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#08c', endColorstr='#0044cc', GradientType=0);border-color:#04c #04c #002a80;border-color:rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25);filter:progid:DXImageTransform.Microsoft.gradient(enabled=false);color:#fff;text-shadow:0 -1px 0 rgba(0,0,0,.25)}.datepicker table tr td span.active.active,.datepicker table tr td span.active.disabled,.datepicker table tr td span.active.disabled.active,.datepicker table tr td span.active.disabled.disabled,.datepicker table tr td span.active.disabled:active,.datepicker table tr td span.active.disabled:hover,.datepicker table tr td span.active.disabled:hover.active,.datepicker table tr td span.active.disabled:hover.disabled,.datepicker table tr td span.active.disabled:hover:active,.datepicker table tr td span.active.disabled:hover:hover,.datepicker table tr td span.active.disabled:hover[disabled],.datepicker table tr td span.active.disabled[disabled],.datepicker table tr td span.active:active,.datepicker table tr td span.active:hover,.datepicker table tr td span.active:hover.active,.datepicker table tr td span.active:hover.disabled,.datepicker table tr td span.active:hover:active,.datepicker table tr td span.active:hover:hover,.datepicker table tr td span.active:hover[disabled],.datepicker table tr td span.active[disabled]{background-color:#04c}.datepicker table tr td span.active.active,.datepicker table tr td span.active.disabled.active,.datepicker table tr td span.active.disabled:active,.datepicker table tr td span.active.disabled:hover.active,.datepicker table tr td span.active.disabled:hover:active,.datepicker table tr td span.active:active,.datepicker table tr td span.active:hover.active,.datepicker table tr td span.active:hover:active{background-color:#039\9}.datepicker table tr td span.new,.datepicker table tr td span.old{color:#999}.datepicker .datepicker-switch{width:145px}.datepicker .datepicker-switch,.datepicker .next,.datepicker .prev,.datepicker tfoot tr th{cursor:pointer}.datepicker .datepicker-switch:hover,.datepicker .next:hover,.datepicker .prev:hover,.datepicker tfoot tr th:hover{background:#eee}.datepicker .next.disabled,.datepicker .prev.disabled{visibility:hidden}.datepicker .cw{font-size:10px;width:12px;padding:0 2px 0 5px;vertical-align:middle}.input-append.date .add-on,.input-prepend.date .add-on{cursor:pointer}.input-append.date .add-on i,.input-prepend.date .add-on i{margin-top:3px}.input-daterange input{text-align:center}.input-daterange input:first-child{-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px}.input-daterange input:last-child{-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0}.input-daterange .add-on{display:inline-block;width:auto;min-width:16px;height:20px;padding:4px 5px;font-weight:400;line-height:20px;text-align:center;text-shadow:0 1px 0 #fff;vertical-align:middle;background-color:#eee;border:1px solid #ccc;margin-left:-5px;margin-right:-5px}.datepicker.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;float:left;display:none;min-width:160px;list-style:none;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);-moz-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;*border-right-width:2px;*border-bottom-width:2px;color:#333;font-size:13px;line-height:20px}.datepicker.datepicker-inline td,.datepicker.datepicker-inline th,.datepicker.dropdown-menu td,.datepicker.dropdown-menu th{padding:4px 5px}
diff --git a/static/hledger.css b/static/hledger.css
--- a/static/hledger.css
+++ b/static/hledger.css
@@ -1,227 +1,1268 @@
-/* hledger web ui styles */
-
-/*------------------------------------------------------------------------------------------*/
-/* 0. revert some things */
-
-/* don't let bootstrap add link URLs when printing */
-@media print {
-  a[href]:after { content: none !important; }
-}
-
-/*------------------------------------------------------------------------------------------*/
-/* 1. colours */
-
-/* green */
-::-moz-placeholder {
-  font-style:italic;
-}
-:-moz-placeholder {
-  font-style:italic;
-}
-::-webkit-input-placeholder {
-  font-style:italic;
-}
- :-ms-input-placeholder {
-  font-style:italic;
-}
-
-/*------------------------------------------------------------------------------------------*/
-/* 2. fonts */
-body {
-  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif;
-}
-
-/*------------------------------------------------------------------------------------------*/
-/* 4. typeahead styles */
-
-.tt-hint {
-  color: #bbb;
-}
-
-.tt-dropdown-menu {
-  padding: 8px 0;
-  background-color: #fff;
-  border: 1px solid #ccc;
-  border: 1px solid rgba(0, 0, 0, 0.2);
-  -webkit-border-radius: 8px;
-     -moz-border-radius: 8px;
-          border-radius: 8px;
-  -webkit-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-     -moz-box-shadow: 0 5px 10px rgba(0,0,0,.2);
-          box-shadow: 0 5px 10px rgba(0,0,0,.2);
-  overflow:auto;
-  max-height:300px;
-}
-
-.tt-suggestion {
-  padding: 3px 20px;
-  font-size: 18px;
-  line-height: 24px;
-}
-
-.tt-suggestion.tt-cursor {
-  color: #fff;
-  background-color: #0097cf;
-}
-
-.tt-suggestion p {
-  margin: 0;
-}
-
-.twitter-typeahead {
-  width:100%;
-}
-
-code {
-  font-weight: bold;
-  color: black;
-}
-
-ul {
-    list-style-type: none;
-    padding: 0;
-}
-
-#main-content {
-    padding-left: 30px;
-}
-
-#message {
-    white-space: pre;
-    overflow-x: auto;
-}
-
-#sidebar-menu {
-    overflow:hidden;
-    border-right: 1px solid #ebebeb;
-}
-#sidebar-menu .main-menu {
-    table-layout: fixed;
-    word-wrap: break-word;
-}
-
-#sidebar-menu .main-menu td {
-    padding: 1px !important;
-    border-top: 1px solid #ebebeb;
-    overflow: hidden;
-    white-space:nowrap;
-    text-overflow:ellipsis;
-    font-size: 16px;
-}
-
-#sidebar-menu .main-menu .ff-wrapper { /* This wrapper is needed because firefox won't apply overflow to a td-tag */
-    overflow:hidden;
-    text-overflow:ellipsis;
-}
-
-#sidebar-menu .main-menu .top {
-    border: none !important;
-}
-
-#sidebar-menu .main-menu a {
-    display: inline;
-    font-size: 16px;
-    font-weight: 500;
-    color: #2F2F2F;
-    padding: 4px 20px;
-}
-
-#sidebar-menu .main-menu a:hover {
-    color: #11427D;
-    text-decoration: none;
-    background-color: transparent;
-}
-
-#sidebar-menu .main-menu .only {
-    visibility: hidden;
-    padding: 1px;
-}
-
-#sidebar-menu .main-menu tr:hover .only {
-    visibility: visible;
-}
-
-#sidebar-menu .main-menu .inacct, #sidebar-menu .main-menu .inacct .acct-name {
-    font-weight: bold;
-    color: #11427D;
-    background-color: #f9f9f9;
-}
-
-#sidebar-menu .main-menu .amount {
-    float: right;
-    overflow-x:auto;
-    font-weight: 500 !important;
-}
-
-#sidebar-menu .main-menu .acct {
-    width:60%;
-    vertical-align:bottom;
-}
-
-.transactionsreport .posting td {
-    border: none !important;
-}
-
-.negative {
-    color: #a94442;
-}
-
-.date {
-    whitespace: nowrap;
-}
-
-.col-any-0 {
-    width:0 !important;
-    height:0 !important;
-    float: left;
-    opacity:0;
-}
-
-.tgl-icon {
-    font-size:large;
-}
-
-@media screen and (max-width: 768px) {
-    .row-offcanvas {
-        position: relative;
-        -webkit-transition: all .25s ease-out;
-        -o-transition: all .25s ease-out;
-        transition: all .25s ease-out;
-    }
-
-    .row-offcanvas-right {
-        right: 0;
-    }
-
-    .row-offcanvas-left {
-        left: 0;
-    }
-
-    .row-offcanvas-right
-    .sidebar-offcanvas {
-        right: -90%;
-    }
-
-    .row-offcanvas-left
-    .sidebar-offcanvas {
-        left: -90%;
-    }
-
-    .row-offcanvas-right.active {
-        right: 90%;
-    }
-
-    .row-offcanvas-left.active {
-        left: 90%;
-    }
-
-    .sidebar-offcanvas {
-        position: absolute;
-        top: 0;
-        width: 90%;
-    }
-
-    #sidebar-menu .main-menu td {
-        max-width: 200px;
-    }
-}
+/* hledger web ui styles
+ *
+ * Conventions and the reasoning behind them: ../STYLE.md
+ * Short version: no build step, nothing from a third party, style lives here
+ * rather than in style= attributes, colors come from the palette in section
+ * 1, and amounts get tabular figures.
+ */
+
+/*------------------------------------------------------------------------------------------*/
+/* 0. revert some things */
+
+/* don't let bootstrap add link URLs when printing */
+@media print {
+  a[href]:after { content: none !important; }
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 1. colors */
+
+/* The pages are light or dark, following the setting of the OS or browser.
+   Every color this file sets is defined here once, light first and dark in
+   the media query below, and the rules use these properties rather than
+   literal colors; only shadows, black in both, are written out. color-scheme
+   lets the browser draw its own widgets (datalist suggestions, date picker,
+   scrollbars) to match. */
+:root {
+  color-scheme: light dark;
+
+  --bg: #fff;
+  --surface: #fff;               /* tooltips, dialogs, form fields, buttons */
+  --border: #ccc;                /* around fields and buttons */
+  --muted: #687385;              /* column headers, and the rule above totals */
+  --header-rule: #e6e8eb;        /* under column headers */
+  --row-hover: #f6f8fa;
+  --row-target: #fcf8e3;         /* the entry the url points to */
+  --negative: #a94442;           /* negative amounts, and errors */
+  --gain: #008300;               /* holdings' gains and losses, as charts colour them */
+  --loss: #e34948;               /* (revenue and expense, in Hledger.Write.Chart.Palette) */
+  --code: black;
+  --dialog-border: rgba(0, 0, 0, .2);
+
+  /* the account sidebar */
+  --account: #2f2f2f;
+  --account-current: #11427d;    /* the account shown, and the one under the pointer */
+  --account-current-bg: #f9f9f9;
+  --sidebar-rule: #ebebeb;
+}
+
+/* Printing is always light. Bootstrap prints every background as
+   transparent, and in the dark scheme the browser's own dark page would
+   show through. */
+@media print {
+  :root {
+    color-scheme: light;
+  }
+}
+
+/* On screen only, so that printing keeps the light colors too. */
+@media screen and (prefers-color-scheme: dark) {
+  :root {
+    /* In the light scheme bootstrap supplies these; section 9 applies
+       them in the dark. */
+    --text: #d3d7dd;
+    --rule: #30353d;             /* between table rows */
+    --link: #6fb1f7;
+    --link-hover: #9ccaff;
+    --surface-hover: #2c3139;    /* a button under the pointer or pressed, and code */
+    --border-hover: #5a626e;
+    --info: #9cc9f5;
+    --info-bg: #172a3d;
+    --info-border: #24476b;
+    --danger-bg: #3a1f22;
+    --danger-border: #6b3034;
+
+    --bg: #1b1e23;
+    --surface: #23272e;
+    --border: #434a54;
+    --muted: #8e98a5;
+    --header-rule: var(--rule);
+    --row-hover: #22262c;
+    --row-target: #3a3420;
+    --negative: #f28b82;
+    --gain: #008300;
+    --loss: #e66767;
+    --code: #eef0f3;
+    --dialog-border: var(--border);
+
+    --account: var(--text);
+    --account-current: #8ec3ff;
+    --account-current-bg: #262b33;
+    --sidebar-rule: var(--rule);
+  }
+}
+
+/* green */
+::placeholder {
+  font-style:italic;
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 2. fonts */
+body {
+  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif;
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 3. tabular data: amounts, dates, column headers */
+
+/* Amounts read as a column of figures: tabular (fixed width) digits, aligned
+   right so the decimal points line up. Both the cell and the amount spans
+   inside it carry .amount, so this reaches either. */
+.amount {
+  font-feature-settings: "tnum";
+  font-variant: tabular-nums;
+  text-align: right;
+}
+
+/* A date is one token; don't break it across lines. */
+td.date {
+  white-space: nowrap;
+}
+
+/* So is an amount, its quantity and commodity symbol. (The sidebar's
+   amounts are laid out by its own rules, below.) */
+#main-content span.amount {
+  white-space: nowrap;
+}
+
+/* One row, one line: descriptions arrive elided, so the width is bounded. */
+@media (min-width: 992px) { /* under md: no room */
+  td.description {
+    white-space: nowrap;
+  }
+}
+
+/* A row lights up under the pointer, which helps when reading a wide row
+   across to its amount. The :target rule further down overrides this. */
+.table > tbody > tr:hover > td {
+  background-color: var(--row-hover);
+}
+
+/* Column headers label the data, they are not part of it: small, spaced and
+   muted. Left alignment comes from bootstrap's th rule; .amount above
+   overrides it for the figure columns. */
+.table > thead > tr > th,
+.table > thead > th {
+  font-size: 12px;
+  font-weight: 500;
+  text-transform: uppercase;
+  letter-spacing: 0.04em;
+  color: var(--muted);
+  border-bottom: 1px solid var(--header-rule);
+  white-space: normal;
+}
+
+/* A balance report can be wider than the page at any window size, and
+   bootstrap's .table-responsive only scrolls below 768px. Without this the
+   whole main pane scrolls instead, dragging the account column, the heading
+   and the search box out of view. */
+.report-table {
+  overflow-x: auto;
+}
+
+/* A note below a report's table, eg about what its totals leave out. */
+.report-note {
+  color: var(--muted);
+}
+
+/* The balance report's table comes from hledger-lib's HTML writer, which
+   marks heading and total cells with border classes (border-bottom-double,
+   border-top-double) for its standalone output. Here the rules above apply
+   instead: one hairline between rows, none vertical, no double lines. The
+   totals, in tfoot, are bold (the writer's <b>) under a hairline in the
+   header color, so the eye finds them without a heavier rule. */
+.table > tfoot > tr > td {
+  border-top: 1px solid var(--muted);
+}
+
+/* A statement's sections: each section's title row, spaced from the
+   section above, and its subtotal rows under a hairline like the
+   footer's. Bootstrap separates the sections' tbodies with a rule of
+   its own. */
+.balancereport > tbody > tr.section > th {
+  padding-top: 1em;
+}
+.balancereport > tbody > tr.subtotal > td {
+  border-top: 1px solid var(--muted);
+}
+
+/* A row of links above a report or under a page heading: to the other
+   reports, to the intervals, and on the balance report to its modes; the
+   years a search matches; the pages. The current one is set in bold, like
+   the sidebar's current account, and is not a link on the pages row. Each
+   link wraps as a unit, so a narrow screen breaks the row between links,
+   not inside one. */
+.report-links a,
+.report-links .current {
+  margin-left: 0.5em;
+  white-space: nowrap;
+}
+/* The state being shown reads as state, not as another link: bold, in
+   the text color. */
+.report-links .current {
+  font-weight: 600;
+  color: inherit;
+}
+/* A faint rule between the links, so that a row of several-word labels
+   ("Income statement", "Cashflow statement") does not read as one sentence.
+   Not on the paging rows, whose numbers and arrows read fine as they are. */
+.report-links:not(.paging):not(.paging-nav) > :is(a, .current) + :is(a, .current) {
+  border-left: 1px solid var(--border);
+  padding-left: 0.5em;
+}
+/* The row of links to the reports, at the top of every page, has no
+   label, so its first link lines up with the search form below. */
+.report-links.reports > :first-child {
+  margin-left: 0;
+}
+/* In a row of links in groups (linksRowGroups), each group after the
+   first starts a little apart. */
+.report-links .group-start {
+  margin-left: 2em;
+}
+/* The rows' labels share a width, so the links start in one column
+   (the collapsed commodity line's label too). */
+.report-links > .row-label,
+div.commodities summary > .row-label {
+  display: inline-block;
+  min-width: 8.5em;
+}
+/* The rows of report controls sit behind this disclosure, closed by
+   default; opening it is remembered per browser (default-layout.hamlet).
+   Bootstrap removes summary's native marker, so it gets its own caret,
+   like the account trees'. */
+details.report-controls {
+  margin: 10px 0;
+}
+/* Open, the controls sit unboxed like the page's other panels, so the
+   heading stays put and only the rows below it appear. */
+details.report-controls[open] {
+  margin-bottom: 16px;
+}
+/* The heading is small and muted like the Chart and Data buttons
+   (.part-toggle), taking the link color on hover. */
+details.report-controls > summary {
+  cursor: pointer;
+  width: max-content;
+  max-width: 100%;
+  font-size: 12px;
+  color: var(--muted);
+}
+details.report-controls > summary:hover {
+  color: var(--link, #337ab7);
+}
+/* Closed, the options in effect follow, muted (Widget.Common.optionsSummary);
+   open, the rows show them. */
+details.report-controls > summary .options-summary {
+  margin-left: 1em;
+  color: var(--muted);
+}
+details.report-controls[open] > summary .options-summary {
+  display: none;
+}
+details.report-controls > summary::before {
+  content: "▸";
+  display: inline-block;
+  width: 1.1em;
+  font-size: 1.25em;
+  line-height: 1;
+  color: var(--link, #337ab7);
+}
+details.report-controls[open] > summary::before {
+  content: "▾";
+}
+details.report-controls[open] > summary {
+  margin-bottom: 8px;
+}
+/* Controls that take effect on other pages (Widget.Common.inertControls)
+   mute only their labels: the links work, setting state for the report
+   pages, and the wrapper's tooltip says so. Not by dimming the links:
+   they sit near the AA contrast floor (see the dark-scheme browser
+   test), and they are not disabled. */
+.controls-inert .row-label {
+  color: var(--muted);
+}
+
+/* Flat-mode account cells marked acct-split (reportTable) show the parent
+   path dimmed and, when long, shortened from its left, keeping the segments
+   nearest the leaf; direction: rtl puts the ellipsis on the left, and the
+   isolated span inside keeps the name's characters in order. The full name
+   stays in the link's tooltip and register link. */
+.report-table td.account .acct-path {
+  color: var(--muted);
+  display: inline-block;
+  max-width: 14em;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+  direction: rtl;
+  vertical-align: bottom;
+}
+.report-table td.account .acct-path > span {
+  direction: ltr;
+  unicode-bidi: isolate;
+}
+/* The path is width-capped above, so keeping the cell on one line cannot
+   widen the column much, and the leaf stays glued to its path. */
+.report-table td.account.acct-split { white-space: nowrap; }
+
+/* The commodity row lists every commodity in the journal; past a few
+   lines it scrolls instead of growing, and many commodities collapse
+   to one line showing the selection (Widget.Common.commodityLinks). */
+div.commodities .report-links {
+  max-height: 7.5em;
+  overflow-y: auto;
+}
+div.commodities summary {
+  cursor: pointer;
+  width: max-content;
+}
+/* The summary's selection reads like the other rows' current choice,
+   and sits in their column; the trailing caret, link-colored like the
+   other carets, is what offers the full list. */
+div.commodities summary .sel {
+  font-weight: 600;
+  margin-left: 0.5em;
+}
+div.commodities summary .sel::after {
+  content: " ▸";
+  color: var(--link, #337ab7);
+  font-weight: normal;
+}
+div.commodities details[open] summary .sel::after {
+  content: " ▾";
+}
+
+/* A short usage hint below a row of controls, eg the years row's
+   shift-click range selection, indented to the links column. */
+.controls-hint {
+  color: var(--muted);
+  font-size: 0.85em;
+  margin: -8px 0 10px 10.6em;
+}
+/* The closed commodity list keeps a row's bottom margin, so the hint
+   below sits as far from it as from any other row. */
+div.commodities > details {
+  margin-bottom: 10px;
+}
+/* The pages row keeps its shape from page to page: the newer and older
+   links hold their places when absent, and each page number has a cell
+   of its own, so the numbers do not shift when a link or a digit
+   appears. */
+.paging-nav a,
+.paging-nav .current,
+.paging-nav .placeholder {
+  display: inline-block;
+  margin-left: 0;
+  text-align: center;
+}
+.paging-nav a:not(.newer):not(.older),
+.paging-nav .current {
+  min-width: 2.2em;
+}
+.paging-nav .newer {
+  margin-right: 0.5em;
+}
+.paging-nav .older {
+  margin-left: 0.5em;
+}
+.paging-nav .placeholder {
+  visibility: hidden;
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 4. the add form */
+
+/* The journal page's link to it, kept a line's space above any rows of
+   links that follow it. */
+#addformlink + .report-links {
+  margin-top: 10px;
+}
+
+/* Each posting row is indented a little under the date and description. */
+#addform .account-group {
+  padding-left: 1em;
+}
+
+/* When the journal has several files, a selector chooses which one to add to.
+   It sits inline after its "Add to:" label instead of filling the row. */
+#addform .file-select {
+  display: inline-block;
+  width: auto;
+}
+
+#addform button[type=submit] {
+  font-weight: bold;
+}
+
+/* The date picker button. */
+#datebutton {
+  cursor: pointer;
+}
+
+/* The date input that backs the picker button. It must be rendered for
+   showPicker to work, so it is placed under the button rather than hidden. */
+#datepicked {
+  position: absolute;
+  bottom: 0;
+  right: 0;
+  width: 1px;
+  height: 1px;
+  padding: 0;
+  border: 0;
+  opacity: 0;
+  pointer-events: none;
+}
+
+/* The add form shown on a page of its own, after a submission was rejected. */
+.add-page {
+  margin-top: 1em;
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 5. entries: the one the url hash targets, and the one under the pointer */
+
+/* Following a link to a transaction or posting marks it. */
+.table > tbody > tr:target > td,
+tr:target > td {
+  background-color: var(--row-target);
+}
+
+/* Hovering a transaction shows its journal entry in this tooltip (see
+   entryTooltipInit in hledger.js), which is as wide as the entry's longest
+   line and set in a fixed-width font, so that the amounts line up as they do
+   in the journal. hledger.js places it and keeps it within the window.
+   Hovering a chart's mark shows its tooltip in a box like it (see
+   chartTooltipInit), in the page's font. */
+.entry-tooltip,
+.chart-tooltip {
+  position: fixed;
+  z-index: 1070;  /* bootstrap's level for tooltips */
+  width: max-content;
+  overflow: hidden;
+  padding: 6px 10px;
+  font-size: 12px;
+  line-height: 1.45;
+  background-color: var(--surface);
+  border: 1px solid var(--dialog-border);
+  border-radius: 4px;
+  box-shadow: 0 3px 9px rgba(0, 0, 0, .2);
+  /* Like a browser tooltip, it is never in the pointer's way. */
+  pointer-events: none;
+}
+.entry-tooltip {
+  font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
+}
+.chart-tooltip {
+  font-size: 13px;
+  font-variant-numeric: tabular-nums;
+}
+.chart-tooltip-head {
+  font-weight: 600;
+}
+/* More lines, eg the accounts an "other" series combines, below the
+   swatch's line and indented to its text. */
+.chart-tooltip-more {
+  padding-left: 16px;
+  color: var(--muted);
+}
+/* The mark's colour, which hledger.js sets as the swatch's color: a square
+   for a bar, a short line for a line, dashed for the average. */
+.chart-tooltip-swatch {
+  display: inline-block;
+  width: 10px;
+  height: 10px;
+  margin-right: 6px;
+  vertical-align: -1px;
+  border-radius: 2px;
+  background-color: currentColor;
+}
+.chart-tooltip-swatch.line,
+.chart-tooltip-swatch.dashed {
+  width: 14px;
+  height: 0;
+  vertical-align: 3px;
+  border-radius: 0;
+  border-top: 3px solid currentColor;
+  background-color: transparent;
+}
+.chart-tooltip-swatch.dashed {
+  border-top-style: dashed;
+  border-top-width: 2px;
+}
+/* The dot hledger.js puts on the line point whose tooltip is shown. */
+.hledger-chart .hover-dot {
+  stroke: var(--surface);
+  stroke-width: 2;
+  pointer-events: none;
+}
+.entry-tooltip > div {
+  white-space: pre-wrap;
+  overflow-wrap: anywhere;
+}
+/* An entry taller than the window is cut off; this marks the cut. */
+.entry-tooltip.clipped::after {
+  content: "…";
+  position: absolute;
+  right: 0;
+  bottom: 0;
+  left: 0;
+  padding: 0 10px;
+  background-color: var(--surface);
+}
+
+code {
+  font-weight: bold;
+  color: var(--code);
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 6. dialogs */
+
+/* The add form and help are <dialog> elements. Browsers draw those with a
+   plain black border, so give them the look of the modals around them. */
+dialog {
+  width: min(900px, calc(100% - 20px));
+  /* Sit near the top of the viewport, where the modals did, rather than
+     centered as a <dialog> is by default. */
+  margin-top: 30px;
+  margin-bottom: 30px;
+  padding: 0;
+  border: 1px solid var(--dialog-border);
+  border-radius: 6px;
+  box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+}
+
+/* The program name and version, at the right of the help dialog's header. */
+.modal-header .version {
+  float: right;
+  margin-right: 4em;
+}
+dialog::backdrop {
+  background-color: rgba(0, 0, 0, .5);
+}
+
+/* showModal() puts focus on the dialog, which is a container rather than
+   something the user tabs to, so it does not need a focus ring. */
+dialog:focus {
+  outline: none;
+}
+
+/* The g key's menu of pages: a small panel near the top, over the page,
+   styled like the dialogs but without a backdrop, since it closes as soon
+   as a key is pressed. */
+#gomenu {
+  position: fixed;
+  top: 30px;
+  left: 50%;
+  transform: translateX(-50%);
+  z-index: 1050;
+  min-width: 16em;
+  padding: 10px 20px;
+  background-color: var(--surface);
+  border: 1px solid var(--dialog-border);
+  border-radius: 6px;
+  box-shadow: 0 3px 9px rgba(0, 0, 0, .5);
+}
+#gomenu[hidden] {
+  display: none;
+}
+#gomenu p {
+  font-weight: 600;
+  margin-bottom: 5px;
+}
+#gomenu ul {
+  list-style: none;
+  margin: 0;
+  padding: 0;
+}
+#gomenu li {
+  padding: 2px 0;
+}
+#gomenu code {
+  margin-right: 0.5em;
+}
+
+/* In the help dialog's lists, an item that starts a new group. */
+.modal-body li.gap-above {
+  margin-top: 1em;
+}
+
+/* The help's headings and notes, and its tables of keys: each key, or
+   each options row's label, in a column of its own, the keys being
+   keycaps, set apart from the search syntax's code. Its two columns
+   stack on a phone (col-sm-6). */
+#helpmodal h4 {
+  margin: 0 0 8px;
+  font-size: 14px;
+  font-weight: bold;
+}
+#helpmodal h5 {
+  margin: 14px 0 6px;
+  font-size: 14px;
+  font-weight: bold;
+}
+#helpmodal h4:not(:first-child) {
+  margin-top: 16px;
+}
+#helpmodal .help-note {
+  margin-bottom: 8px;
+  color: var(--muted);
+}
+.help-keys {
+  margin-bottom: 8px;
+}
+.help-keys th,
+.help-keys td {
+  padding: 1px 0;
+  vertical-align: top;
+}
+.help-keys th {
+  padding-right: 12px;
+  font-weight: normal;
+  white-space: nowrap;
+}
+.help-keys td > span {
+  display: inline-block;
+  margin-right: 12px;
+  white-space: nowrap;
+}
+#helpmodal kbd {
+  display: inline-block;
+  min-width: 20px;
+  padding: 0 4px;
+  font-size: 12px;
+  line-height: 16px;
+  text-align: center;
+  color: inherit;
+  background-color: var(--row-hover);
+  border: 1px solid var(--border);
+  border-bottom-width: 2px;
+  border-radius: 4px;
+  box-shadow: none;
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 7. the report charts */
+
+/* hledger's SVG charts, styled by /chart.css in their own palette, and
+   fitted to the page here: they sit on the page's background, and their
+   tick labels take the page's muted color, which keeps them readable
+   (4.5:1) in both schemes. */
+.report-chart {
+  margin-bottom: 1em;
+}
+.report-chart .hledger-chart .bg {
+  fill: transparent;
+}
+.report-chart .hledger-chart .tick {
+  fill: var(--muted);
+}
+/* The charts' marks are not Bootstrap's highlighted text. */
+.hledger-chart .mark {
+  background-color: transparent;
+  padding: 0;
+}
+
+/* The c key hides a report's chart, and the d key the report's table
+   after it (hledger.js); a page without a chart keeps its table. */
+#main-content.chart-hidden .report-chart,
+#main-content.table-hidden .report-chart ~ .report-table {
+  display: none;
+}
+/* The charts' total or net line (or marks), with its legend entry, is
+   hidden until the N key shows it (hledger.js). The scale is fitted to
+   it either way (with bars, it lies within their extent anyway). */
+#main-content:not(.net-shown) .report-chart .total {
+  display: none;
+}
+
+/* So do the Chart and Data buttons (Widget.Chart.chartToggle, dataToggle),
+   at the right margin, with a caret showing whether their part is shown.
+   Then, taking no room of their own, Chart sits over the chart's top right
+   corner, and Data just above the table's, outside the table, so that it
+   stays at the page's right edge when the table scrolls sideways. While
+   the chart is hidden, both stand on a line of their own. */
+.part-toggle-row {
+  position: relative;
+  height: 0;
+  text-align: right;
+}
+.part-toggle {
+  position: absolute;
+  right: 0;
+  z-index: 1;
+  padding: 0;
+  border: 0;
+  background: none;
+  font-size: 12px;
+  color: var(--muted);
+}
+.part-toggle:hover {
+  color: var(--link, #337ab7);
+}
+.part-toggle::before {
+  content: "▾";
+  display: inline-block;
+  width: 1.1em;
+  font-size: 1.25em;
+  line-height: 1;
+  color: var(--link, #337ab7);
+}
+.chart-toggle-row .part-toggle {
+  top: 0;
+}
+.table-toggle-row .part-toggle {
+  bottom: 0;
+}
+/* A chart with no legend row above it makes room for its button. */
+.chart-toggle-row + .report-chart:not(.with-legend) {
+  padding-top: 18px;
+}
+#main-content.chart-hidden .part-toggle-row {
+  height: auto;
+}
+#main-content.chart-hidden .part-toggle {
+  position: static;
+  vertical-align: top;  /* where Chart is when the chart shows */
+}
+/* A hidden part's button keeps a margin below it. (Data, hidden under a
+   chart, stays where it was, just below the chart.) */
+#main-content.chart-hidden .chart-toggle-row,
+#main-content.table-hidden .table-toggle-row {
+  margin-bottom: 1em;
+}
+#main-content.chart-hidden .chart-toggle-row .part-toggle::before,
+#main-content.table-hidden .table-toggle-row .part-toggle::before {
+  content: "▸";
+}
+
+/* On the register, dragging across a plot (hledger.js) shades the dates
+   selected; on a touch screen a sideways drag selects too, rather than
+   scrolling. */
+.register-chart .hledger-chart {
+  touch-action: pan-y;
+}
+.register-chart .hledger-chart .plot,
+.register-chart .hledger-chart .shade {
+  cursor: crosshair;
+}
+.register-chart .hledger-chart .selection {
+  fill: var(--link, #337ab7);
+  fill-opacity: .15;
+  pointer-events: none;
+}
+
+/* A chart drawn at two widths (Widget.Chart.chartAtWidths), for the main
+   column with the sidebar shown and hidden: only the one for the sidebar's
+   state is shown, so showing or hiding the sidebar needs no redraw. */
+#main-content.col-md-8 .chart-width[data-sidebar=hidden],
+#main-content.col-md-12 .chart-width[data-sidebar=shown] {
+  display: none;
+}
+/* While a chart waits to be redrawn at a new width (hledger.js chartsFit),
+   eg during a window resize, it is stretched or shrunk to fit, keeping its
+   height (chartsStretch). */
+#main-content.charts-stretched .hledger-chart {
+  width: 100%;
+}
+
+/* With several commodities, a legend chooses the one charted, on the
+   register and the report pages (Widget.Chart.chartLegend). Its entries
+   are the labels of radio buttons, hidden but still reached from the
+   keyboard, each followed by its commodity's chart, shown while it is
+   chosen: no javascript needed. The legend makes the first row, the charts
+   and the note of any commodities left out the rows below it. */
+.with-legend {
+  display: flex;
+  flex-wrap: wrap;
+  align-items: baseline;
+  column-gap: 1em;
+}
+.with-legend .chart-legend-label {
+  font-weight: bold;
+}
+.with-legend > input[type=radio] {
+  position: absolute;
+  opacity: 0;
+  pointer-events: none;
+}
+.with-legend > input + label {
+  margin: 0;
+  font-weight: normal;
+  color: var(--link, #337ab7);
+  cursor: pointer;
+}
+.with-legend > input:checked + label {
+  color: inherit;
+  text-decoration: underline 2px;
+  text-underline-offset: 4px;
+}
+.with-legend > input:focus-visible + label {
+  outline: 2px solid var(--link, #337ab7);
+  outline-offset: 2px;
+}
+.with-legend > .chart-panel {
+  display: none;
+  order: 1;
+  flex-basis: 100%;
+}
+.with-legend > input:checked + label + .chart-panel {
+  display: block;
+}
+.report-chart .chart-note {
+  order: 2;
+  flex-basis: 100%;
+  color: var(--muted);
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 8. the manage, edit and upload pages */
+
+/* The list of journal files: each name is centered against its row of buttons. */
+.table.files td.filename {
+  vertical-align: middle;
+}
+
+/* The edit form is a table only for layout; no rules between its cells. */
+.table.edit-form td {
+  border: 0;
+}
+
+/* The upload form's file input is hidden; its label, styled as a button, is
+   the visible control and opens the file dialog. (Bootstrap makes file inputs
+   display:block, which outranks the hidden attribute, hence a rule here.) */
+label.btn > input[type=file] {
+  display: none;
+}
+
+ul {
+    list-style-type: none;
+    padding: 0;
+}
+
+#main-content {
+    padding-left: 30px;
+}
+/* focused only so that the keyboard scrolls it (focusPage in hledger.js) */
+#main-content:focus {
+    outline: none;
+}
+
+#message {
+    white-space: pre;
+    overflow-x: auto;
+}
+
+#sidebar-menu {
+    overflow:hidden;
+    border-right: 1px solid var(--sidebar-rule);
+}
+/* On wider screens, give the sidebar and the main content each their own
+   vertical scrollbar so they scroll independently and the window itself doesn't
+   scroll. This keeps the account list from shifting when the main pane is long,
+   and lets its scroll position be preserved across navigations (restored from
+   sessionStorage in hledger.js). calc leaves room for the header row above, so
+   the last accounts aren't clipped; short lists stay content-height. */
+@media screen and (min-width: 769px) {
+    #sidebar-menu, #main-content {
+        max-height: calc(100vh - 5em);
+        overflow-y: auto;
+    }
+}
+/* fixed, so that a row too wide for the sidebar overflows alone, rather
+   than widening the table and every row with it */
+#sidebar-menu .main-menu {
+    table-layout: fixed;
+    word-wrap: break-word;
+}
+
+/* Each row is laid out on its own, not in columns shared with the other
+   rows: the balance takes the width it needs and the account name the
+   rest, shortened if need be. When that would leave the name less than
+   6em, the balance goes on a line of its own below it. */
+#sidebar-menu .main-menu tr {
+    display: flex;
+    flex-wrap: wrap;
+}
+
+/* a folded row, which the rule above would show */
+#sidebar-menu .main-menu tr.tree-fold-hide {
+    display: none;
+}
+
+/* the line above an account is the row's, so that a balance below its
+   name stays inside it */
+#sidebar-menu .main-menu tr[data-indent], #sidebar-menu .main-menu tr.total {
+    border-top: 1px solid var(--sidebar-rule);
+}
+
+#sidebar-menu .main-menu td {
+    padding: 1px !important;
+    border-top: none;
+    overflow: hidden;
+    white-space:nowrap;
+    text-overflow:ellipsis;
+    font-size: 16px;
+    flex: 1 1 6em;
+    min-width: 0;
+}
+
+#sidebar-menu .main-menu .ff-wrapper { /* This wrapper is needed because firefox won't apply overflow to a td-tag */
+    overflow:hidden;
+    text-overflow:ellipsis;
+}
+
+#sidebar-menu .main-menu .top {
+    border: none !important;
+}
+
+#sidebar-menu .main-menu a {
+    display: inline;
+    font-size: 16px;
+    font-weight: 500;
+    color: var(--account);
+    padding: 4px 20px;
+}
+
+#sidebar-menu .main-menu a:hover {
+    color: var(--account-current);
+    text-decoration: none;
+    background-color: transparent;
+}
+
+#sidebar-menu .main-menu .only {
+    visibility: hidden;
+    padding: 1px;
+    font-size: 12px;
+}
+
+#sidebar-menu .main-menu tr:hover .only {
+    visibility: visible;
+}
+
+#sidebar-menu .main-menu .inacct, #sidebar-menu .main-menu .inacct .acct-name {
+    font-weight: bold;
+    color: var(--account-current);
+    background-color: var(--account-current-bg);
+}
+
+#sidebar-menu .main-menu .amount {
+    flex: none;
+    margin-left: auto;
+    font-weight: 500 !important;
+}
+
+.transactionsreport .posting td {
+    border: none !important;
+}
+
+.negative {
+    color: var(--negative);
+}
+
+/* The holdings table's gains and losses, green and red as the holdings
+   command colors them, in the chart's colors. */
+.gain {
+    color: var(--gain);
+}
+.loss {
+    color: var(--loss);
+}
+
+/* A figure that links is not coloured as a link: the figure's own colour
+   (red for a negative amount, from the span inside) shows through. In the
+   sidebar it is not padded like an account link, and underlines on hover,
+   as the report pages' figures do. */
+.balancereport td.amount a,
+#sidebar-menu .main-menu .amount a {
+    color: inherit;
+}
+#sidebar-menu .main-menu .amount a {
+    padding: 0;
+}
+#sidebar-menu .main-menu .amount a:hover {
+    text-decoration: underline;
+}
+
+.col-any-0 {
+    width:0 !important;
+    height:0 !important;
+    float: left;
+    opacity:0;
+}
+
+/* The sidebar's button, at the top left. With the sidebar hidden, the
+   spacer holding it shrinks to fit it. Its icon's left pane is filled
+   while the sidebar shows. */
+#spacer.sidebar-hidden {
+    width: auto;
+}
+#sidebar-toggle {
+    padding: 4px 8px;
+    line-height: 1;
+}
+#sidebar-toggle .sidebar-icon {
+    display: block;
+}
+/* The icon's sidebar pane is white while the sidebar shows, and filled
+   while it is hidden. */
+#sidebar-toggle .sidebar-icon-pane {
+    fill: currentColor;
+}
+#sidebar-toggle[aria-expanded="true"] .sidebar-icon-pane {
+    fill: none;
+}
+
+/* Full window mode (the f key) shows only the page's heading and data, and
+   the paging links, across the window's full width; a small button at the
+   top right leaves it. */
+body.fullwindow #spacer,
+body.fullwindow #topbar,
+body.fullwindow #sidebar-menu,
+body.fullwindow #searchform,
+body.fullwindow .report-links.reports,
+body.fullwindow details.report-controls,
+body.fullwindow #addformlink,
+body.fullwindow footer {
+    display: none;
+}
+body.fullwindow #main-content {
+    width: 100%;
+}
+#fullwindow-exit {
+    display: none;
+}
+body.fullwindow #fullwindow-exit {
+    display: block;
+    position: fixed;
+    top: 8px;
+    right: 8px;
+    z-index: 10;
+}
+
+@media screen and (max-width: 768px) {
+    .row-offcanvas {
+        position: relative;
+        transition: all .25s ease-out;
+    }
+
+    .row-offcanvas-right {
+        right: 0;
+    }
+
+    .row-offcanvas-left {
+        left: 0;
+    }
+
+    .row-offcanvas-right
+    .sidebar-offcanvas {
+        right: -90%;
+    }
+
+    .row-offcanvas-left
+    .sidebar-offcanvas {
+        left: -90%;
+    }
+
+    .row-offcanvas-right.active {
+        right: 90%;
+    }
+
+    .row-offcanvas-left.active {
+        left: 90%;
+    }
+
+    .sidebar-offcanvas {
+        position: absolute;
+        top: 0;
+        width: 90%;
+    }
+
+    /* Here the sidebar slides in, so hiding it on a wider screen
+       doesn't apply. */
+    #sidebar-menu.col-any-0 {
+        width: 90% !important;
+        height: auto !important;
+        opacity: 1;
+        padding: 0 15px;
+    }
+
+    #sidebar-menu .main-menu td {
+        max-width: 200px;
+    }
+}
+
+/*------------------------------------------------------------------------------------------*/
+/* 9. bootstrap and the browser, in the dark */
+
+/* Bootstrap 3 is light only, as are some of the browser's own defaults for
+   the elements these pages use. In the dark scheme, restyle those parts with
+   the palette from section 1. */
+@media screen and (prefers-color-scheme: dark) {
+  body {
+    color: var(--text);
+    background-color: var(--bg);
+  }
+  a {
+    color: var(--link);
+  }
+  a:hover, a:focus {
+    color: var(--link-hover);
+  }
+  dialog {
+    color: var(--text);
+    background-color: var(--surface);
+  }
+  code {
+    background-color: var(--surface-hover);
+  }
+  pre {
+    color: var(--text);
+    background-color: var(--bg);
+    border-color: var(--border);
+  }
+
+  .table > tbody > tr > td,
+  .table > tbody > tr > th {
+    border-top-color: var(--rule);
+  }
+  .table-responsive,
+  .modal-header {
+    border-color: var(--rule);
+  }
+
+  .form-control,
+  .input-group-addon {
+    color: var(--text);
+    background-color: var(--surface);
+    border-color: var(--border);
+  }
+  .help-block {
+    color: var(--muted);
+  }
+  .has-error .help-block {
+    color: var(--negative);
+  }
+  .has-error .form-control,
+  .has-error .form-control:focus {
+    border-color: var(--negative);
+  }
+  .has-error .form-control:focus {
+    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 6px var(--negative);
+  }
+  .has-error .input-group-addon {
+    color: var(--negative);
+    background-color: var(--danger-bg);
+    border-color: var(--negative);
+  }
+
+  .btn-default {
+    color: var(--text);
+    background-color: var(--surface);
+    border-color: var(--border);
+  }
+  .btn-default:hover,
+  .btn-default:focus,
+  .btn-default:active,
+  .btn-default.active,
+  .btn-default:active:hover,
+  .btn-default:active:focus,
+  .btn-default.active:hover,
+  .btn-default.active:focus {
+    color: var(--text);
+    background-color: var(--surface-hover);
+    border-color: var(--border-hover);
+  }
+  .close,
+  .close:hover,
+  .close:focus {
+    color: var(--text);
+    text-shadow: none;
+  }
+
+  .alert-info {
+    color: var(--info);
+    background-color: var(--info-bg);
+    border-color: var(--info-border);
+  }
+  .alert-danger {
+    color: var(--negative);
+    background-color: var(--danger-bg);
+    border-color: var(--danger-border);
+  }
+}
+
+/* Tree-fold rows: the tree-mode report tables (reportTreeInit in
+   hledger.js) and the sidebar's accounts (the inline script in
+   default-layout.hamlet) are folded with a caret at each group. In the
+   report tables the indent is padding, set by the depth class, so the
+   caret sits at the account name. */
+.tree-fold-hide { display: none; }
+.more-commodities { opacity: .55; white-space: nowrap; }
+#sidebar-menu tr.total > td.total-label { text-align: right; padding-right: 6px; opacity: .7; white-space: nowrap; }
+/* The caret absorbs the indent to its left rather than adding width, so
+   the account names sit exactly where list mode puts them; the glyph
+   hugs the name. */
+.tree-caret { display: inline-block; width: 1.1em; margin-left: -1.1em; text-align: right; padding-right: 0.15em; cursor: pointer; color: var(--link, #337ab7); user-select: none; }
+/* The sidebar's account links have 20px of padding before the name, so
+   there its carets move over it, above the link so a click folds, to hug
+   the name too (and stay on screen when the sidebar slides in). */
+#sidebar-menu .tree-caret { position: relative; left: 20px; z-index: 1; }
+/* Depth 0 has no indent to absorb, so it gets one caret-width of its own. */
+.report-table td.account.indent-0  { padding-left: 1.1em; }
+.report-table td.account.indent-1  { padding-left: 1.6em; }
+.report-table td.account.indent-2  { padding-left: 3.0em; }
+.report-table td.account.indent-3  { padding-left: 4.4em; }
+.report-table td.account.indent-4  { padding-left: 5.8em; }
+.report-table td.account.indent-5  { padding-left: 7.2em; }
+.report-table td.account.indent-6  { padding-left: 8.6em; }
+.report-table td.account.indent-7  { padding-left: 10.0em; }
+.report-table td.account.indent-8  { padding-left: 11.4em; }
+.report-table td.account.indent-9  { padding-left: 12.8em; }
+.report-table td.account.indent-10 { padding-left: 14.2em; }
+.report-table td.account.indent-11 { padding-left: 15.6em; }
+.report-table td.account.indent-12 { padding-left: 17.0em; }
+
+/* The holdings page's tree mode: account heading rows stand out from the
+   position rows (named by their commodity) grouped beneath them. */
+.report-table td.account.acctheading { font-weight: bold; }
+
+/* Beside a report table's account heading, the depth limit's - and +
+   steps (depthStepper), kept quiet like the heading: the links are
+   there when you look for them. Not uppercased, so "Depth 2" reads as
+   a setting, not a column name. */
+.param-switch { margin-left: 1.5em; text-transform: none; letter-spacing: 0; white-space: nowrap; }
+.param-switch > * + * { margin-left: 0.5em; padding-left: 0.5em; border-left: 1px solid var(--border); }
+.param-switch .current { font-weight: 600; color: var(--text, inherit); }
+/* The account heading keeps its controls beside it, whatever the columns. */
+.report-table thead th.account { white-space: nowrap; }
+.depth-stepper { margin-left: 1.5em; text-transform: none; letter-spacing: 0; white-space: nowrap; }
+.depth-stepper .depth-step { display: inline-block; min-width: 1.4em; text-align: center; font-weight: 600; text-decoration: none; }
+.depth-stepper .depth-step.disabled { color: var(--muted); font-weight: normal; }
+/* The row above the sidebar's accounts, small and muted like the
+   table's stepper: the balances' date, right-aligned over the amounts. */
+#sidebar-menu .main-menu tr.depth-row > td { text-align: right; font-size: 12px; color: var(--muted); padding-top: 2px; padding-bottom: 2px; max-width: none; }
+/* The depth stepper, at the left, indented like the account names below
+   it: the content of the All accounts link above, and clear of the left
+   edge, which on a narrow screen is off the screen. */
+#sidebar-menu .main-menu tr.depth-row .depth-stepper { float: left; margin-left: 0; padding-left: 33px; }
+/* The balances' date is a button, like the reports' Chart and Data
+   buttons, that hides the sidebar's balances (the amounts, and the total
+   row), leaving the account names the whole width; it then reads just
+   "Balances". */
+#sidebar-menu .balances-toggle { padding: 0; border: 0; background: none; color: inherit; }
+#sidebar-menu .balances-toggle:hover { color: var(--link, #337ab7); }
+#sidebar-menu .balances-toggle::before { content: "▾"; display: inline-block; width: 1.1em; font-size: 1.25em; line-height: 1; color: var(--link, #337ab7); }
+#sidebar-menu.balances-hidden .balances-toggle::before { content: "▸"; }
+#sidebar-menu .balances-word,
+#sidebar-menu.balances-hidden .balances-date,
+#sidebar-menu.balances-hidden .main-menu td.amount,
+#sidebar-menu.balances-hidden .main-menu tr.total { display: none; }
+#sidebar-menu.balances-hidden .balances-word { display: inline; }
+#sidebar-menu.balances-hidden .main-menu td.acct { max-width: none; }
+/* The sidebar's steps are buttons (they fold in place, not links to
+   another page), looking like the table's link steps. */
+#sidebar-menu .main-menu tr.depth-row button.depth-step { padding: 0; border: 0; background: none; font-size: 12px; font-weight: 600; line-height: inherit; color: var(--link, #337ab7); cursor: pointer; }
+#sidebar-menu .main-menu tr.depth-row button.depth-step:disabled { color: var(--muted); font-weight: normal; cursor: default; }
diff --git a/static/hledger.js b/static/hledger.js
--- a/static/hledger.js
+++ b/static/hledger.js
@@ -3,164 +3,1340 @@
 //----------------------------------------------------------------------
 // STARTUP
 
-$(document).ready(function() {
-
-  // add form helpers XXX move to addForm ?
-
-  // date picker
-  // http://bootstrap-datepicker.readthedocs.io/en/latest/options.html
-  var dateEl = $('#dateWrap').datepicker({
-    showOnFocus: false,
-    autoclose: true,
-    format: 'yyyy-mm-dd',
-    todayHighlight: true,
-    weekStart: 1 // Monday
-  });;
-
-  // focus and pre-fill the add form whenever it is shown
-  $('#addmodal')
-    .on('shown.bs.modal', function() {
-      addformFocus();
-    })
-    .on('hidden.bs.modal', function() {
-      // close the date picker if open
-      dateEl.datepicker('hide');
-    });
-
-  // ensure that the keypress listener on the final amount input is always active
-  $('#addform')
-    .on('focus', '.amount-input:last', function() {
-      addformLastAmountBindKey();
-    });
-
-  // keyboard shortcuts
-  // 'body' seems to hold focus better than document in FF
-  $('body').bind('keydown', 'h',       function(){ $('#helpmodal').modal('toggle'); return false; });
-  $('body').bind('keydown', 'shift+/', function(){ $('#helpmodal').modal('toggle'); return false; });
-  $('body').bind('keydown', 'j',       function(){ location.href = document.hledgerWebBaseurl+'/journal'; return false; });
-  $('body').bind('keydown', 's',       function(){ sidebarToggle(); return false; });
-  $('body').bind('keydown', 'e',       function(){ emptyAccountsToggle(); return false; });
-  $('body').bind('keydown', 'a',       function(){ addformShow(); return false; });
-  $('body').bind('keydown', 'n',       function(){ addformShow(); return false; });
-  $('body').bind('keydown', 'f',       function(){ $('#searchform input').focus(); return false; });
-
-  // highlight the entry from the url hash
-  if (window.location.hash && $(window.location.hash)[0]) {
-    $(window.location.hash).addClass('highlighted');
-  }
-  $(window).on('hashchange', function() {
-    $('.highlighted').removeClass('highlighted');
-    $(window.location.hash).addClass('highlighted');
-  });
-  $('[data-toggle="offcanvas"]').click(function () {
-      $('.row-offcanvas').toggleClass('active');
-  });
-});
-
-//----------------------------------------------------------------------
-// ADD FORM
-
-function addformShow(showmsg) {
-  showmsg = typeof showmsg !== 'undefined' ? showmsg : false;
-  addformReset(showmsg);
-  $('#addmodal').modal('show');
-}
-
-// Make sure the add form is empty and clean and has the default number of rows.
-function addformReset(showmsg) {
-  showmsg = typeof showmsg !== 'undefined' ? showmsg : false;
-  if ($('form#addform').length > 0) {
-    if (!showmsg) $('div#message').html('');
-    $('#addform .account-group.added-row').remove();
-    addformLastAmountBindKey();
-    $('#addform')[0].reset();
-    // reset typehead state (though not fetched completions)
-    $('.typeahead').typeahead('val', '');
-    $('.tt-dropdown-menu').hide();
-  }
-}
-
-// Set the add-new-row-on-keypress handler on the add form's current last amount field, only.
-// (NB: removes all other keypress handlers from all amount fields).
-function addformLastAmountBindKey() {
-  $('input[name=amount]').off('keypress');
-  $('input[name=amount]:last').keypress(addformAddPosting);
-}
-
-// Pre-fill today's date and focus the description field in the add form.
-function addformFocus() {
-  $('#addform input[name=date]').val(isoDate());
-  focus($('#addform input[name=description]'));
-}
-
-function isoDate() {
-  return new Date().toLocaleDateString("sv");  // https://stackoverflow.com/a/58633651/84401
-}
-
-// Focus a jquery-wrapped element, working around http://stackoverflow.com/a/7046837.
-function focus($el) {
-  setTimeout(function (){
-    $el.focus();
-  }, 0);
-}
-
-// Insert another posting row in the add form.
-function addformAddPosting() {
-  if (!$('#addform').is(':visible')) { return; }
-
-  // Clone the last row.
-  var newrow = $('#addform .account-group:last').clone().addClass('added-row');
-  var newnum = $('#addform .account-group').length + 1;
-
-  // Clear the new account and amount fields and update their placeholder text.
-  var accountfield = newrow.find('input[name=account]');
-  var amountfield  = newrow.find('input[name=amount]');
-  accountfield.val('').prop('placeholder', 'Account '+newnum);
-  amountfield.val('').prop('placeholder', 'Amount '+newnum);
-
-  // Enable autocomplete in the new account field.
-  // We must first remove these typehead helper elements cloned from the old row,
-  // or it will recursively add helper elements for those, causing confusion (#2215).
-  newrow.find('.tt-hint').remove();
-  newrow.find('.tt-input').removeClass('tt-input');
-  accountfield.typeahead({ highlight: true }, { source: globalThis.accountsCompleter.ttAdapter(), templates: { suggestion: globalThis.suggestionTemplate } });
-
-  // Add the new row to the page.
-  $('#addform .account-postings').append(newrow);
-
-  // And move the keypress handler to the new last amount field.
-  addformLastAmountBindKey();
-}
-
-// Remove the add form's last posting row, if empty, keeping at least two.
-function addformDeletePosting() {
-  if ($('#addform .account-group').length <= 2) {
-    return;
-  }
-  // remember if the last row's field or button had focus
-  var focuslost =
-    $('.account-input:last').is(':focus')
-    || $('.amount-input:last').is(':focus');
-  // delete last row
-  $('#addform .account-group:last').remove();
-  if (focuslost) {
-    focus($('.account-input:last'));
-  }
-  // move the keypress handler to the new last amount field
-  addformLastAmountBindKey();
-}
-
-//----------------------------------------------------------------------
-// SIDEBAR
-
-function sidebarToggle() {
-  $('#sidebar-menu').toggleClass('col-md-4 col-sm-4 col-any-0');
-  $('#main-content').toggleClass('col-md-8 col-sm-8 col-md-12 col-sm-12');
-  $('#spacer').toggleClass('col-md-4 col-sm-4 col-any-0');
-  $.cookie('showsidebar', $('#sidebar-menu').hasClass('col-any-0') ? '0' : '1');
-}
-
-function emptyAccountsToggle() {
-  $('.acct.empty').parent().toggleClass('hide');
-  $.cookie('hideemptyaccts', $.cookie('hideemptyaccts') === '1' ? '0' : '1')
+document.addEventListener('DOMContentLoaded', function() {
+
+  // First, so that nothing below can stop it.
+  browsePingInit();
+
+  // Open and close the dialogs. The data-toggle/data-target/data-dismiss
+  // attributes in the templates are the hooks.
+  document.querySelectorAll('[data-toggle="modal"]').forEach(function(el) {
+    el.addEventListener('click', function(e) {
+      e.preventDefault();
+      var d = document.querySelector(el.getAttribute('data-target'));
+      if (!d) { return; }
+      if (d.id === 'addmodal') { addformShow(); } else { d.showModal(); }
+    });
+  });
+  document.querySelectorAll('[data-dismiss="modal"]').forEach(function(el) {
+    el.addEventListener('click', function() {
+      var d = el.closest('dialog');
+      if (d) { d.close(); }
+    });
+  });
+  // Clicking the backdrop closes a modal dialog. With showModal() a click on
+  // the backdrop is reported as a click on the dialog element itself.
+  document.querySelectorAll('dialog').forEach(function(d) {
+    d.addEventListener('click', function(e) {
+      if (e.target === d) { d.close(); }
+    });
+  });
+
+  // Fold tree-mode report tables (see reportTreeInit below). The
+  // sidebar's tree is folded earlier, inline right after its markup
+  // (default-layout.hamlet), so it never paints unfolded.
+  reportTreeInit();
+
+  // Shift-clicking in the years row selects a range of years, and in
+  // the account type and commodity rows, several of them.
+  yearsRangeInit();
+  typesMultiInit();
+  commoditiesMultiInit();
+
+  // The controls and commodity disclosures save their state, and control
+  // clicks save the page's scroll position.
+  controlsInit();
+
+  // The Chart and Data buttons do what the c and d keys do.
+  document.querySelectorAll('#main-content [data-report-part]').forEach(function(b) {
+    var chart = b.getAttribute('data-report-part') === 'chart';
+    b.addEventListener('click', function() {
+      reportPartToggle(b, chart ? 'chart-hidden' : 'table-hidden', chart ? 'showchart' : 'showtable');
+    });
+  });
+
+  // The sidebar's Balances heading hides or shows its balances: a class
+  // on the sidebar does it (hledger.css), and a cookie remembers it, which
+  // the server reads, so the next page renders the same way.
+  var balancesToggle = document.querySelector('#sidebar-menu .balances-toggle');
+  if (balancesToggle) {
+    balancesToggle.addEventListener('click', function() {
+      // Balances not served (the default) need the page again, from the
+      // server, keeping the reader's place.
+      if (balancesToggle.hasAttribute('data-reload')) {
+        setCookie('showbalances', '1');
+        try { sessionStorage.setItem('pageScrollTop', document.documentElement.scrollTop); } catch (e) {}
+        location.reload();
+        return;
+      }
+      var hidden = document.getElementById('sidebar-menu').classList.toggle('balances-hidden');
+      setCookie('showbalances', hidden ? '0' : '1');
+    });
+  }
+
+  // The hideemptyaccts cookie was replaced by the empty parameter;
+  // clear it from browsers that still carry it. Older versions set it
+  // with a one-year max-age, so this can safely be removed after
+  // 2028-01-01.
+  if (document.cookie.indexOf('hideemptyaccts=') >= 0) {
+    document.cookie = 'hideemptyaccts=; path=/; max-age=0';
+  }
+
+  // Typing in the last amount field adds another posting row. Delegating from
+  // the form means the handler does not have to be moved as rows come and go.
+  var addform = document.getElementById('addform');
+  if (addform) {
+    addform.addEventListener('keypress', function(e) {
+      if (!e.target.classList.contains('amount-input')) { return; }
+      var amounts = addform.querySelectorAll('.amount-input');
+      if (e.target === amounts[amounts.length - 1]) { addformAddPosting(); }
+    });
+  }
+
+  // The date field is a text input, so hledger's smart dates ("today", "2/15")
+  // keep working. The button beside it opens the browser's own calendar, via
+  // the hidden date input, and what you pick is written back as an iso date.
+  var datebutton = document.getElementById('datebutton');
+  var datepicked = document.getElementById('datepicked');
+  if (datebutton && datepicked) {
+    datebutton.addEventListener('click', function() {
+      var datefield = document.querySelector('#addform input[name=date]');
+      datepicked.value = /^\d{4}-\d{2}-\d{2}$/.test(datefield.value) ? datefield.value : isoDate();
+      if (datepicked.showPicker) { datepicked.showPicker(); }
+    });
+    datepicked.addEventListener('change', function() {
+      var datefield = document.querySelector('#addform input[name=date]');
+      if (datepicked.value) { datefield.value = datepicked.value; }
+    });
+  }
+
+  // Keyboard shortcuts. Not while typing in a field, or the search box would
+  // toggle the sidebar and open the add form as you spell "assets".
+  document.addEventListener('keydown', function(e) {
+    if (e.ctrlKey || e.metaKey || e.altKey) { return; }
+    // Escape closes an open dialog, even from one of its fields. Done here
+    // rather than left to the browser, so that the key is marked handled;
+    // otherwise Safari in full screen also takes it as leaving full screen.
+    var opendialog = document.querySelector('dialog[open]');
+    if (opendialog && e.key === 'Escape') {
+      opendialog.close();
+      e.preventDefault();
+      return;
+    }
+    if (e.target.closest('input, textarea, select')) { return; }
+    // The help keys toggle the help, so they close it too; while a dialog
+    // is open the other keys do nothing.
+    var help = document.getElementById('helpmodal');
+    if (help && help.open && (e.key === 'h' || e.key === '?')) {
+      helpToggle();
+      e.preventDefault();
+      return;
+    }
+    if (document.querySelector('dialog[open]')) { return; }
+    if (gomenuOpen()) {
+      // After g, a page's key goes there; escape or any other key closes the menu.
+      if (e.key.length > 1 && e.key !== 'Escape') { return; }
+      gomenuChoose(e.key);
+      e.preventDefault();
+      return;
+    }
+    if (sidebarDepthKey(e)) { e.preventDefault(); return; }
+    var k = keymapFind(e.key);
+    if (!k || k.run(keyTarget(k), e.key) === false) { return; }
+    e.preventDefault();
+  });
+  // Escape leaves the search field, keeping what was typed, so that the
+  // keyboard shortcuts and scrolling work again.
+  var searchfield = document.querySelector('#searchform input[name=q]');
+  if (searchfield) {
+    searchfield.addEventListener('keydown', function(e) {
+      if (e.key === 'Escape') { focusPage(); e.preventDefault(); }
+    });
+  }
+  var fullwindowexit = document.getElementById('fullwindow-exit');
+  if (fullwindowexit) { fullwindowexit.addEventListener('click', fullWindowToggle); }
+  // A click elsewhere closes the g key's menu, as escape does.
+  document.addEventListener('click', function(e) {
+    if (gomenuOpen() && !e.target.closest('#gomenu')) { gomenuHide(); }
+  });
+
+  // Name the chosen file beside the upload button. Set as text, so a file whose
+  // name contains markup is shown, not parsed.
+  var fileinput = document.getElementById('file');
+  if (fileinput) {
+    fileinput.addEventListener('change', function() {
+      var info = document.getElementById('file-info');
+      if (info) {
+        info.textContent = fileinput.files[0] ? fileinput.files[0].name : '';
+      }
+    });
+  }
+
+  var sidebarButton = document.getElementById('sidebar-toggle');
+  if (sidebarButton) { sidebarButton.addEventListener('click', sidebarToggleHere); }
+  sidebarButtonUpdate();
+
+  entryTooltipInit();
+  chartTooltipInit();
+  registerChartInit();
+  chartWidthRecord();
+  var resizing;
+  window.addEventListener('resize', function() {
+    // the charts fit the column as it changes, until they are redrawn for it
+    chartsStretch(true);
+    clearTimeout(resizing);
+    resizing = setTimeout(function() { chartsFit(); sidebarButtonUpdate(); }, 100);
+  });
+
+  // Unless something has focus already: a long page can be clicked or
+  // tabbed in before it has finished loading.
+  if (!document.activeElement || document.activeElement === document.body) { focusPage(); }
+});
+
+// Focus the main content, so that the arrow keys, space and page up/down
+// scroll it. On wider screens it scrolls by itself, not the window, and
+// browsers send those keys to the window until something in it has focus,
+// so a page could not be scrolled from the keyboard before a click.
+function focusPage() {
+  var main = document.getElementById('main-content');
+  if (main) { main.focus({ preventScroll: true }); }
+}
+
+//----------------------------------------------------------------------
+// KEYS
+
+// The keyboard shortcuts, as a table. Each entry has its keys and what
+// they do, and when they stand for a control on the page, how to find it:
+// a selector, or a function returning the element (nothing when this page
+// has none). The action is given that element and the key pressed, and
+// returns false when the key was not for it, leaving the key to the
+// browser. The keys are cased as hledger-ui's.
+// In full window mode, s, o and / leave it, showing what they ask for.
+var keymap = [
+  { keys: ['h', '?'], run: helpToggle },
+  { keys: ['g'], run: gomenuShow },
+  { keys: ['s'], run: function() { if (fullWindowLeave()) { sidebarShow(); } else { sidebarToggleHere(); } } },
+  { keys: ['b'], at: sidebarBalancesToggle, run: function(button) { if (!button) { return false; } button.click(); } },
+  { keys: ['o'], run: function() { if (fullWindowLeave()) { controlsShow(); } else { controlsToggle(); } } },
+  { keys: ['a'], run: function() { addformShow(); } },
+  // n and p go to the next and previous page, in the g menu's order.
+  { keys: ['n', 'p'], run: function(_, key) {
+      var a = document.querySelector('#pagesteps a[data-stepkey="' + key + '"]');
+      if (!a) { return false; }
+      linkFollow(a);
+    } },
+  { keys: ['f'], run: fullWindowToggle },
+  { keys: ['c'], at: '#main-content .report-chart', run: function(chart) { return reportPartToggle(chart, 'chart-hidden', 'showchart'); } },
+  { keys: ['d'], at: '#main-content .report-chart', run: function(chart) { return reportPartToggle(chart, 'table-hidden', 'showtable'); } },
+  { keys: ['[', ']'], at: '#main-content .with-legend', run: commodityStep },
+  { keys: ['N'], at: '#main-content .report-chart .total', run: netToggle },
+  { keys: ['/'], run: function() { fullWindowLeave(); focusSearch(); } },
+  // As the search form's clear button does, when there is a search.
+  { keys: ['Backspace', 'Delete'], at: '#search-clear', run: function(a) { if (!a) { return false; } linkFollow(a); } },
+  // On the holdings page, the zero rows are its closed positions.
+  { keys: ['z'], at: function() {
+      return document.querySelector('#main-content .closed-positions a:not(.current)') ||
+             document.querySelector('.zero-balances a:not(.current)');
+    }, run: linkFollow },
+  { keys: ['t'], at: rowLink('list', -1),            run: linkToggle },
+  { keys: ['H'], at: rowLink('accum', -1),           run: linkToggle },
+  { keys: ['L'], at: rowLink('lots', 1),             run: linkToggle },
+  { keys: ['V'], at: rowLink('amounts', -1),         run: linkToggle },
+  { keys: ['B'], at: rowLink('amounts', 1),          run: linkToggle },
+  { keys: ['R'], at: rowLink('postings', 1),         run: linkToggle },
+  { keys: ['U'], at: rowLink('status', 1),           run: linkToggle },
+  { keys: ['P'], at: rowLink('status', 2),           run: linkToggle },
+  { keys: ['C'], at: rowLink('status', 3),           run: linkToggle },
+  { keys: ['S'], at: rowLink('sort', 1),             run: linkToggle },
+  // The Extra columns links each toggle their own column.
+  { keys: ['T'], at: rowLink('columns', 0),          run: linkFollow },
+  { keys: ['A'], at: rowLink('columns', 1),          run: linkFollow },
+  { keys: ['Y'], at: rowLink('interval', 1),         run: linkToggle },
+  { keys: ['Q'], at: rowLink('interval', 2),         run: linkToggle },
+  { keys: ['M'], at: rowLink('interval', 3),         run: linkToggle },
+  { keys: ['W'], at: rowLink('interval', 4),         run: linkToggle },
+  { keys: ['D'], at: rowLink('interval', 5),         run: linkToggle },
+  { keys: '0123456789'.split(''), at: rowLink('depth', -1), run: depthSet },
+  { keys: ['-', '_'], at: depthStep(-1),             run: linkFollow },
+  { keys: ['+', '='], at: depthStep(1),              run: linkFollow },
+  // With nothing else to cancel, escape leaves full window mode.
+  { keys: ['Escape'], run: function() { return fullWindowLeave(); } },
+];
+
+function keymapFind(key) {
+  return keymap.find(function(k) { return k.keys.indexOf(key) >= 0; });
+}
+
+// The element a keymap entry stands for on this page, if any.
+function keyTarget(k) {
+  if (!k.at) { return null; }
+  return typeof k.at === 'string' ? document.querySelector(k.at) : k.at();
+}
+
+// A finder for the link at idx (negative counts from the end) in a row of
+// control links. Each row builder says which position its keys rely on
+// (Widget.Common).
+function rowLink(rowCls, idx) {
+  return function() {
+    var links = document.querySelectorAll('#main-content .' + rowCls + ' a');
+    return links[idx < 0 ? links.length + idx : idx];
+  };
+}
+
+function linkFollow(a) {
+  if (a) { location.href = a.href; }
+}
+
+// hledger-ui's toggling keys, on a row of control links: follow the link,
+// or when it is already current, the row's first link, which shows the
+// default.
+function linkToggle(a) {
+  if (!a) { return; }
+  location.href = (a.classList.contains('current') ? a.closest('.report-links').querySelector('a') : a).href;
+}
+
+// A finder for the Depth link the - and + keys go to: the one delta
+// steps from the current one, through 0, 1, ... the deepest (no limit),
+// stopping at either end.
+function depthStep(delta) {
+  return function() {
+    var links = Array.prototype.slice.call(document.querySelectorAll('#main-content .depth a'));
+    var cur = links.findIndex(function(a) { return a.classList.contains('current'); });
+    return cur >= 0 ? links[cur + delta] : undefined;
+  };
+}
+
+// The digit keys set the depth limit, like hledger-ui's: the Depth row's
+// last link, the deepest, carries the page's url without a depth limit,
+// which the depth parameter adds.
+function depthSet(deepest, n) {
+  if (!deepest) { return false; }
+  var url = new URL(deepest.href);
+  url.searchParams.set('depth', n);
+  location.href = url.href;
+}
+
+// The entry targeted by the url hash is marked by a :target rule in
+// hledger.css, which needs no javascript. A hash can be anything, eg an
+// old bookmark's numeric row id, so location.hash must not be passed to
+// querySelector.
+
+// The account sidebar's scroll position is preserved across page navigations
+// by an inline script right after the sidebar's markup in
+// default-layout.hamlet. It must run during page parse, not from this file:
+// this script loads at the end of the body and DOMContentLoaded fires only
+// once the whole document is parsed, while the browser paints the sidebar
+// (at scroll position 0) much earlier when a long journal or register
+// follows it, which made the sidebar visibly jump on page load.
+
+//----------------------------------------------------------------------
+// ADD FORM
+
+function addformShow(showmsg) {
+  var d = document.getElementById('addmodal');
+  if (!d || d.open) { return; }  // showModal() throws if already open
+  addformReset(typeof showmsg !== 'undefined' ? showmsg : false);
+  d.showModal();
+  addformFocus();
+}
+
+function helpToggle() {
+  var d = document.getElementById('helpmodal');
+  if (!d) { return; }
+  if (d.open) {
+    d.close();
+  } else {
+    d.showModal();
+    // showModal() focuses the first focusable element, which here is the
+    // close button; focus the dialog itself so it opens without a focus ring.
+    d.focus();
+  }
+}
+
+// Make sure the add form is empty and clean and has the default number of rows.
+function addformReset(showmsg) {
+  var addform = document.getElementById('addform');
+  if (!addform) { return; }
+  if (!showmsg) {
+    var msg = document.getElementById('message');
+    if (msg) { msg.innerHTML = ''; }
+  }
+  addform.querySelectorAll('.account-group.added-row').forEach(function(el) {
+    el.remove();
+  });
+  addform.reset();
+}
+
+// Pre-fill today's date and focus the description field in the add form.
+function addformFocus() {
+  var addform = document.getElementById('addform');
+  if (!addform) { return; }
+  addform.querySelector('input[name=date]').value = isoDate();
+  // Deferred, so the field is focusable: http://stackoverflow.com/a/7046837
+  setTimeout(function() {
+    addform.querySelector('input[name=description]').focus();
+  }, 0);
+}
+
+function isoDate() {
+  return new Date().toLocaleDateString("sv");  // https://stackoverflow.com/a/58633651/84401
+}
+
+// Focus the search field ready for another query term: rather than
+// selecting the search, put the cursor at its end, after a space.
+function focusSearch() {
+  var q = document.querySelector('#searchform input[name=q]');
+  if (!q) { return; }
+  if (q.value && !/\s$/.test(q.value)) { q.value += ' '; }
+  q.focus();
+  q.setSelectionRange(q.value.length, q.value.length);
+}
+
+// Insert another posting row in the add form.
+function addformAddPosting() {
+  var addform = document.getElementById('addform');
+  if (!addform) { return; }
+  var groups = addform.querySelectorAll('.account-group');
+  var newrow = groups[groups.length - 1].cloneNode(true);
+  newrow.classList.add('added-row');
+  var num = groups.length + 1;
+
+  // The cloned row may carry error styling from a previous failed submit.
+  newrow.querySelectorAll('.has-error').forEach(function(el) { el.classList.remove('has-error'); });
+  newrow.querySelectorAll('.error-block').forEach(function(el) { el.remove(); });
+
+  var account = newrow.querySelector('input[name=account]');
+  var amount = newrow.querySelector('input[name=amount]');
+  account.value = '';
+  amount.value = '';
+  // The placeholder templates come from the page, in its language.
+  var postings = addform.querySelector('.account-postings');
+  account.placeholder = (postings.dataset.accountPlaceholder || 'Account {n}').replace('{n}', num);
+  amount.placeholder = (postings.dataset.amountPlaceholder || 'Amount {n}').replace('{n}', num);
+
+  addform.querySelector('.account-postings').appendChild(newrow);
+}
+
+//----------------------------------------------------------------------
+// SIDEBAR
+
+// The g key's menu (default-layout.hamlet): it lists the pages, each with
+// the key that goes to it, keyed by page rather than position, so that
+// reordering the menu keeps the keys.
+function gomenuOpen() {
+  var menu = document.getElementById('gomenu');
+  return !!menu && !menu.hidden;
+}
+
+function gomenuShow() {
+  var menu = document.getElementById('gomenu');
+  if (menu) { menu.hidden = false; }
+}
+
+function gomenuHide() {
+  var menu = document.getElementById('gomenu');
+  if (menu) { menu.hidden = true; }
+}
+
+function gomenuChoose(key) {
+  var target = Array.prototype.find.call(
+    document.querySelectorAll('#gomenu a[data-gokey]'),
+    function (a) { return a.getAttribute('data-gokey') === key; });
+  gomenuHide();
+  if (target) { location.href = target.href; }
+}
+
+// A shift-click on a link in the years, account type, or commodity rows is
+// always handled here, never by the browser, whose own shift-click opens a
+// new window, or in Safari adds to the Reading List. compose(link) returns
+// the url combining the clicked link with the row's selection, or null to
+// follow the link as a plain click would.
+function shiftClickRow(row, compose) {
+  row.addEventListener('click', function (ev) {
+    if (!ev.shiftKey) { return; }
+    var a = ev.target.closest('a');
+    if (!a) { return; }
+    ev.preventDefault();
+    location.href = compose(a) || a.href;
+  });
+}
+
+// Shift-clicking a year in the years row extends the selection: from the
+// years marked current (a plain click's single year, or an earlier range)
+// to the clicked one, as an end-exclusive date:FIRST..LAST+1 search term,
+// which the row marks year by year. With no year marked (All current), a
+// shift-click selects the clicked year like a plain click.
+function yearsRangeInit() {
+  document.querySelectorAll('p.years').forEach(function (row) {
+    shiftClickRow(row, function (a) {
+      var clicked = parseInt(a.textContent, 10);
+      if (isNaN(clicked)) { return null; }  // the All link
+      var years = [clicked];
+      document.querySelectorAll('p.years a.current').forEach(function (c) {
+        var y = parseInt(c.textContent, 10);
+        if (!isNaN(y)) { years.push(y); }
+      });
+      if (years.length < 2) { return null; }  // nothing to extend from
+      var lo = Math.min.apply(null, years);
+      var hi = Math.max.apply(null, years);
+      // the clicked link's url, with every date: term (a hand-typed
+      // search may hold several) replaced by the range
+      var url = new URL(a.href);
+      var q = (url.searchParams.get('q') || '').replace(/\s*\bdate:\S+/g, '').trim();
+      url.searchParams.set('q', (q ? q + ' ' : '') + 'date:' + lo + '..' + (hi + 1));
+      return url.toString();
+    });
+  });
+}
+
+// Shift-clicking in the account type row adds the clicked type to the
+// selected ones, or removes it, as a single type:AL.. search term; the
+// row marks each selected type (see Widget.Common.typeLinks).
+function typesMultiInit() {
+  document.querySelectorAll('div.types').forEach(function (box) {
+    shiftClickRow(box, function (a) {
+      var typeOf = function (link) {
+        var m = (new URL(link.href).searchParams.get('q') || '').match(/type:(\w+)/);
+        return m && m[1].toUpperCase();
+      };
+      var clicked = typeOf(a);
+      if (!clicked) { return null; }  // the All link
+      var letters = [];
+      box.querySelectorAll('a.current').forEach(function (c) {
+        var t = typeOf(c);
+        if (t && letters.indexOf(t) < 0) { letters.push(t); }
+      });
+      var i = letters.indexOf(clicked);
+      if (i >= 0) { letters.splice(i, 1); } else { letters.push(clicked); }
+      var url = new URL(a.href);
+      // drop every type: term (a hand-typed search may hold several),
+      // then append the one composed term
+      var q = (url.searchParams.get('q') || '').replace(/\s*\btype:\w+/g, '').trim();
+      if (letters.length) { q = (q ? q + ' ' : '') + 'type:' + letters.sort().join(''); }
+      if (q) { url.searchParams.set('q', q); } else { url.searchParams.delete('q'); }
+      return url.toString();
+    });
+  });
+}
+
+// Shift-clicking in the commodity row adds the clicked commodity to the
+// selected ones, or removes it, as a single cur:A|B search term. The
+// links carry their regex-escaped patterns, and the row the search's
+// other terms, as data attributes (Widget.Common.commodityLinks), so no
+// query parsing happens here and any symbol works, spaces included: a
+// composed term containing one is quoted whole.
+function commoditiesMultiInit() {
+  document.querySelectorAll('div.commodities').forEach(function (box) {
+    shiftClickRow(box, function (a) {
+      var clicked = a.getAttribute('data-cur');
+      if (!clicked) { return null; }  // the All link
+      var pats = [];
+      box.querySelectorAll('a.current[data-cur]').forEach(function (c) {
+        pats.push(c.getAttribute('data-cur'));
+      });
+      var i = pats.indexOf(clicked);
+      if (i >= 0) { pats.splice(i, 1); } else { pats.push(clicked); }
+      var q = box.getAttribute('data-rest') || '';
+      if (pats.length) {
+        var term = 'cur:' + pats.join('|');
+        if (/\s/.test(term)) { term = '"' + term + '"'; }
+        q = (q + ' ' + term).trim();
+      }
+      var url = new URL(a.href);
+      if (q) { url.searchParams.set('q', q); } else { url.searchParams.delete('q'); }
+      return url.toString();
+    });
+  });
+}
+
+// A narrow screen (as in hledger.css) slides the sidebar in over the page
+// instead of giving it a column.
+function sidebarNarrow() {
+  return window.matchMedia('(max-width: 768px)').matches;
+}
+
+// Shift with a digit key from 1 to 9 sets the sidebar's depth, as its - and
+// + do (default-layout.hamlet's script), while the sidebar is showing. The
+// key is recognised by its place, since the character it types varies by
+// layout. Where it types a character that is a shortcut already, that
+// wins: the digit itself (eg on AZERTY, setting the report's depth), or eg
+// / (searching, on German keyboards). Says whether it was such a key.
+function sidebarDepthKey(e) {
+  var m = /^Digit([1-9])$/.exec(e.code || '');
+  if (!e.shiftKey || !m || keymapFind(e.key)) { return false; }
+  var menu = document.getElementById('sidebar-menu');
+  if (menu && menu.hledgerDepthTo && sidebarOpen() && !fullWindowOn()) { menu.hledgerDepthTo(parseInt(m[1], 10)); }
+  return true;
+}
+
+// The sidebar's Balances heading, while the sidebar shows.
+function sidebarBalancesToggle() {
+  if (!sidebarOpen() || fullWindowOn()) { return null; }
+  return document.querySelector('#sidebar-menu .balances-toggle');
+}
+
+function sidebarOpen() {
+  if (sidebarNarrow()) {
+    var row = document.querySelector('.row-offcanvas');
+    return !!row && row.classList.contains('active');
+  }
+  var sidebar = document.getElementById('sidebar-menu');
+  return !!sidebar && !sidebar.classList.contains('col-any-0');
+}
+
+// Show or hide the sidebar the way this screen does it (the s key and the
+// sidebar's button).
+function sidebarToggleHere() {
+  if (sidebarNarrow()) {
+    var row = document.querySelector('.row-offcanvas');
+    if (row) { row.classList.toggle('active'); }
+    sidebarButtonUpdate();
+  } else {
+    sidebarToggle();
+  }
+}
+
+function sidebarButtonUpdate() {
+  var button = document.getElementById('sidebar-toggle');
+  if (button) { button.setAttribute('aria-expanded', sidebarOpen() ? 'true' : 'false'); }
+}
+
+// Switch the sidebar, and the columns beside it, between shown and hidden.
+function sidebarClassesToggle() {
+  var sidebar = document.getElementById('sidebar-menu');
+  var main = document.getElementById('main-content');
+  var spacer = document.getElementById('spacer');
+  if (sidebar) { sidebar.classList.toggle('col-md-4'); sidebar.classList.toggle('col-sm-4'); sidebar.classList.toggle('col-any-0'); }
+  // The spacer keeps the sidebar's button, so shrinks to fit it rather than vanishing.
+  if (spacer) { spacer.classList.toggle('col-md-4'); spacer.classList.toggle('col-sm-4'); spacer.classList.toggle('sidebar-hidden'); }
+  if (main) {
+    main.classList.toggle('col-md-8'); main.classList.toggle('col-sm-8');
+    main.classList.toggle('col-md-12'); main.classList.toggle('col-sm-12');
+  }
+}
+
+function sidebarToggle() {
+  var sidebar = document.getElementById('sidebar-menu');
+  sidebarClassesToggle();
+  // The server reads this cookie, so the next page renders the way we left it.
+  setCookie('showsidebar', sidebar && sidebar.classList.contains('col-any-0') ? '0' : '1');
+  sidebarButtonUpdate();
+  chartsFit();
+}
+
+function fullWindowOn() {
+  return document.body.classList.contains('fullwindow');
+}
+
+function fullWindowToggle() {
+  // Full window mode hides all but the report's heading and data
+  // (hledger.css). It is remembered for this tab, and each page restores
+  // it before painting (default-layout-wrapper.hamlet). Session storage,
+  // not a cookie like the sidebar's, since the server needn't know it, and
+  // that is kept per tab and per hledger-web automatically.
+  var on = document.body.classList.toggle('fullwindow');
+  try {
+    if (on) { sessionStorage.setItem('fullwindow', '1'); } else { sessionStorage.removeItem('fullwindow'); }
+  } catch (e) {}
+  chartsFit();
+}
+
+function fullWindowLeave() {
+  // Leave full window mode, saying whether it was on.
+  if (!fullWindowOn()) { return false; }
+  fullWindowToggle();
+  return true;
+}
+
+function sidebarShow() {
+  var sidebar = document.getElementById('sidebar-menu');
+  if (sidebar && sidebar.classList.contains('col-any-0')) { sidebarToggle(); }
+}
+
+// Tree-mode report rows carry indent-N classes, their indent, and
+// depth-N classes, their account's depth (and the table the depth
+// limit to fold to initially, if any; a row starts open when its
+// account is above the limit). Give each group a caret that opens or
+// closes its rows in place, leaving the page's URL alone.
+function reportTreeInit() {
+  document.querySelectorAll('.report-table table').forEach(function(table) {
+    var fold = parseInt(table.getAttribute('data-depth-fold') || '', 10);
+    table.querySelectorAll('tbody').forEach(function(tbody) {
+      var rows = [];
+      tbody.querySelectorAll('tr').forEach(function(tr) {
+        var td = tr.querySelector('td.account');
+        var m = td && td.className.match(/\bindent-(\d+)\b/);
+        var d = td && td.className.match(/\bdepth-(\d+)\b/);
+        if (m) { rows.push({tr: tr, td: td, indent: +m[1], depth: d ? +d[1] : NaN, expanded: true, parent: false}); }
+      });
+      rows.forEach(function(r, i) {
+        r.parent = i + 1 < rows.length && rows[i + 1].indent > r.indent;
+        if (!isNaN(fold)) { r.expanded = r.depth < fold; }
+        var caret = document.createElement('span');
+        caret.className = 'tree-caret';
+        r.td.insertBefore(caret, r.td.firstChild);
+        if (r.parent) {
+          caret.addEventListener('click', function() { r.expanded = !r.expanded; apply(); });
+        }
+      });
+      function apply() {
+        // a row shows when every ancestor is open; the stack holds the
+        // open flags of the current row's ancestors
+        var stack = [];
+        rows.forEach(function(r) {
+          while (stack.length > r.indent) { stack.pop(); }
+          r.tr.classList.toggle('tree-fold-hide', !stack.every(function(open) { return open; }));
+          r.td.querySelector('.tree-caret').textContent = r.parent ? (r.expanded ? '\u25be' : '\u25b8') : '';
+          stack.push(r.expanded);
+        });
+      }
+      if (rows.length) { apply(); }
+    });
+  });
+}
+
+// The report controls disclosure, and the commodity filter's collapsed
+// list inside it, remember their state in cookies (showcontrols,
+// showcommodities), which the server reads to render the next page the
+// way this one was left — nothing moves after paint. The commodity
+// list's scroll position is remembered per tab, and clicking a control
+// link saves the page's scroll position, which the inline script in
+// default-layout.hamlet restores on the next page before it paints.
+function controlsInit() {
+  var d = document.querySelector('#main-content details.report-controls');
+  if (!d) { return; }
+  d.addEventListener('toggle', function () {
+    setCookie('showcontrols', d.open ? '1' : '0');
+  });
+  var cd = d.querySelector('div.commodities details');
+  if (cd) {
+    cd.addEventListener('toggle', function () {
+      setCookie('showcommodities', cd.open ? '1' : '0');
+    });
+    var cl = cd.querySelector('.report-links');
+    if (cl) {
+      try {
+        var ct = parseInt(sessionStorage.getItem('commodityScrollTop'), 10);
+        if (!isNaN(ct)) { cl.scrollTop = ct; }
+      } catch (e) {}
+      cl.addEventListener('scroll', function () {
+        try { sessionStorage.setItem('commodityScrollTop', cl.scrollTop); } catch (e) {}
+      });
+    }
+  }
+  document.addEventListener('click', function (ev) {
+    var a = ev.target.closest('a');
+    if (!a || !a.closest('details.report-controls')) { return; }
+    try { sessionStorage.setItem('pageScrollTop', document.documentElement.scrollTop); } catch (e) {}
+  });
+}
+
+// The c key opens and closes the disclosure like a click on its
+// summary; controlsInit's toggle listener saves the choice either way.
+// The c and d keys hide or show a report's chart, or its table (the
+// report's data), on the pages with a chart: a class on the main
+// column does it (hledger.css), and a cookie remembers it, which the
+// server reads, so the next page renders the same way.
+function reportPartToggle(chart, cls, cookie) {
+  if (!chart) { return false; }
+  var hidden = document.getElementById('main-content').classList.toggle(cls);
+  setCookie(cookie, hidden ? '0' : '1');
+}
+
+// The N key shows or hides the charts' total or net lines (or marks),
+// hidden by default, likewise (the net-shown class, the shownet cookie).
+function netToggle(total) {
+  if (!total) { return false; }
+  var shown = document.getElementById('main-content').classList.toggle('net-shown');
+  setCookie('shownet', shown ? '1' : '0');
+}
+
+// [ and ] choose the previous or next commodity in a chart's legend,
+// wrapping round, by checking its radio button, which the css follows.
+// They are not the arrow keys, which may be scrolling the page sideways.
+function commodityStep(legend, key) {
+  if (!legend) { return false; }
+  var radios = Array.from(legend.querySelectorAll(':scope > input[type=radio]'));
+  var i = radios.findIndex(function(r) { return r.checked; });
+  var n = radios.length;
+  radios[(i + (key === ']' ? 1 : -1) + n) % n].checked = true;
+}
+
+function controlsToggle() {
+  var d = document.querySelector('#main-content details.report-controls');
+  if (d) { d.open = !d.open; }
+}
+
+function controlsShow() {
+  var d = document.querySelector('#main-content details.report-controls');
+  if (d) { d.open = true; }
+}
+
+// The sidebar's account tree is folded by an inline script right after its
+// markup in default-layout.hamlet, like its scroll restore and for the same
+// reason: run from this file it would fold only at DOMContentLoaded, after
+// the browser has painted the tree in full, a visible jump.
+
+// The UI state cookies' names end with the server's port, so that several
+// hledger-webs on one host keep their own (App.uiCookie).
+function uiCookieName(name) {
+  return name + (document.hledgerWebCookieSuffix || '');
+}
+
+function setCookie(name, value) {
+  document.cookie = uiCookieName(name) + '=' + value + '; path=/; max-age=31536000; samesite=lax';
+}
+
+function getCookie(name) {
+  return document.cookie.split('; ').reduce(function(found, c) {
+    var parts = c.split('=');
+    return parts[0] === uiCookieName(name) ? parts.slice(1).join('=') : found;
+  }, undefined);
+}
+
+//----------------------------------------------------------------------
+// ENTRY TOOLTIP
+//
+// Hovering a transaction in the journal or a register shows its journal
+// entry, the way a browser shows a title attribute, but in a fixed-width
+// font so that the amounts line up as they do in the journal. The rows carry
+// the entry in a data-entry attribute; in a title attribute the browser would
+// draw it itself, in a proportional font and wrapped at its own narrow width.
+// As with titles, the innermost one applies: over an account link, the
+// link's title (the full account name) shows instead.
+
+function entryTooltipInit() {
+  if (!document.querySelector('[data-entry]')) { return; }
+  var tip = document.createElement('div');
+  tip.className = 'entry-tooltip';
+  tip.setAttribute('aria-hidden', 'true');
+  tip.hidden = true;
+  document.body.appendChild(tip);
+
+  var row = null;         // the element with an entry under the pointer
+  var timer = null;       // set while waiting to show its entry
+  var clicked = false;    // set by a click, until the pointer leaves the row
+  var x, y;               // the pointer position, where the entry appears
+
+  function show() {
+    timer = null;
+    entryTooltipFill(tip, row.getAttribute('data-entry'));
+    entryTooltipPlace(tip, x, y);
+  }
+  function hide() {
+    clearTimeout(timer);
+    timer = null;
+    tip.hidden = true;
+  }
+
+  // Mouse only. A touch has no hover, and changing the page when a touch
+  // arrives over a link makes iOS treat the first tap as a hover, so the link
+  // would take two taps.
+  function track(e) {
+    if (e.pointerType !== 'mouse') { return; }
+    x = e.clientX;
+    y = e.clientY;
+    var el = e.target.closest('[title], [data-entry]');
+    var over = el && el.hasAttribute('data-entry') ? el : null;
+    if (over !== row) {
+      // Moving on to the next entry while one is showing shows the next at
+      // once, as with browser tooltips; otherwise it appears after a pause.
+      var showing = !tip.hidden;
+      hide();
+      row = over;
+      clicked = false;
+      if (row) {
+        if (showing) { show(); } else { timer = setTimeout(show, 500); }
+      }
+    } else if (row && tip.hidden && !timer && !clicked) {
+      // Still over the row after a scroll or a key press hid it.
+      timer = setTimeout(show, 500);
+    }
+  }
+  document.addEventListener('pointerover', track);
+  document.addEventListener('pointermove', track);
+
+  // Also like a browser tooltip, it goes away when the pointer leaves the
+  // window, and on a click, a key press or a scroll. After a click it stays
+  // away until the pointer leaves the row, so as not to cover a selection
+  // being made. Scroll events don't bubble, and the main pane scrolls by
+  // itself, hence the capture.
+  document.addEventListener('pointerout', function(e) {
+    if (!e.relatedTarget) { hide(); row = null; }
+  });
+  document.addEventListener('pointerdown', function() {
+    hide();
+    clicked = true;
+  });
+  document.addEventListener('keydown', hide);
+  document.addEventListener('scroll', hide, true);
+  window.addEventListener('blur', hide);
+}
+
+// Put an entry's lines in the tooltip.
+function entryTooltipFill(tip, entry) {
+  tip.textContent = '';
+  entry.replace(/\s+$/, '').split('\n').forEach(function(line) {
+    var div = document.createElement('div');
+    // Set as text, so that journal content cannot be parsed as markup.
+    div.textContent = line;
+    // A line too long for the window wraps, and its continuation is indented
+    // past the line's own indentation, so the entry keeps its shape.
+    var indent = (line.match(/^ */)[0].length + 2) + 'ch';
+    div.style.paddingLeft = indent;
+    div.style.textIndent = '-' + indent;
+    tip.appendChild(div);
+  });
+}
+
+// Show the tooltip below the pointer, or above it if there is no room below,
+// and keep it within the window. Or for a tap (above), above the finger.
+function entryTooltipPlace(tip, x, y, above) {
+  var margin = 8;
+  var vw = document.documentElement.clientWidth;
+  var vh = document.documentElement.clientHeight;
+  tip.style.maxWidth = (vw - 2 * margin) + 'px';
+  tip.style.maxHeight = (vh - 2 * margin) + 'px';
+  tip.style.left = '0';
+  tip.style.top = '0';
+  tip.hidden = false;
+  var w = tip.offsetWidth;
+  var h = tip.offsetHeight;
+  // below the pointer, clear of its arrow; or above a finger, which would
+  // hide it, unless there is no room there
+  var top = above ? y - 40 - h : y + 20;
+  if (above && top < margin) { top = y + 40; }
+  if (top + h > vh - margin) { top = y - margin - h; }
+  if (top < margin) { top = vh - margin - h; }
+  // starting at the pointer's arrow, or centred over a finger
+  var left = above ? x - w / 2 : x;
+  tip.style.left = Math.max(margin, Math.min(left, vw - margin - w)) + 'px';
+  tip.style.top = top + 'px';
+  // An entry taller than the window is cut off; the css marks the cut.
+  tip.classList.toggle('clipped', tip.scrollHeight > tip.clientHeight);
+}
+
+//----------------------------------------------------------------------
+// CHART TOOLTIP
+//
+// A chart's marks (bars, lines, the average line) carry their tooltips as SVG
+// titles (see Hledger.Write.Chart.Svg), which a browser shows only after a
+// pause, in its own small box, and not at all on a touch screen. Here,
+// hovering a mark, or tapping it, shows its tooltip at once, in a box like
+// the entry tooltip's: the part before the first " · " (a
+// period, date or account) in bold, then a swatch of the mark's colour and
+// the rest. On a line, a dot marks the point described. The titles become
+// aria-labels, which screen readers still read but browsers don't show.
+
+function chartTooltipInit() {
+  if (!document.querySelector('svg.hledger-chart')) { return; }
+  chartTitlesToLabels(document);
+  var tip = document.createElement('div');
+  tip.className = 'chart-tooltip';
+  tip.setAttribute('aria-hidden', 'true');
+  tip.hidden = true;
+  document.body.appendChild(tip);
+
+  var mark = null;   // the mark whose tooltip is shown
+  var dot = null;    // the dot on a line's point, if one is shown
+  var press = null;  // a touch or pen press in progress: where, on which mark, and the mark shown before it
+
+  function show(g, x, y, above) {
+    if (g !== mark) {
+      hide();
+      mark = g;
+      chartTooltipFill(tip, g);
+      dot = chartTooltipDot(g);
+    }
+    entryTooltipPlace(tip, x, y, above);
+  }
+  function hide() {
+    tip.hidden = true;
+    mark = null;
+    if (dot) { dot.remove(); dot = null; }
+  }
+  // The mark an event happened on, if any.
+  function markAt(e) {
+    return e.target.closest ? e.target.closest('svg.hledger-chart g[data-tip]') : null;
+  }
+
+  // With a mouse, hovering a mark shows its tooltip, as with the entry
+  // tooltip; but not while a button is down, eg while dragging across the
+  // register chart.
+  function track(e) {
+    if (e.pointerType !== 'mouse') { return; }
+    var g = e.buttons ? null : markAt(e);
+    if (g) { show(g, e.clientX, e.clientY, false); } else if (mark) { hide(); }
+  }
+  document.addEventListener('pointerover', track);
+  document.addEventListener('pointermove', track);
+  document.addEventListener('pointerout', function(e) {
+    if (e.pointerType === 'mouse' && !e.relatedTarget) { hide(); }
+  });
+
+  // With a touch or a pen, which can't hover, tapping a mark shows its
+  // tooltip, above the finger, until the next tap: which hides it, or shows
+  // another mark's (tapping the same mark again just hides it). A mark that
+  // is a link, as the register chart's points are, is followed instead; and
+  // a press that moves, eg to scroll, does nothing.
+  document.addEventListener('pointerdown', function(e) {
+    press = e.pointerType === 'mouse' ? null : { x: e.clientX, y: e.clientY, mark: markAt(e), shown: mark };
+    hide();
+  });
+  document.addEventListener('pointerup', function(e) {
+    var p = press;
+    press = null;
+    if (!p || !p.mark || p.mark === p.shown || p.mark.closest('a')) { return; }
+    if (Math.abs(e.clientX - p.x) > 10 || Math.abs(e.clientY - p.y) > 10) { return; }
+    show(p.mark, p.x, p.y, true);
+  });
+  document.addEventListener('pointercancel', function() { press = null; });
+
+  document.addEventListener('keydown', hide);
+  document.addEventListener('scroll', hide, true);
+  window.addEventListener('blur', hide);
+}
+
+// Turn the marks' titles in the charts within root into the data-tip and
+// aria-label attributes that chartTooltipInit's handlers use.
+function chartTitlesToLabels(root) {
+  root.querySelectorAll('svg.hledger-chart g > title').forEach(function(title) {
+    var g = title.parentNode;
+    g.setAttribute('data-tip', title.textContent);
+    g.setAttribute('role', 'img');
+    g.setAttribute('aria-label', title.textContent);
+    title.remove();
+  });
+}
+
+// Put a mark's tooltip in the box: its first part in bold, then a swatch and
+// the rest, then any more lines (eg the accounts an "other" series combines).
+// Set as text, so that journal content cannot be parsed as markup.
+function chartTooltipFill(tip, g) {
+  var lines = g.getAttribute('data-tip').split('\n');
+  var text = lines[0];
+  var i = text.indexOf(' · ');
+  var head = document.createElement('div');
+  head.className = 'chart-tooltip-head';
+  head.textContent = i < 0 ? text : text.slice(0, i);
+  tip.textContent = '';
+  tip.appendChild(head);
+  if (i >= 0) {
+    var rest = document.createElement('div');
+    var swatch = chartTooltipSwatch(g);
+    if (swatch) { rest.appendChild(swatch); }
+    rest.appendChild(document.createTextNode(text.slice(i + 3)));
+    tip.appendChild(rest);
+  }
+  lines.slice(1).forEach(function(l) {
+    var more = document.createElement('div');
+    more.className = 'chart-tooltip-more';
+    more.textContent = l;
+    tip.appendChild(more);
+  });
+}
+
+// The visible line that a line's tooltip target (an invisible .hit or
+// .hit-line, carrying the line's colour class) belongs to, if any.
+function chartTooltipLine(target) {
+  var cls = Array.prototype.filter.call(target.classList, function(c) {
+    return c !== 'hit' && c !== 'hit-line';
+  })[0];
+  return cls ? target.closest('svg').querySelector('.line.' + CSS.escape(cls)) : null;
+}
+
+// A swatch of a mark's colour: a square for a bar, a short line for a line,
+// dashed for the average. None if its colour is not a plain one.
+function chartTooltipSwatch(g) {
+  var el = g.firstElementChild;
+  if (!el) { return null; }
+  var kind = 'line';
+  var colour;
+  if (el.matches('.hit, .hit-line')) {
+    var line = chartTooltipLine(el);
+    colour = line && getComputedStyle(line).stroke;
+  } else if (el.matches('.average, .mark')) {
+    if (el.matches('.average')) { kind = 'dashed'; }
+    colour = getComputedStyle(el).stroke;
+  } else {
+    kind = 'bar';
+    colour = getComputedStyle(el).fill;
+  }
+  if (!colour || colour === 'none' || colour.indexOf('url(') >= 0) { return null; }
+  var swatch = document.createElement('span');
+  swatch.className = 'chart-tooltip-swatch ' + kind;
+  swatch.style.color = colour;
+  return swatch;
+}
+
+// On a line, a dot on the point a tooltip describes: the start of its
+// target's path, or its circle's centre. Its colour is the line's.
+function chartTooltipDot(g) {
+  var el = g.firstElementChild;
+  if (!el || !el.matches('.hit, .hit-line')) { return null; }
+  var p = el.matches('.hit')
+    ? { x: el.cx.baseVal.value, y: el.cy.baseVal.value }
+    : el.getPointAtLength(0);
+  var dot = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
+  dot.setAttribute('class', 'hover-dot');
+  dot.setAttribute('cx', p.x);
+  dot.setAttribute('cy', p.y);
+  dot.setAttribute('r', 4.5);
+  var line = chartTooltipLine(el);
+  if (line) { dot.style.fill = getComputedStyle(line).stroke; }
+  el.closest('svg').appendChild(dot);
+  return dot;
+}
+
+//----------------------------------------------------------------------
+// REGISTER CHART
+//
+// The register page's balance chart is SVG, drawn by the server (see
+// registerChartHtml and chart.hamlet), its points linking to their rows. Here,
+// dragging across one of its plots shows the register for the dates dragged
+// across. Each plot carries its date scale, on a transparent rect.plot under
+// it: its first and last dates (data-d0, data-d1) and their x positions
+// (data-x0, data-x1), between which dates are spaced evenly. The chart carries
+// this register's url without its date terms (data-baselink).
+
+// Keep the width of the page's main column in the chartwidth cookie, for
+// the server to draw charts that wide (chartWidths): a chart drawn wider
+// than its column is shrunk to fit, its text with it. And its widths with
+// the sidebar shown and hidden, in the chartwidths cookie, for the server
+// to draw charts for both, so that showing or hiding the sidebar needs no
+// redraw. Measured on every page, so that they are known before a chart is
+// shown. Returns the width, if known.
+function chartWidthRecord() {
+  var main = document.getElementById('main-content');
+  if (!main) { return 0; }
+  var width = function() {
+    var style = getComputedStyle(main);
+    return Math.max(0, Math.floor(main.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight)));
+  };
+  var w = width();
+  if (!w) { return 0; }
+  if (String(w) !== getCookie('chartwidth')) { setCookie('chartwidth', w); }
+  // the width with the sidebar in its other state, measured by switching
+  // it there and back, before anything is drawn
+  var sidebar = document.getElementById('sidebar-menu');
+  if (sidebar) {
+    sidebarClassesToggle();
+    var other = width();
+    sidebarClassesToggle();
+    var hidden = sidebar.classList.contains('col-any-0');
+    var both = (hidden ? other : w) + ',' + (hidden ? w : other);
+    if (other && both !== getCookie('chartwidths')) { setCookie('chartwidths', both); }
+  }
+  return w;
+}
+
+// When the main column's width changes on this page (the sidebar shown or
+// hidden, full window mode, a window resize), record it, and if the
+// page's charts (the ones for the sidebar's state, if drawn for both)
+// were drawn at another width, redraw them at this one: fetch the page
+// again, now drawn with the new width, and put its charts in place of
+// these. Until then they are stretched or shrunk to fit (chartsStretch).
+// Only the latest redraw's response is used. If it fails, the charts stay
+// as they are.
+var chartsRedraws = 0;
+function chartsFit() {
+  var w = chartWidthRecord();
+  var main = document.getElementById('main-content');
+  var state = main && main.classList.contains('col-md-12') ? 'hidden' : 'shown';
+  var svg = document.querySelector('.chart-width[data-sidebar=' + state + '] svg.hledger-chart') ||
+            document.querySelector('.report-chart svg.hledger-chart');
+  // the width the server draws at for this one (chartWidths)
+  if (!w || !svg || Math.max(320, Math.min(2400, w)) === Number(svg.getAttribute('width'))) {
+    chartsStretch(false);
+    return;
+  }
+  chartsStretch(true);
+  var n = ++chartsRedraws;
+  fetch(location.href, { cache: 'no-store' })
+    .then(function(r) { return r.ok ? r.text() : Promise.reject(r.status); })
+    .then(function(html) {
+      if (n !== chartsRedraws) { return; }
+      chartsReplace(new DOMParser().parseFromString(html, 'text/html'));
+      chartsStretch(false);
+    })
+    .catch(function() {});
+}
+
+// Stretch or shrink the page's charts to the main column's width while
+// they wait to be redrawn at a new width (chartsFit), keeping their
+// heights, so that nothing below them moves, then or when they are
+// redrawn; meanwhile their text is stretched or squeezed sideways a
+// little. Or put them back as they were drawn.
+function chartsStretch(on) {
+  var main = document.getElementById('main-content');
+  if (!main || !main.querySelector('svg.hledger-chart')) { return; }
+  main.classList.toggle('charts-stretched', on);
+  main.querySelectorAll('svg.hledger-chart').forEach(function(svg) {
+    if (on) {
+      svg.setAttribute('preserveAspectRatio', 'none');
+      svg.style.height = svg.getAttribute('height') + 'px';
+    } else {
+      svg.removeAttribute('preserveAspectRatio');
+      svg.style.height = '';
+    }
+  });
+}
+
+// Put the charts of a freshly drawn copy of this page in place of this
+// page's, if it has as many, keeping the commodity chosen in each legend,
+// and the focus if it was in one; then set them up as at page load.
+function chartsReplace(doc) {
+  var sel = '.report-chart, .register-chart';
+  var olds = document.querySelectorAll(sel);
+  var news = doc.querySelectorAll(sel);
+  if (olds.length !== news.length) { return; }
+  var focused = document.activeElement;
+  olds.forEach(function(old, i) {
+    var fresh = document.importNode(news[i], true);
+    var same = function(el) { return el && el.id ? fresh.querySelector('#' + CSS.escape(el.id)) : null; };
+    var chosen = same(old.querySelector('input[type=radio]:checked'));
+    if (chosen) { chosen.checked = true; }
+    var refocus = old.contains(focused) ? same(focused) : null;
+    old.replaceWith(fresh);
+    if (refocus) { refocus.focus(); }
+  });
+  chartTitlesToLabels(document);
+  registerChartInit();
+}
+
+// Let the register chart's plots, if this page has any, be dragged across.
+function registerChartInit() {
+  document.querySelectorAll('.register-chart[data-baselink] svg').forEach(function(svg) {
+    var plots = Array.prototype.slice.call(svg.querySelectorAll('rect.plot[data-d0]'));
+    if (!plots.length) { return; }
+    var drag = null;       // the drag in progress: its plot, where it started, and its selection
+    var dragged = false;   // was the last press a drag, rather than a click ?
+    // The pointer's position in the chart's own coordinates, whatever size
+    // the page draws it at.
+    var point = function(ev) {
+      return new DOMPoint(ev.clientX, ev.clientY).matrixTransform(svg.getScreenCTM().inverse());
+    };
+    svg.addEventListener('pointerdown', function(ev) {
+      dragged = false;
+      if (ev.button !== 0) { return; }
+      var p = point(ev);
+      var plot = plots.find(function(pl) {
+        var r = registerChartPlotBox(pl);
+        return p.x >= r.x && p.x <= r.x + r.width && p.y >= r.y && p.y <= r.y + r.height;
+      });
+      if (!plot) { return; }
+      drag = { plot: plot, x: p.x, selection: null };
+      // no text selection, and no dragging away the link of a point pressed on
+      ev.preventDefault();
+    });
+    svg.addEventListener('dragstart', function(ev) { ev.preventDefault(); });
+    svg.addEventListener('pointermove', function(ev) {
+      if (!drag) { return; }
+      var x = registerChartClamp(drag.plot, point(ev).x);
+      if (!drag.selection) {
+        // a click may wobble a little before it is a drag
+        if (Math.abs(x - drag.x) < 4) { return; }
+        // From here on the pointer is the drag's, wherever it goes. (Not
+        // before: a click would then land on the chart, not a point's link.)
+        svg.setPointerCapture(ev.pointerId);
+        var r = registerChartPlotBox(drag.plot);
+        drag.selection = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+        drag.selection.setAttribute('class', 'selection');
+        drag.selection.setAttribute('y', r.y);
+        drag.selection.setAttribute('height', r.height);
+        svg.appendChild(drag.selection);
+      }
+      drag.selection.setAttribute('x', Math.min(x, drag.x));
+      drag.selection.setAttribute('width', Math.abs(x - drag.x));
+    });
+    svg.addEventListener('pointerup', function(ev) {
+      var d = drag;
+      drag = null;
+      if (!d || !d.selection) { return; }
+      dragged = true;
+      registerChartSelect(svg, d.plot, d.x, registerChartClamp(d.plot, point(ev).x));
+    });
+    svg.addEventListener('pointercancel', function() {
+      if (drag && drag.selection) { drag.selection.remove(); }
+      drag = null;
+    });
+    // A drag ending on a point is not a click on its link.
+    svg.addEventListener('click', function(ev) {
+      if (dragged) { ev.preventDefault(); }
+      dragged = false;
+    }, true);
+  });
+}
+
+// The position and size of a plot, in the chart's coordinates.
+function registerChartPlotBox(plot) {
+  return { x: +plot.getAttribute('x'), y: +plot.getAttribute('y'),
+           width: +plot.getAttribute('width'), height: +plot.getAttribute('height') };
+}
+
+// An x position kept within a plot.
+function registerChartClamp(plot, x) {
+  var r = registerChartPlotBox(plot);
+  return Math.max(r.x, Math.min(r.x + r.width, x));
+}
+
+// Show the register for the dates between two x positions on a plot, by
+// reloading it with a date: query for them.
+function registerChartSelect(svg, plot, xa, xb) {
+  var DAY = 24 * 60 * 60 * 1000;
+  // dates as YYYY-MM-DD are read, and written, as UTC
+  var d0 = Date.parse(plot.getAttribute('data-d0')), d1 = Date.parse(plot.getAttribute('data-d1'));
+  var x0 = +plot.getAttribute('data-x0'), x1 = +plot.getAttribute('data-x1');
+  var span = Math.round((d1 - d0) / DAY);
+  // the day nearest an x position, within the plot's dates
+  var day = function(x) {
+    var k = x1 > x0 ? Math.round((x - x0) / (x1 - x0) * span) : 0;
+    return d0 + Math.max(0, Math.min(span, k)) * DAY;
+  };
+  var iso = function(t) { return new Date(t).toISOString().slice(0, 10); };
+  // as a date: term reads it: YYYY-MM-DD..YYYY-MM-DD, the end exclusive
+  var range = iso(day(Math.min(xa, xb))) + '..' + iso(day(Math.max(xa, xb)) + DAY);
+  var url = new URL(svg.closest('.register-chart').getAttribute('data-baselink'), document.baseURI);
+  var q = url.searchParams.get('q');
+  url.searchParams.set('q', (q ? q + ' ' : '') + 'date:' + range);
+  document.location = url.href;
+}
+
+//----------------------------------------------------------------------
+// BROWSE MODE
+
+// In the default --serve-browse mode the server exits once no browser
+// window has shown it for fifteen minutes (serveAndBrowse in Main.hs). It
+// knows a window is open because the page pings it: on load, every 30
+// seconds, and whenever the page is shown again. Browsers run the timers of
+// background tabs less often, so the pings from a hidden page can be minutes
+// apart; the ping on showing makes up for that as soon as the page is seen.
+// Pages are marked for this by defaultLayout in browse mode only; the server
+// answers /_ping in that mode only. The ping goes to the page's own origin,
+// whatever address the browser reached us at (the policy allows requests to
+// our origin only), under the base url's path, in case a proxy in front of
+// us expects one.
+//
+// A ping that can't reach the server means it has stopped, so the page shows
+// the #server-stopped notice, and hides it again if a later ping gets through
+// (eg after the server was restarted on the same address).
+function browsePingInit() {
+  if (!document.body.hasAttribute('data-browse-mode')) { return; }
+  var base = new URL(document.hledgerWebBaseurl, document.baseURI);
+  var url = base.pathname.replace(/\/$/, '') + '/_ping';
+  var notice = document.getElementById('server-stopped');
+  var ping = function() {
+    fetch(url, { cache: 'no-store' }).then(
+      function() { if (notice) { notice.hidden = true; } },
+      function() { if (notice) { notice.hidden = false; } });
+  };
+  ping();
+  setInterval(ping, 30000);
+  document.addEventListener('visibilitychange', function() {
+    if (document.visibilityState === 'visible') { ping(); }
+  });
+  // A page restored from the back/forward cache didn't run meanwhile.
+  window.addEventListener('pageshow', function(e) {
+    if (e.persisted) { ping(); }
+  });
 }
diff --git a/static/js/bootstrap-datepicker.min.js b/static/js/bootstrap-datepicker.min.js
deleted file mode 100644
--- a/static/js/bootstrap-datepicker.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/*!
- * Datepicker for Bootstrap v1.7.1 (https://github.com/uxsolutions/bootstrap-datepicker)
- *
- * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
- */
-
-!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a("object"==typeof exports?require("jquery"):jQuery)}(function(a,b){function c(){return new Date(Date.UTC.apply(Date,arguments))}function d(){var a=new Date;return c(a.getFullYear(),a.getMonth(),a.getDate())}function e(a,b){return a.getUTCFullYear()===b.getUTCFullYear()&&a.getUTCMonth()===b.getUTCMonth()&&a.getUTCDate()===b.getUTCDate()}function f(c,d){return function(){return d!==b&&a.fn.datepicker.deprecated(d),this[c].apply(this,arguments)}}function g(a){return a&&!isNaN(a.getTime())}function h(b,c){function d(a,b){return b.toLowerCase()}var e,f=a(b).data(),g={},h=new RegExp("^"+c.toLowerCase()+"([A-Z])");c=new RegExp("^"+c.toLowerCase());for(var i in f)c.test(i)&&(e=i.replace(h,d),g[e]=f[i]);return g}function i(b){var c={};if(q[b]||(b=b.split("-")[0],q[b])){var d=q[b];return a.each(p,function(a,b){b in d&&(c[b]=d[b])}),c}}var j=function(){var b={get:function(a){return this.slice(a)[0]},contains:function(a){for(var b=a&&a.valueOf(),c=0,d=this.length;c<d;c++)if(0<=this[c].valueOf()-b&&this[c].valueOf()-b<864e5)return c;return-1},remove:function(a){this.splice(a,1)},replace:function(b){b&&(a.isArray(b)||(b=[b]),this.clear(),this.push.apply(this,b))},clear:function(){this.length=0},copy:function(){var a=new j;return a.replace(this),a}};return function(){var c=[];return c.push.apply(c,arguments),a.extend(c,b),c}}(),k=function(b,c){a.data(b,"datepicker",this),this._process_options(c),this.dates=new j,this.viewDate=this.o.defaultViewDate,this.focusDate=null,this.element=a(b),this.isInput=this.element.is("input"),this.inputField=this.isInput?this.element:this.element.find("input"),this.component=!!this.element.hasClass("date")&&this.element.find(".add-on, .input-group-addon, .btn"),this.component&&0===this.component.length&&(this.component=!1),this.isInline=!this.component&&this.element.is("div"),this.picker=a(r.template),this._check_template(this.o.templates.leftArrow)&&this.picker.find(".prev").html(this.o.templates.leftArrow),this._check_template(this.o.templates.rightArrow)&&this.picker.find(".next").html(this.o.templates.rightArrow),this._buildEvents(),this._attachEvents(),this.isInline?this.picker.addClass("datepicker-inline").appendTo(this.element):this.picker.addClass("datepicker-dropdown dropdown-menu"),this.o.rtl&&this.picker.addClass("datepicker-rtl"),this.o.calendarWeeks&&this.picker.find(".datepicker-days .datepicker-switch, thead .datepicker-title, tfoot .today, tfoot .clear").attr("colspan",function(a,b){return Number(b)+1}),this._process_options({startDate:this._o.startDate,endDate:this._o.endDate,daysOfWeekDisabled:this.o.daysOfWeekDisabled,daysOfWeekHighlighted:this.o.daysOfWeekHighlighted,datesDisabled:this.o.datesDisabled}),this._allow_update=!1,this.setViewMode(this.o.startView),this._allow_update=!0,this.fillDow(),this.fillMonths(),this.update(),this.isInline&&this.show()};k.prototype={constructor:k,_resolveViewName:function(b){return a.each(r.viewModes,function(c,d){if(b===c||a.inArray(b,d.names)!==-1)return b=c,!1}),b},_resolveDaysOfWeek:function(b){return a.isArray(b)||(b=b.split(/[,\s]*/)),a.map(b,Number)},_check_template:function(c){try{if(c===b||""===c)return!1;if((c.match(/[<>]/g)||[]).length<=0)return!0;var d=a(c);return d.length>0}catch(a){return!1}},_process_options:function(b){this._o=a.extend({},this._o,b);var e=this.o=a.extend({},this._o),f=e.language;q[f]||(f=f.split("-")[0],q[f]||(f=o.language)),e.language=f,e.startView=this._resolveViewName(e.startView),e.minViewMode=this._resolveViewName(e.minViewMode),e.maxViewMode=this._resolveViewName(e.maxViewMode),e.startView=Math.max(this.o.minViewMode,Math.min(this.o.maxViewMode,e.startView)),e.multidate!==!0&&(e.multidate=Number(e.multidate)||!1,e.multidate!==!1&&(e.multidate=Math.max(0,e.multidate))),e.multidateSeparator=String(e.multidateSeparator),e.weekStart%=7,e.weekEnd=(e.weekStart+6)%7;var g=r.parseFormat(e.format);e.startDate!==-(1/0)&&(e.startDate?e.startDate instanceof Date?e.startDate=this._local_to_utc(this._zero_time(e.startDate)):e.startDate=r.parseDate(e.startDate,g,e.language,e.assumeNearbyYear):e.startDate=-(1/0)),e.endDate!==1/0&&(e.endDate?e.endDate instanceof Date?e.endDate=this._local_to_utc(this._zero_time(e.endDate)):e.endDate=r.parseDate(e.endDate,g,e.language,e.assumeNearbyYear):e.endDate=1/0),e.daysOfWeekDisabled=this._resolveDaysOfWeek(e.daysOfWeekDisabled||[]),e.daysOfWeekHighlighted=this._resolveDaysOfWeek(e.daysOfWeekHighlighted||[]),e.datesDisabled=e.datesDisabled||[],a.isArray(e.datesDisabled)||(e.datesDisabled=e.datesDisabled.split(",")),e.datesDisabled=a.map(e.datesDisabled,function(a){return r.parseDate(a,g,e.language,e.assumeNearbyYear)});var h=String(e.orientation).toLowerCase().split(/\s+/g),i=e.orientation.toLowerCase();if(h=a.grep(h,function(a){return/^auto|left|right|top|bottom$/.test(a)}),e.orientation={x:"auto",y:"auto"},i&&"auto"!==i)if(1===h.length)switch(h[0]){case"top":case"bottom":e.orientation.y=h[0];break;case"left":case"right":e.orientation.x=h[0]}else i=a.grep(h,function(a){return/^left|right$/.test(a)}),e.orientation.x=i[0]||"auto",i=a.grep(h,function(a){return/^top|bottom$/.test(a)}),e.orientation.y=i[0]||"auto";else;if(e.defaultViewDate instanceof Date||"string"==typeof e.defaultViewDate)e.defaultViewDate=r.parseDate(e.defaultViewDate,g,e.language,e.assumeNearbyYear);else if(e.defaultViewDate){var j=e.defaultViewDate.year||(new Date).getFullYear(),k=e.defaultViewDate.month||0,l=e.defaultViewDate.day||1;e.defaultViewDate=c(j,k,l)}else e.defaultViewDate=d()},_events:[],_secondaryEvents:[],_applyEvents:function(a){for(var c,d,e,f=0;f<a.length;f++)c=a[f][0],2===a[f].length?(d=b,e=a[f][1]):3===a[f].length&&(d=a[f][1],e=a[f][2]),c.on(e,d)},_unapplyEvents:function(a){for(var c,d,e,f=0;f<a.length;f++)c=a[f][0],2===a[f].length?(e=b,d=a[f][1]):3===a[f].length&&(e=a[f][1],d=a[f][2]),c.off(d,e)},_buildEvents:function(){var b={keyup:a.proxy(function(b){a.inArray(b.keyCode,[27,37,39,38,40,32,13,9])===-1&&this.update()},this),keydown:a.proxy(this.keydown,this),paste:a.proxy(this.paste,this)};this.o.showOnFocus===!0&&(b.focus=a.proxy(this.show,this)),this.isInput?this._events=[[this.element,b]]:this.component&&this.inputField.length?this._events=[[this.inputField,b],[this.component,{click:a.proxy(this.show,this)}]]:this._events=[[this.element,{click:a.proxy(this.show,this),keydown:a.proxy(this.keydown,this)}]],this._events.push([this.element,"*",{blur:a.proxy(function(a){this._focused_from=a.target},this)}],[this.element,{blur:a.proxy(function(a){this._focused_from=a.target},this)}]),this.o.immediateUpdates&&this._events.push([this.element,{"changeYear changeMonth":a.proxy(function(a){this.update(a.date)},this)}]),this._secondaryEvents=[[this.picker,{click:a.proxy(this.click,this)}],[this.picker,".prev, .next",{click:a.proxy(this.navArrowsClick,this)}],[this.picker,".day:not(.disabled)",{click:a.proxy(this.dayCellClick,this)}],[a(window),{resize:a.proxy(this.place,this)}],[a(document),{"mousedown touchstart":a.proxy(function(a){this.element.is(a.target)||this.element.find(a.target).length||this.picker.is(a.target)||this.picker.find(a.target).length||this.isInline||this.hide()},this)}]]},_attachEvents:function(){this._detachEvents(),this._applyEvents(this._events)},_detachEvents:function(){this._unapplyEvents(this._events)},_attachSecondaryEvents:function(){this._detachSecondaryEvents(),this._applyEvents(this._secondaryEvents)},_detachSecondaryEvents:function(){this._unapplyEvents(this._secondaryEvents)},_trigger:function(b,c){var d=c||this.dates.get(-1),e=this._utc_to_local(d);this.element.trigger({type:b,date:e,viewMode:this.viewMode,dates:a.map(this.dates,this._utc_to_local),format:a.proxy(function(a,b){0===arguments.length?(a=this.dates.length-1,b=this.o.format):"string"==typeof a&&(b=a,a=this.dates.length-1),b=b||this.o.format;var c=this.dates.get(a);return r.formatDate(c,b,this.o.language)},this)})},show:function(){if(!(this.inputField.prop("disabled")||this.inputField.prop("readonly")&&this.o.enableOnReadonly===!1))return this.isInline||this.picker.appendTo(this.o.container),this.place(),this.picker.show(),this._attachSecondaryEvents(),this._trigger("show"),(window.navigator.msMaxTouchPoints||"ontouchstart"in document)&&this.o.disableTouchKeyboard&&a(this.element).blur(),this},hide:function(){return this.isInline||!this.picker.is(":visible")?this:(this.focusDate=null,this.picker.hide().detach(),this._detachSecondaryEvents(),this.setViewMode(this.o.startView),this.o.forceParse&&this.inputField.val()&&this.setValue(),this._trigger("hide"),this)},destroy:function(){return this.hide(),this._detachEvents(),this._detachSecondaryEvents(),this.picker.remove(),delete this.element.data().datepicker,this.isInput||delete this.element.data().date,this},paste:function(b){var c;if(b.originalEvent.clipboardData&&b.originalEvent.clipboardData.types&&a.inArray("text/plain",b.originalEvent.clipboardData.types)!==-1)c=b.originalEvent.clipboardData.getData("text/plain");else{if(!window.clipboardData)return;c=window.clipboardData.getData("Text")}this.setDate(c),this.update(),b.preventDefault()},_utc_to_local:function(a){if(!a)return a;var b=new Date(a.getTime()+6e4*a.getTimezoneOffset());return b.getTimezoneOffset()!==a.getTimezoneOffset()&&(b=new Date(a.getTime()+6e4*b.getTimezoneOffset())),b},_local_to_utc:function(a){return a&&new Date(a.getTime()-6e4*a.getTimezoneOffset())},_zero_time:function(a){return a&&new Date(a.getFullYear(),a.getMonth(),a.getDate())},_zero_utc_time:function(a){return a&&c(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate())},getDates:function(){return a.map(this.dates,this._utc_to_local)},getUTCDates:function(){return a.map(this.dates,function(a){return new Date(a)})},getDate:function(){return this._utc_to_local(this.getUTCDate())},getUTCDate:function(){var a=this.dates.get(-1);return a!==b?new Date(a):null},clearDates:function(){this.inputField.val(""),this.update(),this._trigger("changeDate"),this.o.autoclose&&this.hide()},setDates:function(){var b=a.isArray(arguments[0])?arguments[0]:arguments;return this.update.apply(this,b),this._trigger("changeDate"),this.setValue(),this},setUTCDates:function(){var b=a.isArray(arguments[0])?arguments[0]:arguments;return this.setDates.apply(this,a.map(b,this._utc_to_local)),this},setDate:f("setDates"),setUTCDate:f("setUTCDates"),remove:f("destroy","Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead"),setValue:function(){var a=this.getFormattedDate();return this.inputField.val(a),this},getFormattedDate:function(c){c===b&&(c=this.o.format);var d=this.o.language;return a.map(this.dates,function(a){return r.formatDate(a,c,d)}).join(this.o.multidateSeparator)},getStartDate:function(){return this.o.startDate},setStartDate:function(a){return this._process_options({startDate:a}),this.update(),this.updateNavArrows(),this},getEndDate:function(){return this.o.endDate},setEndDate:function(a){return this._process_options({endDate:a}),this.update(),this.updateNavArrows(),this},setDaysOfWeekDisabled:function(a){return this._process_options({daysOfWeekDisabled:a}),this.update(),this},setDaysOfWeekHighlighted:function(a){return this._process_options({daysOfWeekHighlighted:a}),this.update(),this},setDatesDisabled:function(a){return this._process_options({datesDisabled:a}),this.update(),this},place:function(){if(this.isInline)return this;var b=this.picker.outerWidth(),c=this.picker.outerHeight(),d=10,e=a(this.o.container),f=e.width(),g="body"===this.o.container?a(document).scrollTop():e.scrollTop(),h=e.offset(),i=[0];this.element.parents().each(function(){var b=a(this).css("z-index");"auto"!==b&&0!==Number(b)&&i.push(Number(b))});var j=Math.max.apply(Math,i)+this.o.zIndexOffset,k=this.component?this.component.parent().offset():this.element.offset(),l=this.component?this.component.outerHeight(!0):this.element.outerHeight(!1),m=this.component?this.component.outerWidth(!0):this.element.outerWidth(!1),n=k.left-h.left,o=k.top-h.top;"body"!==this.o.container&&(o+=g),this.picker.removeClass("datepicker-orient-top datepicker-orient-bottom datepicker-orient-right datepicker-orient-left"),"auto"!==this.o.orientation.x?(this.picker.addClass("datepicker-orient-"+this.o.orientation.x),"right"===this.o.orientation.x&&(n-=b-m)):k.left<0?(this.picker.addClass("datepicker-orient-left"),n-=k.left-d):n+b>f?(this.picker.addClass("datepicker-orient-right"),n+=m-b):this.o.rtl?this.picker.addClass("datepicker-orient-right"):this.picker.addClass("datepicker-orient-left");var p,q=this.o.orientation.y;if("auto"===q&&(p=-g+o-c,q=p<0?"bottom":"top"),this.picker.addClass("datepicker-orient-"+q),"top"===q?o-=c+parseInt(this.picker.css("padding-top")):o+=l,this.o.rtl){var r=f-(n+m);this.picker.css({top:o,right:r,zIndex:j})}else this.picker.css({top:o,left:n,zIndex:j});return this},_allow_update:!0,update:function(){if(!this._allow_update)return this;var b=this.dates.copy(),c=[],d=!1;return arguments.length?(a.each(arguments,a.proxy(function(a,b){b instanceof Date&&(b=this._local_to_utc(b)),c.push(b)},this)),d=!0):(c=this.isInput?this.element.val():this.element.data("date")||this.inputField.val(),c=c&&this.o.multidate?c.split(this.o.multidateSeparator):[c],delete this.element.data().date),c=a.map(c,a.proxy(function(a){return r.parseDate(a,this.o.format,this.o.language,this.o.assumeNearbyYear)},this)),c=a.grep(c,a.proxy(function(a){return!this.dateWithinRange(a)||!a},this),!0),this.dates.replace(c),this.o.updateViewDate&&(this.dates.length?this.viewDate=new Date(this.dates.get(-1)):this.viewDate<this.o.startDate?this.viewDate=new Date(this.o.startDate):this.viewDate>this.o.endDate?this.viewDate=new Date(this.o.endDate):this.viewDate=this.o.defaultViewDate),d?(this.setValue(),this.element.change()):this.dates.length&&String(b)!==String(this.dates)&&d&&(this._trigger("changeDate"),this.element.change()),!this.dates.length&&b.length&&(this._trigger("clearDate"),this.element.change()),this.fill(),this},fillDow:function(){if(this.o.showWeekDays){var b=this.o.weekStart,c="<tr>";for(this.o.calendarWeeks&&(c+='<th class="cw">&#160;</th>');b<this.o.weekStart+7;)c+='<th class="dow',a.inArray(b,this.o.daysOfWeekDisabled)!==-1&&(c+=" disabled"),c+='">'+q[this.o.language].daysMin[b++%7]+"</th>";c+="</tr>",this.picker.find(".datepicker-days thead").append(c)}},fillMonths:function(){for(var a,b=this._utc_to_local(this.viewDate),c="",d=0;d<12;d++)a=b&&b.getMonth()===d?" focused":"",c+='<span class="month'+a+'">'+q[this.o.language].monthsShort[d]+"</span>";this.picker.find(".datepicker-months td").html(c)},setRange:function(b){b&&b.length?this.range=a.map(b,function(a){return a.valueOf()}):delete this.range,this.fill()},getClassNames:function(b){var c=[],f=this.viewDate.getUTCFullYear(),g=this.viewDate.getUTCMonth(),h=d();return b.getUTCFullYear()<f||b.getUTCFullYear()===f&&b.getUTCMonth()<g?c.push("old"):(b.getUTCFullYear()>f||b.getUTCFullYear()===f&&b.getUTCMonth()>g)&&c.push("new"),this.focusDate&&b.valueOf()===this.focusDate.valueOf()&&c.push("focused"),this.o.todayHighlight&&e(b,h)&&c.push("today"),this.dates.contains(b)!==-1&&c.push("active"),this.dateWithinRange(b)||c.push("disabled"),this.dateIsDisabled(b)&&c.push("disabled","disabled-date"),a.inArray(b.getUTCDay(),this.o.daysOfWeekHighlighted)!==-1&&c.push("highlighted"),this.range&&(b>this.range[0]&&b<this.range[this.range.length-1]&&c.push("range"),a.inArray(b.valueOf(),this.range)!==-1&&c.push("selected"),b.valueOf()===this.range[0]&&c.push("range-start"),b.valueOf()===this.range[this.range.length-1]&&c.push("range-end")),c},_fill_yearsView:function(c,d,e,f,g,h,i){for(var j,k,l,m="",n=e/10,o=this.picker.find(c),p=Math.floor(f/e)*e,q=p+9*n,r=Math.floor(this.viewDate.getFullYear()/n)*n,s=a.map(this.dates,function(a){return Math.floor(a.getUTCFullYear()/n)*n}),t=p-n;t<=q+n;t+=n)j=[d],k=null,t===p-n?j.push("old"):t===q+n&&j.push("new"),a.inArray(t,s)!==-1&&j.push("active"),(t<g||t>h)&&j.push("disabled"),t===r&&j.push("focused"),i!==a.noop&&(l=i(new Date(t,0,1)),l===b?l={}:"boolean"==typeof l?l={enabled:l}:"string"==typeof l&&(l={classes:l}),l.enabled===!1&&j.push("disabled"),l.classes&&(j=j.concat(l.classes.split(/\s+/))),l.tooltip&&(k=l.tooltip)),m+='<span class="'+j.join(" ")+'"'+(k?' title="'+k+'"':"")+">"+t+"</span>";o.find(".datepicker-switch").text(p+"-"+q),o.find("td").html(m)},fill:function(){var d,e,f=new Date(this.viewDate),g=f.getUTCFullYear(),h=f.getUTCMonth(),i=this.o.startDate!==-(1/0)?this.o.startDate.getUTCFullYear():-(1/0),j=this.o.startDate!==-(1/0)?this.o.startDate.getUTCMonth():-(1/0),k=this.o.endDate!==1/0?this.o.endDate.getUTCFullYear():1/0,l=this.o.endDate!==1/0?this.o.endDate.getUTCMonth():1/0,m=q[this.o.language].today||q.en.today||"",n=q[this.o.language].clear||q.en.clear||"",o=q[this.o.language].titleFormat||q.en.titleFormat;if(!isNaN(g)&&!isNaN(h)){this.picker.find(".datepicker-days .datepicker-switch").text(r.formatDate(f,o,this.o.language)),this.picker.find("tfoot .today").text(m).css("display",this.o.todayBtn===!0||"linked"===this.o.todayBtn?"table-cell":"none"),this.picker.find("tfoot .clear").text(n).css("display",this.o.clearBtn===!0?"table-cell":"none"),this.picker.find("thead .datepicker-title").text(this.o.title).css("display","string"==typeof this.o.title&&""!==this.o.title?"table-cell":"none"),this.updateNavArrows(),this.fillMonths();var p=c(g,h,0),s=p.getUTCDate();p.setUTCDate(s-(p.getUTCDay()-this.o.weekStart+7)%7);var t=new Date(p);p.getUTCFullYear()<100&&t.setUTCFullYear(p.getUTCFullYear()),t.setUTCDate(t.getUTCDate()+42),t=t.valueOf();for(var u,v,w=[];p.valueOf()<t;){if(u=p.getUTCDay(),u===this.o.weekStart&&(w.push("<tr>"),this.o.calendarWeeks)){var x=new Date(+p+(this.o.weekStart-u-7)%7*864e5),y=new Date(Number(x)+(11-x.getUTCDay())%7*864e5),z=new Date(Number(z=c(y.getUTCFullYear(),0,1))+(11-z.getUTCDay())%7*864e5),A=(y-z)/864e5/7+1;w.push('<td class="cw">'+A+"</td>")}v=this.getClassNames(p),v.push("day");var B=p.getUTCDate();this.o.beforeShowDay!==a.noop&&(e=this.o.beforeShowDay(this._utc_to_local(p)),e===b?e={}:"boolean"==typeof e?e={enabled:e}:"string"==typeof e&&(e={classes:e}),e.enabled===!1&&v.push("disabled"),e.classes&&(v=v.concat(e.classes.split(/\s+/))),e.tooltip&&(d=e.tooltip),e.content&&(B=e.content)),v=a.isFunction(a.uniqueSort)?a.uniqueSort(v):a.unique(v),w.push('<td class="'+v.join(" ")+'"'+(d?' title="'+d+'"':"")+' data-date="'+p.getTime().toString()+'">'+B+"</td>"),d=null,u===this.o.weekEnd&&w.push("</tr>"),p.setUTCDate(p.getUTCDate()+1)}this.picker.find(".datepicker-days tbody").html(w.join(""));var C=q[this.o.language].monthsTitle||q.en.monthsTitle||"Months",D=this.picker.find(".datepicker-months").find(".datepicker-switch").text(this.o.maxViewMode<2?C:g).end().find("tbody span").removeClass("active");if(a.each(this.dates,function(a,b){b.getUTCFullYear()===g&&D.eq(b.getUTCMonth()).addClass("active")}),(g<i||g>k)&&D.addClass("disabled"),g===i&&D.slice(0,j).addClass("disabled"),g===k&&D.slice(l+1).addClass("disabled"),this.o.beforeShowMonth!==a.noop){var E=this;a.each(D,function(c,d){var e=new Date(g,c,1),f=E.o.beforeShowMonth(e);f===b?f={}:"boolean"==typeof f?f={enabled:f}:"string"==typeof f&&(f={classes:f}),f.enabled!==!1||a(d).hasClass("disabled")||a(d).addClass("disabled"),f.classes&&a(d).addClass(f.classes),f.tooltip&&a(d).prop("title",f.tooltip)})}this._fill_yearsView(".datepicker-years","year",10,g,i,k,this.o.beforeShowYear),this._fill_yearsView(".datepicker-decades","decade",100,g,i,k,this.o.beforeShowDecade),this._fill_yearsView(".datepicker-centuries","century",1e3,g,i,k,this.o.beforeShowCentury)}},updateNavArrows:function(){if(this._allow_update){var a,b,c=new Date(this.viewDate),d=c.getUTCFullYear(),e=c.getUTCMonth(),f=this.o.startDate!==-(1/0)?this.o.startDate.getUTCFullYear():-(1/0),g=this.o.startDate!==-(1/0)?this.o.startDate.getUTCMonth():-(1/0),h=this.o.endDate!==1/0?this.o.endDate.getUTCFullYear():1/0,i=this.o.endDate!==1/0?this.o.endDate.getUTCMonth():1/0,j=1;switch(this.viewMode){case 0:a=d<=f&&e<=g,b=d>=h&&e>=i;break;case 4:j*=10;case 3:j*=10;case 2:j*=10;case 1:a=Math.floor(d/j)*j<=f,b=Math.floor(d/j)*j+j>=h}this.picker.find(".prev").toggleClass("disabled",a),this.picker.find(".next").toggleClass("disabled",b)}},click:function(b){b.preventDefault(),b.stopPropagation();var e,f,g,h;e=a(b.target),e.hasClass("datepicker-switch")&&this.viewMode!==this.o.maxViewMode&&this.setViewMode(this.viewMode+1),e.hasClass("today")&&!e.hasClass("day")&&(this.setViewMode(0),this._setDate(d(),"linked"===this.o.todayBtn?null:"view")),e.hasClass("clear")&&this.clearDates(),e.hasClass("disabled")||(e.hasClass("month")||e.hasClass("year")||e.hasClass("decade")||e.hasClass("century"))&&(this.viewDate.setUTCDate(1),f=1,1===this.viewMode?(h=e.parent().find("span").index(e),g=this.viewDate.getUTCFullYear(),this.viewDate.setUTCMonth(h)):(h=0,g=Number(e.text()),this.viewDate.setUTCFullYear(g)),this._trigger(r.viewModes[this.viewMode-1].e,this.viewDate),this.viewMode===this.o.minViewMode?this._setDate(c(g,h,f)):(this.setViewMode(this.viewMode-1),this.fill())),this.picker.is(":visible")&&this._focused_from&&this._focused_from.focus(),delete this._focused_from},dayCellClick:function(b){var c=a(b.currentTarget),d=c.data("date"),e=new Date(d);this.o.updateViewDate&&(e.getUTCFullYear()!==this.viewDate.getUTCFullYear()&&this._trigger("changeYear",this.viewDate),e.getUTCMonth()!==this.viewDate.getUTCMonth()&&this._trigger("changeMonth",this.viewDate)),this._setDate(e)},navArrowsClick:function(b){var c=a(b.currentTarget),d=c.hasClass("prev")?-1:1;0!==this.viewMode&&(d*=12*r.viewModes[this.viewMode].navStep),this.viewDate=this.moveMonth(this.viewDate,d),this._trigger(r.viewModes[this.viewMode].e,this.viewDate),this.fill()},_toggle_multidate:function(a){var b=this.dates.contains(a);if(a||this.dates.clear(),b!==-1?(this.o.multidate===!0||this.o.multidate>1||this.o.toggleActive)&&this.dates.remove(b):this.o.multidate===!1?(this.dates.clear(),this.dates.push(a)):this.dates.push(a),"number"==typeof this.o.multidate)for(;this.dates.length>this.o.multidate;)this.dates.remove(0)},_setDate:function(a,b){b&&"date"!==b||this._toggle_multidate(a&&new Date(a)),(!b&&this.o.updateViewDate||"view"===b)&&(this.viewDate=a&&new Date(a)),this.fill(),this.setValue(),b&&"view"===b||this._trigger("changeDate"),this.inputField.trigger("change"),!this.o.autoclose||b&&"date"!==b||this.hide()},moveDay:function(a,b){var c=new Date(a);return c.setUTCDate(a.getUTCDate()+b),c},moveWeek:function(a,b){return this.moveDay(a,7*b)},moveMonth:function(a,b){if(!g(a))return this.o.defaultViewDate;if(!b)return a;var c,d,e=new Date(a.valueOf()),f=e.getUTCDate(),h=e.getUTCMonth(),i=Math.abs(b);if(b=b>0?1:-1,1===i)d=b===-1?function(){return e.getUTCMonth()===h}:function(){return e.getUTCMonth()!==c},c=h+b,e.setUTCMonth(c),c=(c+12)%12;else{for(var j=0;j<i;j++)e=this.moveMonth(e,b);c=e.getUTCMonth(),e.setUTCDate(f),d=function(){return c!==e.getUTCMonth()}}for(;d();)e.setUTCDate(--f),e.setUTCMonth(c);return e},moveYear:function(a,b){return this.moveMonth(a,12*b)},moveAvailableDate:function(a,b,c){do{if(a=this[c](a,b),!this.dateWithinRange(a))return!1;c="moveDay"}while(this.dateIsDisabled(a));return a},weekOfDateIsDisabled:function(b){return a.inArray(b.getUTCDay(),this.o.daysOfWeekDisabled)!==-1},dateIsDisabled:function(b){return this.weekOfDateIsDisabled(b)||a.grep(this.o.datesDisabled,function(a){return e(b,a)}).length>0},dateWithinRange:function(a){return a>=this.o.startDate&&a<=this.o.endDate},keydown:function(a){if(!this.picker.is(":visible"))return void(40!==a.keyCode&&27!==a.keyCode||(this.show(),a.stopPropagation()));var b,c,d=!1,e=this.focusDate||this.viewDate;switch(a.keyCode){case 27:this.focusDate?(this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill()):this.hide(),a.preventDefault(),a.stopPropagation();break;case 37:case 38:case 39:case 40:if(!this.o.keyboardNavigation||7===this.o.daysOfWeekDisabled.length)break;b=37===a.keyCode||38===a.keyCode?-1:1,0===this.viewMode?a.ctrlKey?(c=this.moveAvailableDate(e,b,"moveYear"),c&&this._trigger("changeYear",this.viewDate)):a.shiftKey?(c=this.moveAvailableDate(e,b,"moveMonth"),c&&this._trigger("changeMonth",this.viewDate)):37===a.keyCode||39===a.keyCode?c=this.moveAvailableDate(e,b,"moveDay"):this.weekOfDateIsDisabled(e)||(c=this.moveAvailableDate(e,b,"moveWeek")):1===this.viewMode?(38!==a.keyCode&&40!==a.keyCode||(b*=4),c=this.moveAvailableDate(e,b,"moveMonth")):2===this.viewMode&&(38!==a.keyCode&&40!==a.keyCode||(b*=4),c=this.moveAvailableDate(e,b,"moveYear")),c&&(this.focusDate=this.viewDate=c,this.setValue(),this.fill(),a.preventDefault());break;case 13:if(!this.o.forceParse)break;e=this.focusDate||this.dates.get(-1)||this.viewDate,this.o.keyboardNavigation&&(this._toggle_multidate(e),d=!0),this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.setValue(),this.fill(),this.picker.is(":visible")&&(a.preventDefault(),a.stopPropagation(),this.o.autoclose&&this.hide());break;case 9:this.focusDate=null,this.viewDate=this.dates.get(-1)||this.viewDate,this.fill(),this.hide()}d&&(this.dates.length?this._trigger("changeDate"):this._trigger("clearDate"),this.inputField.trigger("change"))},setViewMode:function(a){this.viewMode=a,this.picker.children("div").hide().filter(".datepicker-"+r.viewModes[this.viewMode].clsName).show(),this.updateNavArrows(),this._trigger("changeViewMode",new Date(this.viewDate))}};var l=function(b,c){a.data(b,"datepicker",this),this.element=a(b),this.inputs=a.map(c.inputs,function(a){return a.jquery?a[0]:a}),delete c.inputs,this.keepEmptyValues=c.keepEmptyValues,delete c.keepEmptyValues,n.call(a(this.inputs),c).on("changeDate",a.proxy(this.dateUpdated,this)),this.pickers=a.map(this.inputs,function(b){return a.data(b,"datepicker")}),this.updateDates()};l.prototype={updateDates:function(){this.dates=a.map(this.pickers,function(a){return a.getUTCDate()}),this.updateRanges()},updateRanges:function(){var b=a.map(this.dates,function(a){return a.valueOf()});a.each(this.pickers,function(a,c){c.setRange(b)})},dateUpdated:function(c){if(!this.updating){this.updating=!0;var d=a.data(c.target,"datepicker");if(d!==b){var e=d.getUTCDate(),f=this.keepEmptyValues,g=a.inArray(c.target,this.inputs),h=g-1,i=g+1,j=this.inputs.length;if(g!==-1){if(a.each(this.pickers,function(a,b){b.getUTCDate()||b!==d&&f||b.setUTCDate(e)}),e<this.dates[h])for(;h>=0&&e<this.dates[h];)this.pickers[h--].setUTCDate(e);else if(e>this.dates[i])for(;i<j&&e>this.dates[i];)this.pickers[i++].setUTCDate(e);this.updateDates(),delete this.updating}}}},destroy:function(){a.map(this.pickers,function(a){a.destroy()}),a(this.inputs).off("changeDate",this.dateUpdated),delete this.element.data().datepicker},remove:f("destroy","Method `remove` is deprecated and will be removed in version 2.0. Use `destroy` instead")};var m=a.fn.datepicker,n=function(c){var d=Array.apply(null,arguments);d.shift();var e;if(this.each(function(){var b=a(this),f=b.data("datepicker"),g="object"==typeof c&&c;if(!f){var j=h(this,"date"),m=a.extend({},o,j,g),n=i(m.language),p=a.extend({},o,n,j,g);b.hasClass("input-daterange")||p.inputs?(a.extend(p,{inputs:p.inputs||b.find("input").toArray()}),f=new l(this,p)):f=new k(this,p),b.data("datepicker",f)}"string"==typeof c&&"function"==typeof f[c]&&(e=f[c].apply(f,d))}),e===b||e instanceof k||e instanceof l)return this;if(this.length>1)throw new Error("Using only allowed for the collection of a single element ("+c+" function)");return e};a.fn.datepicker=n;var o=a.fn.datepicker.defaults={assumeNearbyYear:!1,autoclose:!1,beforeShowDay:a.noop,beforeShowMonth:a.noop,beforeShowYear:a.noop,beforeShowDecade:a.noop,beforeShowCentury:a.noop,calendarWeeks:!1,clearBtn:!1,toggleActive:!1,daysOfWeekDisabled:[],daysOfWeekHighlighted:[],datesDisabled:[],endDate:1/0,forceParse:!0,format:"mm/dd/yyyy",keepEmptyValues:!1,keyboardNavigation:!0,language:"en",minViewMode:0,maxViewMode:4,multidate:!1,multidateSeparator:",",orientation:"auto",rtl:!1,startDate:-(1/0),startView:0,todayBtn:!1,todayHighlight:!1,updateViewDate:!0,weekStart:0,disableTouchKeyboard:!1,enableOnReadonly:!0,showOnFocus:!0,zIndexOffset:10,container:"body",immediateUpdates:!1,title:"",templates:{leftArrow:"&#x00AB;",rightArrow:"&#x00BB;"},showWeekDays:!0},p=a.fn.datepicker.locale_opts=["format","rtl","weekStart"];a.fn.datepicker.Constructor=k;var q=a.fn.datepicker.dates={en:{days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],daysMin:["Su","Mo","Tu","We","Th","Fr","Sa"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],today:"Today",clear:"Clear",titleFormat:"MM yyyy"}},r={viewModes:[{names:["days","month"],clsName:"days",e:"changeMonth"},{names:["months","year"],clsName:"months",e:"changeYear",navStep:1},{names:["years","decade"],clsName:"years",e:"changeDecade",navStep:10},{names:["decades","century"],clsName:"decades",e:"changeCentury",navStep:100},{names:["centuries","millennium"],clsName:"centuries",e:"changeMillennium",navStep:1e3}],validParts:/dd?|DD?|mm?|MM?|yy(?:yy)?/g,nonpunctuation:/[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,parseFormat:function(a){if("function"==typeof a.toValue&&"function"==typeof a.toDisplay)return a;var b=a.replace(this.validParts,"\0").split("\0"),c=a.match(this.validParts);if(!b||!b.length||!c||0===c.length)throw new Error("Invalid date format.");return{separators:b,parts:c}},parseDate:function(c,e,f,g){function h(a,b){return b===!0&&(b=10),a<100&&(a+=2e3,a>(new Date).getFullYear()+b&&(a-=100)),a}function i(){var a=this.slice(0,j[n].length),b=j[n].slice(0,a.length);return a.toLowerCase()===b.toLowerCase()}if(!c)return b;if(c instanceof Date)return c;if("string"==typeof e&&(e=r.parseFormat(e)),e.toValue)return e.toValue(c,e,f);var j,l,m,n,o,p={d:"moveDay",m:"moveMonth",w:"moveWeek",y:"moveYear"},s={yesterday:"-1d",today:"+0d",tomorrow:"+1d"};if(c in s&&(c=s[c]),/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/i.test(c)){for(j=c.match(/([\-+]\d+)([dmwy])/gi),c=new Date,n=0;n<j.length;n++)l=j[n].match(/([\-+]\d+)([dmwy])/i),m=Number(l[1]),o=p[l[2].toLowerCase()],c=k.prototype[o](c,m);return k.prototype._zero_utc_time(c)}j=c&&c.match(this.nonpunctuation)||[];var t,u,v={},w=["yyyy","yy","M","MM","m","mm","d","dd"],x={yyyy:function(a,b){return a.setUTCFullYear(g?h(b,g):b)},m:function(a,b){if(isNaN(a))return a;for(b-=1;b<0;)b+=12;for(b%=12,a.setUTCMonth(b);a.getUTCMonth()!==b;)a.setUTCDate(a.getUTCDate()-1);return a},d:function(a,b){return a.setUTCDate(b)}};x.yy=x.yyyy,x.M=x.MM=x.mm=x.m,x.dd=x.d,c=d();var y=e.parts.slice();if(j.length!==y.length&&(y=a(y).filter(function(b,c){return a.inArray(c,w)!==-1}).toArray()),j.length===y.length){var z;for(n=0,z=y.length;n<z;n++){if(t=parseInt(j[n],10),l=y[n],isNaN(t))switch(l){case"MM":u=a(q[f].months).filter(i),t=a.inArray(u[0],q[f].months)+1;break;case"M":u=a(q[f].monthsShort).filter(i),t=a.inArray(u[0],q[f].monthsShort)+1}v[l]=t}var A,B;for(n=0;n<w.length;n++)B=w[n],B in v&&!isNaN(v[B])&&(A=new Date(c),x[B](A,v[B]),isNaN(A)||(c=A))}return c},formatDate:function(b,c,d){if(!b)return"";if("string"==typeof c&&(c=r.parseFormat(c)),c.toDisplay)return c.toDisplay(b,c,d);var e={d:b.getUTCDate(),D:q[d].daysShort[b.getUTCDay()],DD:q[d].days[b.getUTCDay()],m:b.getUTCMonth()+1,M:q[d].monthsShort[b.getUTCMonth()],MM:q[d].months[b.getUTCMonth()],yy:b.getUTCFullYear().toString().substring(2),yyyy:b.getUTCFullYear()};e.dd=(e.d<10?"0":"")+e.d,e.mm=(e.m<10?"0":"")+e.m,b=[];for(var f=a.extend([],c.separators),g=0,h=c.parts.length;g<=h;g++)f.length&&b.push(f.shift()),b.push(e[c.parts[g]]);return b.join("")},headTemplate:'<thead><tr><th colspan="7" class="datepicker-title"></th></tr><tr><th class="prev">'+o.templates.leftArrow+'</th><th colspan="5" class="datepicker-switch"></th><th class="next">'+o.templates.rightArrow+"</th></tr></thead>",
-contTemplate:'<tbody><tr><td colspan="7"></td></tr></tbody>',footTemplate:'<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'};r.template='<div class="datepicker"><div class="datepicker-days"><table class="table-condensed">'+r.headTemplate+"<tbody></tbody>"+r.footTemplate+'</table></div><div class="datepicker-months"><table class="table-condensed">'+r.headTemplate+r.contTemplate+r.footTemplate+'</table></div><div class="datepicker-years"><table class="table-condensed">'+r.headTemplate+r.contTemplate+r.footTemplate+'</table></div><div class="datepicker-decades"><table class="table-condensed">'+r.headTemplate+r.contTemplate+r.footTemplate+'</table></div><div class="datepicker-centuries"><table class="table-condensed">'+r.headTemplate+r.contTemplate+r.footTemplate+"</table></div></div>",a.fn.datepicker.DPGlobal=r,a.fn.datepicker.noConflict=function(){return a.fn.datepicker=m,this},a.fn.datepicker.version="1.7.1",a.fn.datepicker.deprecated=function(a){var b=window.console;b&&b.warn&&b.warn("DEPRECATED: "+a)},a(document).on("focus.datepicker.data-api click.datepicker.data-api",'[data-provide="datepicker"]',function(b){var c=a(this);c.data("datepicker")||(b.preventDefault(),n.call(c,"show"))}),a(function(){n.call(a('[data-provide="datepicker-inline"]'))})});
diff --git a/static/js/bootstrap.js b/static/js/bootstrap.js
deleted file mode 100644
--- a/static/js/bootstrap.js
+++ /dev/null
@@ -1,2114 +0,0 @@
-/*!
- * Bootstrap v3.2.0 (http://getbootstrap.com)
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- */
-
-if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') }
-
-/* ========================================================================
- * Bootstrap: transition.js v3.2.0
- * http://getbootstrap.com/javascript/#transitions
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
-  // ============================================================
-
-  function transitionEnd() {
-    var el = document.createElement('bootstrap')
-
-    var transEndEventNames = {
-      WebkitTransition : 'webkitTransitionEnd',
-      MozTransition    : 'transitionend',
-      OTransition      : 'oTransitionEnd otransitionend',
-      transition       : 'transitionend'
-    }
-
-    for (var name in transEndEventNames) {
-      if (el.style[name] !== undefined) {
-        return { end: transEndEventNames[name] }
-      }
-    }
-
-    return false // explicit for ie8 (  ._.)
-  }
-
-  // http://blog.alexmaccaw.com/css-transitions
-  $.fn.emulateTransitionEnd = function (duration) {
-    var called = false
-    var $el = this
-    $(this).one('bsTransitionEnd', function () { called = true })
-    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
-    setTimeout(callback, duration)
-    return this
-  }
-
-  $(function () {
-    $.support.transition = transitionEnd()
-
-    if (!$.support.transition) return
-
-    $.event.special.bsTransitionEnd = {
-      bindType: $.support.transition.end,
-      delegateType: $.support.transition.end,
-      handle: function (e) {
-        if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
-      }
-    }
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: alert.js v3.2.0
- * http://getbootstrap.com/javascript/#alerts
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // ALERT CLASS DEFINITION
-  // ======================
-
-  var dismiss = '[data-dismiss="alert"]'
-  var Alert   = function (el) {
-    $(el).on('click', dismiss, this.close)
-  }
-
-  Alert.VERSION = '3.2.0'
-
-  Alert.prototype.close = function (e) {
-    var $this    = $(this)
-    var selector = $this.attr('data-target')
-
-    if (!selector) {
-      selector = $this.attr('href')
-      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
-    }
-
-    var $parent = $(selector)
-
-    if (e) e.preventDefault()
-
-    if (!$parent.length) {
-      $parent = $this.hasClass('alert') ? $this : $this.parent()
-    }
-
-    $parent.trigger(e = $.Event('close.bs.alert'))
-
-    if (e.isDefaultPrevented()) return
-
-    $parent.removeClass('in')
-
-    function removeElement() {
-      // detach from parent, fire event then clean up data
-      $parent.detach().trigger('closed.bs.alert').remove()
-    }
-
-    $.support.transition && $parent.hasClass('fade') ?
-      $parent
-        .one('bsTransitionEnd', removeElement)
-        .emulateTransitionEnd(150) :
-      removeElement()
-  }
-
-
-  // ALERT PLUGIN DEFINITION
-  // =======================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this = $(this)
-      var data  = $this.data('bs.alert')
-
-      if (!data) $this.data('bs.alert', (data = new Alert(this)))
-      if (typeof option == 'string') data[option].call($this)
-    })
-  }
-
-  var old = $.fn.alert
-
-  $.fn.alert             = Plugin
-  $.fn.alert.Constructor = Alert
-
-
-  // ALERT NO CONFLICT
-  // =================
-
-  $.fn.alert.noConflict = function () {
-    $.fn.alert = old
-    return this
-  }
-
-
-  // ALERT DATA-API
-  // ==============
-
-  $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: button.js v3.2.0
- * http://getbootstrap.com/javascript/#buttons
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // BUTTON PUBLIC CLASS DEFINITION
-  // ==============================
-
-  var Button = function (element, options) {
-    this.$element  = $(element)
-    this.options   = $.extend({}, Button.DEFAULTS, options)
-    this.isLoading = false
-  }
-
-  Button.VERSION  = '3.2.0'
-
-  Button.DEFAULTS = {
-    loadingText: 'loading...'
-  }
-
-  Button.prototype.setState = function (state) {
-    var d    = 'disabled'
-    var $el  = this.$element
-    var val  = $el.is('input') ? 'val' : 'html'
-    var data = $el.data()
-
-    state = state + 'Text'
-
-    if (data.resetText == null) $el.data('resetText', $el[val]())
-
-    $el[val](data[state] == null ? this.options[state] : data[state])
-
-    // push to event loop to allow forms to submit
-    setTimeout($.proxy(function () {
-      if (state == 'loadingText') {
-        this.isLoading = true
-        $el.addClass(d).attr(d, d)
-      } else if (this.isLoading) {
-        this.isLoading = false
-        $el.removeClass(d).removeAttr(d)
-      }
-    }, this), 0)
-  }
-
-  Button.prototype.toggle = function () {
-    var changed = true
-    var $parent = this.$element.closest('[data-toggle="buttons"]')
-
-    if ($parent.length) {
-      var $input = this.$element.find('input')
-      if ($input.prop('type') == 'radio') {
-        if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
-        else $parent.find('.active').removeClass('active')
-      }
-      if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
-    }
-
-    if (changed) this.$element.toggleClass('active')
-  }
-
-
-  // BUTTON PLUGIN DEFINITION
-  // ========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.button')
-      var options = typeof option == 'object' && option
-
-      if (!data) $this.data('bs.button', (data = new Button(this, options)))
-
-      if (option == 'toggle') data.toggle()
-      else if (option) data.setState(option)
-    })
-  }
-
-  var old = $.fn.button
-
-  $.fn.button             = Plugin
-  $.fn.button.Constructor = Button
-
-
-  // BUTTON NO CONFLICT
-  // ==================
-
-  $.fn.button.noConflict = function () {
-    $.fn.button = old
-    return this
-  }
-
-
-  // BUTTON DATA-API
-  // ===============
-
-  $(document).on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
-    var $btn = $(e.target)
-    if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
-    Plugin.call($btn, 'toggle')
-    e.preventDefault()
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: carousel.js v3.2.0
- * http://getbootstrap.com/javascript/#carousel
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // CAROUSEL CLASS DEFINITION
-  // =========================
-
-  var Carousel = function (element, options) {
-    this.$element    = $(element).on('keydown.bs.carousel', $.proxy(this.keydown, this))
-    this.$indicators = this.$element.find('.carousel-indicators')
-    this.options     = options
-    this.paused      =
-    this.sliding     =
-    this.interval    =
-    this.$active     =
-    this.$items      = null
-
-    this.options.pause == 'hover' && this.$element
-      .on('mouseenter.bs.carousel', $.proxy(this.pause, this))
-      .on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
-  }
-
-  Carousel.VERSION  = '3.2.0'
-
-  Carousel.DEFAULTS = {
-    interval: 5000,
-    pause: 'hover',
-    wrap: true
-  }
-
-  Carousel.prototype.keydown = function (e) {
-    switch (e.which) {
-      case 37: this.prev(); break
-      case 39: this.next(); break
-      default: return
-    }
-
-    e.preventDefault()
-  }
-
-  Carousel.prototype.cycle = function (e) {
-    e || (this.paused = false)
-
-    this.interval && clearInterval(this.interval)
-
-    this.options.interval
-      && !this.paused
-      && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
-
-    return this
-  }
-
-  Carousel.prototype.getItemIndex = function (item) {
-    this.$items = item.parent().children('.item')
-    return this.$items.index(item || this.$active)
-  }
-
-  Carousel.prototype.to = function (pos) {
-    var that        = this
-    var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
-
-    if (pos > (this.$items.length - 1) || pos < 0) return
-
-    if (this.sliding)       return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
-    if (activeIndex == pos) return this.pause().cycle()
-
-    return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos]))
-  }
-
-  Carousel.prototype.pause = function (e) {
-    e || (this.paused = true)
-
-    if (this.$element.find('.next, .prev').length && $.support.transition) {
-      this.$element.trigger($.support.transition.end)
-      this.cycle(true)
-    }
-
-    this.interval = clearInterval(this.interval)
-
-    return this
-  }
-
-  Carousel.prototype.next = function () {
-    if (this.sliding) return
-    return this.slide('next')
-  }
-
-  Carousel.prototype.prev = function () {
-    if (this.sliding) return
-    return this.slide('prev')
-  }
-
-  Carousel.prototype.slide = function (type, next) {
-    var $active   = this.$element.find('.item.active')
-    var $next     = next || $active[type]()
-    var isCycling = this.interval
-    var direction = type == 'next' ? 'left' : 'right'
-    var fallback  = type == 'next' ? 'first' : 'last'
-    var that      = this
-
-    if (!$next.length) {
-      if (!this.options.wrap) return
-      $next = this.$element.find('.item')[fallback]()
-    }
-
-    if ($next.hasClass('active')) return (this.sliding = false)
-
-    var relatedTarget = $next[0]
-    var slideEvent = $.Event('slide.bs.carousel', {
-      relatedTarget: relatedTarget,
-      direction: direction
-    })
-    this.$element.trigger(slideEvent)
-    if (slideEvent.isDefaultPrevented()) return
-
-    this.sliding = true
-
-    isCycling && this.pause()
-
-    if (this.$indicators.length) {
-      this.$indicators.find('.active').removeClass('active')
-      var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
-      $nextIndicator && $nextIndicator.addClass('active')
-    }
-
-    var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
-    if ($.support.transition && this.$element.hasClass('slide')) {
-      $next.addClass(type)
-      $next[0].offsetWidth // force reflow
-      $active.addClass(direction)
-      $next.addClass(direction)
-      $active
-        .one('bsTransitionEnd', function () {
-          $next.removeClass([type, direction].join(' ')).addClass('active')
-          $active.removeClass(['active', direction].join(' '))
-          that.sliding = false
-          setTimeout(function () {
-            that.$element.trigger(slidEvent)
-          }, 0)
-        })
-        .emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000)
-    } else {
-      $active.removeClass('active')
-      $next.addClass('active')
-      this.sliding = false
-      this.$element.trigger(slidEvent)
-    }
-
-    isCycling && this.cycle()
-
-    return this
-  }
-
-
-  // CAROUSEL PLUGIN DEFINITION
-  // ==========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.carousel')
-      var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
-      var action  = typeof option == 'string' ? option : options.slide
-
-      if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
-      if (typeof option == 'number') data.to(option)
-      else if (action) data[action]()
-      else if (options.interval) data.pause().cycle()
-    })
-  }
-
-  var old = $.fn.carousel
-
-  $.fn.carousel             = Plugin
-  $.fn.carousel.Constructor = Carousel
-
-
-  // CAROUSEL NO CONFLICT
-  // ====================
-
-  $.fn.carousel.noConflict = function () {
-    $.fn.carousel = old
-    return this
-  }
-
-
-  // CAROUSEL DATA-API
-  // =================
-
-  $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) {
-    var href
-    var $this   = $(this)
-    var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
-    if (!$target.hasClass('carousel')) return
-    var options = $.extend({}, $target.data(), $this.data())
-    var slideIndex = $this.attr('data-slide-to')
-    if (slideIndex) options.interval = false
-
-    Plugin.call($target, options)
-
-    if (slideIndex) {
-      $target.data('bs.carousel').to(slideIndex)
-    }
-
-    e.preventDefault()
-  })
-
-  $(window).on('load', function () {
-    $('[data-ride="carousel"]').each(function () {
-      var $carousel = $(this)
-      Plugin.call($carousel, $carousel.data())
-    })
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: collapse.js v3.2.0
- * http://getbootstrap.com/javascript/#collapse
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // COLLAPSE PUBLIC CLASS DEFINITION
-  // ================================
-
-  var Collapse = function (element, options) {
-    this.$element      = $(element)
-    this.options       = $.extend({}, Collapse.DEFAULTS, options)
-    this.transitioning = null
-
-    if (this.options.parent) this.$parent = $(this.options.parent)
-    if (this.options.toggle) this.toggle()
-  }
-
-  Collapse.VERSION  = '3.2.0'
-
-  Collapse.DEFAULTS = {
-    toggle: true
-  }
-
-  Collapse.prototype.dimension = function () {
-    var hasWidth = this.$element.hasClass('width')
-    return hasWidth ? 'width' : 'height'
-  }
-
-  Collapse.prototype.show = function () {
-    if (this.transitioning || this.$element.hasClass('in')) return
-
-    var startEvent = $.Event('show.bs.collapse')
-    this.$element.trigger(startEvent)
-    if (startEvent.isDefaultPrevented()) return
-
-    var actives = this.$parent && this.$parent.find('> .panel > .in')
-
-    if (actives && actives.length) {
-      var hasData = actives.data('bs.collapse')
-      if (hasData && hasData.transitioning) return
-      Plugin.call(actives, 'hide')
-      hasData || actives.data('bs.collapse', null)
-    }
-
-    var dimension = this.dimension()
-
-    this.$element
-      .removeClass('collapse')
-      .addClass('collapsing')[dimension](0)
-
-    this.transitioning = 1
-
-    var complete = function () {
-      this.$element
-        .removeClass('collapsing')
-        .addClass('collapse in')[dimension]('')
-      this.transitioning = 0
-      this.$element
-        .trigger('shown.bs.collapse')
-    }
-
-    if (!$.support.transition) return complete.call(this)
-
-    var scrollSize = $.camelCase(['scroll', dimension].join('-'))
-
-    this.$element
-      .one('bsTransitionEnd', $.proxy(complete, this))
-      .emulateTransitionEnd(350)[dimension](this.$element[0][scrollSize])
-  }
-
-  Collapse.prototype.hide = function () {
-    if (this.transitioning || !this.$element.hasClass('in')) return
-
-    var startEvent = $.Event('hide.bs.collapse')
-    this.$element.trigger(startEvent)
-    if (startEvent.isDefaultPrevented()) return
-
-    var dimension = this.dimension()
-
-    this.$element[dimension](this.$element[dimension]())[0].offsetHeight
-
-    this.$element
-      .addClass('collapsing')
-      .removeClass('collapse')
-      .removeClass('in')
-
-    this.transitioning = 1
-
-    var complete = function () {
-      this.transitioning = 0
-      this.$element
-        .trigger('hidden.bs.collapse')
-        .removeClass('collapsing')
-        .addClass('collapse')
-    }
-
-    if (!$.support.transition) return complete.call(this)
-
-    this.$element
-      [dimension](0)
-      .one('bsTransitionEnd', $.proxy(complete, this))
-      .emulateTransitionEnd(350)
-  }
-
-  Collapse.prototype.toggle = function () {
-    this[this.$element.hasClass('in') ? 'hide' : 'show']()
-  }
-
-
-  // COLLAPSE PLUGIN DEFINITION
-  // ==========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.collapse')
-      var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
-
-      if (!data && options.toggle && option == 'show') option = !option
-      if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  var old = $.fn.collapse
-
-  $.fn.collapse             = Plugin
-  $.fn.collapse.Constructor = Collapse
-
-
-  // COLLAPSE NO CONFLICT
-  // ====================
-
-  $.fn.collapse.noConflict = function () {
-    $.fn.collapse = old
-    return this
-  }
-
-
-  // COLLAPSE DATA-API
-  // =================
-
-  $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
-    var href
-    var $this   = $(this)
-    var target  = $this.attr('data-target')
-        || e.preventDefault()
-        || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
-    var $target = $(target)
-    var data    = $target.data('bs.collapse')
-    var option  = data ? 'toggle' : $this.data()
-    var parent  = $this.attr('data-parent')
-    var $parent = parent && $(parent)
-
-    if (!data || !data.transitioning) {
-      if ($parent) $parent.find('[data-toggle="collapse"][data-parent="' + parent + '"]').not($this).addClass('collapsed')
-      $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
-    }
-
-    Plugin.call($target, option)
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: dropdown.js v3.2.0
- * http://getbootstrap.com/javascript/#dropdowns
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // DROPDOWN CLASS DEFINITION
-  // =========================
-
-  var backdrop = '.dropdown-backdrop'
-  var toggle   = '[data-toggle="dropdown"]'
-  var Dropdown = function (element) {
-    $(element).on('click.bs.dropdown', this.toggle)
-  }
-
-  Dropdown.VERSION = '3.2.0'
-
-  Dropdown.prototype.toggle = function (e) {
-    var $this = $(this)
-
-    if ($this.is('.disabled, :disabled')) return
-
-    var $parent  = getParent($this)
-    var isActive = $parent.hasClass('open')
-
-    clearMenus()
-
-    if (!isActive) {
-      if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
-        // if mobile we use a backdrop because click events don't delegate
-        $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus)
-      }
-
-      var relatedTarget = { relatedTarget: this }
-      $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
-
-      if (e.isDefaultPrevented()) return
-
-      $this.trigger('focus')
-
-      $parent
-        .toggleClass('open')
-        .trigger('shown.bs.dropdown', relatedTarget)
-    }
-
-    return false
-  }
-
-  Dropdown.prototype.keydown = function (e) {
-    if (!/(38|40|27)/.test(e.keyCode)) return
-
-    var $this = $(this)
-
-    e.preventDefault()
-    e.stopPropagation()
-
-    if ($this.is('.disabled, :disabled')) return
-
-    var $parent  = getParent($this)
-    var isActive = $parent.hasClass('open')
-
-    if (!isActive || (isActive && e.keyCode == 27)) {
-      if (e.which == 27) $parent.find(toggle).trigger('focus')
-      return $this.trigger('click')
-    }
-
-    var desc = ' li:not(.divider):visible a'
-    var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc)
-
-    if (!$items.length) return
-
-    var index = $items.index($items.filter(':focus'))
-
-    if (e.keyCode == 38 && index > 0)                 index--                        // up
-    if (e.keyCode == 40 && index < $items.length - 1) index++                        // down
-    if (!~index)                                      index = 0
-
-    $items.eq(index).trigger('focus')
-  }
-
-  function clearMenus(e) {
-    if (e && e.which === 3) return
-    $(backdrop).remove()
-    $(toggle).each(function () {
-      var $parent = getParent($(this))
-      var relatedTarget = { relatedTarget: this }
-      if (!$parent.hasClass('open')) return
-      $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
-      if (e.isDefaultPrevented()) return
-      $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget)
-    })
-  }
-
-  function getParent($this) {
-    var selector = $this.attr('data-target')
-
-    if (!selector) {
-      selector = $this.attr('href')
-      selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
-    }
-
-    var $parent = selector && $(selector)
-
-    return $parent && $parent.length ? $parent : $this.parent()
-  }
-
-
-  // DROPDOWN PLUGIN DEFINITION
-  // ==========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this = $(this)
-      var data  = $this.data('bs.dropdown')
-
-      if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
-      if (typeof option == 'string') data[option].call($this)
-    })
-  }
-
-  var old = $.fn.dropdown
-
-  $.fn.dropdown             = Plugin
-  $.fn.dropdown.Constructor = Dropdown
-
-
-  // DROPDOWN NO CONFLICT
-  // ====================
-
-  $.fn.dropdown.noConflict = function () {
-    $.fn.dropdown = old
-    return this
-  }
-
-
-  // APPLY TO STANDARD DROPDOWN ELEMENTS
-  // ===================================
-
-  $(document)
-    .on('click.bs.dropdown.data-api', clearMenus)
-    .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
-    .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
-    .on('keydown.bs.dropdown.data-api', toggle + ', [role="menu"], [role="listbox"]', Dropdown.prototype.keydown)
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: modal.js v3.2.0
- * http://getbootstrap.com/javascript/#modals
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // MODAL CLASS DEFINITION
-  // ======================
-
-  var Modal = function (element, options) {
-    this.options        = options
-    this.$body          = $(document.body)
-    this.$element       = $(element)
-    this.$backdrop      =
-    this.isShown        = null
-    this.scrollbarWidth = 0
-
-    if (this.options.remote) {
-      this.$element
-        .find('.modal-content')
-        .load(this.options.remote, $.proxy(function () {
-          this.$element.trigger('loaded.bs.modal')
-        }, this))
-    }
-  }
-
-  Modal.VERSION  = '3.2.0'
-
-  Modal.DEFAULTS = {
-    backdrop: true,
-    keyboard: true,
-    show: true
-  }
-
-  Modal.prototype.toggle = function (_relatedTarget) {
-    return this.isShown ? this.hide() : this.show(_relatedTarget)
-  }
-
-  Modal.prototype.show = function (_relatedTarget) {
-    var that = this
-    var e    = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
-
-    this.$element.trigger(e)
-
-    if (this.isShown || e.isDefaultPrevented()) return
-
-    this.isShown = true
-
-    this.checkScrollbar()
-    this.$body.addClass('modal-open')
-
-    this.setScrollbar()
-    this.escape()
-
-    this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
-
-    this.backdrop(function () {
-      var transition = $.support.transition && that.$element.hasClass('fade')
-
-      if (!that.$element.parent().length) {
-        that.$element.appendTo(that.$body) // don't move modals dom position
-      }
-
-      that.$element
-        .show()
-        .scrollTop(0)
-
-      if (transition) {
-        that.$element[0].offsetWidth // force reflow
-      }
-
-      that.$element
-        .addClass('in')
-        .attr('aria-hidden', false)
-
-      that.enforceFocus()
-
-      var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
-
-      transition ?
-        that.$element.find('.modal-dialog') // wait for modal to slide in
-          .one('bsTransitionEnd', function () {
-            that.$element.trigger('focus').trigger(e)
-          })
-          .emulateTransitionEnd(300) :
-        that.$element.trigger('focus').trigger(e)
-    })
-  }
-
-  Modal.prototype.hide = function (e) {
-    if (e) e.preventDefault()
-
-    e = $.Event('hide.bs.modal')
-
-    this.$element.trigger(e)
-
-    if (!this.isShown || e.isDefaultPrevented()) return
-
-    this.isShown = false
-
-    this.$body.removeClass('modal-open')
-
-    this.resetScrollbar()
-    this.escape()
-
-    $(document).off('focusin.bs.modal')
-
-    this.$element
-      .removeClass('in')
-      .attr('aria-hidden', true)
-      .off('click.dismiss.bs.modal')
-
-    $.support.transition && this.$element.hasClass('fade') ?
-      this.$element
-        .one('bsTransitionEnd', $.proxy(this.hideModal, this))
-        .emulateTransitionEnd(300) :
-      this.hideModal()
-  }
-
-  Modal.prototype.enforceFocus = function () {
-    $(document)
-      .off('focusin.bs.modal') // guard against infinite focus loop
-      .on('focusin.bs.modal', $.proxy(function (e) {
-        if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
-          this.$element.trigger('focus')
-        }
-      }, this))
-  }
-
-  Modal.prototype.escape = function () {
-    if (this.isShown && this.options.keyboard) {
-      this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
-        e.which == 27 && this.hide()
-      }, this))
-    } else if (!this.isShown) {
-      this.$element.off('keyup.dismiss.bs.modal')
-    }
-  }
-
-  Modal.prototype.hideModal = function () {
-    var that = this
-    this.$element.hide()
-    this.backdrop(function () {
-      that.$element.trigger('hidden.bs.modal')
-    })
-  }
-
-  Modal.prototype.removeBackdrop = function () {
-    this.$backdrop && this.$backdrop.remove()
-    this.$backdrop = null
-  }
-
-  Modal.prototype.backdrop = function (callback) {
-    var that = this
-    var animate = this.$element.hasClass('fade') ? 'fade' : ''
-
-    if (this.isShown && this.options.backdrop) {
-      var doAnimate = $.support.transition && animate
-
-      this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
-        .appendTo(this.$body)
-
-      this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
-        if (e.target !== e.currentTarget) return
-        this.options.backdrop == 'static'
-          ? this.$element[0].focus.call(this.$element[0])
-          : this.hide.call(this)
-      }, this))
-
-      if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
-
-      this.$backdrop.addClass('in')
-
-      if (!callback) return
-
-      doAnimate ?
-        this.$backdrop
-          .one('bsTransitionEnd', callback)
-          .emulateTransitionEnd(150) :
-        callback()
-
-    } else if (!this.isShown && this.$backdrop) {
-      this.$backdrop.removeClass('in')
-
-      var callbackRemove = function () {
-        that.removeBackdrop()
-        callback && callback()
-      }
-      $.support.transition && this.$element.hasClass('fade') ?
-        this.$backdrop
-          .one('bsTransitionEnd', callbackRemove)
-          .emulateTransitionEnd(150) :
-        callbackRemove()
-
-    } else if (callback) {
-      callback()
-    }
-  }
-
-  Modal.prototype.checkScrollbar = function () {
-    if (document.body.clientWidth >= window.innerWidth) return
-    this.scrollbarWidth = this.scrollbarWidth || this.measureScrollbar()
-  }
-
-  Modal.prototype.setScrollbar = function () {
-    var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
-    if (this.scrollbarWidth) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
-  }
-
-  Modal.prototype.resetScrollbar = function () {
-    this.$body.css('padding-right', '')
-  }
-
-  Modal.prototype.measureScrollbar = function () { // thx walsh
-    var scrollDiv = document.createElement('div')
-    scrollDiv.className = 'modal-scrollbar-measure'
-    this.$body.append(scrollDiv)
-    var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
-    this.$body[0].removeChild(scrollDiv)
-    return scrollbarWidth
-  }
-
-
-  // MODAL PLUGIN DEFINITION
-  // =======================
-
-  function Plugin(option, _relatedTarget) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.modal')
-      var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
-
-      if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
-      if (typeof option == 'string') data[option](_relatedTarget)
-      else if (options.show) data.show(_relatedTarget)
-    })
-  }
-
-  var old = $.fn.modal
-
-  $.fn.modal             = Plugin
-  $.fn.modal.Constructor = Modal
-
-
-  // MODAL NO CONFLICT
-  // =================
-
-  $.fn.modal.noConflict = function () {
-    $.fn.modal = old
-    return this
-  }
-
-
-  // MODAL DATA-API
-  // ==============
-
-  $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
-    var $this   = $(this)
-    var href    = $this.attr('href')
-    var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
-    var option  = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
-
-    if ($this.is('a')) e.preventDefault()
-
-    $target.one('show.bs.modal', function (showEvent) {
-      if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
-      $target.one('hidden.bs.modal', function () {
-        $this.is(':visible') && $this.trigger('focus')
-      })
-    })
-    Plugin.call($target, option, this)
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: tooltip.js v3.2.0
- * http://getbootstrap.com/javascript/#tooltip
- * Inspired by the original jQuery.tipsy by Jason Frame
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // TOOLTIP PUBLIC CLASS DEFINITION
-  // ===============================
-
-  var Tooltip = function (element, options) {
-    this.type       =
-    this.options    =
-    this.enabled    =
-    this.timeout    =
-    this.hoverState =
-    this.$element   = null
-
-    this.init('tooltip', element, options)
-  }
-
-  Tooltip.VERSION  = '3.2.0'
-
-  Tooltip.DEFAULTS = {
-    animation: true,
-    placement: 'top',
-    selector: false,
-    template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
-    trigger: 'hover focus',
-    title: '',
-    delay: 0,
-    html: false,
-    container: false,
-    viewport: {
-      selector: 'body',
-      padding: 0
-    }
-  }
-
-  Tooltip.prototype.init = function (type, element, options) {
-    this.enabled   = true
-    this.type      = type
-    this.$element  = $(element)
-    this.options   = this.getOptions(options)
-    this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)
-
-    var triggers = this.options.trigger.split(' ')
-
-    for (var i = triggers.length; i--;) {
-      var trigger = triggers[i]
-
-      if (trigger == 'click') {
-        this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
-      } else if (trigger != 'manual') {
-        var eventIn  = trigger == 'hover' ? 'mouseenter' : 'focusin'
-        var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
-
-        this.$element.on(eventIn  + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
-        this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
-      }
-    }
-
-    this.options.selector ?
-      (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :
-      this.fixTitle()
-  }
-
-  Tooltip.prototype.getDefaults = function () {
-    return Tooltip.DEFAULTS
-  }
-
-  Tooltip.prototype.getOptions = function (options) {
-    options = $.extend({}, this.getDefaults(), this.$element.data(), options)
-
-    if (options.delay && typeof options.delay == 'number') {
-      options.delay = {
-        show: options.delay,
-        hide: options.delay
-      }
-    }
-
-    return options
-  }
-
-  Tooltip.prototype.getDelegateOptions = function () {
-    var options  = {}
-    var defaults = this.getDefaults()
-
-    this._options && $.each(this._options, function (key, value) {
-      if (defaults[key] != value) options[key] = value
-    })
-
-    return options
-  }
-
-  Tooltip.prototype.enter = function (obj) {
-    var self = obj instanceof this.constructor ?
-      obj : $(obj.currentTarget).data('bs.' + this.type)
-
-    if (!self) {
-      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
-      $(obj.currentTarget).data('bs.' + this.type, self)
-    }
-
-    clearTimeout(self.timeout)
-
-    self.hoverState = 'in'
-
-    if (!self.options.delay || !self.options.delay.show) return self.show()
-
-    self.timeout = setTimeout(function () {
-      if (self.hoverState == 'in') self.show()
-    }, self.options.delay.show)
-  }
-
-  Tooltip.prototype.leave = function (obj) {
-    var self = obj instanceof this.constructor ?
-      obj : $(obj.currentTarget).data('bs.' + this.type)
-
-    if (!self) {
-      self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
-      $(obj.currentTarget).data('bs.' + this.type, self)
-    }
-
-    clearTimeout(self.timeout)
-
-    self.hoverState = 'out'
-
-    if (!self.options.delay || !self.options.delay.hide) return self.hide()
-
-    self.timeout = setTimeout(function () {
-      if (self.hoverState == 'out') self.hide()
-    }, self.options.delay.hide)
-  }
-
-  Tooltip.prototype.show = function () {
-    var e = $.Event('show.bs.' + this.type)
-
-    if (this.hasContent() && this.enabled) {
-      this.$element.trigger(e)
-
-      var inDom = $.contains(document.documentElement, this.$element[0])
-      if (e.isDefaultPrevented() || !inDom) return
-      var that = this
-
-      var $tip = this.tip()
-
-      var tipId = this.getUID(this.type)
-
-      this.setContent()
-      $tip.attr('id', tipId)
-      this.$element.attr('aria-describedby', tipId)
-
-      if (this.options.animation) $tip.addClass('fade')
-
-      var placement = typeof this.options.placement == 'function' ?
-        this.options.placement.call(this, $tip[0], this.$element[0]) :
-        this.options.placement
-
-      var autoToken = /\s?auto?\s?/i
-      var autoPlace = autoToken.test(placement)
-      if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
-
-      $tip
-        .detach()
-        .css({ top: 0, left: 0, display: 'block' })
-        .addClass(placement)
-        .data('bs.' + this.type, this)
-
-      this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
-
-      var pos          = this.getPosition()
-      var actualWidth  = $tip[0].offsetWidth
-      var actualHeight = $tip[0].offsetHeight
-
-      if (autoPlace) {
-        var orgPlacement = placement
-        var $parent      = this.$element.parent()
-        var parentDim    = this.getPosition($parent)
-
-        placement = placement == 'bottom' && pos.top   + pos.height       + actualHeight - parentDim.scroll > parentDim.height ? 'top'    :
-                    placement == 'top'    && pos.top   - parentDim.scroll - actualHeight < 0                                   ? 'bottom' :
-                    placement == 'right'  && pos.right + actualWidth      > parentDim.width                                    ? 'left'   :
-                    placement == 'left'   && pos.left  - actualWidth      < parentDim.left                                     ? 'right'  :
-                    placement
-
-        $tip
-          .removeClass(orgPlacement)
-          .addClass(placement)
-      }
-
-      var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
-
-      this.applyPlacement(calculatedOffset, placement)
-
-      var complete = function () {
-        that.$element.trigger('shown.bs.' + that.type)
-        that.hoverState = null
-      }
-
-      $.support.transition && this.$tip.hasClass('fade') ?
-        $tip
-          .one('bsTransitionEnd', complete)
-          .emulateTransitionEnd(150) :
-        complete()
-    }
-  }
-
-  Tooltip.prototype.applyPlacement = function (offset, placement) {
-    var $tip   = this.tip()
-    var width  = $tip[0].offsetWidth
-    var height = $tip[0].offsetHeight
-
-    // manually read margins because getBoundingClientRect includes difference
-    var marginTop = parseInt($tip.css('margin-top'), 10)
-    var marginLeft = parseInt($tip.css('margin-left'), 10)
-
-    // we must check for NaN for ie 8/9
-    if (isNaN(marginTop))  marginTop  = 0
-    if (isNaN(marginLeft)) marginLeft = 0
-
-    offset.top  = offset.top  + marginTop
-    offset.left = offset.left + marginLeft
-
-    // $.fn.offset doesn't round pixel values
-    // so we use setOffset directly with our own function B-0
-    $.offset.setOffset($tip[0], $.extend({
-      using: function (props) {
-        $tip.css({
-          top: Math.round(props.top),
-          left: Math.round(props.left)
-        })
-      }
-    }, offset), 0)
-
-    $tip.addClass('in')
-
-    // check to see if placing tip in new offset caused the tip to resize itself
-    var actualWidth  = $tip[0].offsetWidth
-    var actualHeight = $tip[0].offsetHeight
-
-    if (placement == 'top' && actualHeight != height) {
-      offset.top = offset.top + height - actualHeight
-    }
-
-    var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
-
-    if (delta.left) offset.left += delta.left
-    else offset.top += delta.top
-
-    var arrowDelta          = delta.left ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
-    var arrowPosition       = delta.left ? 'left'        : 'top'
-    var arrowOffsetPosition = delta.left ? 'offsetWidth' : 'offsetHeight'
-
-    $tip.offset(offset)
-    this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], arrowPosition)
-  }
-
-  Tooltip.prototype.replaceArrow = function (delta, dimension, position) {
-    this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '')
-  }
-
-  Tooltip.prototype.setContent = function () {
-    var $tip  = this.tip()
-    var title = this.getTitle()
-
-    $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
-    $tip.removeClass('fade in top bottom left right')
-  }
-
-  Tooltip.prototype.hide = function () {
-    var that = this
-    var $tip = this.tip()
-    var e    = $.Event('hide.bs.' + this.type)
-
-    this.$element.removeAttr('aria-describedby')
-
-    function complete() {
-      if (that.hoverState != 'in') $tip.detach()
-      that.$element.trigger('hidden.bs.' + that.type)
-    }
-
-    this.$element.trigger(e)
-
-    if (e.isDefaultPrevented()) return
-
-    $tip.removeClass('in')
-
-    $.support.transition && this.$tip.hasClass('fade') ?
-      $tip
-        .one('bsTransitionEnd', complete)
-        .emulateTransitionEnd(150) :
-      complete()
-
-    this.hoverState = null
-
-    return this
-  }
-
-  Tooltip.prototype.fixTitle = function () {
-    var $e = this.$element
-    if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {
-      $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
-    }
-  }
-
-  Tooltip.prototype.hasContent = function () {
-    return this.getTitle()
-  }
-
-  Tooltip.prototype.getPosition = function ($element) {
-    $element   = $element || this.$element
-    var el     = $element[0]
-    var isBody = el.tagName == 'BODY'
-    return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : null, {
-      scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop(),
-      width:  isBody ? $(window).width()  : $element.outerWidth(),
-      height: isBody ? $(window).height() : $element.outerHeight()
-    }, isBody ? { top: 0, left: 0 } : $element.offset())
-  }
-
-  Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
-    return placement == 'bottom' ? { top: pos.top + pos.height,   left: pos.left + pos.width / 2 - actualWidth / 2  } :
-           placement == 'top'    ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2  } :
-           placement == 'left'   ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
-        /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width   }
-
-  }
-
-  Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
-    var delta = { top: 0, left: 0 }
-    if (!this.$viewport) return delta
-
-    var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
-    var viewportDimensions = this.getPosition(this.$viewport)
-
-    if (/right|left/.test(placement)) {
-      var topEdgeOffset    = pos.top - viewportPadding - viewportDimensions.scroll
-      var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
-      if (topEdgeOffset < viewportDimensions.top) { // top overflow
-        delta.top = viewportDimensions.top - topEdgeOffset
-      } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
-        delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
-      }
-    } else {
-      var leftEdgeOffset  = pos.left - viewportPadding
-      var rightEdgeOffset = pos.left + viewportPadding + actualWidth
-      if (leftEdgeOffset < viewportDimensions.left) { // left overflow
-        delta.left = viewportDimensions.left - leftEdgeOffset
-      } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow
-        delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
-      }
-    }
-
-    return delta
-  }
-
-  Tooltip.prototype.getTitle = function () {
-    var title
-    var $e = this.$element
-    var o  = this.options
-
-    title = $e.attr('data-original-title')
-      || (typeof o.title == 'function' ? o.title.call($e[0]) :  o.title)
-
-    return title
-  }
-
-  Tooltip.prototype.getUID = function (prefix) {
-    do prefix += ~~(Math.random() * 1000000)
-    while (document.getElementById(prefix))
-    return prefix
-  }
-
-  Tooltip.prototype.tip = function () {
-    return (this.$tip = this.$tip || $(this.options.template))
-  }
-
-  Tooltip.prototype.arrow = function () {
-    return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
-  }
-
-  Tooltip.prototype.validate = function () {
-    if (!this.$element[0].parentNode) {
-      this.hide()
-      this.$element = null
-      this.options  = null
-    }
-  }
-
-  Tooltip.prototype.enable = function () {
-    this.enabled = true
-  }
-
-  Tooltip.prototype.disable = function () {
-    this.enabled = false
-  }
-
-  Tooltip.prototype.toggleEnabled = function () {
-    this.enabled = !this.enabled
-  }
-
-  Tooltip.prototype.toggle = function (e) {
-    var self = this
-    if (e) {
-      self = $(e.currentTarget).data('bs.' + this.type)
-      if (!self) {
-        self = new this.constructor(e.currentTarget, this.getDelegateOptions())
-        $(e.currentTarget).data('bs.' + this.type, self)
-      }
-    }
-
-    self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
-  }
-
-  Tooltip.prototype.destroy = function () {
-    clearTimeout(this.timeout)
-    this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
-  }
-
-
-  // TOOLTIP PLUGIN DEFINITION
-  // =========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.tooltip')
-      var options = typeof option == 'object' && option
-
-      if (!data && option == 'destroy') return
-      if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  var old = $.fn.tooltip
-
-  $.fn.tooltip             = Plugin
-  $.fn.tooltip.Constructor = Tooltip
-
-
-  // TOOLTIP NO CONFLICT
-  // ===================
-
-  $.fn.tooltip.noConflict = function () {
-    $.fn.tooltip = old
-    return this
-  }
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: popover.js v3.2.0
- * http://getbootstrap.com/javascript/#popovers
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // POPOVER PUBLIC CLASS DEFINITION
-  // ===============================
-
-  var Popover = function (element, options) {
-    this.init('popover', element, options)
-  }
-
-  if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
-
-  Popover.VERSION  = '3.2.0'
-
-  Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
-    placement: 'right',
-    trigger: 'click',
-    content: '',
-    template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
-  })
-
-
-  // NOTE: POPOVER EXTENDS tooltip.js
-  // ================================
-
-  Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
-
-  Popover.prototype.constructor = Popover
-
-  Popover.prototype.getDefaults = function () {
-    return Popover.DEFAULTS
-  }
-
-  Popover.prototype.setContent = function () {
-    var $tip    = this.tip()
-    var title   = this.getTitle()
-    var content = this.getContent()
-
-    $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
-    $tip.find('.popover-content').empty()[ // we use append for html objects to maintain js events
-      this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
-    ](content)
-
-    $tip.removeClass('fade top bottom left right in')
-
-    // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
-    // this manually by checking the contents.
-    if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
-  }
-
-  Popover.prototype.hasContent = function () {
-    return this.getTitle() || this.getContent()
-  }
-
-  Popover.prototype.getContent = function () {
-    var $e = this.$element
-    var o  = this.options
-
-    return $e.attr('data-content')
-      || (typeof o.content == 'function' ?
-            o.content.call($e[0]) :
-            o.content)
-  }
-
-  Popover.prototype.arrow = function () {
-    return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
-  }
-
-  Popover.prototype.tip = function () {
-    if (!this.$tip) this.$tip = $(this.options.template)
-    return this.$tip
-  }
-
-
-  // POPOVER PLUGIN DEFINITION
-  // =========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.popover')
-      var options = typeof option == 'object' && option
-
-      if (!data && option == 'destroy') return
-      if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  var old = $.fn.popover
-
-  $.fn.popover             = Plugin
-  $.fn.popover.Constructor = Popover
-
-
-  // POPOVER NO CONFLICT
-  // ===================
-
-  $.fn.popover.noConflict = function () {
-    $.fn.popover = old
-    return this
-  }
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: scrollspy.js v3.2.0
- * http://getbootstrap.com/javascript/#scrollspy
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // SCROLLSPY CLASS DEFINITION
-  // ==========================
-
-  function ScrollSpy(element, options) {
-    var process  = $.proxy(this.process, this)
-
-    this.$body          = $('body')
-    this.$scrollElement = $(element).is('body') ? $(window) : $(element)
-    this.options        = $.extend({}, ScrollSpy.DEFAULTS, options)
-    this.selector       = (this.options.target || '') + ' .nav li > a'
-    this.offsets        = []
-    this.targets        = []
-    this.activeTarget   = null
-    this.scrollHeight   = 0
-
-    this.$scrollElement.on('scroll.bs.scrollspy', process)
-    this.refresh()
-    this.process()
-  }
-
-  ScrollSpy.VERSION  = '3.2.0'
-
-  ScrollSpy.DEFAULTS = {
-    offset: 10
-  }
-
-  ScrollSpy.prototype.getScrollHeight = function () {
-    return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
-  }
-
-  ScrollSpy.prototype.refresh = function () {
-    var offsetMethod = 'offset'
-    var offsetBase   = 0
-
-    if (!$.isWindow(this.$scrollElement[0])) {
-      offsetMethod = 'position'
-      offsetBase   = this.$scrollElement.scrollTop()
-    }
-
-    this.offsets = []
-    this.targets = []
-    this.scrollHeight = this.getScrollHeight()
-
-    var self     = this
-
-    this.$body
-      .find(this.selector)
-      .map(function () {
-        var $el   = $(this)
-        var href  = $el.data('target') || $el.attr('href')
-        var $href = /^#./.test(href) && $(href)
-
-        return ($href
-          && $href.length
-          && $href.is(':visible')
-          && [[$href[offsetMethod]().top + offsetBase, href]]) || null
-      })
-      .sort(function (a, b) { return a[0] - b[0] })
-      .each(function () {
-        self.offsets.push(this[0])
-        self.targets.push(this[1])
-      })
-  }
-
-  ScrollSpy.prototype.process = function () {
-    var scrollTop    = this.$scrollElement.scrollTop() + this.options.offset
-    var scrollHeight = this.getScrollHeight()
-    var maxScroll    = this.options.offset + scrollHeight - this.$scrollElement.height()
-    var offsets      = this.offsets
-    var targets      = this.targets
-    var activeTarget = this.activeTarget
-    var i
-
-    if (this.scrollHeight != scrollHeight) {
-      this.refresh()
-    }
-
-    if (scrollTop >= maxScroll) {
-      return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
-    }
-
-    if (activeTarget && scrollTop <= offsets[0]) {
-      return activeTarget != (i = targets[0]) && this.activate(i)
-    }
-
-    for (i = offsets.length; i--;) {
-      activeTarget != targets[i]
-        && scrollTop >= offsets[i]
-        && (!offsets[i + 1] || scrollTop <= offsets[i + 1])
-        && this.activate(targets[i])
-    }
-  }
-
-  ScrollSpy.prototype.activate = function (target) {
-    this.activeTarget = target
-
-    $(this.selector)
-      .parentsUntil(this.options.target, '.active')
-      .removeClass('active')
-
-    var selector = this.selector +
-        '[data-target="' + target + '"],' +
-        this.selector + '[href="' + target + '"]'
-
-    var active = $(selector)
-      .parents('li')
-      .addClass('active')
-
-    if (active.parent('.dropdown-menu').length) {
-      active = active
-        .closest('li.dropdown')
-        .addClass('active')
-    }
-
-    active.trigger('activate.bs.scrollspy')
-  }
-
-
-  // SCROLLSPY PLUGIN DEFINITION
-  // ===========================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.scrollspy')
-      var options = typeof option == 'object' && option
-
-      if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  var old = $.fn.scrollspy
-
-  $.fn.scrollspy             = Plugin
-  $.fn.scrollspy.Constructor = ScrollSpy
-
-
-  // SCROLLSPY NO CONFLICT
-  // =====================
-
-  $.fn.scrollspy.noConflict = function () {
-    $.fn.scrollspy = old
-    return this
-  }
-
-
-  // SCROLLSPY DATA-API
-  // ==================
-
-  $(window).on('load.bs.scrollspy.data-api', function () {
-    $('[data-spy="scroll"]').each(function () {
-      var $spy = $(this)
-      Plugin.call($spy, $spy.data())
-    })
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: tab.js v3.2.0
- * http://getbootstrap.com/javascript/#tabs
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // TAB CLASS DEFINITION
-  // ====================
-
-  var Tab = function (element) {
-    this.element = $(element)
-  }
-
-  Tab.VERSION = '3.2.0'
-
-  Tab.prototype.show = function () {
-    var $this    = this.element
-    var $ul      = $this.closest('ul:not(.dropdown-menu)')
-    var selector = $this.data('target')
-
-    if (!selector) {
-      selector = $this.attr('href')
-      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
-    }
-
-    if ($this.parent('li').hasClass('active')) return
-
-    var previous = $ul.find('.active:last a')[0]
-    var e        = $.Event('show.bs.tab', {
-      relatedTarget: previous
-    })
-
-    $this.trigger(e)
-
-    if (e.isDefaultPrevented()) return
-
-    var $target = $(selector)
-
-    this.activate($this.closest('li'), $ul)
-    this.activate($target, $target.parent(), function () {
-      $this.trigger({
-        type: 'shown.bs.tab',
-        relatedTarget: previous
-      })
-    })
-  }
-
-  Tab.prototype.activate = function (element, container, callback) {
-    var $active    = container.find('> .active')
-    var transition = callback
-      && $.support.transition
-      && $active.hasClass('fade')
-
-    function next() {
-      $active
-        .removeClass('active')
-        .find('> .dropdown-menu > .active')
-        .removeClass('active')
-
-      element.addClass('active')
-
-      if (transition) {
-        element[0].offsetWidth // reflow for transition
-        element.addClass('in')
-      } else {
-        element.removeClass('fade')
-      }
-
-      if (element.parent('.dropdown-menu')) {
-        element.closest('li.dropdown').addClass('active')
-      }
-
-      callback && callback()
-    }
-
-    transition ?
-      $active
-        .one('bsTransitionEnd', next)
-        .emulateTransitionEnd(150) :
-      next()
-
-    $active.removeClass('in')
-  }
-
-
-  // TAB PLUGIN DEFINITION
-  // =====================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this = $(this)
-      var data  = $this.data('bs.tab')
-
-      if (!data) $this.data('bs.tab', (data = new Tab(this)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  var old = $.fn.tab
-
-  $.fn.tab             = Plugin
-  $.fn.tab.Constructor = Tab
-
-
-  // TAB NO CONFLICT
-  // ===============
-
-  $.fn.tab.noConflict = function () {
-    $.fn.tab = old
-    return this
-  }
-
-
-  // TAB DATA-API
-  // ============
-
-  $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
-    e.preventDefault()
-    Plugin.call($(this), 'show')
-  })
-
-}(jQuery);
-
-/* ========================================================================
- * Bootstrap: affix.js v3.2.0
- * http://getbootstrap.com/javascript/#affix
- * ========================================================================
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- * ======================================================================== */
-
-
-+function ($) {
-  'use strict';
-
-  // AFFIX CLASS DEFINITION
-  // ======================
-
-  var Affix = function (element, options) {
-    this.options = $.extend({}, Affix.DEFAULTS, options)
-
-    this.$target = $(this.options.target)
-      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
-      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))
-
-    this.$element     = $(element)
-    this.affixed      =
-    this.unpin        =
-    this.pinnedOffset = null
-
-    this.checkPosition()
-  }
-
-  Affix.VERSION  = '3.2.0'
-
-  Affix.RESET    = 'affix affix-top affix-bottom'
-
-  Affix.DEFAULTS = {
-    offset: 0,
-    target: window
-  }
-
-  Affix.prototype.getPinnedOffset = function () {
-    if (this.pinnedOffset) return this.pinnedOffset
-    this.$element.removeClass(Affix.RESET).addClass('affix')
-    var scrollTop = this.$target.scrollTop()
-    var position  = this.$element.offset()
-    return (this.pinnedOffset = position.top - scrollTop)
-  }
-
-  Affix.prototype.checkPositionWithEventLoop = function () {
-    setTimeout($.proxy(this.checkPosition, this), 1)
-  }
-
-  Affix.prototype.checkPosition = function () {
-    if (!this.$element.is(':visible')) return
-
-    var scrollHeight = $(document).height()
-    var scrollTop    = this.$target.scrollTop()
-    var position     = this.$element.offset()
-    var offset       = this.options.offset
-    var offsetTop    = offset.top
-    var offsetBottom = offset.bottom
-
-    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
-    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
-    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
-
-    var affix = this.unpin   != null && (scrollTop + this.unpin <= position.top) ? false :
-                offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
-                offsetTop    != null && (scrollTop <= offsetTop) ? 'top' : false
-
-    if (this.affixed === affix) return
-    if (this.unpin != null) this.$element.css('top', '')
-
-    var affixType = 'affix' + (affix ? '-' + affix : '')
-    var e         = $.Event(affixType + '.bs.affix')
-
-    this.$element.trigger(e)
-
-    if (e.isDefaultPrevented()) return
-
-    this.affixed = affix
-    this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
-
-    this.$element
-      .removeClass(Affix.RESET)
-      .addClass(affixType)
-      .trigger($.Event(affixType.replace('affix', 'affixed')))
-
-    if (affix == 'bottom') {
-      this.$element.offset({
-        top: scrollHeight - this.$element.height() - offsetBottom
-      })
-    }
-  }
-
-
-  // AFFIX PLUGIN DEFINITION
-  // =======================
-
-  function Plugin(option) {
-    return this.each(function () {
-      var $this   = $(this)
-      var data    = $this.data('bs.affix')
-      var options = typeof option == 'object' && option
-
-      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
-      if (typeof option == 'string') data[option]()
-    })
-  }
-
-  var old = $.fn.affix
-
-  $.fn.affix             = Plugin
-  $.fn.affix.Constructor = Affix
-
-
-  // AFFIX NO CONFLICT
-  // =================
-
-  $.fn.affix.noConflict = function () {
-    $.fn.affix = old
-    return this
-  }
-
-
-  // AFFIX DATA-API
-  // ==============
-
-  $(window).on('load', function () {
-    $('[data-spy="affix"]').each(function () {
-      var $spy = $(this)
-      var data = $spy.data()
-
-      data.offset = data.offset || {}
-
-      if (data.offsetBottom) data.offset.bottom = data.offsetBottom
-      if (data.offsetTop)    data.offset.top    = data.offsetTop
-
-      Plugin.call($spy, data)
-    })
-  })
-
-}(jQuery);
diff --git a/static/js/bootstrap.min.js b/static/js/bootstrap.min.js
deleted file mode 100644
--- a/static/js/bootstrap.min.js
+++ /dev/null
@@ -1,6 +0,0 @@
-/*!
- * Bootstrap v3.2.0 (http://getbootstrap.com)
- * Copyright 2011-2014 Twitter, Inc.
- * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
- */
-if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.2.0",d.prototype.close=function(b){function c(){f.detach().trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",c).emulateTransitionEnd(150):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.2.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),d[e](null==f[b]?this.options[b]:f[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b).on("keydown.bs.carousel",a.proxy(this.keydown,this)),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.2.0",c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.to=function(b){var c=this,d=this.getItemIndex(this.$active=this.$element.find(".item.active"));return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=e[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:g});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,f&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(e)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:g});return a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one("bsTransitionEnd",function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger(m)),f&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(b=!b),e||d.data("bs.collapse",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};c.VERSION="3.2.0",c.DEFAULTS={toggle:!0},c.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},c.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var c=a.Event("show.bs.collapse");if(this.$element.trigger(c),!c.isDefaultPrevented()){var d=this.$parent&&this.$parent.find("> .panel > .in");if(d&&d.length){var e=d.data("bs.collapse");if(e&&e.transitioning)return;b.call(d,"hide"),e||d.data("bs.collapse",null)}var f=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[f](0),this.transitioning=1;var g=function(){this.$element.removeClass("collapsing").addClass("collapse in")[f](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return g.call(this);var h=a.camelCase(["scroll",f].join("-"));this.$element.one("bsTransitionEnd",a.proxy(g,this)).emulateTransitionEnd(350)[f](this.$element[0][h])}}},c.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},c.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var d=a.fn.collapse;a.fn.collapse=b,a.fn.collapse.Constructor=c,a.fn.collapse.noConflict=function(){return a.fn.collapse=d,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(c){var d,e=a(this),f=e.attr("data-target")||c.preventDefault()||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),g=a(f),h=g.data("bs.collapse"),i=h?"toggle":e.data(),j=e.attr("data-parent"),k=j&&a(j);h&&h.transitioning||(k&&k.find('[data-toggle="collapse"][data-parent="'+j+'"]').not(e).addClass("collapsed"),e[g.hasClass("in")?"addClass":"removeClass"]("collapsed")),b.call(g,i)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.2.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(i.filter(":focus"));38==b.keyCode&&j>0&&j--,40==b.keyCode&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f+', [role="menu"], [role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.2.0",c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.$body.addClass("modal-open"),this.setScrollbar(),this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(c.$body),c.$element.show().scrollTop(0),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one("bsTransitionEnd",function(){c.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(300):c.$element.trigger("focus").trigger(e)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.$body.removeClass("modal-open"),this.resetScrollbar(),this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;if(this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;e?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(150):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var f=function(){c.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",f).emulateTransitionEnd(150):f()}else b&&b()},c.prototype.checkScrollbar=function(){document.body.clientWidth>=window.innerWidth||(this.scrollbarWidth=this.scrollbarWidth||this.measureScrollbar())},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.2.0",c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show()},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var c=a.contains(document.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!c)return;var d=this,e=this.tip(),f=this.getUID(this.type);this.setContent(),e.attr("id",f),this.$element.attr("aria-describedby",f),this.options.animation&&e.addClass("fade");var g="function"==typeof this.options.placement?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement,h=/\s?auto?\s?/i,i=h.test(g);i&&(g=g.replace(h,"")||"top"),e.detach().css({top:0,left:0,display:"block"}).addClass(g).data("bs."+this.type,this),this.options.container?e.appendTo(this.options.container):e.insertAfter(this.$element);var j=this.getPosition(),k=e[0].offsetWidth,l=e[0].offsetHeight;if(i){var m=g,n=this.$element.parent(),o=this.getPosition(n);g="bottom"==g&&j.top+j.height+l-o.scroll>o.height?"top":"top"==g&&j.top-o.scroll-l<0?"bottom":"right"==g&&j.right+k>o.width?"left":"left"==g&&j.left-k<o.left?"right":g,e.removeClass(m).addClass(g)}var p=this.getCalculatedOffset(g,j,k,l);this.applyPlacement(p,g);var q=function(){d.$element.trigger("shown.bs."+d.type),d.hoverState=null};a.support.transition&&this.$tip.hasClass("fade")?e.one("bsTransitionEnd",q).emulateTransitionEnd(150):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=k.left?2*k.left-e+i:2*k.top-f+j,m=k.left?"left":"top",n=k.left?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(l,d[0][n],m)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach(),c.$element.trigger("hidden.bs."+c.type)}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.removeAttr("aria-describedby"),this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one("bsTransitionEnd",b).emulateTransitionEnd(150):b(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName;return a.extend({},"function"==typeof c.getBoundingClientRect?c.getBoundingClientRect():null,{scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop(),width:d?a(window).width():b.outerWidth(),height:d?a(window).height():b.outerHeight()},d?{top:0,left:0}:b.offset())},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){clearTimeout(this.timeout),this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.2.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").empty()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.2.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.2.0",c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.closest("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},c.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one("bsTransitionEnd",e).emulateTransitionEnd(150):e(),f.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(c){c.preventDefault(),b.call(a(this),"show")})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.2.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=a(document).height(),d=this.$target.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=b-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){null!=this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:b-this.$element.height()-h}))}}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},d.offsetBottom&&(d.offset.bottom=d.offsetBottom),d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
diff --git a/static/js/excanvas.js b/static/js/excanvas.js
deleted file mode 100644
--- a/static/js/excanvas.js
+++ /dev/null
@@ -1,1427 +0,0 @@
-// Copyright 2006 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//   http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-
-// Known Issues:
-//
-// * Patterns only support repeat.
-// * Radial gradient are not implemented. The VML version of these look very
-//   different from the canvas one.
-// * Clipping paths are not implemented.
-// * Coordsize. The width and height attribute have higher priority than the
-//   width and height style values which isn't correct.
-// * Painting mode isn't implemented.
-// * Canvas width/height should is using content-box by default. IE in
-//   Quirks mode will draw the canvas using border-box. Either change your
-//   doctype to HTML5
-//   (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype)
-//   or use Box Sizing Behavior from WebFX
-//   (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html)
-// * Non uniform scaling does not correctly scale strokes.
-// * Filling very large shapes (above 5000 points) is buggy.
-// * Optimize. There is always room for speed improvements.
-
-// Only add this code if we do not already have a canvas implementation
-if (!document.createElement('canvas').getContext) {
-
-(function() {
-
-  // alias some functions to make (compiled) code shorter
-  var m = Math;
-  var mr = m.round;
-  var ms = m.sin;
-  var mc = m.cos;
-  var abs = m.abs;
-  var sqrt = m.sqrt;
-
-  // this is used for sub pixel precision
-  var Z = 10;
-  var Z2 = Z / 2;
-
-  /**
-   * This function is assigned to the <canvas> elements as element.getContext().
-   * @this {HTMLElement}
-   * @return {CanvasRenderingContext2D_}
-   */
-  function getContext() {
-    return this.context_ ||
-        (this.context_ = new CanvasRenderingContext2D_(this));
-  }
-
-  var slice = Array.prototype.slice;
-
-  /**
-   * Binds a function to an object. The returned function will always use the
-   * passed in {@code obj} as {@code this}.
-   *
-   * Example:
-   *
-   *   g = bind(f, obj, a, b)
-   *   g(c, d) // will do f.call(obj, a, b, c, d)
-   *
-   * @param {Function} f The function to bind the object to
-   * @param {Object} obj The object that should act as this when the function
-   *     is called
-   * @param {*} var_args Rest arguments that will be used as the initial
-   *     arguments when the function is called
-   * @return {Function} A new function that has bound this
-   */
-  function bind(f, obj, var_args) {
-    var a = slice.call(arguments, 2);
-    return function() {
-      return f.apply(obj, a.concat(slice.call(arguments)));
-    };
-  }
-
-  function encodeHtmlAttribute(s) {
-    return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
-  }
-
-  function addNamespacesAndStylesheet(doc) {
-    // create xmlns
-    if (!doc.namespaces['g_vml_']) {
-      doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml',
-                         '#default#VML');
-
-    }
-    if (!doc.namespaces['g_o_']) {
-      doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office',
-                         '#default#VML');
-    }
-
-    // Setup default CSS.  Only add one style sheet per document
-    if (!doc.styleSheets['ex_canvas_']) {
-      var ss = doc.createStyleSheet();
-      ss.owningElement.id = 'ex_canvas_';
-      ss.cssText = 'canvas{display:inline-block;overflow:hidden;' +
-          // default size is 300x150 in Gecko and Opera
-          'text-align:left;width:300px;height:150px}';
-    }
-  }
-
-  // Add namespaces and stylesheet at startup.
-  addNamespacesAndStylesheet(document);
-
-  var G_vmlCanvasManager_ = {
-    init: function(opt_doc) {
-      if (/MSIE/.test(navigator.userAgent) && !window.opera) {
-        var doc = opt_doc || document;
-        // Create a dummy element so that IE will allow canvas elements to be
-        // recognized.
-        doc.createElement('canvas');
-        doc.attachEvent('onreadystatechange', bind(this.init_, this, doc));
-      }
-    },
-
-    init_: function(doc) {
-      // find all canvas elements
-      var els = doc.getElementsByTagName('canvas');
-      for (var i = 0; i < els.length; i++) {
-        this.initElement(els[i]);
-      }
-    },
-
-    /**
-     * Public initializes a canvas element so that it can be used as canvas
-     * element from now on. This is called automatically before the page is
-     * loaded but if you are creating elements using createElement you need to
-     * make sure this is called on the element.
-     * @param {HTMLElement} el The canvas element to initialize.
-     * @return {HTMLElement} the element that was created.
-     */
-    initElement: function(el) {
-      if (!el.getContext) {
-        el.getContext = getContext;
-
-        // Add namespaces and stylesheet to document of the element.
-        addNamespacesAndStylesheet(el.ownerDocument);
-
-        // Remove fallback content. There is no way to hide text nodes so we
-        // just remove all childNodes. We could hide all elements and remove
-        // text nodes but who really cares about the fallback content.
-        el.innerHTML = '';
-
-        // do not use inline function because that will leak memory
-        el.attachEvent('onpropertychange', onPropertyChange);
-        el.attachEvent('onresize', onResize);
-
-        var attrs = el.attributes;
-        if (attrs.width && attrs.width.specified) {
-          // TODO: use runtimeStyle and coordsize
-          // el.getContext().setWidth_(attrs.width.nodeValue);
-          el.style.width = attrs.width.nodeValue + 'px';
-        } else {
-          el.width = el.clientWidth;
-        }
-        if (attrs.height && attrs.height.specified) {
-          // TODO: use runtimeStyle and coordsize
-          // el.getContext().setHeight_(attrs.height.nodeValue);
-          el.style.height = attrs.height.nodeValue + 'px';
-        } else {
-          el.height = el.clientHeight;
-        }
-        //el.getContext().setCoordsize_()
-      }
-      return el;
-    }
-  };
-
-  function onPropertyChange(e) {
-    var el = e.srcElement;
-
-    switch (e.propertyName) {
-      case 'width':
-        el.getContext().clearRect();
-        el.style.width = el.attributes.width.nodeValue + 'px';
-        // In IE8 this does not trigger onresize.
-        el.firstChild.style.width =  el.clientWidth + 'px';
-        break;
-      case 'height':
-        el.getContext().clearRect();
-        el.style.height = el.attributes.height.nodeValue + 'px';
-        el.firstChild.style.height = el.clientHeight + 'px';
-        break;
-    }
-  }
-
-  function onResize(e) {
-    var el = e.srcElement;
-    if (el.firstChild) {
-      el.firstChild.style.width =  el.clientWidth + 'px';
-      el.firstChild.style.height = el.clientHeight + 'px';
-    }
-  }
-
-  G_vmlCanvasManager_.init();
-
-  // precompute "00" to "FF"
-  var decToHex = [];
-  for (var i = 0; i < 16; i++) {
-    for (var j = 0; j < 16; j++) {
-      decToHex[i * 16 + j] = i.toString(16) + j.toString(16);
-    }
-  }
-
-  function createMatrixIdentity() {
-    return [
-      [1, 0, 0],
-      [0, 1, 0],
-      [0, 0, 1]
-    ];
-  }
-
-  function matrixMultiply(m1, m2) {
-    var result = createMatrixIdentity();
-
-    for (var x = 0; x < 3; x++) {
-      for (var y = 0; y < 3; y++) {
-        var sum = 0;
-
-        for (var z = 0; z < 3; z++) {
-          sum += m1[x][z] * m2[z][y];
-        }
-
-        result[x][y] = sum;
-      }
-    }
-    return result;
-  }
-
-  function copyState(o1, o2) {
-    o2.fillStyle     = o1.fillStyle;
-    o2.lineCap       = o1.lineCap;
-    o2.lineJoin      = o1.lineJoin;
-    o2.lineWidth     = o1.lineWidth;
-    o2.miterLimit    = o1.miterLimit;
-    o2.shadowBlur    = o1.shadowBlur;
-    o2.shadowColor   = o1.shadowColor;
-    o2.shadowOffsetX = o1.shadowOffsetX;
-    o2.shadowOffsetY = o1.shadowOffsetY;
-    o2.strokeStyle   = o1.strokeStyle;
-    o2.globalAlpha   = o1.globalAlpha;
-    o2.font          = o1.font;
-    o2.textAlign     = o1.textAlign;
-    o2.textBaseline  = o1.textBaseline;
-    o2.arcScaleX_    = o1.arcScaleX_;
-    o2.arcScaleY_    = o1.arcScaleY_;
-    o2.lineScale_    = o1.lineScale_;
-  }
-
-  var colorData = {
-    aliceblue: '#F0F8FF',
-    antiquewhite: '#FAEBD7',
-    aquamarine: '#7FFFD4',
-    azure: '#F0FFFF',
-    beige: '#F5F5DC',
-    bisque: '#FFE4C4',
-    black: '#000000',
-    blanchedalmond: '#FFEBCD',
-    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',
-    gainsboro: '#DCDCDC',
-    ghostwhite: '#F8F8FF',
-    gold: '#FFD700',
-    goldenrod: '#DAA520',
-    grey: '#808080',
-    greenyellow: '#ADFF2F',
-    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',
-    lightgreen: '#90EE90',
-    lightgrey: '#D3D3D3',
-    lightpink: '#FFB6C1',
-    lightsalmon: '#FFA07A',
-    lightseagreen: '#20B2AA',
-    lightskyblue: '#87CEFA',
-    lightslategray: '#778899',
-    lightslategrey: '#778899',
-    lightsteelblue: '#B0C4DE',
-    lightyellow: '#FFFFE0',
-    limegreen: '#32CD32',
-    linen: '#FAF0E6',
-    magenta: '#FF00FF',
-    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',
-    oldlace: '#FDF5E6',
-    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',
-    rosybrown: '#BC8F8F',
-    royalblue: '#4169E1',
-    saddlebrown: '#8B4513',
-    salmon: '#FA8072',
-    sandybrown: '#F4A460',
-    seagreen: '#2E8B57',
-    seashell: '#FFF5EE',
-    sienna: '#A0522D',
-    skyblue: '#87CEEB',
-    slateblue: '#6A5ACD',
-    slategray: '#708090',
-    slategrey: '#708090',
-    snow: '#FFFAFA',
-    springgreen: '#00FF7F',
-    steelblue: '#4682B4',
-    tan: '#D2B48C',
-    thistle: '#D8BFD8',
-    tomato: '#FF6347',
-    turquoise: '#40E0D0',
-    violet: '#EE82EE',
-    wheat: '#F5DEB3',
-    whitesmoke: '#F5F5F5',
-    yellowgreen: '#9ACD32'
-  };
-
-
-  function getRgbHslContent(styleString) {
-    var start = styleString.indexOf('(', 3);
-    var end = styleString.indexOf(')', start + 1);
-    var parts = styleString.substring(start + 1, end).split(',');
-    // add alpha if needed
-    if (parts.length == 4 && styleString.substr(3, 1) == 'a') {
-      alpha = Number(parts[3]);
-    } else {
-      parts[3] = 1;
-    }
-    return parts;
-  }
-
-  function percent(s) {
-    return parseFloat(s) / 100;
-  }
-
-  function clamp(v, min, max) {
-    return Math.min(max, Math.max(min, v));
-  }
-
-  function hslToRgb(parts){
-    var r, g, b;
-    h = parseFloat(parts[0]) / 360 % 360;
-    if (h < 0)
-      h++;
-    s = clamp(percent(parts[1]), 0, 1);
-    l = clamp(percent(parts[2]), 0, 1);
-    if (s == 0) {
-      r = g = b = l; // achromatic
-    } else {
-      var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
-      var p = 2 * l - q;
-      r = hueToRgb(p, q, h + 1 / 3);
-      g = hueToRgb(p, q, h);
-      b = hueToRgb(p, q, h - 1 / 3);
-    }
-
-    return '#' + decToHex[Math.floor(r * 255)] +
-        decToHex[Math.floor(g * 255)] +
-        decToHex[Math.floor(b * 255)];
-  }
-
-  function hueToRgb(m1, m2, h) {
-    if (h < 0)
-      h++;
-    if (h > 1)
-      h--;
-
-    if (6 * h < 1)
-      return m1 + (m2 - m1) * 6 * h;
-    else if (2 * h < 1)
-      return m2;
-    else if (3 * h < 2)
-      return m1 + (m2 - m1) * (2 / 3 - h) * 6;
-    else
-      return m1;
-  }
-
-  function processStyle(styleString) {
-    var str, alpha = 1;
-
-    styleString = String(styleString);
-    if (styleString.charAt(0) == '#') {
-      str = styleString;
-    } else if (/^rgb/.test(styleString)) {
-      var parts = getRgbHslContent(styleString);
-      var str = '#', n;
-      for (var i = 0; i < 3; i++) {
-        if (parts[i].indexOf('%') != -1) {
-          n = Math.floor(percent(parts[i]) * 255);
-        } else {
-          n = Number(parts[i]);
-        }
-        str += decToHex[clamp(n, 0, 255)];
-      }
-      alpha = parts[3];
-    } else if (/^hsl/.test(styleString)) {
-      var parts = getRgbHslContent(styleString);
-      str = hslToRgb(parts);
-      alpha = parts[3];
-    } else {
-      str = colorData[styleString] || styleString;
-    }
-    return {color: str, alpha: alpha};
-  }
-
-  var DEFAULT_STYLE = {
-    style: 'normal',
-    variant: 'normal',
-    weight: 'normal',
-    size: 10,
-    family: 'sans-serif'
-  };
-
-  // Internal text style cache
-  var fontStyleCache = {};
-
-  function processFontStyle(styleString) {
-    if (fontStyleCache[styleString]) {
-      return fontStyleCache[styleString];
-    }
-
-    var el = document.createElement('div');
-    var style = el.style;
-    try {
-      style.font = styleString;
-    } catch (ex) {
-      // Ignore failures to set to invalid font.
-    }
-
-    return fontStyleCache[styleString] = {
-      style: style.fontStyle || DEFAULT_STYLE.style,
-      variant: style.fontVariant || DEFAULT_STYLE.variant,
-      weight: style.fontWeight || DEFAULT_STYLE.weight,
-      size: style.fontSize || DEFAULT_STYLE.size,
-      family: style.fontFamily || DEFAULT_STYLE.family
-    };
-  }
-
-  function getComputedStyle(style, element) {
-    var computedStyle = {};
-
-    for (var p in style) {
-      computedStyle[p] = style[p];
-    }
-
-    // Compute the size
-    var canvasFontSize = parseFloat(element.currentStyle.fontSize),
-        fontSize = parseFloat(style.size);
-
-    if (typeof style.size == 'number') {
-      computedStyle.size = style.size;
-    } else if (style.size.indexOf('px') != -1) {
-      computedStyle.size = fontSize;
-    } else if (style.size.indexOf('em') != -1) {
-      computedStyle.size = canvasFontSize * fontSize;
-    } else if(style.size.indexOf('%') != -1) {
-      computedStyle.size = (canvasFontSize / 100) * fontSize;
-    } else if (style.size.indexOf('pt') != -1) {
-      computedStyle.size = fontSize / .75;
-    } else {
-      computedStyle.size = canvasFontSize;
-    }
-
-    // Different scaling between normal text and VML text. This was found using
-    // trial and error to get the same size as non VML text.
-    computedStyle.size *= 0.981;
-
-    return computedStyle;
-  }
-
-  function buildStyle(style) {
-    return style.style + ' ' + style.variant + ' ' + style.weight + ' ' +
-        style.size + 'px ' + style.family;
-  }
-
-  function processLineCap(lineCap) {
-    switch (lineCap) {
-      case 'butt':
-        return 'flat';
-      case 'round':
-        return 'round';
-      case 'square':
-      default:
-        return 'square';
-    }
-  }
-
-  /**
-   * This class implements CanvasRenderingContext2D interface as described by
-   * the WHATWG.
-   * @param {HTMLElement} surfaceElement The element that the 2D context should
-   * be associated with
-   */
-  function CanvasRenderingContext2D_(surfaceElement) {
-    this.m_ = createMatrixIdentity();
-
-    this.mStack_ = [];
-    this.aStack_ = [];
-    this.currentPath_ = [];
-
-    // Canvas context properties
-    this.strokeStyle = '#000';
-    this.fillStyle = '#000';
-
-    this.lineWidth = 1;
-    this.lineJoin = 'miter';
-    this.lineCap = 'butt';
-    this.miterLimit = Z * 1;
-    this.globalAlpha = 1;
-    this.font = '10px sans-serif';
-    this.textAlign = 'left';
-    this.textBaseline = 'alphabetic';
-    this.canvas = surfaceElement;
-
-    var el = surfaceElement.ownerDocument.createElement('div');
-    el.style.width =  surfaceElement.clientWidth + 'px';
-    el.style.height = surfaceElement.clientHeight + 'px';
-    el.style.overflow = 'hidden';
-    el.style.position = 'absolute';
-    surfaceElement.appendChild(el);
-
-    this.element_ = el;
-    this.arcScaleX_ = 1;
-    this.arcScaleY_ = 1;
-    this.lineScale_ = 1;
-  }
-
-  var contextPrototype = CanvasRenderingContext2D_.prototype;
-  contextPrototype.clearRect = function() {
-    if (this.textMeasureEl_) {
-      this.textMeasureEl_.removeNode(true);
-      this.textMeasureEl_ = null;
-    }
-    this.element_.innerHTML = '';
-  };
-
-  contextPrototype.beginPath = function() {
-    // TODO: Branch current matrix so that save/restore has no effect
-    //       as per safari docs.
-    this.currentPath_ = [];
-  };
-
-  contextPrototype.moveTo = function(aX, aY) {
-    var p = this.getCoords_(aX, aY);
-    this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y});
-    this.currentX_ = p.x;
-    this.currentY_ = p.y;
-  };
-
-  contextPrototype.lineTo = function(aX, aY) {
-    var p = this.getCoords_(aX, aY);
-    this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y});
-
-    this.currentX_ = p.x;
-    this.currentY_ = p.y;
-  };
-
-  contextPrototype.bezierCurveTo = function(aCP1x, aCP1y,
-                                            aCP2x, aCP2y,
-                                            aX, aY) {
-    var p = this.getCoords_(aX, aY);
-    var cp1 = this.getCoords_(aCP1x, aCP1y);
-    var cp2 = this.getCoords_(aCP2x, aCP2y);
-    bezierCurveTo(this, cp1, cp2, p);
-  };
-
-  // Helper function that takes the already fixed cordinates.
-  function bezierCurveTo(self, cp1, cp2, p) {
-    self.currentPath_.push({
-      type: 'bezierCurveTo',
-      cp1x: cp1.x,
-      cp1y: cp1.y,
-      cp2x: cp2.x,
-      cp2y: cp2.y,
-      x: p.x,
-      y: p.y
-    });
-    self.currentX_ = p.x;
-    self.currentY_ = p.y;
-  }
-
-  contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) {
-    // the following is lifted almost directly from
-    // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes
-
-    var cp = this.getCoords_(aCPx, aCPy);
-    var p = this.getCoords_(aX, aY);
-
-    var cp1 = {
-      x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_),
-      y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_)
-    };
-    var cp2 = {
-      x: cp1.x + (p.x - this.currentX_) / 3.0,
-      y: cp1.y + (p.y - this.currentY_) / 3.0
-    };
-
-    bezierCurveTo(this, cp1, cp2, p);
-  };
-
-  contextPrototype.arc = function(aX, aY, aRadius,
-                                  aStartAngle, aEndAngle, aClockwise) {
-    aRadius *= Z;
-    var arcType = aClockwise ? 'at' : 'wa';
-
-    var xStart = aX + mc(aStartAngle) * aRadius - Z2;
-    var yStart = aY + ms(aStartAngle) * aRadius - Z2;
-
-    var xEnd = aX + mc(aEndAngle) * aRadius - Z2;
-    var yEnd = aY + ms(aEndAngle) * aRadius - Z2;
-
-    // IE won't render arches drawn counter clockwise if xStart == xEnd.
-    if (xStart == xEnd && !aClockwise) {
-      xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something
-                       // that can be represented in binary
-    }
-
-    var p = this.getCoords_(aX, aY);
-    var pStart = this.getCoords_(xStart, yStart);
-    var pEnd = this.getCoords_(xEnd, yEnd);
-
-    this.currentPath_.push({type: arcType,
-                           x: p.x,
-                           y: p.y,
-                           radius: aRadius,
-                           xStart: pStart.x,
-                           yStart: pStart.y,
-                           xEnd: pEnd.x,
-                           yEnd: pEnd.y});
-
-  };
-
-  contextPrototype.rect = function(aX, aY, aWidth, aHeight) {
-    this.moveTo(aX, aY);
-    this.lineTo(aX + aWidth, aY);
-    this.lineTo(aX + aWidth, aY + aHeight);
-    this.lineTo(aX, aY + aHeight);
-    this.closePath();
-  };
-
-  contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) {
-    var oldPath = this.currentPath_;
-    this.beginPath();
-
-    this.moveTo(aX, aY);
-    this.lineTo(aX + aWidth, aY);
-    this.lineTo(aX + aWidth, aY + aHeight);
-    this.lineTo(aX, aY + aHeight);
-    this.closePath();
-    this.stroke();
-
-    this.currentPath_ = oldPath;
-  };
-
-  contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) {
-    var oldPath = this.currentPath_;
-    this.beginPath();
-
-    this.moveTo(aX, aY);
-    this.lineTo(aX + aWidth, aY);
-    this.lineTo(aX + aWidth, aY + aHeight);
-    this.lineTo(aX, aY + aHeight);
-    this.closePath();
-    this.fill();
-
-    this.currentPath_ = oldPath;
-  };
-
-  contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) {
-    var gradient = new CanvasGradient_('gradient');
-    gradient.x0_ = aX0;
-    gradient.y0_ = aY0;
-    gradient.x1_ = aX1;
-    gradient.y1_ = aY1;
-    return gradient;
-  };
-
-  contextPrototype.createRadialGradient = function(aX0, aY0, aR0,
-                                                   aX1, aY1, aR1) {
-    var gradient = new CanvasGradient_('gradientradial');
-    gradient.x0_ = aX0;
-    gradient.y0_ = aY0;
-    gradient.r0_ = aR0;
-    gradient.x1_ = aX1;
-    gradient.y1_ = aY1;
-    gradient.r1_ = aR1;
-    return gradient;
-  };
-
-  contextPrototype.drawImage = function(image, var_args) {
-    var dx, dy, dw, dh, sx, sy, sw, sh;
-
-    // to find the original width we overide the width and height
-    var oldRuntimeWidth = image.runtimeStyle.width;
-    var oldRuntimeHeight = image.runtimeStyle.height;
-    image.runtimeStyle.width = 'auto';
-    image.runtimeStyle.height = 'auto';
-
-    // get the original size
-    var w = image.width;
-    var h = image.height;
-
-    // and remove overides
-    image.runtimeStyle.width = oldRuntimeWidth;
-    image.runtimeStyle.height = oldRuntimeHeight;
-
-    if (arguments.length == 3) {
-      dx = arguments[1];
-      dy = arguments[2];
-      sx = sy = 0;
-      sw = dw = w;
-      sh = dh = h;
-    } else if (arguments.length == 5) {
-      dx = arguments[1];
-      dy = arguments[2];
-      dw = arguments[3];
-      dh = arguments[4];
-      sx = sy = 0;
-      sw = w;
-      sh = h;
-    } else if (arguments.length == 9) {
-      sx = arguments[1];
-      sy = arguments[2];
-      sw = arguments[3];
-      sh = arguments[4];
-      dx = arguments[5];
-      dy = arguments[6];
-      dw = arguments[7];
-      dh = arguments[8];
-    } else {
-      throw Error('Invalid number of arguments');
-    }
-
-    var d = this.getCoords_(dx, dy);
-
-    var w2 = sw / 2;
-    var h2 = sh / 2;
-
-    var vmlStr = [];
-
-    var W = 10;
-    var H = 10;
-
-    // For some reason that I've now forgotten, using divs didn't work
-    vmlStr.push(' <g_vml_:group',
-                ' coordsize="', Z * W, ',', Z * H, '"',
-                ' coordorigin="0,0"' ,
-                ' style="width:', W, 'px;height:', H, 'px;position:absolute;');
-
-    // If filters are necessary (rotation exists), create them
-    // filters are bog-slow, so only create them if abbsolutely necessary
-    // The following check doesn't account for skews (which don't exist
-    // in the canvas spec (yet) anyway.
-
-    if (this.m_[0][0] != 1 || this.m_[0][1] ||
-        this.m_[1][1] != 1 || this.m_[1][0]) {
-      var filter = [];
-
-      // Note the 12/21 reversal
-      filter.push('M11=', this.m_[0][0], ',',
-                  'M12=', this.m_[1][0], ',',
-                  'M21=', this.m_[0][1], ',',
-                  'M22=', this.m_[1][1], ',',
-                  'Dx=', mr(d.x / Z), ',',
-                  'Dy=', mr(d.y / Z), '');
-
-      // Bounding box calculation (need to minimize displayed area so that
-      // filters don't waste time on unused pixels.
-      var max = d;
-      var c2 = this.getCoords_(dx + dw, dy);
-      var c3 = this.getCoords_(dx, dy + dh);
-      var c4 = this.getCoords_(dx + dw, dy + dh);
-
-      max.x = m.max(max.x, c2.x, c3.x, c4.x);
-      max.y = m.max(max.y, c2.y, c3.y, c4.y);
-
-      vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z),
-                  'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(',
-                  filter.join(''), ", sizingmethod='clip');");
-
-    } else {
-      vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;');
-    }
-
-    vmlStr.push(' ">' ,
-                '<g_vml_:image src="', image.src, '"',
-                ' style="width:', Z * dw, 'px;',
-                ' height:', Z * dh, 'px"',
-                ' cropleft="', sx / w, '"',
-                ' croptop="', sy / h, '"',
-                ' cropright="', (w - sx - sw) / w, '"',
-                ' cropbottom="', (h - sy - sh) / h, '"',
-                ' />',
-                '</g_vml_:group>');
-
-    this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join(''));
-  };
-
-  contextPrototype.stroke = function(aFill) {
-    var W = 10;
-    var H = 10;
-    // Divide the shape into chunks if it's too long because IE has a limit
-    // somewhere for how long a VML shape can be. This simple division does
-    // not work with fills, only strokes, unfortunately.
-    var chunkSize = 5000;
-
-    var min = {x: null, y: null};
-    var max = {x: null, y: null};
-
-    for (var j = 0; j < this.currentPath_.length; j += chunkSize) {
-      var lineStr = [];
-      var lineOpen = false;
-
-      lineStr.push('<g_vml_:shape',
-                   ' filled="', !!aFill, '"',
-                   ' style="position:absolute;width:', W, 'px;height:', H, 'px;"',
-                   ' coordorigin="0,0"',
-                   ' coordsize="', Z * W, ',', Z * H, '"',
-                   ' stroked="', !aFill, '"',
-                   ' path="');
-
-      var newSeq = false;
-
-      for (var i = j; i < Math.min(j + chunkSize, this.currentPath_.length); i++) {
-        if (i % chunkSize == 0 && i > 0) { // move into position for next chunk
-          lineStr.push(' m ', mr(this.currentPath_[i-1].x), ',', mr(this.currentPath_[i-1].y));
-        }
-
-        var p = this.currentPath_[i];
-        var c;
-
-        switch (p.type) {
-          case 'moveTo':
-            c = p;
-            lineStr.push(' m ', mr(p.x), ',', mr(p.y));
-            break;
-          case 'lineTo':
-            lineStr.push(' l ', mr(p.x), ',', mr(p.y));
-            break;
-          case 'close':
-            lineStr.push(' x ');
-            p = null;
-            break;
-          case 'bezierCurveTo':
-            lineStr.push(' c ',
-                         mr(p.cp1x), ',', mr(p.cp1y), ',',
-                         mr(p.cp2x), ',', mr(p.cp2y), ',',
-                         mr(p.x), ',', mr(p.y));
-            break;
-          case 'at':
-          case 'wa':
-            lineStr.push(' ', p.type, ' ',
-                         mr(p.x - this.arcScaleX_ * p.radius), ',',
-                         mr(p.y - this.arcScaleY_ * p.radius), ' ',
-                         mr(p.x + this.arcScaleX_ * p.radius), ',',
-                         mr(p.y + this.arcScaleY_ * p.radius), ' ',
-                         mr(p.xStart), ',', mr(p.yStart), ' ',
-                         mr(p.xEnd), ',', mr(p.yEnd));
-            break;
-        }
-  
-  
-        // TODO: Following is broken for curves due to
-        //       move to proper paths.
-  
-        // Figure out dimensions so we can do gradient fills
-        // properly
-        if (p) {
-          if (min.x == null || p.x < min.x) {
-            min.x = p.x;
-          }
-          if (max.x == null || p.x > max.x) {
-            max.x = p.x;
-          }
-          if (min.y == null || p.y < min.y) {
-            min.y = p.y;
-          }
-          if (max.y == null || p.y > max.y) {
-            max.y = p.y;
-          }
-        }
-      }
-      lineStr.push(' ">');
-  
-      if (!aFill) {
-        appendStroke(this, lineStr);
-      } else {
-        appendFill(this, lineStr, min, max);
-      }
-  
-      lineStr.push('</g_vml_:shape>');
-  
-      this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
-    }
-  };
-
-  function appendStroke(ctx, lineStr) {
-    var a = processStyle(ctx.strokeStyle);
-    var color = a.color;
-    var opacity = a.alpha * ctx.globalAlpha;
-    var lineWidth = ctx.lineScale_ * ctx.lineWidth;
-
-    // VML cannot correctly render a line if the width is less than 1px.
-    // In that case, we dilute the color to make the line look thinner.
-    if (lineWidth < 1) {
-      opacity *= lineWidth;
-    }
-
-    lineStr.push(
-      '<g_vml_:stroke',
-      ' opacity="', opacity, '"',
-      ' joinstyle="', ctx.lineJoin, '"',
-      ' miterlimit="', ctx.miterLimit, '"',
-      ' endcap="', processLineCap(ctx.lineCap), '"',
-      ' weight="', lineWidth, 'px"',
-      ' color="', color, '" />'
-    );
-  }
-
-  function appendFill(ctx, lineStr, min, max) {
-    var fillStyle = ctx.fillStyle;
-    var arcScaleX = ctx.arcScaleX_;
-    var arcScaleY = ctx.arcScaleY_;
-    var width = max.x - min.x;
-    var height = max.y - min.y;
-    if (fillStyle instanceof CanvasGradient_) {
-      // TODO: Gradients transformed with the transformation matrix.
-      var angle = 0;
-      var focus = {x: 0, y: 0};
-
-      // additional offset
-      var shift = 0;
-      // scale factor for offset
-      var expansion = 1;
-
-      if (fillStyle.type_ == 'gradient') {
-        var x0 = fillStyle.x0_ / arcScaleX;
-        var y0 = fillStyle.y0_ / arcScaleY;
-        var x1 = fillStyle.x1_ / arcScaleX;
-        var y1 = fillStyle.y1_ / arcScaleY;
-        var p0 = ctx.getCoords_(x0, y0);
-        var p1 = ctx.getCoords_(x1, y1);
-        var dx = p1.x - p0.x;
-        var dy = p1.y - p0.y;
-        angle = Math.atan2(dx, dy) * 180 / Math.PI;
-
-        // The angle should be a non-negative number.
-        if (angle < 0) {
-          angle += 360;
-        }
-
-        // Very small angles produce an unexpected result because they are
-        // converted to a scientific notation string.
-        if (angle < 1e-6) {
-          angle = 0;
-        }
-      } else {
-        var p0 = ctx.getCoords_(fillStyle.x0_, fillStyle.y0_);
-        focus = {
-          x: (p0.x - min.x) / width,
-          y: (p0.y - min.y) / height
-        };
-
-        width  /= arcScaleX * Z;
-        height /= arcScaleY * Z;
-        var dimension = m.max(width, height);
-        shift = 2 * fillStyle.r0_ / dimension;
-        expansion = 2 * fillStyle.r1_ / dimension - shift;
-      }
-
-      // We need to sort the color stops in ascending order by offset,
-      // otherwise IE won't interpret it correctly.
-      var stops = fillStyle.colors_;
-      stops.sort(function(cs1, cs2) {
-        return cs1.offset - cs2.offset;
-      });
-
-      var length = stops.length;
-      var color1 = stops[0].color;
-      var color2 = stops[length - 1].color;
-      var opacity1 = stops[0].alpha * ctx.globalAlpha;
-      var opacity2 = stops[length - 1].alpha * ctx.globalAlpha;
-
-      var colors = [];
-      for (var i = 0; i < length; i++) {
-        var stop = stops[i];
-        colors.push(stop.offset * expansion + shift + ' ' + stop.color);
-      }
-
-      // When colors attribute is used, the meanings of opacity and o:opacity2
-      // are reversed.
-      lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"',
-                   ' method="none" focus="100%"',
-                   ' color="', color1, '"',
-                   ' color2="', color2, '"',
-                   ' colors="', colors.join(','), '"',
-                   ' opacity="', opacity2, '"',
-                   ' g_o_:opacity2="', opacity1, '"',
-                   ' angle="', angle, '"',
-                   ' focusposition="', focus.x, ',', focus.y, '" />');
-    } else if (fillStyle instanceof CanvasPattern_) {
-      if (width && height) {
-        var deltaLeft = -min.x;
-        var deltaTop = -min.y;
-        lineStr.push('<g_vml_:fill',
-                     ' position="',
-                     deltaLeft / width * arcScaleX * arcScaleX, ',',
-                     deltaTop / height * arcScaleY * arcScaleY, '"',
-                     ' type="tile"',
-                     // TODO: Figure out the correct size to fit the scale.
-                     //' size="', w, 'px ', h, 'px"',
-                     ' src="', fillStyle.src_, '" />');
-       }
-    } else {
-      var a = processStyle(ctx.fillStyle);
-      var color = a.color;
-      var opacity = a.alpha * ctx.globalAlpha;
-      lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity,
-                   '" />');
-    }
-  }
-
-  contextPrototype.fill = function() {
-    this.stroke(true);
-  };
-
-  contextPrototype.closePath = function() {
-    this.currentPath_.push({type: 'close'});
-  };
-
-  /**
-   * @private
-   */
-  contextPrototype.getCoords_ = function(aX, aY) {
-    var m = this.m_;
-    return {
-      x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2,
-      y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2
-    };
-  };
-
-  contextPrototype.save = function() {
-    var o = {};
-    copyState(this, o);
-    this.aStack_.push(o);
-    this.mStack_.push(this.m_);
-    this.m_ = matrixMultiply(createMatrixIdentity(), this.m_);
-  };
-
-  contextPrototype.restore = function() {
-    if (this.aStack_.length) {
-      copyState(this.aStack_.pop(), this);
-      this.m_ = this.mStack_.pop();
-    }
-  };
-
-  function matrixIsFinite(m) {
-    return isFinite(m[0][0]) && isFinite(m[0][1]) &&
-        isFinite(m[1][0]) && isFinite(m[1][1]) &&
-        isFinite(m[2][0]) && isFinite(m[2][1]);
-  }
-
-  function setM(ctx, m, updateLineScale) {
-    if (!matrixIsFinite(m)) {
-      return;
-    }
-    ctx.m_ = m;
-
-    if (updateLineScale) {
-      // Get the line scale.
-      // Determinant of this.m_ means how much the area is enlarged by the
-      // transformation. So its square root can be used as a scale factor
-      // for width.
-      var det = m[0][0] * m[1][1] - m[0][1] * m[1][0];
-      ctx.lineScale_ = sqrt(abs(det));
-    }
-  }
-
-  contextPrototype.translate = function(aX, aY) {
-    var m1 = [
-      [1,  0,  0],
-      [0,  1,  0],
-      [aX, aY, 1]
-    ];
-
-    setM(this, matrixMultiply(m1, this.m_), false);
-  };
-
-  contextPrototype.rotate = function(aRot) {
-    var c = mc(aRot);
-    var s = ms(aRot);
-
-    var m1 = [
-      [c,  s, 0],
-      [-s, c, 0],
-      [0,  0, 1]
-    ];
-
-    setM(this, matrixMultiply(m1, this.m_), false);
-  };
-
-  contextPrototype.scale = function(aX, aY) {
-    this.arcScaleX_ *= aX;
-    this.arcScaleY_ *= aY;
-    var m1 = [
-      [aX, 0,  0],
-      [0,  aY, 0],
-      [0,  0,  1]
-    ];
-
-    setM(this, matrixMultiply(m1, this.m_), true);
-  };
-
-  contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) {
-    var m1 = [
-      [m11, m12, 0],
-      [m21, m22, 0],
-      [dx,  dy,  1]
-    ];
-
-    setM(this, matrixMultiply(m1, this.m_), true);
-  };
-
-  contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) {
-    var m = [
-      [m11, m12, 0],
-      [m21, m22, 0],
-      [dx,  dy,  1]
-    ];
-
-    setM(this, m, true);
-  };
-
-  /**
-   * The text drawing function.
-   * The maxWidth argument isn't taken in account, since no browser supports
-   * it yet.
-   */
-  contextPrototype.drawText_ = function(text, x, y, maxWidth, stroke) {
-    var m = this.m_,
-        delta = 1000,
-        left = 0,
-        right = delta,
-        offset = {x: 0, y: 0},
-        lineStr = [];
-
-    var fontStyle = getComputedStyle(processFontStyle(this.font),
-                                     this.element_);
-
-    var fontStyleString = buildStyle(fontStyle);
-
-    var elementStyle = this.element_.currentStyle;
-    var textAlign = this.textAlign.toLowerCase();
-    switch (textAlign) {
-      case 'left':
-      case 'center':
-      case 'right':
-        break;
-      case 'end':
-        textAlign = elementStyle.direction == 'ltr' ? 'right' : 'left';
-        break;
-      case 'start':
-        textAlign = elementStyle.direction == 'rtl' ? 'right' : 'left';
-        break;
-      default:
-        textAlign = 'left';
-    }
-
-    // 1.75 is an arbitrary number, as there is no info about the text baseline
-    switch (this.textBaseline) {
-      case 'hanging':
-      case 'top':
-        offset.y = fontStyle.size / 1.75;
-        break;
-      case 'middle':
-        break;
-      default:
-      case null:
-      case 'alphabetic':
-      case 'ideographic':
-      case 'bottom':
-        offset.y = -fontStyle.size / 2.25;
-        break;
-    }
-
-    switch(textAlign) {
-      case 'right':
-        left = delta;
-        right = 0.05;
-        break;
-      case 'center':
-        left = right = delta / 2;
-        break;
-    }
-
-    var d = this.getCoords_(x + offset.x, y + offset.y);
-
-    lineStr.push('<g_vml_:line from="', -left ,' 0" to="', right ,' 0.05" ',
-                 ' coordsize="100 100" coordorigin="0 0"',
-                 ' filled="', !stroke, '" stroked="', !!stroke,
-                 '" style="position:absolute;width:1px;height:1px;">');
-
-    if (stroke) {
-      appendStroke(this, lineStr);
-    } else {
-      // TODO: Fix the min and max params.
-      appendFill(this, lineStr, {x: -left, y: 0},
-                 {x: right, y: fontStyle.size});
-    }
-
-    var skewM = m[0][0].toFixed(3) + ',' + m[1][0].toFixed(3) + ',' +
-                m[0][1].toFixed(3) + ',' + m[1][1].toFixed(3) + ',0,0';
-
-    var skewOffset = mr(d.x / Z) + ',' + mr(d.y / Z);
-
-    lineStr.push('<g_vml_:skew on="t" matrix="', skewM ,'" ',
-                 ' offset="', skewOffset, '" origin="', left ,' 0" />',
-                 '<g_vml_:path textpathok="true" />',
-                 '<g_vml_:textpath on="true" string="',
-                 encodeHtmlAttribute(text),
-                 '" style="v-text-align:', textAlign,
-                 ';font:', encodeHtmlAttribute(fontStyleString),
-                 '" /></g_vml_:line>');
-
-    this.element_.insertAdjacentHTML('beforeEnd', lineStr.join(''));
-  };
-
-  contextPrototype.fillText = function(text, x, y, maxWidth) {
-    this.drawText_(text, x, y, maxWidth, false);
-  };
-
-  contextPrototype.strokeText = function(text, x, y, maxWidth) {
-    this.drawText_(text, x, y, maxWidth, true);
-  };
-
-  contextPrototype.measureText = function(text) {
-    if (!this.textMeasureEl_) {
-      var s = '<span style="position:absolute;' +
-          'top:-20000px;left:0;padding:0;margin:0;border:none;' +
-          'white-space:pre;"></span>';
-      this.element_.insertAdjacentHTML('beforeEnd', s);
-      this.textMeasureEl_ = this.element_.lastChild;
-    }
-    var doc = this.element_.ownerDocument;
-    this.textMeasureEl_.innerHTML = '';
-    this.textMeasureEl_.style.font = this.font;
-    // Don't use innerHTML or innerText because they allow markup/whitespace.
-    this.textMeasureEl_.appendChild(doc.createTextNode(text));
-    return {width: this.textMeasureEl_.offsetWidth};
-  };
-
-  /******** STUBS ********/
-  contextPrototype.clip = function() {
-    // TODO: Implement
-  };
-
-  contextPrototype.arcTo = function() {
-    // TODO: Implement
-  };
-
-  contextPrototype.createPattern = function(image, repetition) {
-    return new CanvasPattern_(image, repetition);
-  };
-
-  // Gradient / Pattern Stubs
-  function CanvasGradient_(aType) {
-    this.type_ = aType;
-    this.x0_ = 0;
-    this.y0_ = 0;
-    this.r0_ = 0;
-    this.x1_ = 0;
-    this.y1_ = 0;
-    this.r1_ = 0;
-    this.colors_ = [];
-  }
-
-  CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) {
-    aColor = processStyle(aColor);
-    this.colors_.push({offset: aOffset,
-                       color: aColor.color,
-                       alpha: aColor.alpha});
-  };
-
-  function CanvasPattern_(image, repetition) {
-    assertImageIsValid(image);
-    switch (repetition) {
-      case 'repeat':
-      case null:
-      case '':
-        this.repetition_ = 'repeat';
-        break
-      case 'repeat-x':
-      case 'repeat-y':
-      case 'no-repeat':
-        this.repetition_ = repetition;
-        break;
-      default:
-        throwException('SYNTAX_ERR');
-    }
-
-    this.src_ = image.src;
-    this.width_ = image.width;
-    this.height_ = image.height;
-  }
-
-  function throwException(s) {
-    throw new DOMException_(s);
-  }
-
-  function assertImageIsValid(img) {
-    if (!img || img.nodeType != 1 || img.tagName != 'IMG') {
-      throwException('TYPE_MISMATCH_ERR');
-    }
-    if (img.readyState != 'complete') {
-      throwException('INVALID_STATE_ERR');
-    }
-  }
-
-  function DOMException_(s) {
-    this.code = this[s];
-    this.message = s +': DOM Exception ' + this.code;
-  }
-  var p = DOMException_.prototype = new Error;
-  p.INDEX_SIZE_ERR = 1;
-  p.DOMSTRING_SIZE_ERR = 2;
-  p.HIERARCHY_REQUEST_ERR = 3;
-  p.WRONG_DOCUMENT_ERR = 4;
-  p.INVALID_CHARACTER_ERR = 5;
-  p.NO_DATA_ALLOWED_ERR = 6;
-  p.NO_MODIFICATION_ALLOWED_ERR = 7;
-  p.NOT_FOUND_ERR = 8;
-  p.NOT_SUPPORTED_ERR = 9;
-  p.INUSE_ATTRIBUTE_ERR = 10;
-  p.INVALID_STATE_ERR = 11;
-  p.SYNTAX_ERR = 12;
-  p.INVALID_MODIFICATION_ERR = 13;
-  p.NAMESPACE_ERR = 14;
-  p.INVALID_ACCESS_ERR = 15;
-  p.VALIDATION_ERR = 16;
-  p.TYPE_MISMATCH_ERR = 17;
-
-  // set up externs
-  G_vmlCanvasManager = G_vmlCanvasManager_;
-  CanvasRenderingContext2D = CanvasRenderingContext2D_;
-  CanvasGradient = CanvasGradient_;
-  CanvasPattern = CanvasPattern_;
-  DOMException = DOMException_;
-})();
-
-} // if
diff --git a/static/js/excanvas.min.js b/static/js/excanvas.min.js
deleted file mode 100644
--- a/static/js/excanvas.min.js
+++ /dev/null
@@ -1,1 +0,0 @@
-if(!document.createElement("canvas").getContext){(function(){var z=Math;var K=z.round;var J=z.sin;var U=z.cos;var b=z.abs;var k=z.sqrt;var D=10;var F=D/2;function T(){return this.context_||(this.context_=new W(this))}var O=Array.prototype.slice;function G(i,j,m){var Z=O.call(arguments,2);return function(){return i.apply(j,Z.concat(O.call(arguments)))}}function AD(Z){return String(Z).replace(/&/g,"&amp;").replace(/"/g,"&quot;")}function r(i){if(!i.namespaces.g_vml_){i.namespaces.add("g_vml_","urn:schemas-microsoft-com:vml","#default#VML")}if(!i.namespaces.g_o_){i.namespaces.add("g_o_","urn:schemas-microsoft-com:office:office","#default#VML")}if(!i.styleSheets.ex_canvas_){var Z=i.createStyleSheet();Z.owningElement.id="ex_canvas_";Z.cssText="canvas{display:inline-block;overflow:hidden;text-align:left;width:300px;height:150px}"}}r(document);var E={init:function(Z){if(/MSIE/.test(navigator.userAgent)&&!window.opera){var i=Z||document;i.createElement("canvas");i.attachEvent("onreadystatechange",G(this.init_,this,i))}},init_:function(m){var j=m.getElementsByTagName("canvas");for(var Z=0;Z<j.length;Z++){this.initElement(j[Z])}},initElement:function(i){if(!i.getContext){i.getContext=T;r(i.ownerDocument);i.innerHTML="";i.attachEvent("onpropertychange",S);i.attachEvent("onresize",w);var Z=i.attributes;if(Z.width&&Z.width.specified){i.style.width=Z.width.nodeValue+"px"}else{i.width=i.clientWidth}if(Z.height&&Z.height.specified){i.style.height=Z.height.nodeValue+"px"}else{i.height=i.clientHeight}}return i}};function S(i){var Z=i.srcElement;switch(i.propertyName){case"width":Z.getContext().clearRect();Z.style.width=Z.attributes.width.nodeValue+"px";Z.firstChild.style.width=Z.clientWidth+"px";break;case"height":Z.getContext().clearRect();Z.style.height=Z.attributes.height.nodeValue+"px";Z.firstChild.style.height=Z.clientHeight+"px";break}}function w(i){var Z=i.srcElement;if(Z.firstChild){Z.firstChild.style.width=Z.clientWidth+"px";Z.firstChild.style.height=Z.clientHeight+"px"}}E.init();var I=[];for(var AC=0;AC<16;AC++){for(var AB=0;AB<16;AB++){I[AC*16+AB]=AC.toString(16)+AB.toString(16)}}function V(){return[[1,0,0],[0,1,0],[0,0,1]]}function d(m,j){var i=V();for(var Z=0;Z<3;Z++){for(var AF=0;AF<3;AF++){var p=0;for(var AE=0;AE<3;AE++){p+=m[Z][AE]*j[AE][AF]}i[Z][AF]=p}}return i}function Q(i,Z){Z.fillStyle=i.fillStyle;Z.lineCap=i.lineCap;Z.lineJoin=i.lineJoin;Z.lineWidth=i.lineWidth;Z.miterLimit=i.miterLimit;Z.shadowBlur=i.shadowBlur;Z.shadowColor=i.shadowColor;Z.shadowOffsetX=i.shadowOffsetX;Z.shadowOffsetY=i.shadowOffsetY;Z.strokeStyle=i.strokeStyle;Z.globalAlpha=i.globalAlpha;Z.font=i.font;Z.textAlign=i.textAlign;Z.textBaseline=i.textBaseline;Z.arcScaleX_=i.arcScaleX_;Z.arcScaleY_=i.arcScaleY_;Z.lineScale_=i.lineScale_}var B={aliceblue:"#F0F8FF",antiquewhite:"#FAEBD7",aquamarine:"#7FFFD4",azure:"#F0FFFF",beige:"#F5F5DC",bisque:"#FFE4C4",black:"#000000",blanchedalmond:"#FFEBCD",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",gainsboro:"#DCDCDC",ghostwhite:"#F8F8FF",gold:"#FFD700",goldenrod:"#DAA520",grey:"#808080",greenyellow:"#ADFF2F",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",lightgreen:"#90EE90",lightgrey:"#D3D3D3",lightpink:"#FFB6C1",lightsalmon:"#FFA07A",lightseagreen:"#20B2AA",lightskyblue:"#87CEFA",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#B0C4DE",lightyellow:"#FFFFE0",limegreen:"#32CD32",linen:"#FAF0E6",magenta:"#FF00FF",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",oldlace:"#FDF5E6",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",rosybrown:"#BC8F8F",royalblue:"#4169E1",saddlebrown:"#8B4513",salmon:"#FA8072",sandybrown:"#F4A460",seagreen:"#2E8B57",seashell:"#FFF5EE",sienna:"#A0522D",skyblue:"#87CEEB",slateblue:"#6A5ACD",slategray:"#708090",slategrey:"#708090",snow:"#FFFAFA",springgreen:"#00FF7F",steelblue:"#4682B4",tan:"#D2B48C",thistle:"#D8BFD8",tomato:"#FF6347",turquoise:"#40E0D0",violet:"#EE82EE",wheat:"#F5DEB3",whitesmoke:"#F5F5F5",yellowgreen:"#9ACD32"};function g(i){var m=i.indexOf("(",3);var Z=i.indexOf(")",m+1);var j=i.substring(m+1,Z).split(",");if(j.length==4&&i.substr(3,1)=="a"){alpha=Number(j[3])}else{j[3]=1}return j}function C(Z){return parseFloat(Z)/100}function N(i,j,Z){return Math.min(Z,Math.max(j,i))}function c(AF){var j,i,Z;h=parseFloat(AF[0])/360%360;if(h<0){h++}s=N(C(AF[1]),0,1);l=N(C(AF[2]),0,1);if(s==0){j=i=Z=l}else{var m=l<0.5?l*(1+s):l+s-l*s;var AE=2*l-m;j=A(AE,m,h+1/3);i=A(AE,m,h);Z=A(AE,m,h-1/3)}return"#"+I[Math.floor(j*255)]+I[Math.floor(i*255)]+I[Math.floor(Z*255)]}function A(i,Z,j){if(j<0){j++}if(j>1){j--}if(6*j<1){return i+(Z-i)*6*j}else{if(2*j<1){return Z}else{if(3*j<2){return i+(Z-i)*(2/3-j)*6}else{return i}}}}function Y(Z){var AE,p=1;Z=String(Z);if(Z.charAt(0)=="#"){AE=Z}else{if(/^rgb/.test(Z)){var m=g(Z);var AE="#",AF;for(var j=0;j<3;j++){if(m[j].indexOf("%")!=-1){AF=Math.floor(C(m[j])*255)}else{AF=Number(m[j])}AE+=I[N(AF,0,255)]}p=m[3]}else{if(/^hsl/.test(Z)){var m=g(Z);AE=c(m);p=m[3]}else{AE=B[Z]||Z}}}return{color:AE,alpha:p}}var L={style:"normal",variant:"normal",weight:"normal",size:10,family:"sans-serif"};var f={};function X(Z){if(f[Z]){return f[Z]}var m=document.createElement("div");var j=m.style;try{j.font=Z}catch(i){}return f[Z]={style:j.fontStyle||L.style,variant:j.fontVariant||L.variant,weight:j.fontWeight||L.weight,size:j.fontSize||L.size,family:j.fontFamily||L.family}}function P(j,i){var Z={};for(var AF in j){Z[AF]=j[AF]}var AE=parseFloat(i.currentStyle.fontSize),m=parseFloat(j.size);if(typeof j.size=="number"){Z.size=j.size}else{if(j.size.indexOf("px")!=-1){Z.size=m}else{if(j.size.indexOf("em")!=-1){Z.size=AE*m}else{if(j.size.indexOf("%")!=-1){Z.size=(AE/100)*m}else{if(j.size.indexOf("pt")!=-1){Z.size=m/0.75}else{Z.size=AE}}}}}Z.size*=0.981;return Z}function AA(Z){return Z.style+" "+Z.variant+" "+Z.weight+" "+Z.size+"px "+Z.family}function t(Z){switch(Z){case"butt":return"flat";case"round":return"round";case"square":default:return"square"}}function W(i){this.m_=V();this.mStack_=[];this.aStack_=[];this.currentPath_=[];this.strokeStyle="#000";this.fillStyle="#000";this.lineWidth=1;this.lineJoin="miter";this.lineCap="butt";this.miterLimit=D*1;this.globalAlpha=1;this.font="10px sans-serif";this.textAlign="left";this.textBaseline="alphabetic";this.canvas=i;var Z=i.ownerDocument.createElement("div");Z.style.width=i.clientWidth+"px";Z.style.height=i.clientHeight+"px";Z.style.overflow="hidden";Z.style.position="absolute";i.appendChild(Z);this.element_=Z;this.arcScaleX_=1;this.arcScaleY_=1;this.lineScale_=1}var M=W.prototype;M.clearRect=function(){if(this.textMeasureEl_){this.textMeasureEl_.removeNode(true);this.textMeasureEl_=null}this.element_.innerHTML=""};M.beginPath=function(){this.currentPath_=[]};M.moveTo=function(i,Z){var j=this.getCoords_(i,Z);this.currentPath_.push({type:"moveTo",x:j.x,y:j.y});this.currentX_=j.x;this.currentY_=j.y};M.lineTo=function(i,Z){var j=this.getCoords_(i,Z);this.currentPath_.push({type:"lineTo",x:j.x,y:j.y});this.currentX_=j.x;this.currentY_=j.y};M.bezierCurveTo=function(j,i,AI,AH,AG,AE){var Z=this.getCoords_(AG,AE);var AF=this.getCoords_(j,i);var m=this.getCoords_(AI,AH);e(this,AF,m,Z)};function e(Z,m,j,i){Z.currentPath_.push({type:"bezierCurveTo",cp1x:m.x,cp1y:m.y,cp2x:j.x,cp2y:j.y,x:i.x,y:i.y});Z.currentX_=i.x;Z.currentY_=i.y}M.quadraticCurveTo=function(AG,j,i,Z){var AF=this.getCoords_(AG,j);var AE=this.getCoords_(i,Z);var AH={x:this.currentX_+2/3*(AF.x-this.currentX_),y:this.currentY_+2/3*(AF.y-this.currentY_)};var m={x:AH.x+(AE.x-this.currentX_)/3,y:AH.y+(AE.y-this.currentY_)/3};e(this,AH,m,AE)};M.arc=function(AJ,AH,AI,AE,i,j){AI*=D;var AN=j?"at":"wa";var AK=AJ+U(AE)*AI-F;var AM=AH+J(AE)*AI-F;var Z=AJ+U(i)*AI-F;var AL=AH+J(i)*AI-F;if(AK==Z&&!j){AK+=0.125}var m=this.getCoords_(AJ,AH);var AG=this.getCoords_(AK,AM);var AF=this.getCoords_(Z,AL);this.currentPath_.push({type:AN,x:m.x,y:m.y,radius:AI,xStart:AG.x,yStart:AG.y,xEnd:AF.x,yEnd:AF.y})};M.rect=function(j,i,Z,m){this.moveTo(j,i);this.lineTo(j+Z,i);this.lineTo(j+Z,i+m);this.lineTo(j,i+m);this.closePath()};M.strokeRect=function(j,i,Z,m){var p=this.currentPath_;this.beginPath();this.moveTo(j,i);this.lineTo(j+Z,i);this.lineTo(j+Z,i+m);this.lineTo(j,i+m);this.closePath();this.stroke();this.currentPath_=p};M.fillRect=function(j,i,Z,m){var p=this.currentPath_;this.beginPath();this.moveTo(j,i);this.lineTo(j+Z,i);this.lineTo(j+Z,i+m);this.lineTo(j,i+m);this.closePath();this.fill();this.currentPath_=p};M.createLinearGradient=function(i,m,Z,j){var p=new v("gradient");p.x0_=i;p.y0_=m;p.x1_=Z;p.y1_=j;return p};M.createRadialGradient=function(m,AE,j,i,p,Z){var AF=new v("gradientradial");AF.x0_=m;AF.y0_=AE;AF.r0_=j;AF.x1_=i;AF.y1_=p;AF.r1_=Z;return AF};M.drawImage=function(AO,j){var AH,AF,AJ,AV,AM,AK,AQ,AX;var AI=AO.runtimeStyle.width;var AN=AO.runtimeStyle.height;AO.runtimeStyle.width="auto";AO.runtimeStyle.height="auto";var AG=AO.width;var AT=AO.height;AO.runtimeStyle.width=AI;AO.runtimeStyle.height=AN;if(arguments.length==3){AH=arguments[1];AF=arguments[2];AM=AK=0;AQ=AJ=AG;AX=AV=AT}else{if(arguments.length==5){AH=arguments[1];AF=arguments[2];AJ=arguments[3];AV=arguments[4];AM=AK=0;AQ=AG;AX=AT}else{if(arguments.length==9){AM=arguments[1];AK=arguments[2];AQ=arguments[3];AX=arguments[4];AH=arguments[5];AF=arguments[6];AJ=arguments[7];AV=arguments[8]}else{throw Error("Invalid number of arguments")}}}var AW=this.getCoords_(AH,AF);var m=AQ/2;var i=AX/2;var AU=[];var Z=10;var AE=10;AU.push(" <g_vml_:group",' coordsize="',D*Z,",",D*AE,'"',' coordorigin="0,0"',' style="width:',Z,"px;height:",AE,"px;position:absolute;");if(this.m_[0][0]!=1||this.m_[0][1]||this.m_[1][1]!=1||this.m_[1][0]){var p=[];p.push("M11=",this.m_[0][0],",","M12=",this.m_[1][0],",","M21=",this.m_[0][1],",","M22=",this.m_[1][1],",","Dx=",K(AW.x/D),",","Dy=",K(AW.y/D),"");var AS=AW;var AR=this.getCoords_(AH+AJ,AF);var AP=this.getCoords_(AH,AF+AV);var AL=this.getCoords_(AH+AJ,AF+AV);AS.x=z.max(AS.x,AR.x,AP.x,AL.x);AS.y=z.max(AS.y,AR.y,AP.y,AL.y);AU.push("padding:0 ",K(AS.x/D),"px ",K(AS.y/D),"px 0;filter:progid:DXImageTransform.Microsoft.Matrix(",p.join(""),", sizingmethod='clip');")}else{AU.push("top:",K(AW.y/D),"px;left:",K(AW.x/D),"px;")}AU.push(' ">','<g_vml_:image src="',AO.src,'"',' style="width:',D*AJ,"px;"," height:",D*AV,'px"',' cropleft="',AM/AG,'"',' croptop="',AK/AT,'"',' cropright="',(AG-AM-AQ)/AG,'"',' cropbottom="',(AT-AK-AX)/AT,'"'," />","</g_vml_:group>");this.element_.insertAdjacentHTML("BeforeEnd",AU.join(""))};M.stroke=function(AM){var m=10;var AN=10;var AE=5000;var AG={x:null,y:null};var AL={x:null,y:null};for(var AH=0;AH<this.currentPath_.length;AH+=AE){var AK=[];var AF=false;AK.push("<g_vml_:shape",' filled="',!!AM,'"',' style="position:absolute;width:',m,"px;height:",AN,'px;"',' coordorigin="0,0"',' coordsize="',D*m,",",D*AN,'"',' stroked="',!AM,'"',' path="');var AO=false;for(var AI=AH;AI<Math.min(AH+AE,this.currentPath_.length);AI++){if(AI%AE==0&&AI>0){AK.push(" m ",K(this.currentPath_[AI-1].x),",",K(this.currentPath_[AI-1].y))}var Z=this.currentPath_[AI];var AJ;switch(Z.type){case"moveTo":AJ=Z;AK.push(" m ",K(Z.x),",",K(Z.y));break;case"lineTo":AK.push(" l ",K(Z.x),",",K(Z.y));break;case"close":AK.push(" x ");Z=null;break;case"bezierCurveTo":AK.push(" c ",K(Z.cp1x),",",K(Z.cp1y),",",K(Z.cp2x),",",K(Z.cp2y),",",K(Z.x),",",K(Z.y));break;case"at":case"wa":AK.push(" ",Z.type," ",K(Z.x-this.arcScaleX_*Z.radius),",",K(Z.y-this.arcScaleY_*Z.radius)," ",K(Z.x+this.arcScaleX_*Z.radius),",",K(Z.y+this.arcScaleY_*Z.radius)," ",K(Z.xStart),",",K(Z.yStart)," ",K(Z.xEnd),",",K(Z.yEnd));break}if(Z){if(AG.x==null||Z.x<AG.x){AG.x=Z.x}if(AL.x==null||Z.x>AL.x){AL.x=Z.x}if(AG.y==null||Z.y<AG.y){AG.y=Z.y}if(AL.y==null||Z.y>AL.y){AL.y=Z.y}}}AK.push(' ">');if(!AM){R(this,AK)}else{a(this,AK,AG,AL)}AK.push("</g_vml_:shape>");this.element_.insertAdjacentHTML("beforeEnd",AK.join(""))}};function R(j,AE){var i=Y(j.strokeStyle);var m=i.color;var p=i.alpha*j.globalAlpha;var Z=j.lineScale_*j.lineWidth;if(Z<1){p*=Z}AE.push("<g_vml_:stroke",' opacity="',p,'"',' joinstyle="',j.lineJoin,'"',' miterlimit="',j.miterLimit,'"',' endcap="',t(j.lineCap),'"',' weight="',Z,'px"',' color="',m,'" />')}function a(AO,AG,Ah,AP){var AH=AO.fillStyle;var AY=AO.arcScaleX_;var AX=AO.arcScaleY_;var Z=AP.x-Ah.x;var m=AP.y-Ah.y;if(AH instanceof v){var AL=0;var Ac={x:0,y:0};var AU=0;var AK=1;if(AH.type_=="gradient"){var AJ=AH.x0_/AY;var j=AH.y0_/AX;var AI=AH.x1_/AY;var Aj=AH.y1_/AX;var Ag=AO.getCoords_(AJ,j);var Af=AO.getCoords_(AI,Aj);var AE=Af.x-Ag.x;var p=Af.y-Ag.y;AL=Math.atan2(AE,p)*180/Math.PI;if(AL<0){AL+=360}if(AL<0.000001){AL=0}}else{var Ag=AO.getCoords_(AH.x0_,AH.y0_);Ac={x:(Ag.x-Ah.x)/Z,y:(Ag.y-Ah.y)/m};Z/=AY*D;m/=AX*D;var Aa=z.max(Z,m);AU=2*AH.r0_/Aa;AK=2*AH.r1_/Aa-AU}var AS=AH.colors_;AS.sort(function(Ak,i){return Ak.offset-i.offset});var AN=AS.length;var AR=AS[0].color;var AQ=AS[AN-1].color;var AW=AS[0].alpha*AO.globalAlpha;var AV=AS[AN-1].alpha*AO.globalAlpha;var Ab=[];for(var Ae=0;Ae<AN;Ae++){var AM=AS[Ae];Ab.push(AM.offset*AK+AU+" "+AM.color)}AG.push('<g_vml_:fill type="',AH.type_,'"',' method="none" focus="100%"',' color="',AR,'"',' color2="',AQ,'"',' colors="',Ab.join(","),'"',' opacity="',AV,'"',' g_o_:opacity2="',AW,'"',' angle="',AL,'"',' focusposition="',Ac.x,",",Ac.y,'" />')}else{if(AH instanceof u){if(Z&&m){var AF=-Ah.x;var AZ=-Ah.y;AG.push("<g_vml_:fill",' position="',AF/Z*AY*AY,",",AZ/m*AX*AX,'"',' type="tile"',' src="',AH.src_,'" />')}}else{var Ai=Y(AO.fillStyle);var AT=Ai.color;var Ad=Ai.alpha*AO.globalAlpha;AG.push('<g_vml_:fill color="',AT,'" opacity="',Ad,'" />')}}}M.fill=function(){this.stroke(true)};M.closePath=function(){this.currentPath_.push({type:"close"})};M.getCoords_=function(j,i){var Z=this.m_;return{x:D*(j*Z[0][0]+i*Z[1][0]+Z[2][0])-F,y:D*(j*Z[0][1]+i*Z[1][1]+Z[2][1])-F}};M.save=function(){var Z={};Q(this,Z);this.aStack_.push(Z);this.mStack_.push(this.m_);this.m_=d(V(),this.m_)};M.restore=function(){if(this.aStack_.length){Q(this.aStack_.pop(),this);this.m_=this.mStack_.pop()}};function H(Z){return isFinite(Z[0][0])&&isFinite(Z[0][1])&&isFinite(Z[1][0])&&isFinite(Z[1][1])&&isFinite(Z[2][0])&&isFinite(Z[2][1])}function y(i,Z,j){if(!H(Z)){return }i.m_=Z;if(j){var p=Z[0][0]*Z[1][1]-Z[0][1]*Z[1][0];i.lineScale_=k(b(p))}}M.translate=function(j,i){var Z=[[1,0,0],[0,1,0],[j,i,1]];y(this,d(Z,this.m_),false)};M.rotate=function(i){var m=U(i);var j=J(i);var Z=[[m,j,0],[-j,m,0],[0,0,1]];y(this,d(Z,this.m_),false)};M.scale=function(j,i){this.arcScaleX_*=j;this.arcScaleY_*=i;var Z=[[j,0,0],[0,i,0],[0,0,1]];y(this,d(Z,this.m_),true)};M.transform=function(p,m,AF,AE,i,Z){var j=[[p,m,0],[AF,AE,0],[i,Z,1]];y(this,d(j,this.m_),true)};M.setTransform=function(AE,p,AG,AF,j,i){var Z=[[AE,p,0],[AG,AF,0],[j,i,1]];y(this,Z,true)};M.drawText_=function(AK,AI,AH,AN,AG){var AM=this.m_,AQ=1000,i=0,AP=AQ,AF={x:0,y:0},AE=[];var Z=P(X(this.font),this.element_);var j=AA(Z);var AR=this.element_.currentStyle;var p=this.textAlign.toLowerCase();switch(p){case"left":case"center":case"right":break;case"end":p=AR.direction=="ltr"?"right":"left";break;case"start":p=AR.direction=="rtl"?"right":"left";break;default:p="left"}switch(this.textBaseline){case"hanging":case"top":AF.y=Z.size/1.75;break;case"middle":break;default:case null:case"alphabetic":case"ideographic":case"bottom":AF.y=-Z.size/2.25;break}switch(p){case"right":i=AQ;AP=0.05;break;case"center":i=AP=AQ/2;break}var AO=this.getCoords_(AI+AF.x,AH+AF.y);AE.push('<g_vml_:line from="',-i,' 0" to="',AP,' 0.05" ',' coordsize="100 100" coordorigin="0 0"',' filled="',!AG,'" stroked="',!!AG,'" style="position:absolute;width:1px;height:1px;">');if(AG){R(this,AE)}else{a(this,AE,{x:-i,y:0},{x:AP,y:Z.size})}var AL=AM[0][0].toFixed(3)+","+AM[1][0].toFixed(3)+","+AM[0][1].toFixed(3)+","+AM[1][1].toFixed(3)+",0,0";var AJ=K(AO.x/D)+","+K(AO.y/D);AE.push('<g_vml_:skew on="t" matrix="',AL,'" ',' offset="',AJ,'" origin="',i,' 0" />','<g_vml_:path textpathok="true" />','<g_vml_:textpath on="true" string="',AD(AK),'" style="v-text-align:',p,";font:",AD(j),'" /></g_vml_:line>');this.element_.insertAdjacentHTML("beforeEnd",AE.join(""))};M.fillText=function(j,Z,m,i){this.drawText_(j,Z,m,i,false)};M.strokeText=function(j,Z,m,i){this.drawText_(j,Z,m,i,true)};M.measureText=function(j){if(!this.textMeasureEl_){var Z='<span style="position:absolute;top:-20000px;left:0;padding:0;margin:0;border:none;white-space:pre;"></span>';this.element_.insertAdjacentHTML("beforeEnd",Z);this.textMeasureEl_=this.element_.lastChild}var i=this.element_.ownerDocument;this.textMeasureEl_.innerHTML="";this.textMeasureEl_.style.font=this.font;this.textMeasureEl_.appendChild(i.createTextNode(j));return{width:this.textMeasureEl_.offsetWidth}};M.clip=function(){};M.arcTo=function(){};M.createPattern=function(i,Z){return new u(i,Z)};function v(Z){this.type_=Z;this.x0_=0;this.y0_=0;this.r0_=0;this.x1_=0;this.y1_=0;this.r1_=0;this.colors_=[]}v.prototype.addColorStop=function(i,Z){Z=Y(Z);this.colors_.push({offset:i,color:Z.color,alpha:Z.alpha})};function u(i,Z){q(i);switch(Z){case"repeat":case null:case"":this.repetition_="repeat";break;case"repeat-x":case"repeat-y":case"no-repeat":this.repetition_=Z;break;default:n("SYNTAX_ERR")}this.src_=i.src;this.width_=i.width;this.height_=i.height}function n(Z){throw new o(Z)}function q(Z){if(!Z||Z.nodeType!=1||Z.tagName!="IMG"){n("TYPE_MISMATCH_ERR")}if(Z.readyState!="complete"){n("INVALID_STATE_ERR")}}function o(Z){this.code=this[Z];this.message=Z+": DOM Exception "+this.code}var x=o.prototype=new Error;x.INDEX_SIZE_ERR=1;x.DOMSTRING_SIZE_ERR=2;x.HIERARCHY_REQUEST_ERR=3;x.WRONG_DOCUMENT_ERR=4;x.INVALID_CHARACTER_ERR=5;x.NO_DATA_ALLOWED_ERR=6;x.NO_MODIFICATION_ALLOWED_ERR=7;x.NOT_FOUND_ERR=8;x.NOT_SUPPORTED_ERR=9;x.INUSE_ATTRIBUTE_ERR=10;x.INVALID_STATE_ERR=11;x.SYNTAX_ERR=12;x.INVALID_MODIFICATION_ERR=13;x.NAMESPACE_ERR=14;x.INVALID_ACCESS_ERR=15;x.VALIDATION_ERR=16;x.TYPE_MISMATCH_ERR=17;G_vmlCanvasManager=E;CanvasRenderingContext2D=W;CanvasGradient=v;CanvasPattern=u;DOMException=o})()};
diff --git a/static/js/jquery.cookie.js b/static/js/jquery.cookie.js
deleted file mode 100644
--- a/static/js/jquery.cookie.js
+++ /dev/null
@@ -1,117 +0,0 @@
-/*!
- * jQuery Cookie Plugin v1.4.1
- * https://github.com/carhartl/jquery-cookie
- *
- * Copyright 2013 Klaus Hartl
- * Released under the MIT license
- */
-(function (factory) {
-	if (typeof define === 'function' && define.amd) {
-		// AMD
-		define(['jquery'], factory);
-	} else if (typeof exports === 'object') {
-		// CommonJS
-		factory(require('jquery'));
-	} else {
-		// Browser globals
-		factory(jQuery);
-	}
-}(function ($) {
-
-	var pluses = /\+/g;
-
-	function encode(s) {
-		return config.raw ? s : encodeURIComponent(s);
-	}
-
-	function decode(s) {
-		return config.raw ? s : decodeURIComponent(s);
-	}
-
-	function stringifyCookieValue(value) {
-		return encode(config.json ? JSON.stringify(value) : String(value));
-	}
-
-	function parseCookieValue(s) {
-		if (s.indexOf('"') === 0) {
-			// This is a quoted cookie as according to RFC2068, unescape...
-			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
-		}
-
-		try {
-			// Replace server-side written pluses with spaces.
-			// If we can't decode the cookie, ignore it, it's unusable.
-			// If we can't parse the cookie, ignore it, it's unusable.
-			s = decodeURIComponent(s.replace(pluses, ' '));
-			return config.json ? JSON.parse(s) : s;
-		} catch(e) {}
-	}
-
-	function read(s, converter) {
-		var value = config.raw ? s : parseCookieValue(s);
-		return $.isFunction(converter) ? converter(value) : value;
-	}
-
-	var config = $.cookie = function (key, value, options) {
-
-		// Write
-
-		if (value !== undefined && !$.isFunction(value)) {
-			options = $.extend({}, config.defaults, options);
-
-			if (typeof options.expires === 'number') {
-				var days = options.expires, t = options.expires = new Date();
-				t.setTime(+t + days * 864e+5);
-			}
-
-			return (document.cookie = [
-				encode(key), '=', stringifyCookieValue(value),
-				options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
-				options.path    ? '; path=' + options.path : '',
-				options.domain  ? '; domain=' + options.domain : '',
-				options.secure  ? '; secure' : ''
-			].join(''));
-		}
-
-		// Read
-
-		var result = key ? undefined : {};
-
-		// To prevent the for loop in the first place assign an empty array
-		// in case there are no cookies at all. Also prevents odd result when
-		// calling $.cookie().
-		var cookies = document.cookie ? document.cookie.split('; ') : [];
-
-		for (var i = 0, l = cookies.length; i < l; i++) {
-			var parts = cookies[i].split('=');
-			var name = decode(parts.shift());
-			var cookie = parts.join('=');
-
-			if (key && key === name) {
-				// If second argument (value) is a function it's a converter...
-				result = read(cookie, value);
-				break;
-			}
-
-			// Prevent storing a cookie that we couldn't decode.
-			if (!key && (cookie = read(cookie)) !== undefined) {
-				result[name] = cookie;
-			}
-		}
-
-		return result;
-	};
-
-	config.defaults = {};
-
-	$.removeCookie = function (key, options) {
-		if ($.cookie(key) === undefined) {
-			return false;
-		}
-
-		// Must not alter options, thus extending a fresh object...
-		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
-		return !$.cookie(key);
-	};
-
-}));
diff --git a/static/js/jquery.flot.canvas.js b/static/js/jquery.flot.canvas.js
deleted file mode 100644
--- a/static/js/jquery.flot.canvas.js
+++ /dev/null
@@ -1,345 +0,0 @@
-/* Flot plugin for drawing all elements of a plot on the canvas.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-Flot normally produces certain elements, like axis labels and the legend, using
-HTML elements. This permits greater interactivity and customization, and often
-looks better, due to cross-browser canvas text inconsistencies and limitations.
-
-It can also be desirable to render the plot entirely in canvas, particularly
-if the goal is to save it as an image, or if Flot is being used in a context
-where the HTML DOM does not exist, as is the case within Node.js. This plugin
-switches out Flot's standard drawing operations for canvas-only replacements.
-
-Currently the plugin supports only axis labels, but it will eventually allow
-every element of the plot to be rendered directly to canvas.
-
-The plugin supports these options:
-
-{
-    canvas: boolean
-}
-
-The "canvas" option controls whether full canvas drawing is enabled, making it
-possible to toggle on and off. This is useful when a plot uses HTML text in the
-browser, but needs to redraw with canvas text when exporting as an image.
-
-*/
-
-(function($) {
-
-	var options = {
-		canvas: true
-	};
-
-	var render, getTextInfo, addText;
-
-	// Cache the prototype hasOwnProperty for faster access
-
-	var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-	function init(plot, classes) {
-
-		var Canvas = classes.Canvas;
-
-		// We only want to replace the functions once; the second time around
-		// we would just get our new function back.  This whole replacing of
-		// prototype functions is a disaster, and needs to be changed ASAP.
-
-		if (render == null) {
-			getTextInfo = Canvas.prototype.getTextInfo,
-			addText = Canvas.prototype.addText,
-			render = Canvas.prototype.render;
-		}
-
-		// Finishes rendering the canvas, including overlaid text
-
-		Canvas.prototype.render = function() {
-
-			if (!plot.getOptions().canvas) {
-				return render.call(this);
-			}
-
-			var context = this.context,
-				cache = this._textCache;
-
-			// For each text layer, render elements marked as active
-
-			context.save();
-			context.textBaseline = "middle";
-
-			for (var layerKey in cache) {
-				if (hasOwnProperty.call(cache, layerKey)) {
-					var layerCache = cache[layerKey];
-					for (var styleKey in layerCache) {
-						if (hasOwnProperty.call(layerCache, styleKey)) {
-							var styleCache = layerCache[styleKey],
-								updateStyles = true;
-							for (var key in styleCache) {
-								if (hasOwnProperty.call(styleCache, key)) {
-
-									var info = styleCache[key],
-										positions = info.positions,
-										lines = info.lines;
-
-									// Since every element at this level of the cache have the
-									// same font and fill styles, we can just change them once
-									// using the values from the first element.
-
-									if (updateStyles) {
-										context.fillStyle = info.font.color;
-										context.font = info.font.definition;
-										updateStyles = false;
-									}
-
-									for (var i = 0, position; position = positions[i]; i++) {
-										if (position.active) {
-											for (var j = 0, line; line = position.lines[j]; j++) {
-												context.fillText(lines[j].text, line[0], line[1]);
-											}
-										} else {
-											positions.splice(i--, 1);
-										}
-									}
-
-									if (positions.length == 0) {
-										delete styleCache[key];
-									}
-								}
-							}
-						}
-					}
-				}
-			}
-
-			context.restore();
-		};
-
-		// Creates (if necessary) and returns a text info object.
-		//
-		// When the canvas option is set, the object looks like this:
-		//
-		// {
-		//     width: Width of the text's bounding box.
-		//     height: Height of the text's bounding box.
-		//     positions: Array of positions at which this text is drawn.
-		//     lines: [{
-		//         height: Height of this line.
-		//         widths: Width of this line.
-		//         text: Text on this line.
-		//     }],
-		//     font: {
-		//         definition: Canvas font property string.
-		//         color: Color of the text.
-		//     },
-		// }
-		//
-		// The positions array contains objects that look like this:
-		//
-		// {
-		//     active: Flag indicating whether the text should be visible.
-		//     lines: Array of [x, y] coordinates at which to draw the line.
-		//     x: X coordinate at which to draw the text.
-		//     y: Y coordinate at which to draw the text.
-		// }
-
-		Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
-
-			if (!plot.getOptions().canvas) {
-				return getTextInfo.call(this, layer, text, font, angle, width);
-			}
-
-			var textStyle, layerCache, styleCache, info;
-
-			// Cast the value to a string, in case we were given a number
-
-			text = "" + text;
-
-			// If the font is a font-spec object, generate a CSS definition
-
-			if (typeof font === "object") {
-				textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;
-			} else {
-				textStyle = font;
-			}
-
-			// Retrieve (or create) the cache for the text's layer and styles
-
-			layerCache = this._textCache[layer];
-
-			if (layerCache == null) {
-				layerCache = this._textCache[layer] = {};
-			}
-
-			styleCache = layerCache[textStyle];
-
-			if (styleCache == null) {
-				styleCache = layerCache[textStyle] = {};
-			}
-
-			info = styleCache[text];
-
-			if (info == null) {
-
-				var context = this.context;
-
-				// If the font was provided as CSS, create a div with those
-				// classes and examine it to generate a canvas font spec.
-
-				if (typeof font !== "object") {
-
-					var element = $("<div>&nbsp;</div>")
-						.css("position", "absolute")
-						.addClass(typeof font === "string" ? font : null)
-						.appendTo(this.getTextLayer(layer));
-
-					font = {
-						lineHeight: element.height(),
-						style: element.css("font-style"),
-						variant: element.css("font-variant"),
-						weight: element.css("font-weight"),
-						family: element.css("font-family"),
-						color: element.css("color")
-					};
-
-					// Setting line-height to 1, without units, sets it equal
-					// to the font-size, even if the font-size is abstract,
-					// like 'smaller'.  This enables us to read the real size
-					// via the element's height, working around browsers that
-					// return the literal 'smaller' value.
-
-					font.size = element.css("line-height", 1).height();
-
-					element.remove();
-				}
-
-				textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px " + font.family;
-
-				// Create a new info object, initializing the dimensions to
-				// zero so we can count them up line-by-line.
-
-				info = styleCache[text] = {
-					width: 0,
-					height: 0,
-					positions: [],
-					lines: [],
-					font: {
-						definition: textStyle,
-						color: font.color
-					}
-				};
-
-				context.save();
-				context.font = textStyle;
-
-				// Canvas can't handle multi-line strings; break on various
-				// newlines, including HTML brs, to build a list of lines.
-				// Note that we could split directly on regexps, but IE < 9 is
-				// broken; revisit when we drop IE 7/8 support.
-
-				var lines = (text + "").replace(/<br ?\/?>|\r\n|\r/g, "\n").split("\n");
-
-				for (var i = 0; i < lines.length; ++i) {
-
-					var lineText = lines[i],
-						measured = context.measureText(lineText);
-
-					info.width = Math.max(measured.width, info.width);
-					info.height += font.lineHeight;
-
-					info.lines.push({
-						text: lineText,
-						width: measured.width,
-						height: font.lineHeight
-					});
-				}
-
-				context.restore();
-			}
-
-			return info;
-		};
-
-		// Adds a text string to the canvas text overlay.
-
-		Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
-
-			if (!plot.getOptions().canvas) {
-				return addText.call(this, layer, x, y, text, font, angle, width, halign, valign);
-			}
-
-			var info = this.getTextInfo(layer, text, font, angle, width),
-				positions = info.positions,
-				lines = info.lines;
-
-			// Text is drawn with baseline 'middle', which we need to account
-			// for by adding half a line's height to the y position.
-
-			y += info.height / lines.length / 2;
-
-			// Tweak the initial y-position to match vertical alignment
-
-			if (valign == "middle") {
-				y = Math.round(y - info.height / 2);
-			} else if (valign == "bottom") {
-				y = Math.round(y - info.height);
-			} else {
-				y = Math.round(y);
-			}
-
-			// FIXME: LEGACY BROWSER FIX
-			// AFFECTS: Opera < 12.00
-
-			// Offset the y coordinate, since Opera is off pretty
-			// consistently compared to the other browsers.
-
-			if (!!(window.opera && window.opera.version().split(".")[0] < 12)) {
-				y -= 2;
-			}
-
-			// Determine whether this text already exists at this position.
-			// If so, mark it for inclusion in the next render pass.
-
-			for (var i = 0, position; position = positions[i]; i++) {
-				if (position.x == x && position.y == y) {
-					position.active = true;
-					return;
-				}
-			}
-
-			// If the text doesn't exist at this position, create a new entry
-
-			position = {
-				active: true,
-				lines: [],
-				x: x,
-				y: y
-			};
-
-			positions.push(position);
-
-			// Fill in the x & y positions of each line, adjusting them
-			// individually for horizontal alignment.
-
-			for (var i = 0, line; line = lines[i]; i++) {
-				if (halign == "center") {
-					position.lines.push([Math.round(x - line.width / 2), y]);
-				} else if (halign == "right") {
-					position.lines.push([Math.round(x - line.width), y]);
-				} else {
-					position.lines.push([Math.round(x), y]);
-				}
-				y += line.height;
-			}
-		};
-	}
-
-	$.plot.plugins.push({
-		init: init,
-		options: options,
-		name: "canvas",
-		version: "1.0"
-	});
-
-})(jQuery);
diff --git a/static/js/jquery.flot.canvas.min.js b/static/js/jquery.flot.canvas.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.canvas.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={canvas:true};var render,getTextInfo,addText;var hasOwnProperty=Object.prototype.hasOwnProperty;function init(plot,classes){var Canvas=classes.Canvas;if(render==null){getTextInfo=Canvas.prototype.getTextInfo,addText=Canvas.prototype.addText,render=Canvas.prototype.render}Canvas.prototype.render=function(){if(!plot.getOptions().canvas){return render.call(this)}var context=this.context,cache=this._textCache;context.save();context.textBaseline="middle";for(var layerKey in cache){if(hasOwnProperty.call(cache,layerKey)){var layerCache=cache[layerKey];for(var styleKey in layerCache){if(hasOwnProperty.call(layerCache,styleKey)){var styleCache=layerCache[styleKey],updateStyles=true;for(var key in styleCache){if(hasOwnProperty.call(styleCache,key)){var info=styleCache[key],positions=info.positions,lines=info.lines;if(updateStyles){context.fillStyle=info.font.color;context.font=info.font.definition;updateStyles=false}for(var i=0,position;position=positions[i];i++){if(position.active){for(var j=0,line;line=position.lines[j];j++){context.fillText(lines[j].text,line[0],line[1])}}else{positions.splice(i--,1)}}if(positions.length==0){delete styleCache[key]}}}}}}}context.restore()};Canvas.prototype.getTextInfo=function(layer,text,font,angle,width){if(!plot.getOptions().canvas){return getTextInfo.call(this,layer,text,font,angle,width)}var textStyle,layerCache,styleCache,info;text=""+text;if(typeof font==="object"){textStyle=font.style+" "+font.variant+" "+font.weight+" "+font.size+"px "+font.family}else{textStyle=font}layerCache=this._textCache[layer];if(layerCache==null){layerCache=this._textCache[layer]={}}styleCache=layerCache[textStyle];if(styleCache==null){styleCache=layerCache[textStyle]={}}info=styleCache[text];if(info==null){var context=this.context;if(typeof font!=="object"){var element=$("<div>&nbsp;</div>").css("position","absolute").addClass(typeof font==="string"?font:null).appendTo(this.getTextLayer(layer));font={lineHeight:element.height(),style:element.css("font-style"),variant:element.css("font-variant"),weight:element.css("font-weight"),family:element.css("font-family"),color:element.css("color")};font.size=element.css("line-height",1).height();element.remove()}textStyle=font.style+" "+font.variant+" "+font.weight+" "+font.size+"px "+font.family;info=styleCache[text]={width:0,height:0,positions:[],lines:[],font:{definition:textStyle,color:font.color}};context.save();context.font=textStyle;var lines=(text+"").replace(/<br ?\/?>|\r\n|\r/g,"\n").split("\n");for(var i=0;i<lines.length;++i){var lineText=lines[i],measured=context.measureText(lineText);info.width=Math.max(measured.width,info.width);info.height+=font.lineHeight;info.lines.push({text:lineText,width:measured.width,height:font.lineHeight})}context.restore()}return info};Canvas.prototype.addText=function(layer,x,y,text,font,angle,width,halign,valign){if(!plot.getOptions().canvas){return addText.call(this,layer,x,y,text,font,angle,width,halign,valign)}var info=this.getTextInfo(layer,text,font,angle,width),positions=info.positions,lines=info.lines;y+=info.height/lines.length/2;if(valign=="middle"){y=Math.round(y-info.height/2)}else if(valign=="bottom"){y=Math.round(y-info.height)}else{y=Math.round(y)}if(!!(window.opera&&window.opera.version().split(".")[0]<12)){y-=2}for(var i=0,position;position=positions[i];i++){if(position.x==x&&position.y==y){position.active=true;return}}position={active:true,lines:[],x:x,y:y};positions.push(position);for(var i=0,line;line=lines[i];i++){if(halign=="center"){position.lines.push([Math.round(x-line.width/2),y])}else if(halign=="right"){position.lines.push([Math.round(x-line.width),y])}else{position.lines.push([Math.round(x),y])}y+=line.height}}}$.plot.plugins.push({init:init,options:options,name:"canvas",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.categories.js b/static/js/jquery.flot.categories.js
deleted file mode 100644
--- a/static/js/jquery.flot.categories.js
+++ /dev/null
@@ -1,190 +0,0 @@
-/* Flot plugin for plotting textual data or categories.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-Consider a dataset like [["February", 34], ["March", 20], ...]. This plugin
-allows you to plot such a dataset directly.
-
-To enable it, you must specify mode: "categories" on the axis with the textual
-labels, e.g.
-
-	$.plot("#placeholder", data, { xaxis: { mode: "categories" } });
-
-By default, the labels are ordered as they are met in the data series. If you
-need a different ordering, you can specify "categories" on the axis options
-and list the categories there:
-
-	xaxis: {
-		mode: "categories",
-		categories: ["February", "March", "April"]
-	}
-
-If you need to customize the distances between the categories, you can specify
-"categories" as an object mapping labels to values
-
-	xaxis: {
-		mode: "categories",
-		categories: { "February": 1, "March": 3, "April": 4 }
-	}
-
-If you don't specify all categories, the remaining categories will be numbered
-from the max value plus 1 (with a spacing of 1 between each).
-
-Internally, the plugin works by transforming the input data through an auto-
-generated mapping where the first category becomes 0, the second 1, etc.
-Hence, a point like ["February", 34] becomes [0, 34] internally in Flot (this
-is visible in hover and click events that return numbers rather than the
-category labels). The plugin also overrides the tick generator to spit out the
-categories as ticks instead of the values.
-
-If you need to map a value back to its label, the mapping is always accessible
-as "categories" on the axis object, e.g. plot.getAxes().xaxis.categories.
-
-*/
-
-(function ($) {
-    var options = {
-        xaxis: {
-            categories: null
-        },
-        yaxis: {
-            categories: null
-        }
-    };
-    
-    function processRawData(plot, series, data, datapoints) {
-        // if categories are enabled, we need to disable
-        // auto-transformation to numbers so the strings are intact
-        // for later processing
-
-        var xCategories = series.xaxis.options.mode == "categories",
-            yCategories = series.yaxis.options.mode == "categories";
-        
-        if (!(xCategories || yCategories))
-            return;
-
-        var format = datapoints.format;
-
-        if (!format) {
-            // FIXME: auto-detection should really not be defined here
-            var s = series;
-            format = [];
-            format.push({ x: true, number: true, required: true });
-            format.push({ y: true, number: true, required: true });
-
-            if (s.bars.show || (s.lines.show && s.lines.fill)) {
-                var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
-                format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
-                if (s.bars.horizontal) {
-                    delete format[format.length - 1].y;
-                    format[format.length - 1].x = true;
-                }
-            }
-            
-            datapoints.format = format;
-        }
-
-        for (var m = 0; m < format.length; ++m) {
-            if (format[m].x && xCategories)
-                format[m].number = false;
-            
-            if (format[m].y && yCategories)
-                format[m].number = false;
-        }
-    }
-
-    function getNextIndex(categories) {
-        var index = -1;
-        
-        for (var v in categories)
-            if (categories[v] > index)
-                index = categories[v];
-
-        return index + 1;
-    }
-
-    function categoriesTickGenerator(axis) {
-        var res = [];
-        for (var label in axis.categories) {
-            var v = axis.categories[label];
-            if (v >= axis.min && v <= axis.max)
-                res.push([v, label]);
-        }
-
-        res.sort(function (a, b) { return a[0] - b[0]; });
-
-        return res;
-    }
-    
-    function setupCategoriesForAxis(series, axis, datapoints) {
-        if (series[axis].options.mode != "categories")
-            return;
-        
-        if (!series[axis].categories) {
-            // parse options
-            var c = {}, o = series[axis].options.categories || {};
-            if ($.isArray(o)) {
-                for (var i = 0; i < o.length; ++i)
-                    c[o[i]] = i;
-            }
-            else {
-                for (var v in o)
-                    c[v] = o[v];
-            }
-            
-            series[axis].categories = c;
-        }
-
-        // fix ticks
-        if (!series[axis].options.ticks)
-            series[axis].options.ticks = categoriesTickGenerator;
-
-        transformPointsOnAxis(datapoints, axis, series[axis].categories);
-    }
-    
-    function transformPointsOnAxis(datapoints, axis, categories) {
-        // go through the points, transforming them
-        var points = datapoints.points,
-            ps = datapoints.pointsize,
-            format = datapoints.format,
-            formatColumn = axis.charAt(0),
-            index = getNextIndex(categories);
-
-        for (var i = 0; i < points.length; i += ps) {
-            if (points[i] == null)
-                continue;
-            
-            for (var m = 0; m < ps; ++m) {
-                var val = points[i + m];
-
-                if (val == null || !format[m][formatColumn])
-                    continue;
-
-                if (!(val in categories)) {
-                    categories[val] = index;
-                    ++index;
-                }
-                
-                points[i + m] = categories[val];
-            }
-        }
-    }
-
-    function processDatapoints(plot, series, datapoints) {
-        setupCategoriesForAxis(series, "xaxis", datapoints);
-        setupCategoriesForAxis(series, "yaxis", datapoints);
-    }
-
-    function init(plot) {
-        plot.hooks.processRawData.push(processRawData);
-        plot.hooks.processDatapoints.push(processDatapoints);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'categories',
-        version: '1.0'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.categories.min.js b/static/js/jquery.flot.categories.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.categories.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={xaxis:{categories:null},yaxis:{categories:null}};function processRawData(plot,series,data,datapoints){var xCategories=series.xaxis.options.mode=="categories",yCategories=series.yaxis.options.mode=="categories";if(!(xCategories||yCategories))return;var format=datapoints.format;if(!format){var s=series;format=[];format.push({x:true,number:true,required:true});format.push({y:true,number:true,required:true});if(s.bars.show||s.lines.show&&s.lines.fill){var autoscale=!!(s.bars.show&&s.bars.zero||s.lines.show&&s.lines.zero);format.push({y:true,number:true,required:false,defaultValue:0,autoscale:autoscale});if(s.bars.horizontal){delete format[format.length-1].y;format[format.length-1].x=true}}datapoints.format=format}for(var m=0;m<format.length;++m){if(format[m].x&&xCategories)format[m].number=false;if(format[m].y&&yCategories)format[m].number=false}}function getNextIndex(categories){var index=-1;for(var v in categories)if(categories[v]>index)index=categories[v];return index+1}function categoriesTickGenerator(axis){var res=[];for(var label in axis.categories){var v=axis.categories[label];if(v>=axis.min&&v<=axis.max)res.push([v,label])}res.sort(function(a,b){return a[0]-b[0]});return res}function setupCategoriesForAxis(series,axis,datapoints){if(series[axis].options.mode!="categories")return;if(!series[axis].categories){var c={},o=series[axis].options.categories||{};if($.isArray(o)){for(var i=0;i<o.length;++i)c[o[i]]=i}else{for(var v in o)c[v]=o[v]}series[axis].categories=c}if(!series[axis].options.ticks)series[axis].options.ticks=categoriesTickGenerator;transformPointsOnAxis(datapoints,axis,series[axis].categories)}function transformPointsOnAxis(datapoints,axis,categories){var points=datapoints.points,ps=datapoints.pointsize,format=datapoints.format,formatColumn=axis.charAt(0),index=getNextIndex(categories);for(var i=0;i<points.length;i+=ps){if(points[i]==null)continue;for(var m=0;m<ps;++m){var val=points[i+m];if(val==null||!format[m][formatColumn])continue;if(!(val in categories)){categories[val]=index;++index}points[i+m]=categories[val]}}}function processDatapoints(plot,series,datapoints){setupCategoriesForAxis(series,"xaxis",datapoints);setupCategoriesForAxis(series,"yaxis",datapoints)}function init(plot){plot.hooks.processRawData.push(processRawData);plot.hooks.processDatapoints.push(processDatapoints)}$.plot.plugins.push({init:init,options:options,name:"categories",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.crosshair.js b/static/js/jquery.flot.crosshair.js
deleted file mode 100644
--- a/static/js/jquery.flot.crosshair.js
+++ /dev/null
@@ -1,176 +0,0 @@
-/* Flot plugin for showing crosshairs when the mouse hovers over the plot.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The plugin supports these options:
-
-	crosshair: {
-		mode: null or "x" or "y" or "xy"
-		color: color
-		lineWidth: number
-	}
-
-Set the mode to one of "x", "y" or "xy". The "x" mode enables a vertical
-crosshair that lets you trace the values on the x axis, "y" enables a
-horizontal crosshair and "xy" enables them both. "color" is the color of the
-crosshair (default is "rgba(170, 0, 0, 0.80)"), "lineWidth" is the width of
-the drawn lines (default is 1).
-
-The plugin also adds four public methods:
-
-  - setCrosshair( pos )
-
-    Set the position of the crosshair. Note that this is cleared if the user
-    moves the mouse. "pos" is in coordinates of the plot and should be on the
-    form { x: xpos, y: ypos } (you can use x2/x3/... if you're using multiple
-    axes), which is coincidentally the same format as what you get from a
-    "plothover" event. If "pos" is null, the crosshair is cleared.
-
-  - clearCrosshair()
-
-    Clear the crosshair.
-
-  - lockCrosshair(pos)
-
-    Cause the crosshair to lock to the current location, no longer updating if
-    the user moves the mouse. Optionally supply a position (passed on to
-    setCrosshair()) to move it to.
-
-    Example usage:
-
-	var myFlot = $.plot( $("#graph"), ..., { crosshair: { mode: "x" } } };
-	$("#graph").bind( "plothover", function ( evt, position, item ) {
-		if ( item ) {
-			// Lock the crosshair to the data point being hovered
-			myFlot.lockCrosshair({
-				x: item.datapoint[ 0 ],
-				y: item.datapoint[ 1 ]
-			});
-		} else {
-			// Return normal crosshair operation
-			myFlot.unlockCrosshair();
-		}
-	});
-
-  - unlockCrosshair()
-
-    Free the crosshair to move again after locking it.
-*/
-
-(function ($) {
-    var options = {
-        crosshair: {
-            mode: null, // one of null, "x", "y" or "xy",
-            color: "rgba(170, 0, 0, 0.80)",
-            lineWidth: 1
-        }
-    };
-    
-    function init(plot) {
-        // position of crosshair in pixels
-        var crosshair = { x: -1, y: -1, locked: false };
-
-        plot.setCrosshair = function setCrosshair(pos) {
-            if (!pos)
-                crosshair.x = -1;
-            else {
-                var o = plot.p2c(pos);
-                crosshair.x = Math.max(0, Math.min(o.left, plot.width()));
-                crosshair.y = Math.max(0, Math.min(o.top, plot.height()));
-            }
-            
-            plot.triggerRedrawOverlay();
-        };
-        
-        plot.clearCrosshair = plot.setCrosshair; // passes null for pos
-        
-        plot.lockCrosshair = function lockCrosshair(pos) {
-            if (pos)
-                plot.setCrosshair(pos);
-            crosshair.locked = true;
-        };
-
-        plot.unlockCrosshair = function unlockCrosshair() {
-            crosshair.locked = false;
-        };
-
-        function onMouseOut(e) {
-            if (crosshair.locked)
-                return;
-
-            if (crosshair.x != -1) {
-                crosshair.x = -1;
-                plot.triggerRedrawOverlay();
-            }
-        }
-
-        function onMouseMove(e) {
-            if (crosshair.locked)
-                return;
-                
-            if (plot.getSelection && plot.getSelection()) {
-                crosshair.x = -1; // hide the crosshair while selecting
-                return;
-            }
-                
-            var offset = plot.offset();
-            crosshair.x = Math.max(0, Math.min(e.pageX - offset.left, plot.width()));
-            crosshair.y = Math.max(0, Math.min(e.pageY - offset.top, plot.height()));
-            plot.triggerRedrawOverlay();
-        }
-        
-        plot.hooks.bindEvents.push(function (plot, eventHolder) {
-            if (!plot.getOptions().crosshair.mode)
-                return;
-
-            eventHolder.mouseout(onMouseOut);
-            eventHolder.mousemove(onMouseMove);
-        });
-
-        plot.hooks.drawOverlay.push(function (plot, ctx) {
-            var c = plot.getOptions().crosshair;
-            if (!c.mode)
-                return;
-
-            var plotOffset = plot.getPlotOffset();
-            
-            ctx.save();
-            ctx.translate(plotOffset.left, plotOffset.top);
-
-            if (crosshair.x != -1) {
-                var adj = plot.getOptions().crosshair.lineWidth % 2 ? 0.5 : 0;
-
-                ctx.strokeStyle = c.color;
-                ctx.lineWidth = c.lineWidth;
-                ctx.lineJoin = "round";
-
-                ctx.beginPath();
-                if (c.mode.indexOf("x") != -1) {
-                    var drawX = Math.floor(crosshair.x) + adj;
-                    ctx.moveTo(drawX, 0);
-                    ctx.lineTo(drawX, plot.height());
-                }
-                if (c.mode.indexOf("y") != -1) {
-                    var drawY = Math.floor(crosshair.y) + adj;
-                    ctx.moveTo(0, drawY);
-                    ctx.lineTo(plot.width(), drawY);
-                }
-                ctx.stroke();
-            }
-            ctx.restore();
-        });
-
-        plot.hooks.shutdown.push(function (plot, eventHolder) {
-            eventHolder.unbind("mouseout", onMouseOut);
-            eventHolder.unbind("mousemove", onMouseMove);
-        });
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'crosshair',
-        version: '1.0'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.crosshair.min.js b/static/js/jquery.flot.crosshair.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.crosshair.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={crosshair:{mode:null,color:"rgba(170, 0, 0, 0.80)",lineWidth:1}};function init(plot){var crosshair={x:-1,y:-1,locked:false};plot.setCrosshair=function setCrosshair(pos){if(!pos)crosshair.x=-1;else{var o=plot.p2c(pos);crosshair.x=Math.max(0,Math.min(o.left,plot.width()));crosshair.y=Math.max(0,Math.min(o.top,plot.height()))}plot.triggerRedrawOverlay()};plot.clearCrosshair=plot.setCrosshair;plot.lockCrosshair=function lockCrosshair(pos){if(pos)plot.setCrosshair(pos);crosshair.locked=true};plot.unlockCrosshair=function unlockCrosshair(){crosshair.locked=false};function onMouseOut(e){if(crosshair.locked)return;if(crosshair.x!=-1){crosshair.x=-1;plot.triggerRedrawOverlay()}}function onMouseMove(e){if(crosshair.locked)return;if(plot.getSelection&&plot.getSelection()){crosshair.x=-1;return}var offset=plot.offset();crosshair.x=Math.max(0,Math.min(e.pageX-offset.left,plot.width()));crosshair.y=Math.max(0,Math.min(e.pageY-offset.top,plot.height()));plot.triggerRedrawOverlay()}plot.hooks.bindEvents.push(function(plot,eventHolder){if(!plot.getOptions().crosshair.mode)return;eventHolder.mouseout(onMouseOut);eventHolder.mousemove(onMouseMove)});plot.hooks.drawOverlay.push(function(plot,ctx){var c=plot.getOptions().crosshair;if(!c.mode)return;var plotOffset=plot.getPlotOffset();ctx.save();ctx.translate(plotOffset.left,plotOffset.top);if(crosshair.x!=-1){var adj=plot.getOptions().crosshair.lineWidth%2?.5:0;ctx.strokeStyle=c.color;ctx.lineWidth=c.lineWidth;ctx.lineJoin="round";ctx.beginPath();if(c.mode.indexOf("x")!=-1){var drawX=Math.floor(crosshair.x)+adj;ctx.moveTo(drawX,0);ctx.lineTo(drawX,plot.height())}if(c.mode.indexOf("y")!=-1){var drawY=Math.floor(crosshair.y)+adj;ctx.moveTo(0,drawY);ctx.lineTo(plot.width(),drawY)}ctx.stroke()}ctx.restore()});plot.hooks.shutdown.push(function(plot,eventHolder){eventHolder.unbind("mouseout",onMouseOut);eventHolder.unbind("mousemove",onMouseMove)})}$.plot.plugins.push({init:init,options:options,name:"crosshair",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.errorbars.js b/static/js/jquery.flot.errorbars.js
deleted file mode 100644
--- a/static/js/jquery.flot.errorbars.js
+++ /dev/null
@@ -1,353 +0,0 @@
-/* Flot plugin for plotting error bars.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-Error bars are used to show standard deviation and other statistical
-properties in a plot.
-
-* Created by Rui Pereira  -  rui (dot) pereira (at) gmail (dot) com
-
-This plugin allows you to plot error-bars over points. Set "errorbars" inside
-the points series to the axis name over which there will be error values in
-your data array (*even* if you do not intend to plot them later, by setting
-"show: null" on xerr/yerr).
-
-The plugin supports these options:
-
-	series: {
-		points: {
-			errorbars: "x" or "y" or "xy",
-			xerr: {
-				show: null/false or true,
-				asymmetric: null/false or true,
-				upperCap: null or "-" or function,
-				lowerCap: null or "-" or function,
-				color: null or color,
-				radius: null or number
-			},
-			yerr: { same options as xerr }
-		}
-	}
-
-Each data point array is expected to be of the type:
-
-	"x"  [ x, y, xerr ]
-	"y"  [ x, y, yerr ]
-	"xy" [ x, y, xerr, yerr ]
-
-Where xerr becomes xerr_lower,xerr_upper for the asymmetric error case, and
-equivalently for yerr. Eg., a datapoint for the "xy" case with symmetric
-error-bars on X and asymmetric on Y would be:
-
-	[ x, y, xerr, yerr_lower, yerr_upper ]
-
-By default no end caps are drawn. Setting upperCap and/or lowerCap to "-" will
-draw a small cap perpendicular to the error bar. They can also be set to a
-user-defined drawing function, with (ctx, x, y, radius) as parameters, as eg.
-
-	function drawSemiCircle( ctx, x, y, radius ) {
-		ctx.beginPath();
-		ctx.arc( x, y, radius, 0, Math.PI, false );
-		ctx.moveTo( x - radius, y );
-		ctx.lineTo( x + radius, y );
-		ctx.stroke();
-	}
-
-Color and radius both default to the same ones of the points series if not
-set. The independent radius parameter on xerr/yerr is useful for the case when
-we may want to add error-bars to a line, without showing the interconnecting
-points (with radius: 0), and still showing end caps on the error-bars.
-shadowSize and lineWidth are derived as well from the points series.
-
-*/
-
-(function ($) {
-    var options = {
-        series: {
-            points: {
-                errorbars: null, //should be 'x', 'y' or 'xy'
-                xerr: { err: 'x', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null},
-                yerr: { err: 'y', show: null, asymmetric: null, upperCap: null, lowerCap: null, color: null, radius: null}
-            }
-        }
-    };
-
-    function processRawData(plot, series, data, datapoints){
-        if (!series.points.errorbars)
-            return;
-
-        // x,y values
-        var format = [
-            { x: true, number: true, required: true },
-            { y: true, number: true, required: true }
-        ];
-
-        var errors = series.points.errorbars;
-        // error bars - first X then Y
-        if (errors == 'x' || errors == 'xy') {
-            // lower / upper error
-            if (series.points.xerr.asymmetric) {
-                format.push({ x: true, number: true, required: true });
-                format.push({ x: true, number: true, required: true });
-            } else
-                format.push({ x: true, number: true, required: true });
-        }
-        if (errors == 'y' || errors == 'xy') {
-            // lower / upper error
-            if (series.points.yerr.asymmetric) {
-                format.push({ y: true, number: true, required: true });
-                format.push({ y: true, number: true, required: true });
-            } else
-                format.push({ y: true, number: true, required: true });
-        }
-        datapoints.format = format;
-    }
-
-    function parseErrors(series, i){
-
-        var points = series.datapoints.points;
-
-        // read errors from points array
-        var exl = null,
-                exu = null,
-                eyl = null,
-                eyu = null;
-        var xerr = series.points.xerr,
-                yerr = series.points.yerr;
-
-        var eb = series.points.errorbars;
-        // error bars - first X
-        if (eb == 'x' || eb == 'xy') {
-            if (xerr.asymmetric) {
-                exl = points[i + 2];
-                exu = points[i + 3];
-                if (eb == 'xy')
-                    if (yerr.asymmetric){
-                        eyl = points[i + 4];
-                        eyu = points[i + 5];
-                    } else eyl = points[i + 4];
-            } else {
-                exl = points[i + 2];
-                if (eb == 'xy')
-                    if (yerr.asymmetric) {
-                        eyl = points[i + 3];
-                        eyu = points[i + 4];
-                    } else eyl = points[i + 3];
-            }
-        // only Y
-        } else if (eb == 'y')
-            if (yerr.asymmetric) {
-                eyl = points[i + 2];
-                eyu = points[i + 3];
-            } else eyl = points[i + 2];
-
-        // symmetric errors?
-        if (exu == null) exu = exl;
-        if (eyu == null) eyu = eyl;
-
-        var errRanges = [exl, exu, eyl, eyu];
-        // nullify if not showing
-        if (!xerr.show){
-            errRanges[0] = null;
-            errRanges[1] = null;
-        }
-        if (!yerr.show){
-            errRanges[2] = null;
-            errRanges[3] = null;
-        }
-        return errRanges;
-    }
-
-    function drawSeriesErrors(plot, ctx, s){
-
-        var points = s.datapoints.points,
-                ps = s.datapoints.pointsize,
-                ax = [s.xaxis, s.yaxis],
-                radius = s.points.radius,
-                err = [s.points.xerr, s.points.yerr];
-
-        //sanity check, in case some inverted axis hack is applied to flot
-        var invertX = false;
-        if (ax[0].p2c(ax[0].max) < ax[0].p2c(ax[0].min)) {
-            invertX = true;
-            var tmp = err[0].lowerCap;
-            err[0].lowerCap = err[0].upperCap;
-            err[0].upperCap = tmp;
-        }
-
-        var invertY = false;
-        if (ax[1].p2c(ax[1].min) < ax[1].p2c(ax[1].max)) {
-            invertY = true;
-            var tmp = err[1].lowerCap;
-            err[1].lowerCap = err[1].upperCap;
-            err[1].upperCap = tmp;
-        }
-
-        for (var i = 0; i < s.datapoints.points.length; i += ps) {
-
-            //parse
-            var errRanges = parseErrors(s, i);
-
-            //cycle xerr & yerr
-            for (var e = 0; e < err.length; e++){
-
-                var minmax = [ax[e].min, ax[e].max];
-
-                //draw this error?
-                if (errRanges[e * err.length]){
-
-                    //data coordinates
-                    var x = points[i],
-                        y = points[i + 1];
-
-                    //errorbar ranges
-                    var upper = [x, y][e] + errRanges[e * err.length + 1],
-                        lower = [x, y][e] - errRanges[e * err.length];
-
-                    //points outside of the canvas
-                    if (err[e].err == 'x')
-                        if (y > ax[1].max || y < ax[1].min || upper < ax[0].min || lower > ax[0].max)
-                            continue;
-                    if (err[e].err == 'y')
-                        if (x > ax[0].max || x < ax[0].min || upper < ax[1].min || lower > ax[1].max)
-                            continue;
-
-                    // prevent errorbars getting out of the canvas
-                    var drawUpper = true,
-                        drawLower = true;
-
-                    if (upper > minmax[1]) {
-                        drawUpper = false;
-                        upper = minmax[1];
-                    }
-                    if (lower < minmax[0]) {
-                        drawLower = false;
-                        lower = minmax[0];
-                    }
-
-                    //sanity check, in case some inverted axis hack is applied to flot
-                    if ((err[e].err == 'x' && invertX) || (err[e].err == 'y' && invertY)) {
-                        //swap coordinates
-                        var tmp = lower;
-                        lower = upper;
-                        upper = tmp;
-                        tmp = drawLower;
-                        drawLower = drawUpper;
-                        drawUpper = tmp;
-                        tmp = minmax[0];
-                        minmax[0] = minmax[1];
-                        minmax[1] = tmp;
-                    }
-
-                    // convert to pixels
-                    x = ax[0].p2c(x),
-                        y = ax[1].p2c(y),
-                        upper = ax[e].p2c(upper);
-                    lower = ax[e].p2c(lower);
-                    minmax[0] = ax[e].p2c(minmax[0]);
-                    minmax[1] = ax[e].p2c(minmax[1]);
-
-                    //same style as points by default
-                    var lw = err[e].lineWidth ? err[e].lineWidth : s.points.lineWidth,
-                        sw = s.points.shadowSize != null ? s.points.shadowSize : s.shadowSize;
-
-                    //shadow as for points
-                    if (lw > 0 && sw > 0) {
-                        var w = sw / 2;
-                        ctx.lineWidth = w;
-                        ctx.strokeStyle = "rgba(0,0,0,0.1)";
-                        drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w + w/2, minmax);
-
-                        ctx.strokeStyle = "rgba(0,0,0,0.2)";
-                        drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, w/2, minmax);
-                    }
-
-                    ctx.strokeStyle = err[e].color? err[e].color: s.color;
-                    ctx.lineWidth = lw;
-                    //draw it
-                    drawError(ctx, err[e], x, y, upper, lower, drawUpper, drawLower, radius, 0, minmax);
-                }
-            }
-        }
-    }
-
-    function drawError(ctx,err,x,y,upper,lower,drawUpper,drawLower,radius,offset,minmax){
-
-        //shadow offset
-        y += offset;
-        upper += offset;
-        lower += offset;
-
-        // error bar - avoid plotting over circles
-        if (err.err == 'x'){
-            if (upper > x + radius) drawPath(ctx, [[upper,y],[Math.max(x + radius,minmax[0]),y]]);
-            else drawUpper = false;
-            if (lower < x - radius) drawPath(ctx, [[Math.min(x - radius,minmax[1]),y],[lower,y]] );
-            else drawLower = false;
-        }
-        else {
-            if (upper < y - radius) drawPath(ctx, [[x,upper],[x,Math.min(y - radius,minmax[0])]] );
-            else drawUpper = false;
-            if (lower > y + radius) drawPath(ctx, [[x,Math.max(y + radius,minmax[1])],[x,lower]] );
-            else drawLower = false;
-        }
-
-        //internal radius value in errorbar, allows to plot radius 0 points and still keep proper sized caps
-        //this is a way to get errorbars on lines without visible connecting dots
-        radius = err.radius != null? err.radius: radius;
-
-        // upper cap
-        if (drawUpper) {
-            if (err.upperCap == '-'){
-                if (err.err=='x') drawPath(ctx, [[upper,y - radius],[upper,y + radius]] );
-                else drawPath(ctx, [[x - radius,upper],[x + radius,upper]] );
-            } else if ($.isFunction(err.upperCap)){
-                if (err.err=='x') err.upperCap(ctx, upper, y, radius);
-                else err.upperCap(ctx, x, upper, radius);
-            }
-        }
-        // lower cap
-        if (drawLower) {
-            if (err.lowerCap == '-'){
-                if (err.err=='x') drawPath(ctx, [[lower,y - radius],[lower,y + radius]] );
-                else drawPath(ctx, [[x - radius,lower],[x + radius,lower]] );
-            } else if ($.isFunction(err.lowerCap)){
-                if (err.err=='x') err.lowerCap(ctx, lower, y, radius);
-                else err.lowerCap(ctx, x, lower, radius);
-            }
-        }
-    }
-
-    function drawPath(ctx, pts){
-        ctx.beginPath();
-        ctx.moveTo(pts[0][0], pts[0][1]);
-        for (var p=1; p < pts.length; p++)
-            ctx.lineTo(pts[p][0], pts[p][1]);
-        ctx.stroke();
-    }
-
-    function draw(plot, ctx){
-        var plotOffset = plot.getPlotOffset();
-
-        ctx.save();
-        ctx.translate(plotOffset.left, plotOffset.top);
-        $.each(plot.getData(), function (i, s) {
-            if (s.points.errorbars && (s.points.xerr.show || s.points.yerr.show))
-                drawSeriesErrors(plot, ctx, s);
-        });
-        ctx.restore();
-    }
-
-    function init(plot) {
-        plot.hooks.processRawData.push(processRawData);
-        plot.hooks.draw.push(draw);
-    }
-
-    $.plot.plugins.push({
-                init: init,
-                options: options,
-                name: 'errorbars',
-                version: '1.0'
-            });
-})(jQuery);
diff --git a/static/js/jquery.flot.errorbars.min.js b/static/js/jquery.flot.errorbars.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.errorbars.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={series:{points:{errorbars:null,xerr:{err:"x",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null},yerr:{err:"y",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null}}}};function processRawData(plot,series,data,datapoints){if(!series.points.errorbars)return;var format=[{x:true,number:true,required:true},{y:true,number:true,required:true}];var errors=series.points.errorbars;if(errors=="x"||errors=="xy"){if(series.points.xerr.asymmetric){format.push({x:true,number:true,required:true});format.push({x:true,number:true,required:true})}else format.push({x:true,number:true,required:true})}if(errors=="y"||errors=="xy"){if(series.points.yerr.asymmetric){format.push({y:true,number:true,required:true});format.push({y:true,number:true,required:true})}else format.push({y:true,number:true,required:true})}datapoints.format=format}function parseErrors(series,i){var points=series.datapoints.points;var exl=null,exu=null,eyl=null,eyu=null;var xerr=series.points.xerr,yerr=series.points.yerr;var eb=series.points.errorbars;if(eb=="x"||eb=="xy"){if(xerr.asymmetric){exl=points[i+2];exu=points[i+3];if(eb=="xy")if(yerr.asymmetric){eyl=points[i+4];eyu=points[i+5]}else eyl=points[i+4]}else{exl=points[i+2];if(eb=="xy")if(yerr.asymmetric){eyl=points[i+3];eyu=points[i+4]}else eyl=points[i+3]}}else if(eb=="y")if(yerr.asymmetric){eyl=points[i+2];eyu=points[i+3]}else eyl=points[i+2];if(exu==null)exu=exl;if(eyu==null)eyu=eyl;var errRanges=[exl,exu,eyl,eyu];if(!xerr.show){errRanges[0]=null;errRanges[1]=null}if(!yerr.show){errRanges[2]=null;errRanges[3]=null}return errRanges}function drawSeriesErrors(plot,ctx,s){var points=s.datapoints.points,ps=s.datapoints.pointsize,ax=[s.xaxis,s.yaxis],radius=s.points.radius,err=[s.points.xerr,s.points.yerr];var invertX=false;if(ax[0].p2c(ax[0].max)<ax[0].p2c(ax[0].min)){invertX=true;var tmp=err[0].lowerCap;err[0].lowerCap=err[0].upperCap;err[0].upperCap=tmp}var invertY=false;if(ax[1].p2c(ax[1].min)<ax[1].p2c(ax[1].max)){invertY=true;var tmp=err[1].lowerCap;err[1].lowerCap=err[1].upperCap;err[1].upperCap=tmp}for(var i=0;i<s.datapoints.points.length;i+=ps){var errRanges=parseErrors(s,i);for(var e=0;e<err.length;e++){var minmax=[ax[e].min,ax[e].max];if(errRanges[e*err.length]){var x=points[i],y=points[i+1];var upper=[x,y][e]+errRanges[e*err.length+1],lower=[x,y][e]-errRanges[e*err.length];if(err[e].err=="x")if(y>ax[1].max||y<ax[1].min||upper<ax[0].min||lower>ax[0].max)continue;if(err[e].err=="y")if(x>ax[0].max||x<ax[0].min||upper<ax[1].min||lower>ax[1].max)continue;var drawUpper=true,drawLower=true;if(upper>minmax[1]){drawUpper=false;upper=minmax[1]}if(lower<minmax[0]){drawLower=false;lower=minmax[0]}if(err[e].err=="x"&&invertX||err[e].err=="y"&&invertY){var tmp=lower;lower=upper;upper=tmp;tmp=drawLower;drawLower=drawUpper;drawUpper=tmp;tmp=minmax[0];minmax[0]=minmax[1];minmax[1]=tmp}x=ax[0].p2c(x),y=ax[1].p2c(y),upper=ax[e].p2c(upper);lower=ax[e].p2c(lower);minmax[0]=ax[e].p2c(minmax[0]);minmax[1]=ax[e].p2c(minmax[1]);var lw=err[e].lineWidth?err[e].lineWidth:s.points.lineWidth,sw=s.points.shadowSize!=null?s.points.shadowSize:s.shadowSize;if(lw>0&&sw>0){var w=sw/2;ctx.lineWidth=w;ctx.strokeStyle="rgba(0,0,0,0.1)";drawError(ctx,err[e],x,y,upper,lower,drawUpper,drawLower,radius,w+w/2,minmax);ctx.strokeStyle="rgba(0,0,0,0.2)";drawError(ctx,err[e],x,y,upper,lower,drawUpper,drawLower,radius,w/2,minmax)}ctx.strokeStyle=err[e].color?err[e].color:s.color;ctx.lineWidth=lw;drawError(ctx,err[e],x,y,upper,lower,drawUpper,drawLower,radius,0,minmax)}}}}function drawError(ctx,err,x,y,upper,lower,drawUpper,drawLower,radius,offset,minmax){y+=offset;upper+=offset;lower+=offset;if(err.err=="x"){if(upper>x+radius)drawPath(ctx,[[upper,y],[Math.max(x+radius,minmax[0]),y]]);else drawUpper=false;if(lower<x-radius)drawPath(ctx,[[Math.min(x-radius,minmax[1]),y],[lower,y]]);else drawLower=false}else{if(upper<y-radius)drawPath(ctx,[[x,upper],[x,Math.min(y-radius,minmax[0])]]);else drawUpper=false;if(lower>y+radius)drawPath(ctx,[[x,Math.max(y+radius,minmax[1])],[x,lower]]);else drawLower=false}radius=err.radius!=null?err.radius:radius;if(drawUpper){if(err.upperCap=="-"){if(err.err=="x")drawPath(ctx,[[upper,y-radius],[upper,y+radius]]);else drawPath(ctx,[[x-radius,upper],[x+radius,upper]])}else if($.isFunction(err.upperCap)){if(err.err=="x")err.upperCap(ctx,upper,y,radius);else err.upperCap(ctx,x,upper,radius)}}if(drawLower){if(err.lowerCap=="-"){if(err.err=="x")drawPath(ctx,[[lower,y-radius],[lower,y+radius]]);else drawPath(ctx,[[x-radius,lower],[x+radius,lower]])}else if($.isFunction(err.lowerCap)){if(err.err=="x")err.lowerCap(ctx,lower,y,radius);else err.lowerCap(ctx,x,lower,radius)}}}function drawPath(ctx,pts){ctx.beginPath();ctx.moveTo(pts[0][0],pts[0][1]);for(var p=1;p<pts.length;p++)ctx.lineTo(pts[p][0],pts[p][1]);ctx.stroke()}function draw(plot,ctx){var plotOffset=plot.getPlotOffset();ctx.save();ctx.translate(plotOffset.left,plotOffset.top);$.each(plot.getData(),function(i,s){if(s.points.errorbars&&(s.points.xerr.show||s.points.yerr.show))drawSeriesErrors(plot,ctx,s)});ctx.restore()}function init(plot){plot.hooks.processRawData.push(processRawData);plot.hooks.draw.push(draw)}$.plot.plugins.push({init:init,options:options,name:"errorbars",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.fillbetween.js b/static/js/jquery.flot.fillbetween.js
deleted file mode 100644
--- a/static/js/jquery.flot.fillbetween.js
+++ /dev/null
@@ -1,226 +0,0 @@
-/* Flot plugin for computing bottoms for filled line and bar charts.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The case: you've got two series that you want to fill the area between. In Flot
-terms, you need to use one as the fill bottom of the other. You can specify the
-bottom of each data point as the third coordinate manually, or you can use this
-plugin to compute it for you.
-
-In order to name the other series, you need to give it an id, like this:
-
-	var dataset = [
-		{ data: [ ... ], id: "foo" } ,         // use default bottom
-		{ data: [ ... ], fillBetween: "foo" }, // use first dataset as bottom
-	];
-
-	$.plot($("#placeholder"), dataset, { lines: { show: true, fill: true }});
-
-As a convenience, if the id given is a number that doesn't appear as an id in
-the series, it is interpreted as the index in the array instead (so fillBetween:
-0 can also mean the first series).
-
-Internally, the plugin modifies the datapoints in each series. For line series,
-extra data points might be inserted through interpolation. Note that at points
-where the bottom line is not defined (due to a null point or start/end of line),
-the current line will show a gap too. The algorithm comes from the
-jquery.flot.stack.js plugin, possibly some code could be shared.
-
-*/
-
-(function ( $ ) {
-
-	var options = {
-		series: {
-			fillBetween: null	// or number
-		}
-	};
-
-	function init( plot ) {
-
-		function findBottomSeries( s, allseries ) {
-
-			var i;
-
-			for ( i = 0; i < allseries.length; ++i ) {
-				if ( allseries[ i ].id === s.fillBetween ) {
-					return allseries[ i ];
-				}
-			}
-
-			if ( typeof s.fillBetween === "number" ) {
-				if ( s.fillBetween < 0 || s.fillBetween >= allseries.length ) {
-					return null;
-				}
-				return allseries[ s.fillBetween ];
-			}
-
-			return null;
-		}
-
-		function computeFillBottoms( plot, s, datapoints ) {
-
-			if ( s.fillBetween == null ) {
-				return;
-			}
-
-			var other = findBottomSeries( s, plot.getData() );
-
-			if ( !other ) {
-				return;
-			}
-
-			var ps = datapoints.pointsize,
-				points = datapoints.points,
-				otherps = other.datapoints.pointsize,
-				otherpoints = other.datapoints.points,
-				newpoints = [],
-				px, py, intery, qx, qy, bottom,
-				withlines = s.lines.show,
-				withbottom = ps > 2 && datapoints.format[2].y,
-				withsteps = withlines && s.lines.steps,
-				fromgap = true,
-				i = 0,
-				j = 0,
-				l, m;
-
-			while ( true ) {
-
-				if ( i >= points.length ) {
-					break;
-				}
-
-				l = newpoints.length;
-
-				if ( points[ i ] == null ) {
-
-					// copy gaps
-
-					for ( m = 0; m < ps; ++m ) {
-						newpoints.push( points[ i + m ] );
-					}
-
-					i += ps;
-
-				} else if ( j >= otherpoints.length ) {
-
-					// for lines, we can't use the rest of the points
-
-					if ( !withlines ) {
-						for ( m = 0; m < ps; ++m ) {
-							newpoints.push( points[ i + m ] );
-						}
-					}
-
-					i += ps;
-
-				} else if ( otherpoints[ j ] == null ) {
-
-					// oops, got a gap
-
-					for ( m = 0; m < ps; ++m ) {
-						newpoints.push( null );
-					}
-
-					fromgap = true;
-					j += otherps;
-
-				} else {
-
-					// cases where we actually got two points
-
-					px = points[ i ];
-					py = points[ i + 1 ];
-					qx = otherpoints[ j ];
-					qy = otherpoints[ j + 1 ];
-					bottom = 0;
-
-					if ( px === qx ) {
-
-						for ( m = 0; m < ps; ++m ) {
-							newpoints.push( points[ i + m ] );
-						}
-
-						//newpoints[ l + 1 ] += qy;
-						bottom = qy;
-
-						i += ps;
-						j += otherps;
-
-					} else if ( px > qx ) {
-
-						// we got past point below, might need to
-						// insert interpolated extra point
-
-						if ( withlines && i > 0 && points[ i - ps ] != null ) {
-							intery = py + ( points[ i - ps + 1 ] - py ) * ( qx - px ) / ( points[ i - ps ] - px );
-							newpoints.push( qx );
-							newpoints.push( intery );
-							for ( m = 2; m < ps; ++m ) {
-								newpoints.push( points[ i + m ] );
-							}
-							bottom = qy;
-						}
-
-						j += otherps;
-
-					} else { // px < qx
-
-						// if we come from a gap, we just skip this point
-
-						if ( fromgap && withlines ) {
-							i += ps;
-							continue;
-						}
-
-						for ( m = 0; m < ps; ++m ) {
-							newpoints.push( points[ i + m ] );
-						}
-
-						// we might be able to interpolate a point below,
-						// this can give us a better y
-
-						if ( withlines && j > 0 && otherpoints[ j - otherps ] != null ) {
-							bottom = qy + ( otherpoints[ j - otherps + 1 ] - qy ) * ( px - qx ) / ( otherpoints[ j - otherps ] - qx );
-						}
-
-						//newpoints[l + 1] += bottom;
-
-						i += ps;
-					}
-
-					fromgap = false;
-
-					if ( l !== newpoints.length && withbottom ) {
-						newpoints[ l + 2 ] = bottom;
-					}
-				}
-
-				// maintain the line steps invariant
-
-				if ( withsteps && l !== newpoints.length && l > 0 &&
-					newpoints[ l ] !== null &&
-					newpoints[ l ] !== newpoints[ l - ps ] &&
-					newpoints[ l + 1 ] !== newpoints[ l - ps + 1 ] ) {
-					for (m = 0; m < ps; ++m) {
-						newpoints[ l + ps + m ] = newpoints[ l + m ];
-					}
-					newpoints[ l + 1 ] = newpoints[ l - ps + 1 ];
-				}
-			}
-
-			datapoints.points = newpoints;
-		}
-
-		plot.hooks.processDatapoints.push( computeFillBottoms );
-	}
-
-	$.plot.plugins.push({
-		init: init,
-		options: options,
-		name: "fillbetween",
-		version: "1.0"
-	});
-
-})(jQuery);
diff --git a/static/js/jquery.flot.fillbetween.min.js b/static/js/jquery.flot.fillbetween.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.fillbetween.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={series:{fillBetween:null}};function init(plot){function findBottomSeries(s,allseries){var i;for(i=0;i<allseries.length;++i){if(allseries[i].id===s.fillBetween){return allseries[i]}}if(typeof s.fillBetween==="number"){if(s.fillBetween<0||s.fillBetween>=allseries.length){return null}return allseries[s.fillBetween]}return null}function computeFillBottoms(plot,s,datapoints){if(s.fillBetween==null){return}var other=findBottomSeries(s,plot.getData());if(!other){return}var ps=datapoints.pointsize,points=datapoints.points,otherps=other.datapoints.pointsize,otherpoints=other.datapoints.points,newpoints=[],px,py,intery,qx,qy,bottom,withlines=s.lines.show,withbottom=ps>2&&datapoints.format[2].y,withsteps=withlines&&s.lines.steps,fromgap=true,i=0,j=0,l,m;while(true){if(i>=points.length){break}l=newpoints.length;if(points[i]==null){for(m=0;m<ps;++m){newpoints.push(points[i+m])}i+=ps}else if(j>=otherpoints.length){if(!withlines){for(m=0;m<ps;++m){newpoints.push(points[i+m])}}i+=ps}else if(otherpoints[j]==null){for(m=0;m<ps;++m){newpoints.push(null)}fromgap=true;j+=otherps}else{px=points[i];py=points[i+1];qx=otherpoints[j];qy=otherpoints[j+1];bottom=0;if(px===qx){for(m=0;m<ps;++m){newpoints.push(points[i+m])}bottom=qy;i+=ps;j+=otherps}else if(px>qx){if(withlines&&i>0&&points[i-ps]!=null){intery=py+(points[i-ps+1]-py)*(qx-px)/(points[i-ps]-px);newpoints.push(qx);newpoints.push(intery);for(m=2;m<ps;++m){newpoints.push(points[i+m])}bottom=qy}j+=otherps}else{if(fromgap&&withlines){i+=ps;continue}for(m=0;m<ps;++m){newpoints.push(points[i+m])}if(withlines&&j>0&&otherpoints[j-otherps]!=null){bottom=qy+(otherpoints[j-otherps+1]-qy)*(px-qx)/(otherpoints[j-otherps]-qx)}i+=ps}fromgap=false;if(l!==newpoints.length&&withbottom){newpoints[l+2]=bottom}}if(withsteps&&l!==newpoints.length&&l>0&&newpoints[l]!==null&&newpoints[l]!==newpoints[l-ps]&&newpoints[l+1]!==newpoints[l-ps+1]){for(m=0;m<ps;++m){newpoints[l+ps+m]=newpoints[l+m]}newpoints[l+1]=newpoints[l-ps+1]}}datapoints.points=newpoints}plot.hooks.processDatapoints.push(computeFillBottoms)}$.plot.plugins.push({init:init,options:options,name:"fillbetween",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.image.js b/static/js/jquery.flot.image.js
deleted file mode 100644
--- a/static/js/jquery.flot.image.js
+++ /dev/null
@@ -1,241 +0,0 @@
-/* Flot plugin for plotting images.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The data syntax is [ [ image, x1, y1, x2, y2 ], ... ] where (x1, y1) and
-(x2, y2) are where you intend the two opposite corners of the image to end up
-in the plot. Image must be a fully loaded Javascript image (you can make one
-with new Image()). If the image is not complete, it's skipped when plotting.
-
-There are two helpers included for retrieving images. The easiest work the way
-that you put in URLs instead of images in the data, like this:
-
-	[ "myimage.png", 0, 0, 10, 10 ]
-
-Then call $.plot.image.loadData( data, options, callback ) where data and
-options are the same as you pass in to $.plot. This loads the images, replaces
-the URLs in the data with the corresponding images and calls "callback" when
-all images are loaded (or failed loading). In the callback, you can then call
-$.plot with the data set. See the included example.
-
-A more low-level helper, $.plot.image.load(urls, callback) is also included.
-Given a list of URLs, it calls callback with an object mapping from URL to
-Image object when all images are loaded or have failed loading.
-
-The plugin supports these options:
-
-	series: {
-		images: {
-			show: boolean
-			anchor: "corner" or "center"
-			alpha: [ 0, 1 ]
-		}
-	}
-
-They can be specified for a specific series:
-
-	$.plot( $("#placeholder"), [{
-		data: [ ... ],
-		images: { ... }
-	])
-
-Note that because the data format is different from usual data points, you
-can't use images with anything else in a specific data series.
-
-Setting "anchor" to "center" causes the pixels in the image to be anchored at
-the corner pixel centers inside of at the pixel corners, effectively letting
-half a pixel stick out to each side in the plot.
-
-A possible future direction could be support for tiling for large images (like
-Google Maps).
-
-*/
-
-(function ($) {
-    var options = {
-        series: {
-            images: {
-                show: false,
-                alpha: 1,
-                anchor: "corner" // or "center"
-            }
-        }
-    };
-
-    $.plot.image = {};
-
-    $.plot.image.loadDataImages = function (series, options, callback) {
-        var urls = [], points = [];
-
-        var defaultShow = options.series.images.show;
-        
-        $.each(series, function (i, s) {
-            if (!(defaultShow || s.images.show))
-                return;
-            
-            if (s.data)
-                s = s.data;
-
-            $.each(s, function (i, p) {
-                if (typeof p[0] == "string") {
-                    urls.push(p[0]);
-                    points.push(p);
-                }
-            });
-        });
-
-        $.plot.image.load(urls, function (loadedImages) {
-            $.each(points, function (i, p) {
-                var url = p[0];
-                if (loadedImages[url])
-                    p[0] = loadedImages[url];
-            });
-
-            callback();
-        });
-    }
-    
-    $.plot.image.load = function (urls, callback) {
-        var missing = urls.length, loaded = {};
-        if (missing == 0)
-            callback({});
-
-        $.each(urls, function (i, url) {
-            var handler = function () {
-                --missing;
-                
-                loaded[url] = this;
-                
-                if (missing == 0)
-                    callback(loaded);
-            };
-
-            $('<img />').load(handler).error(handler).attr('src', url);
-        });
-    };
-    
-    function drawSeries(plot, ctx, series) {
-        var plotOffset = plot.getPlotOffset();
-        
-        if (!series.images || !series.images.show)
-            return;
-        
-        var points = series.datapoints.points,
-            ps = series.datapoints.pointsize;
-        
-        for (var i = 0; i < points.length; i += ps) {
-            var img = points[i],
-                x1 = points[i + 1], y1 = points[i + 2],
-                x2 = points[i + 3], y2 = points[i + 4],
-                xaxis = series.xaxis, yaxis = series.yaxis,
-                tmp;
-
-            // actually we should check img.complete, but it
-            // appears to be a somewhat unreliable indicator in
-            // IE6 (false even after load event)
-            if (!img || img.width <= 0 || img.height <= 0)
-                continue;
-
-            if (x1 > x2) {
-                tmp = x2;
-                x2 = x1;
-                x1 = tmp;
-            }
-            if (y1 > y2) {
-                tmp = y2;
-                y2 = y1;
-                y1 = tmp;
-            }
-            
-            // if the anchor is at the center of the pixel, expand the 
-            // image by 1/2 pixel in each direction
-            if (series.images.anchor == "center") {
-                tmp = 0.5 * (x2-x1) / (img.width - 1);
-                x1 -= tmp;
-                x2 += tmp;
-                tmp = 0.5 * (y2-y1) / (img.height - 1);
-                y1 -= tmp;
-                y2 += tmp;
-            }
-            
-            // clip
-            if (x1 == x2 || y1 == y2 ||
-                x1 >= xaxis.max || x2 <= xaxis.min ||
-                y1 >= yaxis.max || y2 <= yaxis.min)
-                continue;
-
-            var sx1 = 0, sy1 = 0, sx2 = img.width, sy2 = img.height;
-            if (x1 < xaxis.min) {
-                sx1 += (sx2 - sx1) * (xaxis.min - x1) / (x2 - x1);
-                x1 = xaxis.min;
-            }
-
-            if (x2 > xaxis.max) {
-                sx2 += (sx2 - sx1) * (xaxis.max - x2) / (x2 - x1);
-                x2 = xaxis.max;
-            }
-
-            if (y1 < yaxis.min) {
-                sy2 += (sy1 - sy2) * (yaxis.min - y1) / (y2 - y1);
-                y1 = yaxis.min;
-            }
-
-            if (y2 > yaxis.max) {
-                sy1 += (sy1 - sy2) * (yaxis.max - y2) / (y2 - y1);
-                y2 = yaxis.max;
-            }
-            
-            x1 = xaxis.p2c(x1);
-            x2 = xaxis.p2c(x2);
-            y1 = yaxis.p2c(y1);
-            y2 = yaxis.p2c(y2);
-            
-            // the transformation may have swapped us
-            if (x1 > x2) {
-                tmp = x2;
-                x2 = x1;
-                x1 = tmp;
-            }
-            if (y1 > y2) {
-                tmp = y2;
-                y2 = y1;
-                y1 = tmp;
-            }
-
-            tmp = ctx.globalAlpha;
-            ctx.globalAlpha *= series.images.alpha;
-            ctx.drawImage(img,
-                          sx1, sy1, sx2 - sx1, sy2 - sy1,
-                          x1 + plotOffset.left, y1 + plotOffset.top,
-                          x2 - x1, y2 - y1);
-            ctx.globalAlpha = tmp;
-        }
-    }
-
-    function processRawData(plot, series, data, datapoints) {
-        if (!series.images.show)
-            return;
-
-        // format is Image, x1, y1, x2, y2 (opposite corners)
-        datapoints.format = [
-            { required: true },
-            { x: true, number: true, required: true },
-            { y: true, number: true, required: true },
-            { x: true, number: true, required: true },
-            { y: true, number: true, required: true }
-        ];
-    }
-    
-    function init(plot) {
-        plot.hooks.processRawData.push(processRawData);
-        plot.hooks.drawSeries.push(drawSeries);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'image',
-        version: '1.1'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.image.min.js b/static/js/jquery.flot.image.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.image.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={series:{images:{show:false,alpha:1,anchor:"corner"}}};$.plot.image={};$.plot.image.loadDataImages=function(series,options,callback){var urls=[],points=[];var defaultShow=options.series.images.show;$.each(series,function(i,s){if(!(defaultShow||s.images.show))return;if(s.data)s=s.data;$.each(s,function(i,p){if(typeof p[0]=="string"){urls.push(p[0]);points.push(p)}})});$.plot.image.load(urls,function(loadedImages){$.each(points,function(i,p){var url=p[0];if(loadedImages[url])p[0]=loadedImages[url]});callback()})};$.plot.image.load=function(urls,callback){var missing=urls.length,loaded={};if(missing==0)callback({});$.each(urls,function(i,url){var handler=function(){--missing;loaded[url]=this;if(missing==0)callback(loaded)};$("<img />").load(handler).error(handler).attr("src",url)})};function drawSeries(plot,ctx,series){var plotOffset=plot.getPlotOffset();if(!series.images||!series.images.show)return;var points=series.datapoints.points,ps=series.datapoints.pointsize;for(var i=0;i<points.length;i+=ps){var img=points[i],x1=points[i+1],y1=points[i+2],x2=points[i+3],y2=points[i+4],xaxis=series.xaxis,yaxis=series.yaxis,tmp;if(!img||img.width<=0||img.height<=0)continue;if(x1>x2){tmp=x2;x2=x1;x1=tmp}if(y1>y2){tmp=y2;y2=y1;y1=tmp}if(series.images.anchor=="center"){tmp=.5*(x2-x1)/(img.width-1);x1-=tmp;x2+=tmp;tmp=.5*(y2-y1)/(img.height-1);y1-=tmp;y2+=tmp}if(x1==x2||y1==y2||x1>=xaxis.max||x2<=xaxis.min||y1>=yaxis.max||y2<=yaxis.min)continue;var sx1=0,sy1=0,sx2=img.width,sy2=img.height;if(x1<xaxis.min){sx1+=(sx2-sx1)*(xaxis.min-x1)/(x2-x1);x1=xaxis.min}if(x2>xaxis.max){sx2+=(sx2-sx1)*(xaxis.max-x2)/(x2-x1);x2=xaxis.max}if(y1<yaxis.min){sy2+=(sy1-sy2)*(yaxis.min-y1)/(y2-y1);y1=yaxis.min}if(y2>yaxis.max){sy1+=(sy1-sy2)*(yaxis.max-y2)/(y2-y1);y2=yaxis.max}x1=xaxis.p2c(x1);x2=xaxis.p2c(x2);y1=yaxis.p2c(y1);y2=yaxis.p2c(y2);if(x1>x2){tmp=x2;x2=x1;x1=tmp}if(y1>y2){tmp=y2;y2=y1;y1=tmp}tmp=ctx.globalAlpha;ctx.globalAlpha*=series.images.alpha;ctx.drawImage(img,sx1,sy1,sx2-sx1,sy2-sy1,x1+plotOffset.left,y1+plotOffset.top,x2-x1,y2-y1);ctx.globalAlpha=tmp}}function processRawData(plot,series,data,datapoints){if(!series.images.show)return;datapoints.format=[{required:true},{x:true,number:true,required:true},{y:true,number:true,required:true},{x:true,number:true,required:true},{y:true,number:true,required:true}]}function init(plot){plot.hooks.processRawData.push(processRawData);plot.hooks.drawSeries.push(drawSeries)}$.plot.plugins.push({init:init,options:options,name:"image",version:"1.1"})})(jQuery);
diff --git a/static/js/jquery.flot.js b/static/js/jquery.flot.js
deleted file mode 100644
--- a/static/js/jquery.flot.js
+++ /dev/null
@@ -1,3168 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-
-// first an inline dependency, jquery.colorhelpers.js, we inline it here
-// for convenience
-
-/* Plugin for jQuery for working with colors.
- *
- * Version 1.1.
- *
- * Inspiration from jQuery color animation plugin by John Resig.
- *
- * Released under the MIT license by Ole Laursen, October 2009.
- *
- * Examples:
- *
- *   $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString()
- *   var c = $.color.extract($("#mydiv"), 'background-color');
- *   console.log(c.r, c.g, c.b, c.a);
- *   $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)"
- *
- * Note that .scale() and .add() return the same modified object
- * instead of making a new one.
- *
- * V. 1.1: Fix error handling so e.g. parsing an empty string does
- * produce a color rather than just crashing.
- */
-(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
-
-// the actual Flot code
-(function($) {
-
-	// Cache the prototype hasOwnProperty for faster access
-
-	var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-    // A shim to provide 'detach' to jQuery versions prior to 1.4.  Using a DOM
-    // operation produces the same effect as detach, i.e. removing the element
-    // without touching its jQuery data.
-
-    // Do not merge this into Flot 0.9, since it requires jQuery 1.4.4+.
-
-    if (!$.fn.detach) {
-        $.fn.detach = function() {
-            return this.each(function() {
-                if (this.parentNode) {
-                    this.parentNode.removeChild( this );
-                }
-            });
-        };
-    }
-
-	///////////////////////////////////////////////////////////////////////////
-	// The Canvas object is a wrapper around an HTML5 <canvas> tag.
-	//
-	// @constructor
-	// @param {string} cls List of classes to apply to the canvas.
-	// @param {element} container Element onto which to append the canvas.
-	//
-	// Requiring a container is a little iffy, but unfortunately canvas
-	// operations don't work unless the canvas is attached to the DOM.
-
-	function Canvas(cls, container) {
-
-		var element = container.children("." + cls)[0];
-
-		if (element == null) {
-
-			element = document.createElement("canvas");
-			element.className = cls;
-
-			$(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 })
-				.appendTo(container);
-
-			// If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas
-
-			if (!element.getContext) {
-				if (window.G_vmlCanvasManager) {
-					element = window.G_vmlCanvasManager.initElement(element);
-				} else {
-					throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.");
-				}
-			}
-		}
-
-		this.element = element;
-
-		var context = this.context = element.getContext("2d");
-
-		// Determine the screen's ratio of physical to device-independent
-		// pixels.  This is the ratio between the canvas width that the browser
-		// advertises and the number of pixels actually present in that space.
-
-		// The iPhone 4, for example, has a device-independent width of 320px,
-		// but its screen is actually 640px wide.  It therefore has a pixel
-		// ratio of 2, while most normal devices have a ratio of 1.
-
-		var devicePixelRatio = window.devicePixelRatio || 1,
-			backingStoreRatio =
-				context.webkitBackingStorePixelRatio ||
-				context.mozBackingStorePixelRatio ||
-				context.msBackingStorePixelRatio ||
-				context.oBackingStorePixelRatio ||
-				context.backingStorePixelRatio || 1;
-
-		this.pixelRatio = devicePixelRatio / backingStoreRatio;
-
-		// Size the canvas to match the internal dimensions of its container
-
-		this.resize(container.width(), container.height());
-
-		// Collection of HTML div layers for text overlaid onto the canvas
-
-		this.textContainer = null;
-		this.text = {};
-
-		// Cache of text fragments and metrics, so we can avoid expensively
-		// re-calculating them when the plot is re-rendered in a loop.
-
-		this._textCache = {};
-	}
-
-	// Resizes the canvas to the given dimensions.
-	//
-	// @param {number} width New width of the canvas, in pixels.
-	// @param {number} width New height of the canvas, in pixels.
-
-	Canvas.prototype.resize = function(width, height) {
-
-		if (width <= 0 || height <= 0) {
-			throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height);
-		}
-
-		var element = this.element,
-			context = this.context,
-			pixelRatio = this.pixelRatio;
-
-		// Resize the canvas, increasing its density based on the display's
-		// pixel ratio; basically giving it more pixels without increasing the
-		// size of its element, to take advantage of the fact that retina
-		// displays have that many more pixels in the same advertised space.
-
-		// Resizing should reset the state (excanvas seems to be buggy though)
-
-		if (this.width != width) {
-			element.width = width * pixelRatio;
-			element.style.width = width + "px";
-			this.width = width;
-		}
-
-		if (this.height != height) {
-			element.height = height * pixelRatio;
-			element.style.height = height + "px";
-			this.height = height;
-		}
-
-		// Save the context, so we can reset in case we get replotted.  The
-		// restore ensure that we're really back at the initial state, and
-		// should be safe even if we haven't saved the initial state yet.
-
-		context.restore();
-		context.save();
-
-		// Scale the coordinate space to match the display density; so even though we
-		// may have twice as many pixels, we still want lines and other drawing to
-		// appear at the same size; the extra pixels will just make them crisper.
-
-		context.scale(pixelRatio, pixelRatio);
-	};
-
-	// Clears the entire canvas area, not including any overlaid HTML text
-
-	Canvas.prototype.clear = function() {
-		this.context.clearRect(0, 0, this.width, this.height);
-	};
-
-	// Finishes rendering the canvas, including managing the text overlay.
-
-	Canvas.prototype.render = function() {
-
-		var cache = this._textCache;
-
-		// For each text layer, add elements marked as active that haven't
-		// already been rendered, and remove those that are no longer active.
-
-		for (var layerKey in cache) {
-			if (hasOwnProperty.call(cache, layerKey)) {
-
-				var layer = this.getTextLayer(layerKey),
-					layerCache = cache[layerKey];
-
-				layer.hide();
-
-				for (var styleKey in layerCache) {
-					if (hasOwnProperty.call(layerCache, styleKey)) {
-						var styleCache = layerCache[styleKey];
-						for (var key in styleCache) {
-							if (hasOwnProperty.call(styleCache, key)) {
-
-								var positions = styleCache[key].positions;
-
-								for (var i = 0, position; position = positions[i]; i++) {
-									if (position.active) {
-										if (!position.rendered) {
-											layer.append(position.element);
-											position.rendered = true;
-										}
-									} else {
-										positions.splice(i--, 1);
-										if (position.rendered) {
-											position.element.detach();
-										}
-									}
-								}
-
-								if (positions.length == 0) {
-									delete styleCache[key];
-								}
-							}
-						}
-					}
-				}
-
-				layer.show();
-			}
-		}
-	};
-
-	// Creates (if necessary) and returns the text overlay container.
-	//
-	// @param {string} classes String of space-separated CSS classes used to
-	//     uniquely identify the text layer.
-	// @return {object} The jQuery-wrapped text-layer div.
-
-	Canvas.prototype.getTextLayer = function(classes) {
-
-		var layer = this.text[classes];
-
-		// Create the text layer if it doesn't exist
-
-		if (layer == null) {
-
-			// Create the text layer container, if it doesn't exist
-
-			if (this.textContainer == null) {
-				this.textContainer = $("<div class='flot-text'></div>")
-					.css({
-						position: "absolute",
-						top: 0,
-						left: 0,
-						bottom: 0,
-						right: 0,
-						'font-size': "smaller",
-						color: "#545454"
-					})
-					.insertAfter(this.element);
-			}
-
-			layer = this.text[classes] = $("<div></div>")
-				.addClass(classes)
-				.css({
-					position: "absolute",
-					top: 0,
-					left: 0,
-					bottom: 0,
-					right: 0
-				})
-				.appendTo(this.textContainer);
-		}
-
-		return layer;
-	};
-
-	// Creates (if necessary) and returns a text info object.
-	//
-	// The object looks like this:
-	//
-	// {
-	//     width: Width of the text's wrapper div.
-	//     height: Height of the text's wrapper div.
-	//     element: The jQuery-wrapped HTML div containing the text.
-	//     positions: Array of positions at which this text is drawn.
-	// }
-	//
-	// The positions array contains objects that look like this:
-	//
-	// {
-	//     active: Flag indicating whether the text should be visible.
-	//     rendered: Flag indicating whether the text is currently visible.
-	//     element: The jQuery-wrapped HTML div containing the text.
-	//     x: X coordinate at which to draw the text.
-	//     y: Y coordinate at which to draw the text.
-	// }
-	//
-	// Each position after the first receives a clone of the original element.
-	//
-	// The idea is that that the width, height, and general 'identity' of the
-	// text is constant no matter where it is placed; the placements are a
-	// secondary property.
-	//
-	// Canvas maintains a cache of recently-used text info objects; getTextInfo
-	// either returns the cached element or creates a new entry.
-	//
-	// @param {string} layer A string of space-separated CSS classes uniquely
-	//     identifying the layer containing this text.
-	// @param {string} text Text string to retrieve info for.
-	// @param {(string|object)=} font Either a string of space-separated CSS
-	//     classes or a font-spec object, defining the text's font and style.
-	// @param {number=} angle Angle at which to rotate the text, in degrees.
-	//     Angle is currently unused, it will be implemented in the future.
-	// @param {number=} width Maximum width of the text before it wraps.
-	// @return {object} a text info object.
-
-	Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) {
-
-		var textStyle, layerCache, styleCache, info;
-
-		// Cast the value to a string, in case we were given a number or such
-
-		text = "" + text;
-
-		// If the font is a font-spec object, generate a CSS font definition
-
-		if (typeof font === "object") {
-			textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family;
-		} else {
-			textStyle = font;
-		}
-
-		// Retrieve (or create) the cache for the text's layer and styles
-
-		layerCache = this._textCache[layer];
-
-		if (layerCache == null) {
-			layerCache = this._textCache[layer] = {};
-		}
-
-		styleCache = layerCache[textStyle];
-
-		if (styleCache == null) {
-			styleCache = layerCache[textStyle] = {};
-		}
-
-		info = styleCache[text];
-
-		// If we can't find a matching element in our cache, create a new one
-
-		if (info == null) {
-
-			var element = $("<div></div>").html(text)
-				.css({
-					position: "absolute",
-					'max-width': width,
-					top: -9999
-				})
-				.appendTo(this.getTextLayer(layer));
-
-			if (typeof font === "object") {
-				element.css({
-					font: textStyle,
-					color: font.color
-				});
-			} else if (typeof font === "string") {
-				element.addClass(font);
-			}
-
-			info = styleCache[text] = {
-				width: element.outerWidth(true),
-				height: element.outerHeight(true),
-				element: element,
-				positions: []
-			};
-
-			element.detach();
-		}
-
-		return info;
-	};
-
-	// Adds a text string to the canvas text overlay.
-	//
-	// The text isn't drawn immediately; it is marked as rendering, which will
-	// result in its addition to the canvas on the next render pass.
-	//
-	// @param {string} layer A string of space-separated CSS classes uniquely
-	//     identifying the layer containing this text.
-	// @param {number} x X coordinate at which to draw the text.
-	// @param {number} y Y coordinate at which to draw the text.
-	// @param {string} text Text string to draw.
-	// @param {(string|object)=} font Either a string of space-separated CSS
-	//     classes or a font-spec object, defining the text's font and style.
-	// @param {number=} angle Angle at which to rotate the text, in degrees.
-	//     Angle is currently unused, it will be implemented in the future.
-	// @param {number=} width Maximum width of the text before it wraps.
-	// @param {string=} halign Horizontal alignment of the text; either "left",
-	//     "center" or "right".
-	// @param {string=} valign Vertical alignment of the text; either "top",
-	//     "middle" or "bottom".
-
-	Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) {
-
-		var info = this.getTextInfo(layer, text, font, angle, width),
-			positions = info.positions;
-
-		// Tweak the div's position to match the text's alignment
-
-		if (halign == "center") {
-			x -= info.width / 2;
-		} else if (halign == "right") {
-			x -= info.width;
-		}
-
-		if (valign == "middle") {
-			y -= info.height / 2;
-		} else if (valign == "bottom") {
-			y -= info.height;
-		}
-
-		// Determine whether this text already exists at this position.
-		// If so, mark it for inclusion in the next render pass.
-
-		for (var i = 0, position; position = positions[i]; i++) {
-			if (position.x == x && position.y == y) {
-				position.active = true;
-				return;
-			}
-		}
-
-		// If the text doesn't exist at this position, create a new entry
-
-		// For the very first position we'll re-use the original element,
-		// while for subsequent ones we'll clone it.
-
-		position = {
-			active: true,
-			rendered: false,
-			element: positions.length ? info.element.clone() : info.element,
-			x: x,
-			y: y
-		};
-
-		positions.push(position);
-
-		// Move the element to its final position within the container
-
-		position.element.css({
-			top: Math.round(y),
-			left: Math.round(x),
-			'text-align': halign	// In case the text wraps
-		});
-	};
-
-	// Removes one or more text strings from the canvas text overlay.
-	//
-	// If no parameters are given, all text within the layer is removed.
-	//
-	// Note that the text is not immediately removed; it is simply marked as
-	// inactive, which will result in its removal on the next render pass.
-	// This avoids the performance penalty for 'clear and redraw' behavior,
-	// where we potentially get rid of all text on a layer, but will likely
-	// add back most or all of it later, as when redrawing axes, for example.
-	//
-	// @param {string} layer A string of space-separated CSS classes uniquely
-	//     identifying the layer containing this text.
-	// @param {number=} x X coordinate of the text.
-	// @param {number=} y Y coordinate of the text.
-	// @param {string=} text Text string to remove.
-	// @param {(string|object)=} font Either a string of space-separated CSS
-	//     classes or a font-spec object, defining the text's font and style.
-	// @param {number=} angle Angle at which the text is rotated, in degrees.
-	//     Angle is currently unused, it will be implemented in the future.
-
-	Canvas.prototype.removeText = function(layer, x, y, text, font, angle) {
-		if (text == null) {
-			var layerCache = this._textCache[layer];
-			if (layerCache != null) {
-				for (var styleKey in layerCache) {
-					if (hasOwnProperty.call(layerCache, styleKey)) {
-						var styleCache = layerCache[styleKey];
-						for (var key in styleCache) {
-							if (hasOwnProperty.call(styleCache, key)) {
-								var positions = styleCache[key].positions;
-								for (var i = 0, position; position = positions[i]; i++) {
-									position.active = false;
-								}
-							}
-						}
-					}
-				}
-			}
-		} else {
-			var positions = this.getTextInfo(layer, text, font, angle).positions;
-			for (var i = 0, position; position = positions[i]; i++) {
-				if (position.x == x && position.y == y) {
-					position.active = false;
-				}
-			}
-		}
-	};
-
-	///////////////////////////////////////////////////////////////////////////
-	// The top-level container for the entire plot.
-
-    function Plot(placeholder, data_, options_, plugins) {
-        // data is on the form:
-        //   [ series1, series2 ... ]
-        // where series is either just the data as [ [x1, y1], [x2, y2], ... ]
-        // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... }
-
-        var series = [],
-            options = {
-                // the color theme used for graphs
-                colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"],
-                legend: {
-                    show: true,
-                    noColumns: 1, // number of columns in legend table
-                    labelFormatter: null, // fn: string -> string
-                    labelBoxBorderColor: "#ccc", // border color for the little label boxes
-                    container: null, // container (as jQuery object) to put legend in, null means default on top of graph
-                    position: "ne", // position of default legend container within plot
-                    margin: 5, // distance from grid edge to default legend container within plot
-                    backgroundColor: null, // null means auto-detect
-                    backgroundOpacity: 0.85, // set to 0 to avoid background
-                    sorted: null    // default to no legend sorting
-                },
-                xaxis: {
-                    show: null, // null = auto-detect, true = always, false = never
-                    position: "bottom", // or "top"
-                    mode: null, // null or "time"
-                    font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" }
-                    color: null, // base color, labels, ticks
-                    tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)"
-                    transform: null, // null or f: number -> number to transform axis
-                    inverseTransform: null, // if transform is set, this should be the inverse function
-                    min: null, // min. value to show, null means set automatically
-                    max: null, // max. value to show, null means set automatically
-                    autoscaleMargin: null, // margin in % to add if auto-setting min/max
-                    ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks
-                    tickFormatter: null, // fn: number -> string
-                    labelWidth: null, // size of tick labels in pixels
-                    labelHeight: null,
-                    reserveSpace: null, // whether to reserve space even if axis isn't shown
-                    tickLength: null, // size in pixels of ticks, or "full" for whole line
-                    alignTicksWithAxis: null, // axis number or null for no sync
-                    tickDecimals: null, // no. of decimals, null means auto
-                    tickSize: null, // number or [number, "unit"]
-                    minTickSize: null // number or [number, "unit"]
-                },
-                yaxis: {
-                    autoscaleMargin: 0.02,
-                    position: "left" // or "right"
-                },
-                xaxes: [],
-                yaxes: [],
-                series: {
-                    points: {
-                        show: false,
-                        radius: 3,
-                        lineWidth: 2, // in pixels
-                        fill: true,
-                        fillColor: "#ffffff",
-                        symbol: "circle" // or callback
-                    },
-                    lines: {
-                        // we don't put in show: false so we can see
-                        // whether lines were actively disabled
-                        lineWidth: 2, // in pixels
-                        fill: false,
-                        fillColor: null,
-                        steps: false
-                        // Omit 'zero', so we can later default its value to
-                        // match that of the 'fill' option.
-                    },
-                    bars: {
-                        show: false,
-                        lineWidth: 2, // in pixels
-                        barWidth: 1, // in units of the x axis
-                        fill: true,
-                        fillColor: null,
-                        align: "left", // "left", "right", or "center"
-                        horizontal: false,
-                        zero: true
-                    },
-                    shadowSize: 3,
-                    highlightColor: null
-                },
-                grid: {
-                    show: true,
-                    aboveData: false,
-                    color: "#545454", // primary color used for outline and labels
-                    backgroundColor: null, // null for transparent, else color
-                    borderColor: null, // set if different from the grid color
-                    tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)"
-                    margin: 0, // distance from the canvas edge to the grid
-                    labelMargin: 5, // in pixels
-                    axisMargin: 8, // in pixels
-                    borderWidth: 2, // in pixels
-                    minBorderMargin: null, // in pixels, null means taken from points radius
-                    markings: null, // array of ranges or fn: axes -> array of ranges
-                    markingsColor: "#f4f4f4",
-                    markingsLineWidth: 2,
-                    // interactive stuff
-                    clickable: false,
-                    hoverable: false,
-                    autoHighlight: true, // highlight in case mouse is near
-                    mouseActiveRadius: 10 // how far the mouse can be away to activate an item
-                },
-                interaction: {
-                    redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow
-                },
-                hooks: {}
-            },
-        surface = null,     // the canvas for the plot itself
-        overlay = null,     // canvas for interactive stuff on top of plot
-        eventHolder = null, // jQuery object that events should be bound to
-        ctx = null, octx = null,
-        xaxes = [], yaxes = [],
-        plotOffset = { left: 0, right: 0, top: 0, bottom: 0},
-        plotWidth = 0, plotHeight = 0,
-        hooks = {
-            processOptions: [],
-            processRawData: [],
-            processDatapoints: [],
-            processOffset: [],
-            drawBackground: [],
-            drawSeries: [],
-            draw: [],
-            bindEvents: [],
-            drawOverlay: [],
-            shutdown: []
-        },
-        plot = this;
-
-        // public functions
-        plot.setData = setData;
-        plot.setupGrid = setupGrid;
-        plot.draw = draw;
-        plot.getPlaceholder = function() { return placeholder; };
-        plot.getCanvas = function() { return surface.element; };
-        plot.getPlotOffset = function() { return plotOffset; };
-        plot.width = function () { return plotWidth; };
-        plot.height = function () { return plotHeight; };
-        plot.offset = function () {
-            var o = eventHolder.offset();
-            o.left += plotOffset.left;
-            o.top += plotOffset.top;
-            return o;
-        };
-        plot.getData = function () { return series; };
-        plot.getAxes = function () {
-            var res = {}, i;
-            $.each(xaxes.concat(yaxes), function (_, axis) {
-                if (axis)
-                    res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis;
-            });
-            return res;
-        };
-        plot.getXAxes = function () { return xaxes; };
-        plot.getYAxes = function () { return yaxes; };
-        plot.c2p = canvasToAxisCoords;
-        plot.p2c = axisToCanvasCoords;
-        plot.getOptions = function () { return options; };
-        plot.highlight = highlight;
-        plot.unhighlight = unhighlight;
-        plot.triggerRedrawOverlay = triggerRedrawOverlay;
-        plot.pointOffset = function(point) {
-            return {
-                left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10),
-                top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10)
-            };
-        };
-        plot.shutdown = shutdown;
-        plot.destroy = function () {
-            shutdown();
-            placeholder.removeData("plot").empty();
-
-            series = [];
-            options = null;
-            surface = null;
-            overlay = null;
-            eventHolder = null;
-            ctx = null;
-            octx = null;
-            xaxes = [];
-            yaxes = [];
-            hooks = null;
-            highlights = [];
-            plot = null;
-        };
-        plot.resize = function () {
-        	var width = placeholder.width(),
-        		height = placeholder.height();
-            surface.resize(width, height);
-            overlay.resize(width, height);
-        };
-
-        // public attributes
-        plot.hooks = hooks;
-
-        // initialize
-        initPlugins(plot);
-        parseOptions(options_);
-        setupCanvases();
-        setData(data_);
-        setupGrid();
-        draw();
-        bindEvents();
-
-
-        function executeHooks(hook, args) {
-            args = [plot].concat(args);
-            for (var i = 0; i < hook.length; ++i)
-                hook[i].apply(this, args);
-        }
-
-        function initPlugins() {
-
-            // References to key classes, allowing plugins to modify them
-
-            var classes = {
-                Canvas: Canvas
-            };
-
-            for (var i = 0; i < plugins.length; ++i) {
-                var p = plugins[i];
-                p.init(plot, classes);
-                if (p.options)
-                    $.extend(true, options, p.options);
-            }
-        }
-
-        function parseOptions(opts) {
-
-            $.extend(true, options, opts);
-
-            // $.extend merges arrays, rather than replacing them.  When less
-            // colors are provided than the size of the default palette, we
-            // end up with those colors plus the remaining defaults, which is
-            // not expected behavior; avoid it by replacing them here.
-
-            if (opts && opts.colors) {
-            	options.colors = opts.colors;
-            }
-
-            if (options.xaxis.color == null)
-                options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
-            if (options.yaxis.color == null)
-                options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString();
-
-            if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility
-                options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color;
-            if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility
-                options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color;
-
-            if (options.grid.borderColor == null)
-                options.grid.borderColor = options.grid.color;
-            if (options.grid.tickColor == null)
-                options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString();
-
-            // Fill in defaults for axis options, including any unspecified
-            // font-spec fields, if a font-spec was provided.
-
-            // If no x/y axis options were provided, create one of each anyway,
-            // since the rest of the code assumes that they exist.
-
-            var i, axisOptions, axisCount,
-                fontSize = placeholder.css("font-size"),
-                fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13,
-                fontDefaults = {
-                    style: placeholder.css("font-style"),
-                    size: Math.round(0.8 * fontSizeDefault),
-                    variant: placeholder.css("font-variant"),
-                    weight: placeholder.css("font-weight"),
-                    family: placeholder.css("font-family")
-                };
-
-            axisCount = options.xaxes.length || 1;
-            for (i = 0; i < axisCount; ++i) {
-
-                axisOptions = options.xaxes[i];
-                if (axisOptions && !axisOptions.tickColor) {
-                    axisOptions.tickColor = axisOptions.color;
-                }
-
-                axisOptions = $.extend(true, {}, options.xaxis, axisOptions);
-                options.xaxes[i] = axisOptions;
-
-                if (axisOptions.font) {
-                    axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
-                    if (!axisOptions.font.color) {
-                        axisOptions.font.color = axisOptions.color;
-                    }
-                    if (!axisOptions.font.lineHeight) {
-                        axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
-                    }
-                }
-            }
-
-            axisCount = options.yaxes.length || 1;
-            for (i = 0; i < axisCount; ++i) {
-
-                axisOptions = options.yaxes[i];
-                if (axisOptions && !axisOptions.tickColor) {
-                    axisOptions.tickColor = axisOptions.color;
-                }
-
-                axisOptions = $.extend(true, {}, options.yaxis, axisOptions);
-                options.yaxes[i] = axisOptions;
-
-                if (axisOptions.font) {
-                    axisOptions.font = $.extend({}, fontDefaults, axisOptions.font);
-                    if (!axisOptions.font.color) {
-                        axisOptions.font.color = axisOptions.color;
-                    }
-                    if (!axisOptions.font.lineHeight) {
-                        axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15);
-                    }
-                }
-            }
-
-            // backwards compatibility, to be removed in future
-            if (options.xaxis.noTicks && options.xaxis.ticks == null)
-                options.xaxis.ticks = options.xaxis.noTicks;
-            if (options.yaxis.noTicks && options.yaxis.ticks == null)
-                options.yaxis.ticks = options.yaxis.noTicks;
-            if (options.x2axis) {
-                options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis);
-                options.xaxes[1].position = "top";
-                // Override the inherit to allow the axis to auto-scale
-                if (options.x2axis.min == null) {
-                    options.xaxes[1].min = null;
-                }
-                if (options.x2axis.max == null) {
-                    options.xaxes[1].max = null;
-                }
-            }
-            if (options.y2axis) {
-                options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis);
-                options.yaxes[1].position = "right";
-                // Override the inherit to allow the axis to auto-scale
-                if (options.y2axis.min == null) {
-                    options.yaxes[1].min = null;
-                }
-                if (options.y2axis.max == null) {
-                    options.yaxes[1].max = null;
-                }
-            }
-            if (options.grid.coloredAreas)
-                options.grid.markings = options.grid.coloredAreas;
-            if (options.grid.coloredAreasColor)
-                options.grid.markingsColor = options.grid.coloredAreasColor;
-            if (options.lines)
-                $.extend(true, options.series.lines, options.lines);
-            if (options.points)
-                $.extend(true, options.series.points, options.points);
-            if (options.bars)
-                $.extend(true, options.series.bars, options.bars);
-            if (options.shadowSize != null)
-                options.series.shadowSize = options.shadowSize;
-            if (options.highlightColor != null)
-                options.series.highlightColor = options.highlightColor;
-
-            // save options on axes for future reference
-            for (i = 0; i < options.xaxes.length; ++i)
-                getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i];
-            for (i = 0; i < options.yaxes.length; ++i)
-                getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i];
-
-            // add hooks from options
-            for (var n in hooks)
-                if (options.hooks[n] && options.hooks[n].length)
-                    hooks[n] = hooks[n].concat(options.hooks[n]);
-
-            executeHooks(hooks.processOptions, [options]);
-        }
-
-        function setData(d) {
-            series = parseData(d);
-            fillInSeriesOptions();
-            processData();
-        }
-
-        function parseData(d) {
-            var res = [];
-            for (var i = 0; i < d.length; ++i) {
-                var s = $.extend(true, {}, options.series);
-
-                if (d[i].data != null) {
-                    s.data = d[i].data; // move the data instead of deep-copy
-                    delete d[i].data;
-
-                    $.extend(true, s, d[i]);
-
-                    d[i].data = s.data;
-                }
-                else
-                    s.data = d[i];
-                res.push(s);
-            }
-
-            return res;
-        }
-
-        function axisNumber(obj, coord) {
-            var a = obj[coord + "axis"];
-            if (typeof a == "object") // if we got a real axis, extract number
-                a = a.n;
-            if (typeof a != "number")
-                a = 1; // default to first axis
-            return a;
-        }
-
-        function allAxes() {
-            // return flat array without annoying null entries
-            return $.grep(xaxes.concat(yaxes), function (a) { return a; });
-        }
-
-        function canvasToAxisCoords(pos) {
-            // return an object with x/y corresponding to all used axes
-            var res = {}, i, axis;
-            for (i = 0; i < xaxes.length; ++i) {
-                axis = xaxes[i];
-                if (axis && axis.used)
-                    res["x" + axis.n] = axis.c2p(pos.left);
-            }
-
-            for (i = 0; i < yaxes.length; ++i) {
-                axis = yaxes[i];
-                if (axis && axis.used)
-                    res["y" + axis.n] = axis.c2p(pos.top);
-            }
-
-            if (res.x1 !== undefined)
-                res.x = res.x1;
-            if (res.y1 !== undefined)
-                res.y = res.y1;
-
-            return res;
-        }
-
-        function axisToCanvasCoords(pos) {
-            // get canvas coords from the first pair of x/y found in pos
-            var res = {}, i, axis, key;
-
-            for (i = 0; i < xaxes.length; ++i) {
-                axis = xaxes[i];
-                if (axis && axis.used) {
-                    key = "x" + axis.n;
-                    if (pos[key] == null && axis.n == 1)
-                        key = "x";
-
-                    if (pos[key] != null) {
-                        res.left = axis.p2c(pos[key]);
-                        break;
-                    }
-                }
-            }
-
-            for (i = 0; i < yaxes.length; ++i) {
-                axis = yaxes[i];
-                if (axis && axis.used) {
-                    key = "y" + axis.n;
-                    if (pos[key] == null && axis.n == 1)
-                        key = "y";
-
-                    if (pos[key] != null) {
-                        res.top = axis.p2c(pos[key]);
-                        break;
-                    }
-                }
-            }
-
-            return res;
-        }
-
-        function getOrCreateAxis(axes, number) {
-            if (!axes[number - 1])
-                axes[number - 1] = {
-                    n: number, // save the number for future reference
-                    direction: axes == xaxes ? "x" : "y",
-                    options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis)
-                };
-
-            return axes[number - 1];
-        }
-
-        function fillInSeriesOptions() {
-
-            var neededColors = series.length, maxIndex = -1, i;
-
-            // Subtract the number of series that already have fixed colors or
-            // color indexes from the number that we still need to generate.
-
-            for (i = 0; i < series.length; ++i) {
-                var sc = series[i].color;
-                if (sc != null) {
-                    neededColors--;
-                    if (typeof sc == "number" && sc > maxIndex) {
-                        maxIndex = sc;
-                    }
-                }
-            }
-
-            // If any of the series have fixed color indexes, then we need to
-            // generate at least as many colors as the highest index.
-
-            if (neededColors <= maxIndex) {
-                neededColors = maxIndex + 1;
-            }
-
-            // Generate all the colors, using first the option colors and then
-            // variations on those colors once they're exhausted.
-
-            var c, colors = [], colorPool = options.colors,
-                colorPoolSize = colorPool.length, variation = 0;
-
-            for (i = 0; i < neededColors; i++) {
-
-                c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
-
-                // Each time we exhaust the colors in the pool we adjust
-                // a scaling factor used to produce more variations on
-                // those colors. The factor alternates negative/positive
-                // to produce lighter/darker colors.
-
-                // Reset the variation after every few cycles, or else
-                // it will end up producing only white or black colors.
-
-                if (i % colorPoolSize == 0 && i) {
-                    if (variation >= 0) {
-                        if (variation < 0.5) {
-                            variation = -variation - 0.2;
-                        } else variation = 0;
-                    } else variation = -variation;
-                }
-
-                colors[i] = c.scale('rgb', 1 + variation);
-            }
-
-            // Finalize the series options, filling in their colors
-
-            var colori = 0, s;
-            for (i = 0; i < series.length; ++i) {
-                s = series[i];
-
-                // assign colors
-                if (s.color == null) {
-                    s.color = colors[colori].toString();
-                    ++colori;
-                }
-                else if (typeof s.color == "number")
-                    s.color = colors[s.color].toString();
-
-                // turn on lines automatically in case nothing is set
-                if (s.lines.show == null) {
-                    var v, show = true;
-                    for (v in s)
-                        if (s[v] && s[v].show) {
-                            show = false;
-                            break;
-                        }
-                    if (show)
-                        s.lines.show = true;
-                }
-
-                // If nothing was provided for lines.zero, default it to match
-                // lines.fill, since areas by default should extend to zero.
-
-                if (s.lines.zero == null) {
-                    s.lines.zero = !!s.lines.fill;
-                }
-
-                // setup axes
-                s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x"));
-                s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y"));
-            }
-        }
-
-        function processData() {
-            var topSentry = Number.POSITIVE_INFINITY,
-                bottomSentry = Number.NEGATIVE_INFINITY,
-                fakeInfinity = Number.MAX_VALUE,
-                i, j, k, m, length,
-                s, points, ps, x, y, axis, val, f, p,
-                data, format;
-
-            function updateAxis(axis, min, max) {
-                if (min < axis.datamin && min != -fakeInfinity)
-                    axis.datamin = min;
-                if (max > axis.datamax && max != fakeInfinity)
-                    axis.datamax = max;
-            }
-
-            $.each(allAxes(), function (_, axis) {
-                // init axis
-                axis.datamin = topSentry;
-                axis.datamax = bottomSentry;
-                axis.used = false;
-            });
-
-            for (i = 0; i < series.length; ++i) {
-                s = series[i];
-                s.datapoints = { points: [] };
-
-                executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]);
-            }
-
-            // first pass: clean and copy data
-            for (i = 0; i < series.length; ++i) {
-                s = series[i];
-
-                data = s.data;
-                format = s.datapoints.format;
-
-                if (!format) {
-                    format = [];
-                    // find out how to copy
-                    format.push({ x: true, number: true, required: true });
-                    format.push({ y: true, number: true, required: true });
-
-                    if (s.bars.show || (s.lines.show && s.lines.fill)) {
-                        var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero));
-                        format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale });
-                        if (s.bars.horizontal) {
-                            delete format[format.length - 1].y;
-                            format[format.length - 1].x = true;
-                        }
-                    }
-
-                    s.datapoints.format = format;
-                }
-
-                if (s.datapoints.pointsize != null)
-                    continue; // already filled in
-
-                s.datapoints.pointsize = format.length;
-
-                ps = s.datapoints.pointsize;
-                points = s.datapoints.points;
-
-                var insertSteps = s.lines.show && s.lines.steps;
-                s.xaxis.used = s.yaxis.used = true;
-
-                for (j = k = 0; j < data.length; ++j, k += ps) {
-                    p = data[j];
-
-                    var nullify = p == null;
-                    if (!nullify) {
-                        for (m = 0; m < ps; ++m) {
-                            val = p[m];
-                            f = format[m];
-
-                            if (f) {
-                                if (f.number && val != null) {
-                                    val = +val; // convert to number
-                                    if (isNaN(val))
-                                        val = null;
-                                    else if (val == Infinity)
-                                        val = fakeInfinity;
-                                    else if (val == -Infinity)
-                                        val = -fakeInfinity;
-                                }
-
-                                if (val == null) {
-                                    if (f.required)
-                                        nullify = true;
-
-                                    if (f.defaultValue != null)
-                                        val = f.defaultValue;
-                                }
-                            }
-
-                            points[k + m] = val;
-                        }
-                    }
-
-                    if (nullify) {
-                        for (m = 0; m < ps; ++m) {
-                            val = points[k + m];
-                            if (val != null) {
-                                f = format[m];
-                                // extract min/max info
-                                if (f.autoscale !== false) {
-                                    if (f.x) {
-                                        updateAxis(s.xaxis, val, val);
-                                    }
-                                    if (f.y) {
-                                        updateAxis(s.yaxis, val, val);
-                                    }
-                                }
-                            }
-                            points[k + m] = null;
-                        }
-                    }
-                    else {
-                        // a little bit of line specific stuff that
-                        // perhaps shouldn't be here, but lacking
-                        // better means...
-                        if (insertSteps && k > 0
-                            && points[k - ps] != null
-                            && points[k - ps] != points[k]
-                            && points[k - ps + 1] != points[k + 1]) {
-                            // copy the point to make room for a middle point
-                            for (m = 0; m < ps; ++m)
-                                points[k + ps + m] = points[k + m];
-
-                            // middle point has same y
-                            points[k + 1] = points[k - ps + 1];
-
-                            // we've added a point, better reflect that
-                            k += ps;
-                        }
-                    }
-                }
-            }
-
-            // give the hooks a chance to run
-            for (i = 0; i < series.length; ++i) {
-                s = series[i];
-
-                executeHooks(hooks.processDatapoints, [ s, s.datapoints]);
-            }
-
-            // second pass: find datamax/datamin for auto-scaling
-            for (i = 0; i < series.length; ++i) {
-                s = series[i];
-                points = s.datapoints.points;
-                ps = s.datapoints.pointsize;
-                format = s.datapoints.format;
-
-                var xmin = topSentry, ymin = topSentry,
-                    xmax = bottomSentry, ymax = bottomSentry;
-
-                for (j = 0; j < points.length; j += ps) {
-                    if (points[j] == null)
-                        continue;
-
-                    for (m = 0; m < ps; ++m) {
-                        val = points[j + m];
-                        f = format[m];
-                        if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity)
-                            continue;
-
-                        if (f.x) {
-                            if (val < xmin)
-                                xmin = val;
-                            if (val > xmax)
-                                xmax = val;
-                        }
-                        if (f.y) {
-                            if (val < ymin)
-                                ymin = val;
-                            if (val > ymax)
-                                ymax = val;
-                        }
-                    }
-                }
-
-                if (s.bars.show) {
-                    // make sure we got room for the bar on the dancing floor
-                    var delta;
-
-                    switch (s.bars.align) {
-                        case "left":
-                            delta = 0;
-                            break;
-                        case "right":
-                            delta = -s.bars.barWidth;
-                            break;
-                        default:
-                            delta = -s.bars.barWidth / 2;
-                    }
-
-                    if (s.bars.horizontal) {
-                        ymin += delta;
-                        ymax += delta + s.bars.barWidth;
-                    }
-                    else {
-                        xmin += delta;
-                        xmax += delta + s.bars.barWidth;
-                    }
-                }
-
-                updateAxis(s.xaxis, xmin, xmax);
-                updateAxis(s.yaxis, ymin, ymax);
-            }
-
-            $.each(allAxes(), function (_, axis) {
-                if (axis.datamin == topSentry)
-                    axis.datamin = null;
-                if (axis.datamax == bottomSentry)
-                    axis.datamax = null;
-            });
-        }
-
-        function setupCanvases() {
-
-            // Make sure the placeholder is clear of everything except canvases
-            // from a previous plot in this container that we'll try to re-use.
-
-            placeholder.css("padding", 0) // padding messes up the positioning
-                .children().filter(function(){
-                    return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base');
-                }).remove();
-
-            if (placeholder.css("position") == 'static')
-                placeholder.css("position", "relative"); // for positioning labels and overlay
-
-            surface = new Canvas("flot-base", placeholder);
-            overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features
-
-            ctx = surface.context;
-            octx = overlay.context;
-
-            // define which element we're listening for events on
-            eventHolder = $(overlay.element).unbind();
-
-            // If we're re-using a plot object, shut down the old one
-
-            var existing = placeholder.data("plot");
-
-            if (existing) {
-                existing.shutdown();
-                overlay.clear();
-            }
-
-            // save in case we get replotted
-            placeholder.data("plot", plot);
-        }
-
-        function bindEvents() {
-            // bind events
-            if (options.grid.hoverable) {
-                eventHolder.mousemove(onMouseMove);
-
-                // Use bind, rather than .mouseleave, because we officially
-                // still support jQuery 1.2.6, which doesn't define a shortcut
-                // for mouseenter or mouseleave.  This was a bug/oversight that
-                // was fixed somewhere around 1.3.x.  We can return to using
-                // .mouseleave when we drop support for 1.2.6.
-
-                eventHolder.bind("mouseleave", onMouseLeave);
-            }
-
-            if (options.grid.clickable)
-                eventHolder.click(onClick);
-
-            executeHooks(hooks.bindEvents, [eventHolder]);
-        }
-
-        function shutdown() {
-            if (redrawTimeout)
-                clearTimeout(redrawTimeout);
-
-            eventHolder.unbind("mousemove", onMouseMove);
-            eventHolder.unbind("mouseleave", onMouseLeave);
-            eventHolder.unbind("click", onClick);
-
-            executeHooks(hooks.shutdown, [eventHolder]);
-        }
-
-        function setTransformationHelpers(axis) {
-            // set helper functions on the axis, assumes plot area
-            // has been computed already
-
-            function identity(x) { return x; }
-
-            var s, m, t = axis.options.transform || identity,
-                it = axis.options.inverseTransform;
-
-            // precompute how much the axis is scaling a point
-            // in canvas space
-            if (axis.direction == "x") {
-                s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min));
-                m = Math.min(t(axis.max), t(axis.min));
-            }
-            else {
-                s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min));
-                s = -s;
-                m = Math.max(t(axis.max), t(axis.min));
-            }
-
-            // data point to canvas coordinate
-            if (t == identity) // slight optimization
-                axis.p2c = function (p) { return (p - m) * s; };
-            else
-                axis.p2c = function (p) { return (t(p) - m) * s; };
-            // canvas coordinate to data point
-            if (!it)
-                axis.c2p = function (c) { return m + c / s; };
-            else
-                axis.c2p = function (c) { return it(m + c / s); };
-        }
-
-        function measureTickLabels(axis) {
-
-            var opts = axis.options,
-                ticks = axis.ticks || [],
-                labelWidth = opts.labelWidth || 0,
-                labelHeight = opts.labelHeight || 0,
-                maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null),
-                legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
-                layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
-                font = opts.font || "flot-tick-label tickLabel";
-
-            for (var i = 0; i < ticks.length; ++i) {
-
-                var t = ticks[i];
-
-                if (!t.label)
-                    continue;
-
-                var info = surface.getTextInfo(layer, t.label, font, null, maxWidth);
-
-                labelWidth = Math.max(labelWidth, info.width);
-                labelHeight = Math.max(labelHeight, info.height);
-            }
-
-            axis.labelWidth = opts.labelWidth || labelWidth;
-            axis.labelHeight = opts.labelHeight || labelHeight;
-        }
-
-        function allocateAxisBoxFirstPhase(axis) {
-            // find the bounding box of the axis by looking at label
-            // widths/heights and ticks, make room by diminishing the
-            // plotOffset; this first phase only looks at one
-            // dimension per axis, the other dimension depends on the
-            // other axes so will have to wait
-
-            var lw = axis.labelWidth,
-                lh = axis.labelHeight,
-                pos = axis.options.position,
-                isXAxis = axis.direction === "x",
-                tickLength = axis.options.tickLength,
-                axisMargin = options.grid.axisMargin,
-                padding = options.grid.labelMargin,
-                innermost = true,
-                outermost = true,
-                first = true,
-                found = false;
-
-            // Determine the axis's position in its direction and on its side
-
-            $.each(isXAxis ? xaxes : yaxes, function(i, a) {
-                if (a && (a.show || a.reserveSpace)) {
-                    if (a === axis) {
-                        found = true;
-                    } else if (a.options.position === pos) {
-                        if (found) {
-                            outermost = false;
-                        } else {
-                            innermost = false;
-                        }
-                    }
-                    if (!found) {
-                        first = false;
-                    }
-                }
-            });
-
-            // The outermost axis on each side has no margin
-
-            if (outermost) {
-                axisMargin = 0;
-            }
-
-            // The ticks for the first axis in each direction stretch across
-
-            if (tickLength == null) {
-                tickLength = first ? "full" : 5;
-            }
-
-            if (!isNaN(+tickLength))
-                padding += +tickLength;
-
-            if (isXAxis) {
-                lh += padding;
-
-                if (pos == "bottom") {
-                    plotOffset.bottom += lh + axisMargin;
-                    axis.box = { top: surface.height - plotOffset.bottom, height: lh };
-                }
-                else {
-                    axis.box = { top: plotOffset.top + axisMargin, height: lh };
-                    plotOffset.top += lh + axisMargin;
-                }
-            }
-            else {
-                lw += padding;
-
-                if (pos == "left") {
-                    axis.box = { left: plotOffset.left + axisMargin, width: lw };
-                    plotOffset.left += lw + axisMargin;
-                }
-                else {
-                    plotOffset.right += lw + axisMargin;
-                    axis.box = { left: surface.width - plotOffset.right, width: lw };
-                }
-            }
-
-             // save for future reference
-            axis.position = pos;
-            axis.tickLength = tickLength;
-            axis.box.padding = padding;
-            axis.innermost = innermost;
-        }
-
-        function allocateAxisBoxSecondPhase(axis) {
-            // now that all axis boxes have been placed in one
-            // dimension, we can set the remaining dimension coordinates
-            if (axis.direction == "x") {
-                axis.box.left = plotOffset.left - axis.labelWidth / 2;
-                axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth;
-            }
-            else {
-                axis.box.top = plotOffset.top - axis.labelHeight / 2;
-                axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight;
-            }
-        }
-
-        function adjustLayoutForThingsStickingOut() {
-            // possibly adjust plot offset to ensure everything stays
-            // inside the canvas and isn't clipped off
-
-            var minMargin = options.grid.minBorderMargin,
-                axis, i;
-
-            // check stuff from the plot (FIXME: this should just read
-            // a value from the series, otherwise it's impossible to
-            // customize)
-            if (minMargin == null) {
-                minMargin = 0;
-                for (i = 0; i < series.length; ++i)
-                    minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2));
-            }
-
-            var margins = {
-                left: minMargin,
-                right: minMargin,
-                top: minMargin,
-                bottom: minMargin
-            };
-
-            // check axis labels, note we don't check the actual
-            // labels but instead use the overall width/height to not
-            // jump as much around with replots
-            $.each(allAxes(), function (_, axis) {
-                if (axis.reserveSpace && axis.ticks && axis.ticks.length) {
-                    if (axis.direction === "x") {
-                        margins.left = Math.max(margins.left, axis.labelWidth / 2);
-                        margins.right = Math.max(margins.right, axis.labelWidth / 2);
-                    } else {
-                        margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2);
-                        margins.top = Math.max(margins.top, axis.labelHeight / 2);
-                    }
-                }
-            });
-
-            plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left));
-            plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right));
-            plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top));
-            plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom));
-        }
-
-        function setupGrid() {
-            var i, axes = allAxes(), showGrid = options.grid.show;
-
-            // Initialize the plot's offset from the edge of the canvas
-
-            for (var a in plotOffset) {
-                var margin = options.grid.margin || 0;
-                plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0;
-            }
-
-            executeHooks(hooks.processOffset, [plotOffset]);
-
-            // If the grid is visible, add its border width to the offset
-
-            for (var a in plotOffset) {
-                if(typeof(options.grid.borderWidth) == "object") {
-                    plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0;
-                }
-                else {
-                    plotOffset[a] += showGrid ? options.grid.borderWidth : 0;
-                }
-            }
-
-            $.each(axes, function (_, axis) {
-                var axisOpts = axis.options;
-                axis.show = axisOpts.show == null ? axis.used : axisOpts.show;
-                axis.reserveSpace = axisOpts.reserveSpace == null ? axis.show : axisOpts.reserveSpace;
-                setRange(axis);
-            });
-
-            if (showGrid) {
-
-                var allocatedAxes = $.grep(axes, function (axis) {
-                    return axis.show || axis.reserveSpace;
-                });
-
-                $.each(allocatedAxes, function (_, axis) {
-                    // make the ticks
-                    setupTickGeneration(axis);
-                    setTicks(axis);
-                    snapRangeToTicks(axis, axis.ticks);
-                    // find labelWidth/Height for axis
-                    measureTickLabels(axis);
-                });
-
-                // with all dimensions calculated, we can compute the
-                // axis bounding boxes, start from the outside
-                // (reverse order)
-                for (i = allocatedAxes.length - 1; i >= 0; --i)
-                    allocateAxisBoxFirstPhase(allocatedAxes[i]);
-
-                // make sure we've got enough space for things that
-                // might stick out
-                adjustLayoutForThingsStickingOut();
-
-                $.each(allocatedAxes, function (_, axis) {
-                    allocateAxisBoxSecondPhase(axis);
-                });
-            }
-
-            plotWidth = surface.width - plotOffset.left - plotOffset.right;
-            plotHeight = surface.height - plotOffset.bottom - plotOffset.top;
-
-            // now we got the proper plot dimensions, we can compute the scaling
-            $.each(axes, function (_, axis) {
-                setTransformationHelpers(axis);
-            });
-
-            if (showGrid) {
-                drawAxisLabels();
-            }
-
-            insertLegend();
-        }
-
-        function setRange(axis) {
-            var opts = axis.options,
-                min = +(opts.min != null ? opts.min : axis.datamin),
-                max = +(opts.max != null ? opts.max : axis.datamax),
-                delta = max - min;
-
-            if (delta == 0.0) {
-                // degenerate case
-                var widen = max == 0 ? 1 : 0.01;
-
-                if (opts.min == null)
-                    min -= widen;
-                // always widen max if we couldn't widen min to ensure we
-                // don't fall into min == max which doesn't work
-                if (opts.max == null || opts.min != null)
-                    max += widen;
-            }
-            else {
-                // consider autoscaling
-                var margin = opts.autoscaleMargin;
-                if (margin != null) {
-                    if (opts.min == null) {
-                        min -= delta * margin;
-                        // make sure we don't go below zero if all values
-                        // are positive
-                        if (min < 0 && axis.datamin != null && axis.datamin >= 0)
-                            min = 0;
-                    }
-                    if (opts.max == null) {
-                        max += delta * margin;
-                        if (max > 0 && axis.datamax != null && axis.datamax <= 0)
-                            max = 0;
-                    }
-                }
-            }
-            axis.min = min;
-            axis.max = max;
-        }
-
-        function setupTickGeneration(axis) {
-            var opts = axis.options;
-
-            // estimate number of ticks
-            var noTicks;
-            if (typeof opts.ticks == "number" && opts.ticks > 0)
-                noTicks = opts.ticks;
-            else
-                // heuristic based on the model a*sqrt(x) fitted to
-                // some data points that seemed reasonable
-                noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height);
-
-            var delta = (axis.max - axis.min) / noTicks,
-                dec = -Math.floor(Math.log(delta) / Math.LN10),
-                maxDec = opts.tickDecimals;
-
-            if (maxDec != null && dec > maxDec) {
-                dec = maxDec;
-            }
-
-            var magn = Math.pow(10, -dec),
-                norm = delta / magn, // norm is between 1.0 and 10.0
-                size;
-
-            if (norm < 1.5) {
-                size = 1;
-            } else if (norm < 3) {
-                size = 2;
-                // special case for 2.5, requires an extra decimal
-                if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) {
-                    size = 2.5;
-                    ++dec;
-                }
-            } else if (norm < 7.5) {
-                size = 5;
-            } else {
-                size = 10;
-            }
-
-            size *= magn;
-
-            if (opts.minTickSize != null && size < opts.minTickSize) {
-                size = opts.minTickSize;
-            }
-
-            axis.delta = delta;
-            axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec);
-            axis.tickSize = opts.tickSize || size;
-
-            // Time mode was moved to a plug-in in 0.8, and since so many people use it
-            // we'll add an especially friendly reminder to make sure they included it.
-
-            if (opts.mode == "time" && !axis.tickGenerator) {
-                throw new Error("Time mode requires the flot.time plugin.");
-            }
-
-            // Flot supports base-10 axes; any other mode else is handled by a plug-in,
-            // like flot.time.js.
-
-            if (!axis.tickGenerator) {
-
-                axis.tickGenerator = function (axis) {
-
-                    var ticks = [],
-                        start = floorInBase(axis.min, axis.tickSize),
-                        i = 0,
-                        v = Number.NaN,
-                        prev;
-
-                    do {
-                        prev = v;
-                        v = start + i * axis.tickSize;
-                        ticks.push(v);
-                        ++i;
-                    } while (v < axis.max && v != prev);
-                    return ticks;
-                };
-
-				axis.tickFormatter = function (value, axis) {
-
-					var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1;
-					var formatted = "" + Math.round(value * factor) / factor;
-
-					// If tickDecimals was specified, ensure that we have exactly that
-					// much precision; otherwise default to the value's own precision.
-
-					if (axis.tickDecimals != null) {
-						var decimal = formatted.indexOf(".");
-						var precision = decimal == -1 ? 0 : formatted.length - decimal - 1;
-						if (precision < axis.tickDecimals) {
-							return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision);
-						}
-					}
-
-                    return formatted;
-                };
-            }
-
-            if ($.isFunction(opts.tickFormatter))
-                axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); };
-
-            if (opts.alignTicksWithAxis != null) {
-                var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1];
-                if (otherAxis && otherAxis.used && otherAxis != axis) {
-                    // consider snapping min/max to outermost nice ticks
-                    var niceTicks = axis.tickGenerator(axis);
-                    if (niceTicks.length > 0) {
-                        if (opts.min == null)
-                            axis.min = Math.min(axis.min, niceTicks[0]);
-                        if (opts.max == null && niceTicks.length > 1)
-                            axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]);
-                    }
-
-                    axis.tickGenerator = function (axis) {
-                        // copy ticks, scaled to this axis
-                        var ticks = [], v, i;
-                        for (i = 0; i < otherAxis.ticks.length; ++i) {
-                            v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min);
-                            v = axis.min + v * (axis.max - axis.min);
-                            ticks.push(v);
-                        }
-                        return ticks;
-                    };
-
-                    // we might need an extra decimal since forced
-                    // ticks don't necessarily fit naturally
-                    if (!axis.mode && opts.tickDecimals == null) {
-                        var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1),
-                            ts = axis.tickGenerator(axis);
-
-                        // only proceed if the tick interval rounded
-                        // with an extra decimal doesn't give us a
-                        // zero at end
-                        if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec))))
-                            axis.tickDecimals = extraDec;
-                    }
-                }
-            }
-        }
-
-        function setTicks(axis) {
-            var oticks = axis.options.ticks, ticks = [];
-            if (oticks == null || (typeof oticks == "number" && oticks > 0))
-                ticks = axis.tickGenerator(axis);
-            else if (oticks) {
-                if ($.isFunction(oticks))
-                    // generate the ticks
-                    ticks = oticks(axis);
-                else
-                    ticks = oticks;
-            }
-
-            // clean up/labelify the supplied ticks, copy them over
-            var i, v;
-            axis.ticks = [];
-            for (i = 0; i < ticks.length; ++i) {
-                var label = null;
-                var t = ticks[i];
-                if (typeof t == "object") {
-                    v = +t[0];
-                    if (t.length > 1)
-                        label = t[1];
-                }
-                else
-                    v = +t;
-                if (label == null)
-                    label = axis.tickFormatter(v, axis);
-                if (!isNaN(v))
-                    axis.ticks.push({ v: v, label: label });
-            }
-        }
-
-        function snapRangeToTicks(axis, ticks) {
-            if (axis.options.autoscaleMargin && ticks.length > 0) {
-                // snap to ticks
-                if (axis.options.min == null)
-                    axis.min = Math.min(axis.min, ticks[0].v);
-                if (axis.options.max == null && ticks.length > 1)
-                    axis.max = Math.max(axis.max, ticks[ticks.length - 1].v);
-            }
-        }
-
-        function draw() {
-
-            surface.clear();
-
-            executeHooks(hooks.drawBackground, [ctx]);
-
-            var grid = options.grid;
-
-            // draw background, if any
-            if (grid.show && grid.backgroundColor)
-                drawBackground();
-
-            if (grid.show && !grid.aboveData) {
-                drawGrid();
-            }
-
-            for (var i = 0; i < series.length; ++i) {
-                executeHooks(hooks.drawSeries, [ctx, series[i]]);
-                drawSeries(series[i]);
-            }
-
-            executeHooks(hooks.draw, [ctx]);
-
-            if (grid.show && grid.aboveData) {
-                drawGrid();
-            }
-
-            surface.render();
-
-            // A draw implies that either the axes or data have changed, so we
-            // should probably update the overlay highlights as well.
-
-            triggerRedrawOverlay();
-        }
-
-        function extractRange(ranges, coord) {
-            var axis, from, to, key, axes = allAxes();
-
-            for (var i = 0; i < axes.length; ++i) {
-                axis = axes[i];
-                if (axis.direction == coord) {
-                    key = coord + axis.n + "axis";
-                    if (!ranges[key] && axis.n == 1)
-                        key = coord + "axis"; // support x1axis as xaxis
-                    if (ranges[key]) {
-                        from = ranges[key].from;
-                        to = ranges[key].to;
-                        break;
-                    }
-                }
-            }
-
-            // backwards-compat stuff - to be removed in future
-            if (!ranges[key]) {
-                axis = coord == "x" ? xaxes[0] : yaxes[0];
-                from = ranges[coord + "1"];
-                to = ranges[coord + "2"];
-            }
-
-            // auto-reverse as an added bonus
-            if (from != null && to != null && from > to) {
-                var tmp = from;
-                from = to;
-                to = tmp;
-            }
-
-            return { from: from, to: to, axis: axis };
-        }
-
-        function drawBackground() {
-            ctx.save();
-            ctx.translate(plotOffset.left, plotOffset.top);
-
-            ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)");
-            ctx.fillRect(0, 0, plotWidth, plotHeight);
-            ctx.restore();
-        }
-
-        function drawGrid() {
-            var i, axes, bw, bc;
-
-            ctx.save();
-            ctx.translate(plotOffset.left, plotOffset.top);
-
-            // draw markings
-            var markings = options.grid.markings;
-            if (markings) {
-                if ($.isFunction(markings)) {
-                    axes = plot.getAxes();
-                    // xmin etc. is backwards compatibility, to be
-                    // removed in the future
-                    axes.xmin = axes.xaxis.min;
-                    axes.xmax = axes.xaxis.max;
-                    axes.ymin = axes.yaxis.min;
-                    axes.ymax = axes.yaxis.max;
-
-                    markings = markings(axes);
-                }
-
-                for (i = 0; i < markings.length; ++i) {
-                    var m = markings[i],
-                        xrange = extractRange(m, "x"),
-                        yrange = extractRange(m, "y");
-
-                    // fill in missing
-                    if (xrange.from == null)
-                        xrange.from = xrange.axis.min;
-                    if (xrange.to == null)
-                        xrange.to = xrange.axis.max;
-                    if (yrange.from == null)
-                        yrange.from = yrange.axis.min;
-                    if (yrange.to == null)
-                        yrange.to = yrange.axis.max;
-
-                    // clip
-                    if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max ||
-                        yrange.to < yrange.axis.min || yrange.from > yrange.axis.max)
-                        continue;
-
-                    xrange.from = Math.max(xrange.from, xrange.axis.min);
-                    xrange.to = Math.min(xrange.to, xrange.axis.max);
-                    yrange.from = Math.max(yrange.from, yrange.axis.min);
-                    yrange.to = Math.min(yrange.to, yrange.axis.max);
-
-                    var xequal = xrange.from === xrange.to,
-                        yequal = yrange.from === yrange.to;
-
-                    if (xequal && yequal) {
-                        continue;
-                    }
-
-                    // then draw
-                    xrange.from = Math.floor(xrange.axis.p2c(xrange.from));
-                    xrange.to = Math.floor(xrange.axis.p2c(xrange.to));
-                    yrange.from = Math.floor(yrange.axis.p2c(yrange.from));
-                    yrange.to = Math.floor(yrange.axis.p2c(yrange.to));
-
-                    if (xequal || yequal) {
-                        var lineWidth = m.lineWidth || options.grid.markingsLineWidth,
-                            subPixel = lineWidth % 2 ? 0.5 : 0;
-                        ctx.beginPath();
-                        ctx.strokeStyle = m.color || options.grid.markingsColor;
-                        ctx.lineWidth = lineWidth;
-                        if (xequal) {
-                            ctx.moveTo(xrange.to + subPixel, yrange.from);
-                            ctx.lineTo(xrange.to + subPixel, yrange.to);
-                        } else {
-                            ctx.moveTo(xrange.from, yrange.to + subPixel);
-                            ctx.lineTo(xrange.to, yrange.to + subPixel);                            
-                        }
-                        ctx.stroke();
-                    } else {
-                        ctx.fillStyle = m.color || options.grid.markingsColor;
-                        ctx.fillRect(xrange.from, yrange.to,
-                                     xrange.to - xrange.from,
-                                     yrange.from - yrange.to);
-                    }
-                }
-            }
-
-            // draw the ticks
-            axes = allAxes();
-            bw = options.grid.borderWidth;
-
-            for (var j = 0; j < axes.length; ++j) {
-                var axis = axes[j], box = axis.box,
-                    t = axis.tickLength, x, y, xoff, yoff;
-                if (!axis.show || axis.ticks.length == 0)
-                    continue;
-
-                ctx.lineWidth = 1;
-
-                // find the edges
-                if (axis.direction == "x") {
-                    x = 0;
-                    if (t == "full")
-                        y = (axis.position == "top" ? 0 : plotHeight);
-                    else
-                        y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0);
-                }
-                else {
-                    y = 0;
-                    if (t == "full")
-                        x = (axis.position == "left" ? 0 : plotWidth);
-                    else
-                        x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0);
-                }
-
-                // draw tick bar
-                if (!axis.innermost) {
-                    ctx.strokeStyle = axis.options.color;
-                    ctx.beginPath();
-                    xoff = yoff = 0;
-                    if (axis.direction == "x")
-                        xoff = plotWidth + 1;
-                    else
-                        yoff = plotHeight + 1;
-
-                    if (ctx.lineWidth == 1) {
-                        if (axis.direction == "x") {
-                            y = Math.floor(y) + 0.5;
-                        } else {
-                            x = Math.floor(x) + 0.5;
-                        }
-                    }
-
-                    ctx.moveTo(x, y);
-                    ctx.lineTo(x + xoff, y + yoff);
-                    ctx.stroke();
-                }
-
-                // draw ticks
-
-                ctx.strokeStyle = axis.options.tickColor;
-
-                ctx.beginPath();
-                for (i = 0; i < axis.ticks.length; ++i) {
-                    var v = axis.ticks[i].v;
-
-                    xoff = yoff = 0;
-
-                    if (isNaN(v) || v < axis.min || v > axis.max
-                        // skip those lying on the axes if we got a border
-                        || (t == "full"
-                            && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0)
-                            && (v == axis.min || v == axis.max)))
-                        continue;
-
-                    if (axis.direction == "x") {
-                        x = axis.p2c(v);
-                        yoff = t == "full" ? -plotHeight : t;
-
-                        if (axis.position == "top")
-                            yoff = -yoff;
-                    }
-                    else {
-                        y = axis.p2c(v);
-                        xoff = t == "full" ? -plotWidth : t;
-
-                        if (axis.position == "left")
-                            xoff = -xoff;
-                    }
-
-                    if (ctx.lineWidth == 1) {
-                        if (axis.direction == "x")
-                            x = Math.floor(x) + 0.5;
-                        else
-                            y = Math.floor(y) + 0.5;
-                    }
-
-                    ctx.moveTo(x, y);
-                    ctx.lineTo(x + xoff, y + yoff);
-                }
-
-                ctx.stroke();
-            }
-
-
-            // draw border
-            if (bw) {
-                // If either borderWidth or borderColor is an object, then draw the border
-                // line by line instead of as one rectangle
-                bc = options.grid.borderColor;
-                if(typeof bw == "object" || typeof bc == "object") {
-                    if (typeof bw !== "object") {
-                        bw = {top: bw, right: bw, bottom: bw, left: bw};
-                    }
-                    if (typeof bc !== "object") {
-                        bc = {top: bc, right: bc, bottom: bc, left: bc};
-                    }
-
-                    if (bw.top > 0) {
-                        ctx.strokeStyle = bc.top;
-                        ctx.lineWidth = bw.top;
-                        ctx.beginPath();
-                        ctx.moveTo(0 - bw.left, 0 - bw.top/2);
-                        ctx.lineTo(plotWidth, 0 - bw.top/2);
-                        ctx.stroke();
-                    }
-
-                    if (bw.right > 0) {
-                        ctx.strokeStyle = bc.right;
-                        ctx.lineWidth = bw.right;
-                        ctx.beginPath();
-                        ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top);
-                        ctx.lineTo(plotWidth + bw.right / 2, plotHeight);
-                        ctx.stroke();
-                    }
-
-                    if (bw.bottom > 0) {
-                        ctx.strokeStyle = bc.bottom;
-                        ctx.lineWidth = bw.bottom;
-                        ctx.beginPath();
-                        ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2);
-                        ctx.lineTo(0, plotHeight + bw.bottom / 2);
-                        ctx.stroke();
-                    }
-
-                    if (bw.left > 0) {
-                        ctx.strokeStyle = bc.left;
-                        ctx.lineWidth = bw.left;
-                        ctx.beginPath();
-                        ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom);
-                        ctx.lineTo(0- bw.left/2, 0);
-                        ctx.stroke();
-                    }
-                }
-                else {
-                    ctx.lineWidth = bw;
-                    ctx.strokeStyle = options.grid.borderColor;
-                    ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw);
-                }
-            }
-
-            ctx.restore();
-        }
-
-        function drawAxisLabels() {
-
-            $.each(allAxes(), function (_, axis) {
-                var box = axis.box,
-                    legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis",
-                    layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles,
-                    font = axis.options.font || "flot-tick-label tickLabel",
-                    tick, x, y, halign, valign;
-
-                // Remove text before checking for axis.show and ticks.length;
-                // otherwise plugins, like flot-tickrotor, that draw their own
-                // tick labels will end up with both theirs and the defaults.
-
-                surface.removeText(layer);
-
-                if (!axis.show || axis.ticks.length == 0)
-                    return;
-
-                for (var i = 0; i < axis.ticks.length; ++i) {
-
-                    tick = axis.ticks[i];
-                    if (!tick.label || tick.v < axis.min || tick.v > axis.max)
-                        continue;
-
-                    if (axis.direction == "x") {
-                        halign = "center";
-                        x = plotOffset.left + axis.p2c(tick.v);
-                        if (axis.position == "bottom") {
-                            y = box.top + box.padding;
-                        } else {
-                            y = box.top + box.height - box.padding;
-                            valign = "bottom";
-                        }
-                    } else {
-                        valign = "middle";
-                        y = plotOffset.top + axis.p2c(tick.v);
-                        if (axis.position == "left") {
-                            x = box.left + box.width - box.padding;
-                            halign = "right";
-                        } else {
-                            x = box.left + box.padding;
-                        }
-                    }
-
-                    surface.addText(layer, x, y, tick.label, font, null, null, halign, valign);
-                }
-            });
-        }
-
-        function drawSeries(series) {
-            if (series.lines.show)
-                drawSeriesLines(series);
-            if (series.bars.show)
-                drawSeriesBars(series);
-            if (series.points.show)
-                drawSeriesPoints(series);
-        }
-
-        function drawSeriesLines(series) {
-            function plotLine(datapoints, xoffset, yoffset, axisx, axisy) {
-                var points = datapoints.points,
-                    ps = datapoints.pointsize,
-                    prevx = null, prevy = null;
-
-                ctx.beginPath();
-                for (var i = ps; i < points.length; i += ps) {
-                    var x1 = points[i - ps], y1 = points[i - ps + 1],
-                        x2 = points[i], y2 = points[i + 1];
-
-                    if (x1 == null || x2 == null)
-                        continue;
-
-                    // clip with ymin
-                    if (y1 <= y2 && y1 < axisy.min) {
-                        if (y2 < axisy.min)
-                            continue;   // line segment is outside
-                        // compute new intersection point
-                        x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y1 = axisy.min;
-                    }
-                    else if (y2 <= y1 && y2 < axisy.min) {
-                        if (y1 < axisy.min)
-                            continue;
-                        x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y2 = axisy.min;
-                    }
-
-                    // clip with ymax
-                    if (y1 >= y2 && y1 > axisy.max) {
-                        if (y2 > axisy.max)
-                            continue;
-                        x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y1 = axisy.max;
-                    }
-                    else if (y2 >= y1 && y2 > axisy.max) {
-                        if (y1 > axisy.max)
-                            continue;
-                        x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y2 = axisy.max;
-                    }
-
-                    // clip with xmin
-                    if (x1 <= x2 && x1 < axisx.min) {
-                        if (x2 < axisx.min)
-                            continue;
-                        y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x1 = axisx.min;
-                    }
-                    else if (x2 <= x1 && x2 < axisx.min) {
-                        if (x1 < axisx.min)
-                            continue;
-                        y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x2 = axisx.min;
-                    }
-
-                    // clip with xmax
-                    if (x1 >= x2 && x1 > axisx.max) {
-                        if (x2 > axisx.max)
-                            continue;
-                        y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x1 = axisx.max;
-                    }
-                    else if (x2 >= x1 && x2 > axisx.max) {
-                        if (x1 > axisx.max)
-                            continue;
-                        y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x2 = axisx.max;
-                    }
-
-                    if (x1 != prevx || y1 != prevy)
-                        ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset);
-
-                    prevx = x2;
-                    prevy = y2;
-                    ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset);
-                }
-                ctx.stroke();
-            }
-
-            function plotLineArea(datapoints, axisx, axisy) {
-                var points = datapoints.points,
-                    ps = datapoints.pointsize,
-                    bottom = Math.min(Math.max(0, axisy.min), axisy.max),
-                    i = 0, top, areaOpen = false,
-                    ypos = 1, segmentStart = 0, segmentEnd = 0;
-
-                // we process each segment in two turns, first forward
-                // direction to sketch out top, then once we hit the
-                // end we go backwards to sketch the bottom
-                while (true) {
-                    if (ps > 0 && i > points.length + ps)
-                        break;
-
-                    i += ps; // ps is negative if going backwards
-
-                    var x1 = points[i - ps],
-                        y1 = points[i - ps + ypos],
-                        x2 = points[i], y2 = points[i + ypos];
-
-                    if (areaOpen) {
-                        if (ps > 0 && x1 != null && x2 == null) {
-                            // at turning point
-                            segmentEnd = i;
-                            ps = -ps;
-                            ypos = 2;
-                            continue;
-                        }
-
-                        if (ps < 0 && i == segmentStart + ps) {
-                            // done with the reverse sweep
-                            ctx.fill();
-                            areaOpen = false;
-                            ps = -ps;
-                            ypos = 1;
-                            i = segmentStart = segmentEnd + ps;
-                            continue;
-                        }
-                    }
-
-                    if (x1 == null || x2 == null)
-                        continue;
-
-                    // clip x values
-
-                    // clip with xmin
-                    if (x1 <= x2 && x1 < axisx.min) {
-                        if (x2 < axisx.min)
-                            continue;
-                        y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x1 = axisx.min;
-                    }
-                    else if (x2 <= x1 && x2 < axisx.min) {
-                        if (x1 < axisx.min)
-                            continue;
-                        y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x2 = axisx.min;
-                    }
-
-                    // clip with xmax
-                    if (x1 >= x2 && x1 > axisx.max) {
-                        if (x2 > axisx.max)
-                            continue;
-                        y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x1 = axisx.max;
-                    }
-                    else if (x2 >= x1 && x2 > axisx.max) {
-                        if (x1 > axisx.max)
-                            continue;
-                        y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1;
-                        x2 = axisx.max;
-                    }
-
-                    if (!areaOpen) {
-                        // open area
-                        ctx.beginPath();
-                        ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom));
-                        areaOpen = true;
-                    }
-
-                    // now first check the case where both is outside
-                    if (y1 >= axisy.max && y2 >= axisy.max) {
-                        ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max));
-                        ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max));
-                        continue;
-                    }
-                    else if (y1 <= axisy.min && y2 <= axisy.min) {
-                        ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min));
-                        ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min));
-                        continue;
-                    }
-
-                    // else it's a bit more complicated, there might
-                    // be a flat maxed out rectangle first, then a
-                    // triangular cutout or reverse; to find these
-                    // keep track of the current x values
-                    var x1old = x1, x2old = x2;
-
-                    // clip the y values, without shortcutting, we
-                    // go through all cases in turn
-
-                    // clip with ymin
-                    if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) {
-                        x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y1 = axisy.min;
-                    }
-                    else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) {
-                        x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y2 = axisy.min;
-                    }
-
-                    // clip with ymax
-                    if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) {
-                        x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y1 = axisy.max;
-                    }
-                    else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) {
-                        x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1;
-                        y2 = axisy.max;
-                    }
-
-                    // if the x value was changed we got a rectangle
-                    // to fill
-                    if (x1 != x1old) {
-                        ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1));
-                        // it goes to (x1, y1), but we fill that below
-                    }
-
-                    // fill triangular section, this sometimes result
-                    // in redundant points if (x1, y1) hasn't changed
-                    // from previous line to, but we just ignore that
-                    ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1));
-                    ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
-
-                    // fill the other rectangle if it's there
-                    if (x2 != x2old) {
-                        ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2));
-                        ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2));
-                    }
-                }
-            }
-
-            ctx.save();
-            ctx.translate(plotOffset.left, plotOffset.top);
-            ctx.lineJoin = "round";
-
-            var lw = series.lines.lineWidth,
-                sw = series.shadowSize;
-            // FIXME: consider another form of shadow when filling is turned on
-            if (lw > 0 && sw > 0) {
-                // draw shadow as a thick and thin line with transparency
-                ctx.lineWidth = sw;
-                ctx.strokeStyle = "rgba(0,0,0,0.1)";
-                // position shadow at angle from the mid of line
-                var angle = Math.PI/18;
-                plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis);
-                ctx.lineWidth = sw/2;
-                plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis);
-            }
-
-            ctx.lineWidth = lw;
-            ctx.strokeStyle = series.color;
-            var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight);
-            if (fillStyle) {
-                ctx.fillStyle = fillStyle;
-                plotLineArea(series.datapoints, series.xaxis, series.yaxis);
-            }
-
-            if (lw > 0)
-                plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis);
-            ctx.restore();
-        }
-
-        function drawSeriesPoints(series) {
-            function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) {
-                var points = datapoints.points, ps = datapoints.pointsize;
-
-                for (var i = 0; i < points.length; i += ps) {
-                    var x = points[i], y = points[i + 1];
-                    if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
-                        continue;
-
-                    ctx.beginPath();
-                    x = axisx.p2c(x);
-                    y = axisy.p2c(y) + offset;
-                    if (symbol == "circle")
-                        ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false);
-                    else
-                        symbol(ctx, x, y, radius, shadow);
-                    ctx.closePath();
-
-                    if (fillStyle) {
-                        ctx.fillStyle = fillStyle;
-                        ctx.fill();
-                    }
-                    ctx.stroke();
-                }
-            }
-
-            ctx.save();
-            ctx.translate(plotOffset.left, plotOffset.top);
-
-            var lw = series.points.lineWidth,
-                sw = series.shadowSize,
-                radius = series.points.radius,
-                symbol = series.points.symbol;
-
-            // If the user sets the line width to 0, we change it to a very 
-            // small value. A line width of 0 seems to force the default of 1.
-            // Doing the conditional here allows the shadow setting to still be 
-            // optional even with a lineWidth of 0.
-
-            if( lw == 0 )
-                lw = 0.0001;
-
-            if (lw > 0 && sw > 0) {
-                // draw shadow in two steps
-                var w = sw / 2;
-                ctx.lineWidth = w;
-                ctx.strokeStyle = "rgba(0,0,0,0.1)";
-                plotPoints(series.datapoints, radius, null, w + w/2, true,
-                           series.xaxis, series.yaxis, symbol);
-
-                ctx.strokeStyle = "rgba(0,0,0,0.2)";
-                plotPoints(series.datapoints, radius, null, w/2, true,
-                           series.xaxis, series.yaxis, symbol);
-            }
-
-            ctx.lineWidth = lw;
-            ctx.strokeStyle = series.color;
-            plotPoints(series.datapoints, radius,
-                       getFillStyle(series.points, series.color), 0, false,
-                       series.xaxis, series.yaxis, symbol);
-            ctx.restore();
-        }
-
-        function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) {
-            var left, right, bottom, top,
-                drawLeft, drawRight, drawTop, drawBottom,
-                tmp;
-
-            // in horizontal mode, we start the bar from the left
-            // instead of from the bottom so it appears to be
-            // horizontal rather than vertical
-            if (horizontal) {
-                drawBottom = drawRight = drawTop = true;
-                drawLeft = false;
-                left = b;
-                right = x;
-                top = y + barLeft;
-                bottom = y + barRight;
-
-                // account for negative bars
-                if (right < left) {
-                    tmp = right;
-                    right = left;
-                    left = tmp;
-                    drawLeft = true;
-                    drawRight = false;
-                }
-            }
-            else {
-                drawLeft = drawRight = drawTop = true;
-                drawBottom = false;
-                left = x + barLeft;
-                right = x + barRight;
-                bottom = b;
-                top = y;
-
-                // account for negative bars
-                if (top < bottom) {
-                    tmp = top;
-                    top = bottom;
-                    bottom = tmp;
-                    drawBottom = true;
-                    drawTop = false;
-                }
-            }
-
-            // clip
-            if (right < axisx.min || left > axisx.max ||
-                top < axisy.min || bottom > axisy.max)
-                return;
-
-            if (left < axisx.min) {
-                left = axisx.min;
-                drawLeft = false;
-            }
-
-            if (right > axisx.max) {
-                right = axisx.max;
-                drawRight = false;
-            }
-
-            if (bottom < axisy.min) {
-                bottom = axisy.min;
-                drawBottom = false;
-            }
-
-            if (top > axisy.max) {
-                top = axisy.max;
-                drawTop = false;
-            }
-
-            left = axisx.p2c(left);
-            bottom = axisy.p2c(bottom);
-            right = axisx.p2c(right);
-            top = axisy.p2c(top);
-
-            // fill the bar
-            if (fillStyleCallback) {
-                c.fillStyle = fillStyleCallback(bottom, top);
-                c.fillRect(left, top, right - left, bottom - top)
-            }
-
-            // draw outline
-            if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) {
-                c.beginPath();
-
-                // FIXME: inline moveTo is buggy with excanvas
-                c.moveTo(left, bottom);
-                if (drawLeft)
-                    c.lineTo(left, top);
-                else
-                    c.moveTo(left, top);
-                if (drawTop)
-                    c.lineTo(right, top);
-                else
-                    c.moveTo(right, top);
-                if (drawRight)
-                    c.lineTo(right, bottom);
-                else
-                    c.moveTo(right, bottom);
-                if (drawBottom)
-                    c.lineTo(left, bottom);
-                else
-                    c.moveTo(left, bottom);
-                c.stroke();
-            }
-        }
-
-        function drawSeriesBars(series) {
-            function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) {
-                var points = datapoints.points, ps = datapoints.pointsize;
-
-                for (var i = 0; i < points.length; i += ps) {
-                    if (points[i] == null)
-                        continue;
-                    drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth);
-                }
-            }
-
-            ctx.save();
-            ctx.translate(plotOffset.left, plotOffset.top);
-
-            // FIXME: figure out a way to add shadows (for instance along the right edge)
-            ctx.lineWidth = series.bars.lineWidth;
-            ctx.strokeStyle = series.color;
-
-            var barLeft;
-
-            switch (series.bars.align) {
-                case "left":
-                    barLeft = 0;
-                    break;
-                case "right":
-                    barLeft = -series.bars.barWidth;
-                    break;
-                default:
-                    barLeft = -series.bars.barWidth / 2;
-            }
-
-            var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null;
-            plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis);
-            ctx.restore();
-        }
-
-        function getFillStyle(filloptions, seriesColor, bottom, top) {
-            var fill = filloptions.fill;
-            if (!fill)
-                return null;
-
-            if (filloptions.fillColor)
-                return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor);
-
-            var c = $.color.parse(seriesColor);
-            c.a = typeof fill == "number" ? fill : 0.4;
-            c.normalize();
-            return c.toString();
-        }
-
-        function insertLegend() {
-
-            if (options.legend.container != null) {
-                $(options.legend.container).html("");
-            } else {
-                placeholder.find(".legend").remove();
-            }
-
-            if (!options.legend.show) {
-                return;
-            }
-
-            var fragments = [], entries = [], rowStarted = false,
-                lf = options.legend.labelFormatter, s, label;
-
-            // Build a list of legend entries, with each having a label and a color
-
-            for (var i = 0; i < series.length; ++i) {
-                s = series[i];
-                if (s.label) {
-                    label = lf ? lf(s.label, s) : s.label;
-                    if (label) {
-                        entries.push({
-                            label: label,
-                            color: s.color
-                        });
-                    }
-                }
-            }
-
-            // Sort the legend using either the default or a custom comparator
-
-            if (options.legend.sorted) {
-                if ($.isFunction(options.legend.sorted)) {
-                    entries.sort(options.legend.sorted);
-                } else if (options.legend.sorted == "reverse") {
-                	entries.reverse();
-                } else {
-                    var ascending = options.legend.sorted != "descending";
-                    entries.sort(function(a, b) {
-                        return a.label == b.label ? 0 : (
-                            (a.label < b.label) != ascending ? 1 : -1   // Logical XOR
-                        );
-                    });
-                }
-            }
-
-            // Generate markup for the list of entries, in their final order
-
-            for (var i = 0; i < entries.length; ++i) {
-
-                var entry = entries[i];
-
-                if (i % options.legend.noColumns == 0) {
-                    if (rowStarted)
-                        fragments.push('</tr>');
-                    fragments.push('<tr>');
-                    rowStarted = true;
-                }
-
-                fragments.push(
-                    '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' +
-                    '<td class="legendLabel">' + entry.label + '</td>'
-                );
-            }
-
-            if (rowStarted)
-                fragments.push('</tr>');
-
-            if (fragments.length == 0)
-                return;
-
-            var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>';
-            if (options.legend.container != null)
-                $(options.legend.container).html(table);
-            else {
-                var pos = "",
-                    p = options.legend.position,
-                    m = options.legend.margin;
-                if (m[0] == null)
-                    m = [m, m];
-                if (p.charAt(0) == "n")
-                    pos += 'top:' + (m[1] + plotOffset.top) + 'px;';
-                else if (p.charAt(0) == "s")
-                    pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;';
-                if (p.charAt(1) == "e")
-                    pos += 'right:' + (m[0] + plotOffset.right) + 'px;';
-                else if (p.charAt(1) == "w")
-                    pos += 'left:' + (m[0] + plotOffset.left) + 'px;';
-                var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder);
-                if (options.legend.backgroundOpacity != 0.0) {
-                    // put in the transparent background
-                    // separately to avoid blended labels and
-                    // label boxes
-                    var c = options.legend.backgroundColor;
-                    if (c == null) {
-                        c = options.grid.backgroundColor;
-                        if (c && typeof c == "string")
-                            c = $.color.parse(c);
-                        else
-                            c = $.color.extract(legend, 'background-color');
-                        c.a = 1;
-                        c = c.toString();
-                    }
-                    var div = legend.children();
-                    $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity);
-                }
-            }
-        }
-
-
-        // interactive features
-
-        var highlights = [],
-            redrawTimeout = null;
-
-        // returns the data item the mouse is over, or null if none is found
-        function findNearbyItem(mouseX, mouseY, seriesFilter) {
-            var maxDistance = options.grid.mouseActiveRadius,
-                smallestDistance = maxDistance * maxDistance + 1,
-                item = null, foundPoint = false, i, j, ps;
-
-            for (i = series.length - 1; i >= 0; --i) {
-                if (!seriesFilter(series[i]))
-                    continue;
-
-                var s = series[i],
-                    axisx = s.xaxis,
-                    axisy = s.yaxis,
-                    points = s.datapoints.points,
-                    mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster
-                    my = axisy.c2p(mouseY),
-                    maxx = maxDistance / axisx.scale,
-                    maxy = maxDistance / axisy.scale;
-
-                ps = s.datapoints.pointsize;
-                // with inverse transforms, we can't use the maxx/maxy
-                // optimization, sadly
-                if (axisx.options.inverseTransform)
-                    maxx = Number.MAX_VALUE;
-                if (axisy.options.inverseTransform)
-                    maxy = Number.MAX_VALUE;
-
-                if (s.lines.show || s.points.show) {
-                    for (j = 0; j < points.length; j += ps) {
-                        var x = points[j], y = points[j + 1];
-                        if (x == null)
-                            continue;
-
-                        // For points and lines, the cursor must be within a
-                        // certain distance to the data point
-                        if (x - mx > maxx || x - mx < -maxx ||
-                            y - my > maxy || y - my < -maxy)
-                            continue;
-
-                        // We have to calculate distances in pixels, not in
-                        // data units, because the scales of the axes may be different
-                        var dx = Math.abs(axisx.p2c(x) - mouseX),
-                            dy = Math.abs(axisy.p2c(y) - mouseY),
-                            dist = dx * dx + dy * dy; // we save the sqrt
-
-                        // use <= to ensure last point takes precedence
-                        // (last generally means on top of)
-                        if (dist < smallestDistance) {
-                            smallestDistance = dist;
-                            item = [i, j / ps];
-                        }
-                    }
-                }
-
-                if (s.bars.show && !item) { // no other point can be nearby
-
-                    var barLeft, barRight;
-
-                    switch (s.bars.align) {
-                        case "left":
-                            barLeft = 0;
-                            break;
-                        case "right":
-                            barLeft = -s.bars.barWidth;
-                            break;
-                        default:
-                            barLeft = -s.bars.barWidth / 2;
-                    }
-
-                    barRight = barLeft + s.bars.barWidth;
-
-                    for (j = 0; j < points.length; j += ps) {
-                        var x = points[j], y = points[j + 1], b = points[j + 2];
-                        if (x == null)
-                            continue;
-
-                        // for a bar graph, the cursor must be inside the bar
-                        if (series[i].bars.horizontal ?
-                            (mx <= Math.max(b, x) && mx >= Math.min(b, x) &&
-                             my >= y + barLeft && my <= y + barRight) :
-                            (mx >= x + barLeft && mx <= x + barRight &&
-                             my >= Math.min(b, y) && my <= Math.max(b, y)))
-                                item = [i, j / ps];
-                    }
-                }
-            }
-
-            if (item) {
-                i = item[0];
-                j = item[1];
-                ps = series[i].datapoints.pointsize;
-
-                return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps),
-                         dataIndex: j,
-                         series: series[i],
-                         seriesIndex: i };
-            }
-
-            return null;
-        }
-
-        function onMouseMove(e) {
-            if (options.grid.hoverable)
-                triggerClickHoverEvent("plothover", e,
-                                       function (s) { return s["hoverable"] != false; });
-        }
-
-        function onMouseLeave(e) {
-            if (options.grid.hoverable)
-                triggerClickHoverEvent("plothover", e,
-                                       function (s) { return false; });
-        }
-
-        function onClick(e) {
-            triggerClickHoverEvent("plotclick", e,
-                                   function (s) { return s["clickable"] != false; });
-        }
-
-        // trigger click or hover event (they send the same parameters
-        // so we share their code)
-        function triggerClickHoverEvent(eventname, event, seriesFilter) {
-            var offset = eventHolder.offset(),
-                canvasX = event.pageX - offset.left - plotOffset.left,
-                canvasY = event.pageY - offset.top - plotOffset.top,
-            pos = canvasToAxisCoords({ left: canvasX, top: canvasY });
-
-            pos.pageX = event.pageX;
-            pos.pageY = event.pageY;
-
-            var item = findNearbyItem(canvasX, canvasY, seriesFilter);
-
-            if (item) {
-                // fill in mouse pos for any listeners out there
-                item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10);
-                item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10);
-            }
-
-            if (options.grid.autoHighlight) {
-                // clear auto-highlights
-                for (var i = 0; i < highlights.length; ++i) {
-                    var h = highlights[i];
-                    if (h.auto == eventname &&
-                        !(item && h.series == item.series &&
-                          h.point[0] == item.datapoint[0] &&
-                          h.point[1] == item.datapoint[1]))
-                        unhighlight(h.series, h.point);
-                }
-
-                if (item)
-                    highlight(item.series, item.datapoint, eventname);
-            }
-
-            placeholder.trigger(eventname, [ pos, item ]);
-        }
-
-        function triggerRedrawOverlay() {
-            var t = options.interaction.redrawOverlayInterval;
-            if (t == -1) {      // skip event queue
-                drawOverlay();
-                return;
-            }
-
-            if (!redrawTimeout)
-                redrawTimeout = setTimeout(drawOverlay, t);
-        }
-
-        function drawOverlay() {
-            redrawTimeout = null;
-
-            // draw highlights
-            octx.save();
-            overlay.clear();
-            octx.translate(plotOffset.left, plotOffset.top);
-
-            var i, hi;
-            for (i = 0; i < highlights.length; ++i) {
-                hi = highlights[i];
-
-                if (hi.series.bars.show)
-                    drawBarHighlight(hi.series, hi.point);
-                else
-                    drawPointHighlight(hi.series, hi.point);
-            }
-            octx.restore();
-
-            executeHooks(hooks.drawOverlay, [octx]);
-        }
-
-        function highlight(s, point, auto) {
-            if (typeof s == "number")
-                s = series[s];
-
-            if (typeof point == "number") {
-                var ps = s.datapoints.pointsize;
-                point = s.datapoints.points.slice(ps * point, ps * (point + 1));
-            }
-
-            var i = indexOfHighlight(s, point);
-            if (i == -1) {
-                highlights.push({ series: s, point: point, auto: auto });
-
-                triggerRedrawOverlay();
-            }
-            else if (!auto)
-                highlights[i].auto = false;
-        }
-
-        function unhighlight(s, point) {
-            if (s == null && point == null) {
-                highlights = [];
-                triggerRedrawOverlay();
-                return;
-            }
-
-            if (typeof s == "number")
-                s = series[s];
-
-            if (typeof point == "number") {
-                var ps = s.datapoints.pointsize;
-                point = s.datapoints.points.slice(ps * point, ps * (point + 1));
-            }
-
-            var i = indexOfHighlight(s, point);
-            if (i != -1) {
-                highlights.splice(i, 1);
-
-                triggerRedrawOverlay();
-            }
-        }
-
-        function indexOfHighlight(s, p) {
-            for (var i = 0; i < highlights.length; ++i) {
-                var h = highlights[i];
-                if (h.series == s && h.point[0] == p[0]
-                    && h.point[1] == p[1])
-                    return i;
-            }
-            return -1;
-        }
-
-        function drawPointHighlight(series, point) {
-            var x = point[0], y = point[1],
-                axisx = series.xaxis, axisy = series.yaxis,
-                highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString();
-
-            if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max)
-                return;
-
-            var pointRadius = series.points.radius + series.points.lineWidth / 2;
-            octx.lineWidth = pointRadius;
-            octx.strokeStyle = highlightColor;
-            var radius = 1.5 * pointRadius;
-            x = axisx.p2c(x);
-            y = axisy.p2c(y);
-
-            octx.beginPath();
-            if (series.points.symbol == "circle")
-                octx.arc(x, y, radius, 0, 2 * Math.PI, false);
-            else
-                series.points.symbol(octx, x, y, radius, false);
-            octx.closePath();
-            octx.stroke();
-        }
-
-        function drawBarHighlight(series, point) {
-            var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(),
-                fillStyle = highlightColor,
-                barLeft;
-
-            switch (series.bars.align) {
-                case "left":
-                    barLeft = 0;
-                    break;
-                case "right":
-                    barLeft = -series.bars.barWidth;
-                    break;
-                default:
-                    barLeft = -series.bars.barWidth / 2;
-            }
-
-            octx.lineWidth = series.bars.lineWidth;
-            octx.strokeStyle = highlightColor;
-
-            drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth,
-                    function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth);
-        }
-
-        function getColorOrGradient(spec, bottom, top, defaultColor) {
-            if (typeof spec == "string")
-                return spec;
-            else {
-                // assume this is a gradient spec; IE currently only
-                // supports a simple vertical gradient properly, so that's
-                // what we support too
-                var gradient = ctx.createLinearGradient(0, top, 0, bottom);
-
-                for (var i = 0, l = spec.colors.length; i < l; ++i) {
-                    var c = spec.colors[i];
-                    if (typeof c != "string") {
-                        var co = $.color.parse(defaultColor);
-                        if (c.brightness != null)
-                            co = co.scale('rgb', c.brightness);
-                        if (c.opacity != null)
-                            co.a *= c.opacity;
-                        c = co.toString();
-                    }
-                    gradient.addColorStop(i / (l - 1), c);
-                }
-
-                return gradient;
-            }
-        }
-    }
-
-    // Add the plot function to the top level of the jQuery object
-
-    $.plot = function(placeholder, data, options) {
-        //var t0 = new Date();
-        var plot = new Plot($(placeholder), data, options, $.plot.plugins);
-        //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime()));
-        return plot;
-    };
-
-    $.plot.version = "0.8.3";
-
-    $.plot.plugins = [];
-
-    // Also add the plot function as a chainable property
-
-    $.fn.plot = function(data, options) {
-        return this.each(function() {
-            $.plot(this, data, options);
-        });
-    };
-
-    // round to nearby lower multiple of base
-    function floorInBase(n, base) {
-        return base * Math.floor(n / base);
-    }
-
-})(jQuery);
diff --git a/static/js/jquery.flot.min.js b/static/js/jquery.flot.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.min.js
+++ /dev/null
@@ -1,8 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);(function($){var hasOwnProperty=Object.prototype.hasOwnProperty;if(!$.fn.detach){$.fn.detach=function(){return this.each(function(){if(this.parentNode){this.parentNode.removeChild(this)}})}}function Canvas(cls,container){var element=container.children("."+cls)[0];if(element==null){element=document.createElement("canvas");element.className=cls;$(element).css({direction:"ltr",position:"absolute",left:0,top:0}).appendTo(container);if(!element.getContext){if(window.G_vmlCanvasManager){element=window.G_vmlCanvasManager.initElement(element)}else{throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode.")}}}this.element=element;var context=this.context=element.getContext("2d");var devicePixelRatio=window.devicePixelRatio||1,backingStoreRatio=context.webkitBackingStorePixelRatio||context.mozBackingStorePixelRatio||context.msBackingStorePixelRatio||context.oBackingStorePixelRatio||context.backingStorePixelRatio||1;this.pixelRatio=devicePixelRatio/backingStoreRatio;this.resize(container.width(),container.height());this.textContainer=null;this.text={};this._textCache={}}Canvas.prototype.resize=function(width,height){if(width<=0||height<=0){throw new Error("Invalid dimensions for plot, width = "+width+", height = "+height)}var element=this.element,context=this.context,pixelRatio=this.pixelRatio;if(this.width!=width){element.width=width*pixelRatio;element.style.width=width+"px";this.width=width}if(this.height!=height){element.height=height*pixelRatio;element.style.height=height+"px";this.height=height}context.restore();context.save();context.scale(pixelRatio,pixelRatio)};Canvas.prototype.clear=function(){this.context.clearRect(0,0,this.width,this.height)};Canvas.prototype.render=function(){var cache=this._textCache;for(var layerKey in cache){if(hasOwnProperty.call(cache,layerKey)){var layer=this.getTextLayer(layerKey),layerCache=cache[layerKey];layer.hide();for(var styleKey in layerCache){if(hasOwnProperty.call(layerCache,styleKey)){var styleCache=layerCache[styleKey];for(var key in styleCache){if(hasOwnProperty.call(styleCache,key)){var positions=styleCache[key].positions;for(var i=0,position;position=positions[i];i++){if(position.active){if(!position.rendered){layer.append(position.element);position.rendered=true}}else{positions.splice(i--,1);if(position.rendered){position.element.detach()}}}if(positions.length==0){delete styleCache[key]}}}}}layer.show()}}};Canvas.prototype.getTextLayer=function(classes){var layer=this.text[classes];if(layer==null){if(this.textContainer==null){this.textContainer=$("<div class='flot-text'></div>").css({position:"absolute",top:0,left:0,bottom:0,right:0,"font-size":"smaller",color:"#545454"}).insertAfter(this.element)}layer=this.text[classes]=$("<div></div>").addClass(classes).css({position:"absolute",top:0,left:0,bottom:0,right:0}).appendTo(this.textContainer)}return layer};Canvas.prototype.getTextInfo=function(layer,text,font,angle,width){var textStyle,layerCache,styleCache,info;text=""+text;if(typeof font==="object"){textStyle=font.style+" "+font.variant+" "+font.weight+" "+font.size+"px/"+font.lineHeight+"px "+font.family}else{textStyle=font}layerCache=this._textCache[layer];if(layerCache==null){layerCache=this._textCache[layer]={}}styleCache=layerCache[textStyle];if(styleCache==null){styleCache=layerCache[textStyle]={}}info=styleCache[text];if(info==null){var element=$("<div></div>").html(text).css({position:"absolute","max-width":width,top:-9999}).appendTo(this.getTextLayer(layer));if(typeof font==="object"){element.css({font:textStyle,color:font.color})}else if(typeof font==="string"){element.addClass(font)}info=styleCache[text]={width:element.outerWidth(true),height:element.outerHeight(true),element:element,positions:[]};element.detach()}return info};Canvas.prototype.addText=function(layer,x,y,text,font,angle,width,halign,valign){var info=this.getTextInfo(layer,text,font,angle,width),positions=info.positions;if(halign=="center"){x-=info.width/2}else if(halign=="right"){x-=info.width}if(valign=="middle"){y-=info.height/2}else if(valign=="bottom"){y-=info.height}for(var i=0,position;position=positions[i];i++){if(position.x==x&&position.y==y){position.active=true;return}}position={active:true,rendered:false,element:positions.length?info.element.clone():info.element,x:x,y:y};positions.push(position);position.element.css({top:Math.round(y),left:Math.round(x),"text-align":halign})};Canvas.prototype.removeText=function(layer,x,y,text,font,angle){if(text==null){var layerCache=this._textCache[layer];if(layerCache!=null){for(var styleKey in layerCache){if(hasOwnProperty.call(layerCache,styleKey)){var styleCache=layerCache[styleKey];for(var key in styleCache){if(hasOwnProperty.call(styleCache,key)){var positions=styleCache[key].positions;for(var i=0,position;position=positions[i];i++){position.active=false}}}}}}}else{var positions=this.getTextInfo(layer,text,font,angle).positions;for(var i=0,position;position=positions[i];i++){if(position.x==x&&position.y==y){position.active=false}}}};function Plot(placeholder,data_,options_,plugins){var series=[],options={colors:["#edc240","#afd8f8","#cb4b4b","#4da74d","#9440ed"],legend:{show:true,noColumns:1,labelFormatter:null,labelBoxBorderColor:"#ccc",container:null,position:"ne",margin:5,backgroundColor:null,backgroundOpacity:.85,sorted:null},xaxis:{show:null,position:"bottom",mode:null,font:null,color:null,tickColor:null,transform:null,inverseTransform:null,min:null,max:null,autoscaleMargin:null,ticks:null,tickFormatter:null,labelWidth:null,labelHeight:null,reserveSpace:null,tickLength:null,alignTicksWithAxis:null,tickDecimals:null,tickSize:null,minTickSize:null},yaxis:{autoscaleMargin:.02,position:"left"},xaxes:[],yaxes:[],series:{points:{show:false,radius:3,lineWidth:2,fill:true,fillColor:"#ffffff",symbol:"circle"},lines:{lineWidth:2,fill:false,fillColor:null,steps:false},bars:{show:false,lineWidth:2,barWidth:1,fill:true,fillColor:null,align:"left",horizontal:false,zero:true},shadowSize:3,highlightColor:null},grid:{show:true,aboveData:false,color:"#545454",backgroundColor:null,borderColor:null,tickColor:null,margin:0,labelMargin:5,axisMargin:8,borderWidth:2,minBorderMargin:null,markings:null,markingsColor:"#f4f4f4",markingsLineWidth:2,clickable:false,hoverable:false,autoHighlight:true,mouseActiveRadius:10},interaction:{redrawOverlayInterval:1e3/60},hooks:{}},surface=null,overlay=null,eventHolder=null,ctx=null,octx=null,xaxes=[],yaxes=[],plotOffset={left:0,right:0,top:0,bottom:0},plotWidth=0,plotHeight=0,hooks={processOptions:[],processRawData:[],processDatapoints:[],processOffset:[],drawBackground:[],drawSeries:[],draw:[],bindEvents:[],drawOverlay:[],shutdown:[]},plot=this;plot.setData=setData;plot.setupGrid=setupGrid;plot.draw=draw;plot.getPlaceholder=function(){return placeholder};plot.getCanvas=function(){return surface.element};plot.getPlotOffset=function(){return plotOffset};plot.width=function(){return plotWidth};plot.height=function(){return plotHeight};plot.offset=function(){var o=eventHolder.offset();o.left+=plotOffset.left;o.top+=plotOffset.top;return o};plot.getData=function(){return series};plot.getAxes=function(){var res={},i;$.each(xaxes.concat(yaxes),function(_,axis){if(axis)res[axis.direction+(axis.n!=1?axis.n:"")+"axis"]=axis});return res};plot.getXAxes=function(){return xaxes};plot.getYAxes=function(){return yaxes};plot.c2p=canvasToAxisCoords;plot.p2c=axisToCanvasCoords;plot.getOptions=function(){return options};plot.highlight=highlight;plot.unhighlight=unhighlight;plot.triggerRedrawOverlay=triggerRedrawOverlay;plot.pointOffset=function(point){return{left:parseInt(xaxes[axisNumber(point,"x")-1].p2c(+point.x)+plotOffset.left,10),top:parseInt(yaxes[axisNumber(point,"y")-1].p2c(+point.y)+plotOffset.top,10)}};plot.shutdown=shutdown;plot.destroy=function(){shutdown();placeholder.removeData("plot").empty();series=[];options=null;surface=null;overlay=null;eventHolder=null;ctx=null;octx=null;xaxes=[];yaxes=[];hooks=null;highlights=[];plot=null};plot.resize=function(){var width=placeholder.width(),height=placeholder.height();surface.resize(width,height);overlay.resize(width,height)};plot.hooks=hooks;initPlugins(plot);parseOptions(options_);setupCanvases();setData(data_);setupGrid();draw();bindEvents();function executeHooks(hook,args){args=[plot].concat(args);for(var i=0;i<hook.length;++i)hook[i].apply(this,args)}function initPlugins(){var classes={Canvas:Canvas};for(var i=0;i<plugins.length;++i){var p=plugins[i];p.init(plot,classes);if(p.options)$.extend(true,options,p.options)}}function parseOptions(opts){$.extend(true,options,opts);if(opts&&opts.colors){options.colors=opts.colors}if(options.xaxis.color==null)options.xaxis.color=$.color.parse(options.grid.color).scale("a",.22).toString();if(options.yaxis.color==null)options.yaxis.color=$.color.parse(options.grid.color).scale("a",.22).toString();if(options.xaxis.tickColor==null)options.xaxis.tickColor=options.grid.tickColor||options.xaxis.color;if(options.yaxis.tickColor==null)options.yaxis.tickColor=options.grid.tickColor||options.yaxis.color;if(options.grid.borderColor==null)options.grid.borderColor=options.grid.color;if(options.grid.tickColor==null)options.grid.tickColor=$.color.parse(options.grid.color).scale("a",.22).toString();var i,axisOptions,axisCount,fontSize=placeholder.css("font-size"),fontSizeDefault=fontSize?+fontSize.replace("px",""):13,fontDefaults={style:placeholder.css("font-style"),size:Math.round(.8*fontSizeDefault),variant:placeholder.css("font-variant"),weight:placeholder.css("font-weight"),family:placeholder.css("font-family")};axisCount=options.xaxes.length||1;for(i=0;i<axisCount;++i){axisOptions=options.xaxes[i];if(axisOptions&&!axisOptions.tickColor){axisOptions.tickColor=axisOptions.color}axisOptions=$.extend(true,{},options.xaxis,axisOptions);options.xaxes[i]=axisOptions;if(axisOptions.font){axisOptions.font=$.extend({},fontDefaults,axisOptions.font);if(!axisOptions.font.color){axisOptions.font.color=axisOptions.color}if(!axisOptions.font.lineHeight){axisOptions.font.lineHeight=Math.round(axisOptions.font.size*1.15)}}}axisCount=options.yaxes.length||1;for(i=0;i<axisCount;++i){axisOptions=options.yaxes[i];if(axisOptions&&!axisOptions.tickColor){axisOptions.tickColor=axisOptions.color}axisOptions=$.extend(true,{},options.yaxis,axisOptions);options.yaxes[i]=axisOptions;if(axisOptions.font){axisOptions.font=$.extend({},fontDefaults,axisOptions.font);if(!axisOptions.font.color){axisOptions.font.color=axisOptions.color}if(!axisOptions.font.lineHeight){axisOptions.font.lineHeight=Math.round(axisOptions.font.size*1.15)}}}if(options.xaxis.noTicks&&options.xaxis.ticks==null)options.xaxis.ticks=options.xaxis.noTicks;if(options.yaxis.noTicks&&options.yaxis.ticks==null)options.yaxis.ticks=options.yaxis.noTicks;if(options.x2axis){options.xaxes[1]=$.extend(true,{},options.xaxis,options.x2axis);options.xaxes[1].position="top";if(options.x2axis.min==null){options.xaxes[1].min=null}if(options.x2axis.max==null){options.xaxes[1].max=null}}if(options.y2axis){options.yaxes[1]=$.extend(true,{},options.yaxis,options.y2axis);options.yaxes[1].position="right";if(options.y2axis.min==null){options.yaxes[1].min=null}if(options.y2axis.max==null){options.yaxes[1].max=null}}if(options.grid.coloredAreas)options.grid.markings=options.grid.coloredAreas;if(options.grid.coloredAreasColor)options.grid.markingsColor=options.grid.coloredAreasColor;if(options.lines)$.extend(true,options.series.lines,options.lines);if(options.points)$.extend(true,options.series.points,options.points);if(options.bars)$.extend(true,options.series.bars,options.bars);if(options.shadowSize!=null)options.series.shadowSize=options.shadowSize;if(options.highlightColor!=null)options.series.highlightColor=options.highlightColor;for(i=0;i<options.xaxes.length;++i)getOrCreateAxis(xaxes,i+1).options=options.xaxes[i];for(i=0;i<options.yaxes.length;++i)getOrCreateAxis(yaxes,i+1).options=options.yaxes[i];for(var n in hooks)if(options.hooks[n]&&options.hooks[n].length)hooks[n]=hooks[n].concat(options.hooks[n]);executeHooks(hooks.processOptions,[options])}function setData(d){series=parseData(d);fillInSeriesOptions();processData()}function parseData(d){var res=[];for(var i=0;i<d.length;++i){var s=$.extend(true,{},options.series);if(d[i].data!=null){s.data=d[i].data;delete d[i].data;$.extend(true,s,d[i]);d[i].data=s.data}else s.data=d[i];res.push(s)}return res}function axisNumber(obj,coord){var a=obj[coord+"axis"];if(typeof a=="object")a=a.n;if(typeof a!="number")a=1;return a}function allAxes(){return $.grep(xaxes.concat(yaxes),function(a){return a})}function canvasToAxisCoords(pos){var res={},i,axis;for(i=0;i<xaxes.length;++i){axis=xaxes[i];if(axis&&axis.used)res["x"+axis.n]=axis.c2p(pos.left)}for(i=0;i<yaxes.length;++i){axis=yaxes[i];if(axis&&axis.used)res["y"+axis.n]=axis.c2p(pos.top)}if(res.x1!==undefined)res.x=res.x1;if(res.y1!==undefined)res.y=res.y1;return res}function axisToCanvasCoords(pos){var res={},i,axis,key;for(i=0;i<xaxes.length;++i){axis=xaxes[i];if(axis&&axis.used){key="x"+axis.n;if(pos[key]==null&&axis.n==1)key="x";if(pos[key]!=null){res.left=axis.p2c(pos[key]);break}}}for(i=0;i<yaxes.length;++i){axis=yaxes[i];if(axis&&axis.used){key="y"+axis.n;if(pos[key]==null&&axis.n==1)key="y";if(pos[key]!=null){res.top=axis.p2c(pos[key]);break}}}return res}function getOrCreateAxis(axes,number){if(!axes[number-1])axes[number-1]={n:number,direction:axes==xaxes?"x":"y",options:$.extend(true,{},axes==xaxes?options.xaxis:options.yaxis)};return axes[number-1]}function fillInSeriesOptions(){var neededColors=series.length,maxIndex=-1,i;for(i=0;i<series.length;++i){var sc=series[i].color;if(sc!=null){neededColors--;if(typeof sc=="number"&&sc>maxIndex){maxIndex=sc}}}if(neededColors<=maxIndex){neededColors=maxIndex+1}var c,colors=[],colorPool=options.colors,colorPoolSize=colorPool.length,variation=0;for(i=0;i<neededColors;i++){c=$.color.parse(colorPool[i%colorPoolSize]||"#666");if(i%colorPoolSize==0&&i){if(variation>=0){if(variation<.5){variation=-variation-.2}else variation=0}else variation=-variation}colors[i]=c.scale("rgb",1+variation)}var colori=0,s;for(i=0;i<series.length;++i){s=series[i];if(s.color==null){s.color=colors[colori].toString();++colori}else if(typeof s.color=="number")s.color=colors[s.color].toString();if(s.lines.show==null){var v,show=true;for(v in s)if(s[v]&&s[v].show){show=false;break}if(show)s.lines.show=true}if(s.lines.zero==null){s.lines.zero=!!s.lines.fill}s.xaxis=getOrCreateAxis(xaxes,axisNumber(s,"x"));s.yaxis=getOrCreateAxis(yaxes,axisNumber(s,"y"))}}function processData(){var topSentry=Number.POSITIVE_INFINITY,bottomSentry=Number.NEGATIVE_INFINITY,fakeInfinity=Number.MAX_VALUE,i,j,k,m,length,s,points,ps,x,y,axis,val,f,p,data,format;function updateAxis(axis,min,max){if(min<axis.datamin&&min!=-fakeInfinity)axis.datamin=min;if(max>axis.datamax&&max!=fakeInfinity)axis.datamax=max}$.each(allAxes(),function(_,axis){axis.datamin=topSentry;axis.datamax=bottomSentry;axis.used=false});for(i=0;i<series.length;++i){s=series[i];s.datapoints={points:[]};executeHooks(hooks.processRawData,[s,s.data,s.datapoints])}for(i=0;i<series.length;++i){s=series[i];data=s.data;format=s.datapoints.format;if(!format){format=[];format.push({x:true,number:true,required:true});format.push({y:true,number:true,required:true});if(s.bars.show||s.lines.show&&s.lines.fill){var autoscale=!!(s.bars.show&&s.bars.zero||s.lines.show&&s.lines.zero);format.push({y:true,number:true,required:false,defaultValue:0,autoscale:autoscale});if(s.bars.horizontal){delete format[format.length-1].y;format[format.length-1].x=true}}s.datapoints.format=format}if(s.datapoints.pointsize!=null)continue;s.datapoints.pointsize=format.length;ps=s.datapoints.pointsize;points=s.datapoints.points;var insertSteps=s.lines.show&&s.lines.steps;s.xaxis.used=s.yaxis.used=true;for(j=k=0;j<data.length;++j,k+=ps){p=data[j];var nullify=p==null;if(!nullify){for(m=0;m<ps;++m){val=p[m];f=format[m];if(f){if(f.number&&val!=null){val=+val;if(isNaN(val))val=null;else if(val==Infinity)val=fakeInfinity;else if(val==-Infinity)val=-fakeInfinity}if(val==null){if(f.required)nullify=true;if(f.defaultValue!=null)val=f.defaultValue}}points[k+m]=val}}if(nullify){for(m=0;m<ps;++m){val=points[k+m];if(val!=null){f=format[m];if(f.autoscale!==false){if(f.x){updateAxis(s.xaxis,val,val)}if(f.y){updateAxis(s.yaxis,val,val)}}}points[k+m]=null}}else{if(insertSteps&&k>0&&points[k-ps]!=null&&points[k-ps]!=points[k]&&points[k-ps+1]!=points[k+1]){for(m=0;m<ps;++m)points[k+ps+m]=points[k+m];points[k+1]=points[k-ps+1];k+=ps}}}}for(i=0;i<series.length;++i){s=series[i];executeHooks(hooks.processDatapoints,[s,s.datapoints])}for(i=0;i<series.length;++i){s=series[i];points=s.datapoints.points;ps=s.datapoints.pointsize;format=s.datapoints.format;var xmin=topSentry,ymin=topSentry,xmax=bottomSentry,ymax=bottomSentry;for(j=0;j<points.length;j+=ps){if(points[j]==null)continue;for(m=0;m<ps;++m){val=points[j+m];f=format[m];if(!f||f.autoscale===false||val==fakeInfinity||val==-fakeInfinity)continue;if(f.x){if(val<xmin)xmin=val;if(val>xmax)xmax=val}if(f.y){if(val<ymin)ymin=val;if(val>ymax)ymax=val}}}if(s.bars.show){var delta;switch(s.bars.align){case"left":delta=0;break;case"right":delta=-s.bars.barWidth;break;default:delta=-s.bars.barWidth/2}if(s.bars.horizontal){ymin+=delta;ymax+=delta+s.bars.barWidth}else{xmin+=delta;xmax+=delta+s.bars.barWidth}}updateAxis(s.xaxis,xmin,xmax);updateAxis(s.yaxis,ymin,ymax)}$.each(allAxes(),function(_,axis){if(axis.datamin==topSentry)axis.datamin=null;if(axis.datamax==bottomSentry)axis.datamax=null})}function setupCanvases(){placeholder.css("padding",0).children().filter(function(){return!$(this).hasClass("flot-overlay")&&!$(this).hasClass("flot-base")}).remove();if(placeholder.css("position")=="static")placeholder.css("position","relative");surface=new Canvas("flot-base",placeholder);overlay=new Canvas("flot-overlay",placeholder);ctx=surface.context;octx=overlay.context;eventHolder=$(overlay.element).unbind();var existing=placeholder.data("plot");if(existing){existing.shutdown();overlay.clear()}placeholder.data("plot",plot)}function bindEvents(){if(options.grid.hoverable){eventHolder.mousemove(onMouseMove);eventHolder.bind("mouseleave",onMouseLeave)}if(options.grid.clickable)eventHolder.click(onClick);executeHooks(hooks.bindEvents,[eventHolder])}function shutdown(){if(redrawTimeout)clearTimeout(redrawTimeout);eventHolder.unbind("mousemove",onMouseMove);eventHolder.unbind("mouseleave",onMouseLeave);eventHolder.unbind("click",onClick);executeHooks(hooks.shutdown,[eventHolder])}function setTransformationHelpers(axis){function identity(x){return x}var s,m,t=axis.options.transform||identity,it=axis.options.inverseTransform;if(axis.direction=="x"){s=axis.scale=plotWidth/Math.abs(t(axis.max)-t(axis.min));m=Math.min(t(axis.max),t(axis.min))}else{s=axis.scale=plotHeight/Math.abs(t(axis.max)-t(axis.min));s=-s;m=Math.max(t(axis.max),t(axis.min))}if(t==identity)axis.p2c=function(p){return(p-m)*s};else axis.p2c=function(p){return(t(p)-m)*s};if(!it)axis.c2p=function(c){return m+c/s};else axis.c2p=function(c){return it(m+c/s)}}function measureTickLabels(axis){var opts=axis.options,ticks=axis.ticks||[],labelWidth=opts.labelWidth||0,labelHeight=opts.labelHeight||0,maxWidth=labelWidth||(axis.direction=="x"?Math.floor(surface.width/(ticks.length||1)):null),legacyStyles=axis.direction+"Axis "+axis.direction+axis.n+"Axis",layer="flot-"+axis.direction+"-axis flot-"+axis.direction+axis.n+"-axis "+legacyStyles,font=opts.font||"flot-tick-label tickLabel";for(var i=0;i<ticks.length;++i){var t=ticks[i];if(!t.label)continue;var info=surface.getTextInfo(layer,t.label,font,null,maxWidth);labelWidth=Math.max(labelWidth,info.width);labelHeight=Math.max(labelHeight,info.height)}axis.labelWidth=opts.labelWidth||labelWidth;axis.labelHeight=opts.labelHeight||labelHeight}function allocateAxisBoxFirstPhase(axis){var lw=axis.labelWidth,lh=axis.labelHeight,pos=axis.options.position,isXAxis=axis.direction==="x",tickLength=axis.options.tickLength,axisMargin=options.grid.axisMargin,padding=options.grid.labelMargin,innermost=true,outermost=true,first=true,found=false;$.each(isXAxis?xaxes:yaxes,function(i,a){if(a&&(a.show||a.reserveSpace)){if(a===axis){found=true}else if(a.options.position===pos){if(found){outermost=false}else{innermost=false}}if(!found){first=false}}});if(outermost){axisMargin=0}if(tickLength==null){tickLength=first?"full":5}if(!isNaN(+tickLength))padding+=+tickLength;if(isXAxis){lh+=padding;if(pos=="bottom"){plotOffset.bottom+=lh+axisMargin;axis.box={top:surface.height-plotOffset.bottom,height:lh}}else{axis.box={top:plotOffset.top+axisMargin,height:lh};plotOffset.top+=lh+axisMargin}}else{lw+=padding;if(pos=="left"){axis.box={left:plotOffset.left+axisMargin,width:lw};plotOffset.left+=lw+axisMargin}else{plotOffset.right+=lw+axisMargin;axis.box={left:surface.width-plotOffset.right,width:lw}}}axis.position=pos;axis.tickLength=tickLength;axis.box.padding=padding;axis.innermost=innermost}function allocateAxisBoxSecondPhase(axis){if(axis.direction=="x"){axis.box.left=plotOffset.left-axis.labelWidth/2;axis.box.width=surface.width-plotOffset.left-plotOffset.right+axis.labelWidth}else{axis.box.top=plotOffset.top-axis.labelHeight/2;axis.box.height=surface.height-plotOffset.bottom-plotOffset.top+axis.labelHeight}}function adjustLayoutForThingsStickingOut(){var minMargin=options.grid.minBorderMargin,axis,i;if(minMargin==null){minMargin=0;for(i=0;i<series.length;++i)minMargin=Math.max(minMargin,2*(series[i].points.radius+series[i].points.lineWidth/2))}var margins={left:minMargin,right:minMargin,top:minMargin,bottom:minMargin};$.each(allAxes(),function(_,axis){if(axis.reserveSpace&&axis.ticks&&axis.ticks.length){if(axis.direction==="x"){margins.left=Math.max(margins.left,axis.labelWidth/2);margins.right=Math.max(margins.right,axis.labelWidth/2)}else{margins.bottom=Math.max(margins.bottom,axis.labelHeight/2);margins.top=Math.max(margins.top,axis.labelHeight/2)}}});plotOffset.left=Math.ceil(Math.max(margins.left,plotOffset.left));plotOffset.right=Math.ceil(Math.max(margins.right,plotOffset.right));plotOffset.top=Math.ceil(Math.max(margins.top,plotOffset.top));plotOffset.bottom=Math.ceil(Math.max(margins.bottom,plotOffset.bottom))}function setupGrid(){var i,axes=allAxes(),showGrid=options.grid.show;for(var a in plotOffset){var margin=options.grid.margin||0;plotOffset[a]=typeof margin=="number"?margin:margin[a]||0}executeHooks(hooks.processOffset,[plotOffset]);for(var a in plotOffset){if(typeof options.grid.borderWidth=="object"){plotOffset[a]+=showGrid?options.grid.borderWidth[a]:0}else{plotOffset[a]+=showGrid?options.grid.borderWidth:0}}$.each(axes,function(_,axis){var axisOpts=axis.options;axis.show=axisOpts.show==null?axis.used:axisOpts.show;axis.reserveSpace=axisOpts.reserveSpace==null?axis.show:axisOpts.reserveSpace;setRange(axis)});if(showGrid){var allocatedAxes=$.grep(axes,function(axis){return axis.show||axis.reserveSpace});$.each(allocatedAxes,function(_,axis){setupTickGeneration(axis);setTicks(axis);snapRangeToTicks(axis,axis.ticks);measureTickLabels(axis)});for(i=allocatedAxes.length-1;i>=0;--i)allocateAxisBoxFirstPhase(allocatedAxes[i]);adjustLayoutForThingsStickingOut();$.each(allocatedAxes,function(_,axis){allocateAxisBoxSecondPhase(axis)})}plotWidth=surface.width-plotOffset.left-plotOffset.right;plotHeight=surface.height-plotOffset.bottom-plotOffset.top;$.each(axes,function(_,axis){setTransformationHelpers(axis)});if(showGrid){drawAxisLabels()}insertLegend()}function setRange(axis){var opts=axis.options,min=+(opts.min!=null?opts.min:axis.datamin),max=+(opts.max!=null?opts.max:axis.datamax),delta=max-min;if(delta==0){var widen=max==0?1:.01;if(opts.min==null)min-=widen;if(opts.max==null||opts.min!=null)max+=widen}else{var margin=opts.autoscaleMargin;if(margin!=null){if(opts.min==null){min-=delta*margin;if(min<0&&axis.datamin!=null&&axis.datamin>=0)min=0}if(opts.max==null){max+=delta*margin;if(max>0&&axis.datamax!=null&&axis.datamax<=0)max=0}}}axis.min=min;axis.max=max}function setupTickGeneration(axis){var opts=axis.options;var noTicks;if(typeof opts.ticks=="number"&&opts.ticks>0)noTicks=opts.ticks;else noTicks=.3*Math.sqrt(axis.direction=="x"?surface.width:surface.height);var delta=(axis.max-axis.min)/noTicks,dec=-Math.floor(Math.log(delta)/Math.LN10),maxDec=opts.tickDecimals;if(maxDec!=null&&dec>maxDec){dec=maxDec}var magn=Math.pow(10,-dec),norm=delta/magn,size;if(norm<1.5){size=1}else if(norm<3){size=2;if(norm>2.25&&(maxDec==null||dec+1<=maxDec)){size=2.5;++dec}}else if(norm<7.5){size=5}else{size=10}size*=magn;if(opts.minTickSize!=null&&size<opts.minTickSize){size=opts.minTickSize}axis.delta=delta;axis.tickDecimals=Math.max(0,maxDec!=null?maxDec:dec);axis.tickSize=opts.tickSize||size;if(opts.mode=="time"&&!axis.tickGenerator){throw new Error("Time mode requires the flot.time plugin.")}if(!axis.tickGenerator){axis.tickGenerator=function(axis){var ticks=[],start=floorInBase(axis.min,axis.tickSize),i=0,v=Number.NaN,prev;do{prev=v;v=start+i*axis.tickSize;ticks.push(v);++i}while(v<axis.max&&v!=prev);return ticks};axis.tickFormatter=function(value,axis){var factor=axis.tickDecimals?Math.pow(10,axis.tickDecimals):1;var formatted=""+Math.round(value*factor)/factor;if(axis.tickDecimals!=null){var decimal=formatted.indexOf(".");var precision=decimal==-1?0:formatted.length-decimal-1;if(precision<axis.tickDecimals){return(precision?formatted:formatted+".")+(""+factor).substr(1,axis.tickDecimals-precision)}}return formatted}}if($.isFunction(opts.tickFormatter))axis.tickFormatter=function(v,axis){return""+opts.tickFormatter(v,axis)};if(opts.alignTicksWithAxis!=null){var otherAxis=(axis.direction=="x"?xaxes:yaxes)[opts.alignTicksWithAxis-1];if(otherAxis&&otherAxis.used&&otherAxis!=axis){var niceTicks=axis.tickGenerator(axis);if(niceTicks.length>0){if(opts.min==null)axis.min=Math.min(axis.min,niceTicks[0]);if(opts.max==null&&niceTicks.length>1)axis.max=Math.max(axis.max,niceTicks[niceTicks.length-1])}axis.tickGenerator=function(axis){var ticks=[],v,i;for(i=0;i<otherAxis.ticks.length;++i){v=(otherAxis.ticks[i].v-otherAxis.min)/(otherAxis.max-otherAxis.min);v=axis.min+v*(axis.max-axis.min);ticks.push(v)}return ticks};if(!axis.mode&&opts.tickDecimals==null){var extraDec=Math.max(0,-Math.floor(Math.log(axis.delta)/Math.LN10)+1),ts=axis.tickGenerator(axis);if(!(ts.length>1&&/\..*0$/.test((ts[1]-ts[0]).toFixed(extraDec))))axis.tickDecimals=extraDec}}}}function setTicks(axis){var oticks=axis.options.ticks,ticks=[];if(oticks==null||typeof oticks=="number"&&oticks>0)ticks=axis.tickGenerator(axis);else if(oticks){if($.isFunction(oticks))ticks=oticks(axis);else ticks=oticks}var i,v;axis.ticks=[];for(i=0;i<ticks.length;++i){var label=null;var t=ticks[i];if(typeof t=="object"){v=+t[0];if(t.length>1)label=t[1]}else v=+t;if(label==null)label=axis.tickFormatter(v,axis);if(!isNaN(v))axis.ticks.push({v:v,label:label})}}function snapRangeToTicks(axis,ticks){if(axis.options.autoscaleMargin&&ticks.length>0){if(axis.options.min==null)axis.min=Math.min(axis.min,ticks[0].v);if(axis.options.max==null&&ticks.length>1)axis.max=Math.max(axis.max,ticks[ticks.length-1].v)}}function draw(){surface.clear();executeHooks(hooks.drawBackground,[ctx]);var grid=options.grid;if(grid.show&&grid.backgroundColor)drawBackground();if(grid.show&&!grid.aboveData){drawGrid()}for(var i=0;i<series.length;++i){executeHooks(hooks.drawSeries,[ctx,series[i]]);drawSeries(series[i])}executeHooks(hooks.draw,[ctx]);if(grid.show&&grid.aboveData){drawGrid()}surface.render();triggerRedrawOverlay()}function extractRange(ranges,coord){var axis,from,to,key,axes=allAxes();for(var i=0;i<axes.length;++i){axis=axes[i];if(axis.direction==coord){key=coord+axis.n+"axis";if(!ranges[key]&&axis.n==1)key=coord+"axis";if(ranges[key]){from=ranges[key].from;to=ranges[key].to;break}}}if(!ranges[key]){axis=coord=="x"?xaxes[0]:yaxes[0];from=ranges[coord+"1"];to=ranges[coord+"2"]}if(from!=null&&to!=null&&from>to){var tmp=from;from=to;to=tmp}return{from:from,to:to,axis:axis}}function drawBackground(){ctx.save();ctx.translate(plotOffset.left,plotOffset.top);ctx.fillStyle=getColorOrGradient(options.grid.backgroundColor,plotHeight,0,"rgba(255, 255, 255, 0)");ctx.fillRect(0,0,plotWidth,plotHeight);ctx.restore()}function drawGrid(){var i,axes,bw,bc;ctx.save();ctx.translate(plotOffset.left,plotOffset.top);var markings=options.grid.markings;if(markings){if($.isFunction(markings)){axes=plot.getAxes();axes.xmin=axes.xaxis.min;axes.xmax=axes.xaxis.max;axes.ymin=axes.yaxis.min;axes.ymax=axes.yaxis.max;markings=markings(axes)}for(i=0;i<markings.length;++i){var m=markings[i],xrange=extractRange(m,"x"),yrange=extractRange(m,"y");if(xrange.from==null)xrange.from=xrange.axis.min;if(xrange.to==null)xrange.to=xrange.axis.max;
-if(yrange.from==null)yrange.from=yrange.axis.min;if(yrange.to==null)yrange.to=yrange.axis.max;if(xrange.to<xrange.axis.min||xrange.from>xrange.axis.max||yrange.to<yrange.axis.min||yrange.from>yrange.axis.max)continue;xrange.from=Math.max(xrange.from,xrange.axis.min);xrange.to=Math.min(xrange.to,xrange.axis.max);yrange.from=Math.max(yrange.from,yrange.axis.min);yrange.to=Math.min(yrange.to,yrange.axis.max);var xequal=xrange.from===xrange.to,yequal=yrange.from===yrange.to;if(xequal&&yequal){continue}xrange.from=Math.floor(xrange.axis.p2c(xrange.from));xrange.to=Math.floor(xrange.axis.p2c(xrange.to));yrange.from=Math.floor(yrange.axis.p2c(yrange.from));yrange.to=Math.floor(yrange.axis.p2c(yrange.to));if(xequal||yequal){var lineWidth=m.lineWidth||options.grid.markingsLineWidth,subPixel=lineWidth%2?.5:0;ctx.beginPath();ctx.strokeStyle=m.color||options.grid.markingsColor;ctx.lineWidth=lineWidth;if(xequal){ctx.moveTo(xrange.to+subPixel,yrange.from);ctx.lineTo(xrange.to+subPixel,yrange.to)}else{ctx.moveTo(xrange.from,yrange.to+subPixel);ctx.lineTo(xrange.to,yrange.to+subPixel)}ctx.stroke()}else{ctx.fillStyle=m.color||options.grid.markingsColor;ctx.fillRect(xrange.from,yrange.to,xrange.to-xrange.from,yrange.from-yrange.to)}}}axes=allAxes();bw=options.grid.borderWidth;for(var j=0;j<axes.length;++j){var axis=axes[j],box=axis.box,t=axis.tickLength,x,y,xoff,yoff;if(!axis.show||axis.ticks.length==0)continue;ctx.lineWidth=1;if(axis.direction=="x"){x=0;if(t=="full")y=axis.position=="top"?0:plotHeight;else y=box.top-plotOffset.top+(axis.position=="top"?box.height:0)}else{y=0;if(t=="full")x=axis.position=="left"?0:plotWidth;else x=box.left-plotOffset.left+(axis.position=="left"?box.width:0)}if(!axis.innermost){ctx.strokeStyle=axis.options.color;ctx.beginPath();xoff=yoff=0;if(axis.direction=="x")xoff=plotWidth+1;else yoff=plotHeight+1;if(ctx.lineWidth==1){if(axis.direction=="x"){y=Math.floor(y)+.5}else{x=Math.floor(x)+.5}}ctx.moveTo(x,y);ctx.lineTo(x+xoff,y+yoff);ctx.stroke()}ctx.strokeStyle=axis.options.tickColor;ctx.beginPath();for(i=0;i<axis.ticks.length;++i){var v=axis.ticks[i].v;xoff=yoff=0;if(isNaN(v)||v<axis.min||v>axis.max||t=="full"&&(typeof bw=="object"&&bw[axis.position]>0||bw>0)&&(v==axis.min||v==axis.max))continue;if(axis.direction=="x"){x=axis.p2c(v);yoff=t=="full"?-plotHeight:t;if(axis.position=="top")yoff=-yoff}else{y=axis.p2c(v);xoff=t=="full"?-plotWidth:t;if(axis.position=="left")xoff=-xoff}if(ctx.lineWidth==1){if(axis.direction=="x")x=Math.floor(x)+.5;else y=Math.floor(y)+.5}ctx.moveTo(x,y);ctx.lineTo(x+xoff,y+yoff)}ctx.stroke()}if(bw){bc=options.grid.borderColor;if(typeof bw=="object"||typeof bc=="object"){if(typeof bw!=="object"){bw={top:bw,right:bw,bottom:bw,left:bw}}if(typeof bc!=="object"){bc={top:bc,right:bc,bottom:bc,left:bc}}if(bw.top>0){ctx.strokeStyle=bc.top;ctx.lineWidth=bw.top;ctx.beginPath();ctx.moveTo(0-bw.left,0-bw.top/2);ctx.lineTo(plotWidth,0-bw.top/2);ctx.stroke()}if(bw.right>0){ctx.strokeStyle=bc.right;ctx.lineWidth=bw.right;ctx.beginPath();ctx.moveTo(plotWidth+bw.right/2,0-bw.top);ctx.lineTo(plotWidth+bw.right/2,plotHeight);ctx.stroke()}if(bw.bottom>0){ctx.strokeStyle=bc.bottom;ctx.lineWidth=bw.bottom;ctx.beginPath();ctx.moveTo(plotWidth+bw.right,plotHeight+bw.bottom/2);ctx.lineTo(0,plotHeight+bw.bottom/2);ctx.stroke()}if(bw.left>0){ctx.strokeStyle=bc.left;ctx.lineWidth=bw.left;ctx.beginPath();ctx.moveTo(0-bw.left/2,plotHeight+bw.bottom);ctx.lineTo(0-bw.left/2,0);ctx.stroke()}}else{ctx.lineWidth=bw;ctx.strokeStyle=options.grid.borderColor;ctx.strokeRect(-bw/2,-bw/2,plotWidth+bw,plotHeight+bw)}}ctx.restore()}function drawAxisLabels(){$.each(allAxes(),function(_,axis){var box=axis.box,legacyStyles=axis.direction+"Axis "+axis.direction+axis.n+"Axis",layer="flot-"+axis.direction+"-axis flot-"+axis.direction+axis.n+"-axis "+legacyStyles,font=axis.options.font||"flot-tick-label tickLabel",tick,x,y,halign,valign;surface.removeText(layer);if(!axis.show||axis.ticks.length==0)return;for(var i=0;i<axis.ticks.length;++i){tick=axis.ticks[i];if(!tick.label||tick.v<axis.min||tick.v>axis.max)continue;if(axis.direction=="x"){halign="center";x=plotOffset.left+axis.p2c(tick.v);if(axis.position=="bottom"){y=box.top+box.padding}else{y=box.top+box.height-box.padding;valign="bottom"}}else{valign="middle";y=plotOffset.top+axis.p2c(tick.v);if(axis.position=="left"){x=box.left+box.width-box.padding;halign="right"}else{x=box.left+box.padding}}surface.addText(layer,x,y,tick.label,font,null,null,halign,valign)}})}function drawSeries(series){if(series.lines.show)drawSeriesLines(series);if(series.bars.show)drawSeriesBars(series);if(series.points.show)drawSeriesPoints(series)}function drawSeriesLines(series){function plotLine(datapoints,xoffset,yoffset,axisx,axisy){var points=datapoints.points,ps=datapoints.pointsize,prevx=null,prevy=null;ctx.beginPath();for(var i=ps;i<points.length;i+=ps){var x1=points[i-ps],y1=points[i-ps+1],x2=points[i],y2=points[i+1];if(x1==null||x2==null)continue;if(y1<=y2&&y1<axisy.min){if(y2<axisy.min)continue;x1=(axisy.min-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.min}else if(y2<=y1&&y2<axisy.min){if(y1<axisy.min)continue;x2=(axisy.min-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.min}if(y1>=y2&&y1>axisy.max){if(y2>axisy.max)continue;x1=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.max}else if(y2>=y1&&y2>axisy.max){if(y1>axisy.max)continue;x2=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.max}if(x1<=x2&&x1<axisx.min){if(x2<axisx.min)continue;y1=(axisx.min-x1)/(x2-x1)*(y2-y1)+y1;x1=axisx.min}else if(x2<=x1&&x2<axisx.min){if(x1<axisx.min)continue;y2=(axisx.min-x1)/(x2-x1)*(y2-y1)+y1;x2=axisx.min}if(x1>=x2&&x1>axisx.max){if(x2>axisx.max)continue;y1=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x1=axisx.max}else if(x2>=x1&&x2>axisx.max){if(x1>axisx.max)continue;y2=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x2=axisx.max}if(x1!=prevx||y1!=prevy)ctx.moveTo(axisx.p2c(x1)+xoffset,axisy.p2c(y1)+yoffset);prevx=x2;prevy=y2;ctx.lineTo(axisx.p2c(x2)+xoffset,axisy.p2c(y2)+yoffset)}ctx.stroke()}function plotLineArea(datapoints,axisx,axisy){var points=datapoints.points,ps=datapoints.pointsize,bottom=Math.min(Math.max(0,axisy.min),axisy.max),i=0,top,areaOpen=false,ypos=1,segmentStart=0,segmentEnd=0;while(true){if(ps>0&&i>points.length+ps)break;i+=ps;var x1=points[i-ps],y1=points[i-ps+ypos],x2=points[i],y2=points[i+ypos];if(areaOpen){if(ps>0&&x1!=null&&x2==null){segmentEnd=i;ps=-ps;ypos=2;continue}if(ps<0&&i==segmentStart+ps){ctx.fill();areaOpen=false;ps=-ps;ypos=1;i=segmentStart=segmentEnd+ps;continue}}if(x1==null||x2==null)continue;if(x1<=x2&&x1<axisx.min){if(x2<axisx.min)continue;y1=(axisx.min-x1)/(x2-x1)*(y2-y1)+y1;x1=axisx.min}else if(x2<=x1&&x2<axisx.min){if(x1<axisx.min)continue;y2=(axisx.min-x1)/(x2-x1)*(y2-y1)+y1;x2=axisx.min}if(x1>=x2&&x1>axisx.max){if(x2>axisx.max)continue;y1=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x1=axisx.max}else if(x2>=x1&&x2>axisx.max){if(x1>axisx.max)continue;y2=(axisx.max-x1)/(x2-x1)*(y2-y1)+y1;x2=axisx.max}if(!areaOpen){ctx.beginPath();ctx.moveTo(axisx.p2c(x1),axisy.p2c(bottom));areaOpen=true}if(y1>=axisy.max&&y2>=axisy.max){ctx.lineTo(axisx.p2c(x1),axisy.p2c(axisy.max));ctx.lineTo(axisx.p2c(x2),axisy.p2c(axisy.max));continue}else if(y1<=axisy.min&&y2<=axisy.min){ctx.lineTo(axisx.p2c(x1),axisy.p2c(axisy.min));ctx.lineTo(axisx.p2c(x2),axisy.p2c(axisy.min));continue}var x1old=x1,x2old=x2;if(y1<=y2&&y1<axisy.min&&y2>=axisy.min){x1=(axisy.min-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.min}else if(y2<=y1&&y2<axisy.min&&y1>=axisy.min){x2=(axisy.min-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.min}if(y1>=y2&&y1>axisy.max&&y2<=axisy.max){x1=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y1=axisy.max}else if(y2>=y1&&y2>axisy.max&&y1<=axisy.max){x2=(axisy.max-y1)/(y2-y1)*(x2-x1)+x1;y2=axisy.max}if(x1!=x1old){ctx.lineTo(axisx.p2c(x1old),axisy.p2c(y1))}ctx.lineTo(axisx.p2c(x1),axisy.p2c(y1));ctx.lineTo(axisx.p2c(x2),axisy.p2c(y2));if(x2!=x2old){ctx.lineTo(axisx.p2c(x2),axisy.p2c(y2));ctx.lineTo(axisx.p2c(x2old),axisy.p2c(y2))}}}ctx.save();ctx.translate(plotOffset.left,plotOffset.top);ctx.lineJoin="round";var lw=series.lines.lineWidth,sw=series.shadowSize;if(lw>0&&sw>0){ctx.lineWidth=sw;ctx.strokeStyle="rgba(0,0,0,0.1)";var angle=Math.PI/18;plotLine(series.datapoints,Math.sin(angle)*(lw/2+sw/2),Math.cos(angle)*(lw/2+sw/2),series.xaxis,series.yaxis);ctx.lineWidth=sw/2;plotLine(series.datapoints,Math.sin(angle)*(lw/2+sw/4),Math.cos(angle)*(lw/2+sw/4),series.xaxis,series.yaxis)}ctx.lineWidth=lw;ctx.strokeStyle=series.color;var fillStyle=getFillStyle(series.lines,series.color,0,plotHeight);if(fillStyle){ctx.fillStyle=fillStyle;plotLineArea(series.datapoints,series.xaxis,series.yaxis)}if(lw>0)plotLine(series.datapoints,0,0,series.xaxis,series.yaxis);ctx.restore()}function drawSeriesPoints(series){function plotPoints(datapoints,radius,fillStyle,offset,shadow,axisx,axisy,symbol){var points=datapoints.points,ps=datapoints.pointsize;for(var i=0;i<points.length;i+=ps){var x=points[i],y=points[i+1];if(x==null||x<axisx.min||x>axisx.max||y<axisy.min||y>axisy.max)continue;ctx.beginPath();x=axisx.p2c(x);y=axisy.p2c(y)+offset;if(symbol=="circle")ctx.arc(x,y,radius,0,shadow?Math.PI:Math.PI*2,false);else symbol(ctx,x,y,radius,shadow);ctx.closePath();if(fillStyle){ctx.fillStyle=fillStyle;ctx.fill()}ctx.stroke()}}ctx.save();ctx.translate(plotOffset.left,plotOffset.top);var lw=series.points.lineWidth,sw=series.shadowSize,radius=series.points.radius,symbol=series.points.symbol;if(lw==0)lw=1e-4;if(lw>0&&sw>0){var w=sw/2;ctx.lineWidth=w;ctx.strokeStyle="rgba(0,0,0,0.1)";plotPoints(series.datapoints,radius,null,w+w/2,true,series.xaxis,series.yaxis,symbol);ctx.strokeStyle="rgba(0,0,0,0.2)";plotPoints(series.datapoints,radius,null,w/2,true,series.xaxis,series.yaxis,symbol)}ctx.lineWidth=lw;ctx.strokeStyle=series.color;plotPoints(series.datapoints,radius,getFillStyle(series.points,series.color),0,false,series.xaxis,series.yaxis,symbol);ctx.restore()}function drawBar(x,y,b,barLeft,barRight,fillStyleCallback,axisx,axisy,c,horizontal,lineWidth){var left,right,bottom,top,drawLeft,drawRight,drawTop,drawBottom,tmp;if(horizontal){drawBottom=drawRight=drawTop=true;drawLeft=false;left=b;right=x;top=y+barLeft;bottom=y+barRight;if(right<left){tmp=right;right=left;left=tmp;drawLeft=true;drawRight=false}}else{drawLeft=drawRight=drawTop=true;drawBottom=false;left=x+barLeft;right=x+barRight;bottom=b;top=y;if(top<bottom){tmp=top;top=bottom;bottom=tmp;drawBottom=true;drawTop=false}}if(right<axisx.min||left>axisx.max||top<axisy.min||bottom>axisy.max)return;if(left<axisx.min){left=axisx.min;drawLeft=false}if(right>axisx.max){right=axisx.max;drawRight=false}if(bottom<axisy.min){bottom=axisy.min;drawBottom=false}if(top>axisy.max){top=axisy.max;drawTop=false}left=axisx.p2c(left);bottom=axisy.p2c(bottom);right=axisx.p2c(right);top=axisy.p2c(top);if(fillStyleCallback){c.fillStyle=fillStyleCallback(bottom,top);c.fillRect(left,top,right-left,bottom-top)}if(lineWidth>0&&(drawLeft||drawRight||drawTop||drawBottom)){c.beginPath();c.moveTo(left,bottom);if(drawLeft)c.lineTo(left,top);else c.moveTo(left,top);if(drawTop)c.lineTo(right,top);else c.moveTo(right,top);if(drawRight)c.lineTo(right,bottom);else c.moveTo(right,bottom);if(drawBottom)c.lineTo(left,bottom);else c.moveTo(left,bottom);c.stroke()}}function drawSeriesBars(series){function plotBars(datapoints,barLeft,barRight,fillStyleCallback,axisx,axisy){var points=datapoints.points,ps=datapoints.pointsize;for(var i=0;i<points.length;i+=ps){if(points[i]==null)continue;drawBar(points[i],points[i+1],points[i+2],barLeft,barRight,fillStyleCallback,axisx,axisy,ctx,series.bars.horizontal,series.bars.lineWidth)}}ctx.save();ctx.translate(plotOffset.left,plotOffset.top);ctx.lineWidth=series.bars.lineWidth;ctx.strokeStyle=series.color;var barLeft;switch(series.bars.align){case"left":barLeft=0;break;case"right":barLeft=-series.bars.barWidth;break;default:barLeft=-series.bars.barWidth/2}var fillStyleCallback=series.bars.fill?function(bottom,top){return getFillStyle(series.bars,series.color,bottom,top)}:null;plotBars(series.datapoints,barLeft,barLeft+series.bars.barWidth,fillStyleCallback,series.xaxis,series.yaxis);ctx.restore()}function getFillStyle(filloptions,seriesColor,bottom,top){var fill=filloptions.fill;if(!fill)return null;if(filloptions.fillColor)return getColorOrGradient(filloptions.fillColor,bottom,top,seriesColor);var c=$.color.parse(seriesColor);c.a=typeof fill=="number"?fill:.4;c.normalize();return c.toString()}function insertLegend(){if(options.legend.container!=null){$(options.legend.container).html("")}else{placeholder.find(".legend").remove()}if(!options.legend.show){return}var fragments=[],entries=[],rowStarted=false,lf=options.legend.labelFormatter,s,label;for(var i=0;i<series.length;++i){s=series[i];if(s.label){label=lf?lf(s.label,s):s.label;if(label){entries.push({label:label,color:s.color})}}}if(options.legend.sorted){if($.isFunction(options.legend.sorted)){entries.sort(options.legend.sorted)}else if(options.legend.sorted=="reverse"){entries.reverse()}else{var ascending=options.legend.sorted!="descending";entries.sort(function(a,b){return a.label==b.label?0:a.label<b.label!=ascending?1:-1})}}for(var i=0;i<entries.length;++i){var entry=entries[i];if(i%options.legend.noColumns==0){if(rowStarted)fragments.push("</tr>");fragments.push("<tr>");rowStarted=true}fragments.push('<td class="legendColorBox"><div style="border:1px solid '+options.legend.labelBoxBorderColor+';padding:1px"><div style="width:4px;height:0;border:5px solid '+entry.color+';overflow:hidden"></div></div></td>'+'<td class="legendLabel">'+entry.label+"</td>")}if(rowStarted)fragments.push("</tr>");if(fragments.length==0)return;var table='<table style="font-size:smaller;color:'+options.grid.color+'">'+fragments.join("")+"</table>";if(options.legend.container!=null)$(options.legend.container).html(table);else{var pos="",p=options.legend.position,m=options.legend.margin;if(m[0]==null)m=[m,m];if(p.charAt(0)=="n")pos+="top:"+(m[1]+plotOffset.top)+"px;";else if(p.charAt(0)=="s")pos+="bottom:"+(m[1]+plotOffset.bottom)+"px;";if(p.charAt(1)=="e")pos+="right:"+(m[0]+plotOffset.right)+"px;";else if(p.charAt(1)=="w")pos+="left:"+(m[0]+plotOffset.left)+"px;";var legend=$('<div class="legend">'+table.replace('style="','style="position:absolute;'+pos+";")+"</div>").appendTo(placeholder);if(options.legend.backgroundOpacity!=0){var c=options.legend.backgroundColor;if(c==null){c=options.grid.backgroundColor;if(c&&typeof c=="string")c=$.color.parse(c);else c=$.color.extract(legend,"background-color");c.a=1;c=c.toString()}var div=legend.children();$('<div style="position:absolute;width:'+div.width()+"px;height:"+div.height()+"px;"+pos+"background-color:"+c+';"> </div>').prependTo(legend).css("opacity",options.legend.backgroundOpacity)}}}var highlights=[],redrawTimeout=null;function findNearbyItem(mouseX,mouseY,seriesFilter){var maxDistance=options.grid.mouseActiveRadius,smallestDistance=maxDistance*maxDistance+1,item=null,foundPoint=false,i,j,ps;for(i=series.length-1;i>=0;--i){if(!seriesFilter(series[i]))continue;var s=series[i],axisx=s.xaxis,axisy=s.yaxis,points=s.datapoints.points,mx=axisx.c2p(mouseX),my=axisy.c2p(mouseY),maxx=maxDistance/axisx.scale,maxy=maxDistance/axisy.scale;ps=s.datapoints.pointsize;if(axisx.options.inverseTransform)maxx=Number.MAX_VALUE;if(axisy.options.inverseTransform)maxy=Number.MAX_VALUE;if(s.lines.show||s.points.show){for(j=0;j<points.length;j+=ps){var x=points[j],y=points[j+1];if(x==null)continue;if(x-mx>maxx||x-mx<-maxx||y-my>maxy||y-my<-maxy)continue;var dx=Math.abs(axisx.p2c(x)-mouseX),dy=Math.abs(axisy.p2c(y)-mouseY),dist=dx*dx+dy*dy;if(dist<smallestDistance){smallestDistance=dist;item=[i,j/ps]}}}if(s.bars.show&&!item){var barLeft,barRight;switch(s.bars.align){case"left":barLeft=0;break;case"right":barLeft=-s.bars.barWidth;break;default:barLeft=-s.bars.barWidth/2}barRight=barLeft+s.bars.barWidth;for(j=0;j<points.length;j+=ps){var x=points[j],y=points[j+1],b=points[j+2];if(x==null)continue;if(series[i].bars.horizontal?mx<=Math.max(b,x)&&mx>=Math.min(b,x)&&my>=y+barLeft&&my<=y+barRight:mx>=x+barLeft&&mx<=x+barRight&&my>=Math.min(b,y)&&my<=Math.max(b,y))item=[i,j/ps]}}}if(item){i=item[0];j=item[1];ps=series[i].datapoints.pointsize;return{datapoint:series[i].datapoints.points.slice(j*ps,(j+1)*ps),dataIndex:j,series:series[i],seriesIndex:i}}return null}function onMouseMove(e){if(options.grid.hoverable)triggerClickHoverEvent("plothover",e,function(s){return s["hoverable"]!=false})}function onMouseLeave(e){if(options.grid.hoverable)triggerClickHoverEvent("plothover",e,function(s){return false})}function onClick(e){triggerClickHoverEvent("plotclick",e,function(s){return s["clickable"]!=false})}function triggerClickHoverEvent(eventname,event,seriesFilter){var offset=eventHolder.offset(),canvasX=event.pageX-offset.left-plotOffset.left,canvasY=event.pageY-offset.top-plotOffset.top,pos=canvasToAxisCoords({left:canvasX,top:canvasY});pos.pageX=event.pageX;pos.pageY=event.pageY;var item=findNearbyItem(canvasX,canvasY,seriesFilter);if(item){item.pageX=parseInt(item.series.xaxis.p2c(item.datapoint[0])+offset.left+plotOffset.left,10);item.pageY=parseInt(item.series.yaxis.p2c(item.datapoint[1])+offset.top+plotOffset.top,10)}if(options.grid.autoHighlight){for(var i=0;i<highlights.length;++i){var h=highlights[i];if(h.auto==eventname&&!(item&&h.series==item.series&&h.point[0]==item.datapoint[0]&&h.point[1]==item.datapoint[1]))unhighlight(h.series,h.point)}if(item)highlight(item.series,item.datapoint,eventname)}placeholder.trigger(eventname,[pos,item])}function triggerRedrawOverlay(){var t=options.interaction.redrawOverlayInterval;if(t==-1){drawOverlay();return}if(!redrawTimeout)redrawTimeout=setTimeout(drawOverlay,t)}function drawOverlay(){redrawTimeout=null;octx.save();overlay.clear();octx.translate(plotOffset.left,plotOffset.top);var i,hi;for(i=0;i<highlights.length;++i){hi=highlights[i];if(hi.series.bars.show)drawBarHighlight(hi.series,hi.point);else drawPointHighlight(hi.series,hi.point)}octx.restore();executeHooks(hooks.drawOverlay,[octx])}function highlight(s,point,auto){if(typeof s=="number")s=series[s];if(typeof point=="number"){var ps=s.datapoints.pointsize;point=s.datapoints.points.slice(ps*point,ps*(point+1))}var i=indexOfHighlight(s,point);if(i==-1){highlights.push({series:s,point:point,auto:auto});triggerRedrawOverlay()}else if(!auto)highlights[i].auto=false}function unhighlight(s,point){if(s==null&&point==null){highlights=[];triggerRedrawOverlay();return}if(typeof s=="number")s=series[s];if(typeof point=="number"){var ps=s.datapoints.pointsize;point=s.datapoints.points.slice(ps*point,ps*(point+1))}var i=indexOfHighlight(s,point);if(i!=-1){highlights.splice(i,1);triggerRedrawOverlay()}}function indexOfHighlight(s,p){for(var i=0;i<highlights.length;++i){var h=highlights[i];if(h.series==s&&h.point[0]==p[0]&&h.point[1]==p[1])return i}return-1}function drawPointHighlight(series,point){var x=point[0],y=point[1],axisx=series.xaxis,axisy=series.yaxis,highlightColor=typeof series.highlightColor==="string"?series.highlightColor:$.color.parse(series.color).scale("a",.5).toString();if(x<axisx.min||x>axisx.max||y<axisy.min||y>axisy.max)return;var pointRadius=series.points.radius+series.points.lineWidth/2;octx.lineWidth=pointRadius;octx.strokeStyle=highlightColor;var radius=1.5*pointRadius;x=axisx.p2c(x);y=axisy.p2c(y);octx.beginPath();if(series.points.symbol=="circle")octx.arc(x,y,radius,0,2*Math.PI,false);else series.points.symbol(octx,x,y,radius,false);octx.closePath();octx.stroke()}function drawBarHighlight(series,point){var highlightColor=typeof series.highlightColor==="string"?series.highlightColor:$.color.parse(series.color).scale("a",.5).toString(),fillStyle=highlightColor,barLeft;switch(series.bars.align){case"left":barLeft=0;break;case"right":barLeft=-series.bars.barWidth;break;default:barLeft=-series.bars.barWidth/2}octx.lineWidth=series.bars.lineWidth;octx.strokeStyle=highlightColor;drawBar(point[0],point[1],point[2]||0,barLeft,barLeft+series.bars.barWidth,function(){return fillStyle},series.xaxis,series.yaxis,octx,series.bars.horizontal,series.bars.lineWidth)}function getColorOrGradient(spec,bottom,top,defaultColor){if(typeof spec=="string")return spec;else{var gradient=ctx.createLinearGradient(0,top,0,bottom);for(var i=0,l=spec.colors.length;i<l;++i){var c=spec.colors[i];if(typeof c!="string"){var co=$.color.parse(defaultColor);if(c.brightness!=null)co=co.scale("rgb",c.brightness);if(c.opacity!=null)co.a*=c.opacity;c=co.toString()}gradient.addColorStop(i/(l-1),c)}return gradient}}}$.plot=function(placeholder,data,options){var plot=new Plot($(placeholder),data,options,$.plot.plugins);return plot};$.plot.version="0.8.3";$.plot.plugins=[];$.fn.plot=function(data,options){return this.each(function(){$.plot(this,data,options)})};function floorInBase(n,base){return base*Math.floor(n/base)}})(jQuery);
diff --git a/static/js/jquery.flot.navigate.js b/static/js/jquery.flot.navigate.js
deleted file mode 100644
--- a/static/js/jquery.flot.navigate.js
+++ /dev/null
@@ -1,346 +0,0 @@
-/* Flot plugin for adding the ability to pan and zoom the plot.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The default behaviour is double click and scrollwheel up/down to zoom in, drag
-to pan. The plugin defines plot.zoom({ center }), plot.zoomOut() and
-plot.pan( offset ) so you easily can add custom controls. It also fires
-"plotpan" and "plotzoom" events, useful for synchronizing plots.
-
-The plugin supports these options:
-
-	zoom: {
-		interactive: false
-		trigger: "dblclick" // or "click" for single click
-		amount: 1.5         // 2 = 200% (zoom in), 0.5 = 50% (zoom out)
-	}
-
-	pan: {
-		interactive: false
-		cursor: "move"      // CSS mouse cursor value used when dragging, e.g. "pointer"
-		frameRate: 20
-	}
-
-	xaxis, yaxis, x2axis, y2axis: {
-		zoomRange: null  // or [ number, number ] (min range, max range) or false
-		panRange: null   // or [ number, number ] (min, max) or false
-	}
-
-"interactive" enables the built-in drag/click behaviour. If you enable
-interactive for pan, then you'll have a basic plot that supports moving
-around; the same for zoom.
-
-"amount" specifies the default amount to zoom in (so 1.5 = 150%) relative to
-the current viewport.
-
-"cursor" is a standard CSS mouse cursor string used for visual feedback to the
-user when dragging.
-
-"frameRate" specifies the maximum number of times per second the plot will
-update itself while the user is panning around on it (set to null to disable
-intermediate pans, the plot will then not update until the mouse button is
-released).
-
-"zoomRange" is the interval in which zooming can happen, e.g. with zoomRange:
-[1, 100] the zoom will never scale the axis so that the difference between min
-and max is smaller than 1 or larger than 100. You can set either end to null
-to ignore, e.g. [1, null]. If you set zoomRange to false, zooming on that axis
-will be disabled.
-
-"panRange" confines the panning to stay within a range, e.g. with panRange:
-[-10, 20] panning stops at -10 in one end and at 20 in the other. Either can
-be null, e.g. [-10, null]. If you set panRange to false, panning on that axis
-will be disabled.
-
-Example API usage:
-
-	plot = $.plot(...);
-
-	// zoom default amount in on the pixel ( 10, 20 )
-	plot.zoom({ center: { left: 10, top: 20 } });
-
-	// zoom out again
-	plot.zoomOut({ center: { left: 10, top: 20 } });
-
-	// zoom 200% in on the pixel (10, 20)
-	plot.zoom({ amount: 2, center: { left: 10, top: 20 } });
-
-	// pan 100 pixels to the left and 20 down
-	plot.pan({ left: -100, top: 20 })
-
-Here, "center" specifies where the center of the zooming should happen. Note
-that this is defined in pixel space, not the space of the data points (you can
-use the p2c helpers on the axes in Flot to help you convert between these).
-
-"amount" is the amount to zoom the viewport relative to the current range, so
-1 is 100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out). You
-can set the default in the options.
-
-*/
-
-// First two dependencies, jquery.event.drag.js and
-// jquery.mousewheel.js, we put them inline here to save people the
-// effort of downloading them.
-
-/*
-jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
-Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
-*/
-(function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case"mousedown":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,"mousemove mouseup",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&"mousemove":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)<l.distance)break;h.target=l.target,k=f(h,"dragstart",j),k!==!1&&(d.dragging=j,d.proxy=h.dragProxy=a(k||j)[0]);case"mousemove":if(d.dragging){if(k=f(h,"drag",j),c.drop&&(c.drop.allowed=k!==!1,c.drop.handler(h)),k!==!1)break;h.type="mouseup"}case"mouseup":b.remove(document,"mousemove mouseup",e),d.dragging&&(c.drop&&c.drop.handler(h),f(h,"dragend",j)),i(j,!0),d.dragging=d.proxy=l.elem=!1}return!0}function f(b,c,d){b.type=c;var e=a.event.dispatch.call(d,b);return e===!1?!1:e||b.result}function g(a){return Math.pow(a,2)}function h(){return d.dragging===!1}function i(a,b){a&&(a.unselectable=b?"off":"on",a.onselectstart=function(){return b},a.style&&(a.style.MozUserSelect=b?"":"none"))}a.fn.drag=function(a,b,c){return b&&this.bind("dragstart",a),c&&this.bind("dragend",c),a?this.bind("drag",b?b:a):this.trigger("drag")};var b=a.event,c=b.special,d=c.drag={not:":input",distance:0,which:1,dragging:!1,setup:function(c){c=a.extend({distance:d.distance,which:d.which,not:d.not},c||{}),c.distance=g(c.distance),b.add(this,"mousedown",e,c),this.attachEvent&&this.attachEvent("ondragstart",h)},teardown:function(){b.remove(this,"mousedown",e),this===d.dragging&&(d.dragging=d.proxy=!1),i(this,!0),this.detachEvent&&this.detachEvent("ondragstart",h)}};c.dragstart=c.dragend={setup:function(){},teardown:function(){}}})(jQuery);
-
-/* jquery.mousewheel.min.js
- * Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
- * Licensed under the MIT License (LICENSE.txt).
- * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
- * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
- * Thanks to: Seamus Leahy for adding deltaX and deltaY
- *
- * Version: 3.0.6
- *
- * Requires: 1.2.2+
- */
-(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;void 0!==b.axis&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);void 0!==b.wheelDeltaY&&(g=b.wheelDeltaY/120);void 0!==b.wheelDeltaX&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,!1);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
-
-
-
-
-(function ($) {
-    var options = {
-        xaxis: {
-            zoomRange: null, // or [number, number] (min range, max range)
-            panRange: null // or [number, number] (min, max)
-        },
-        zoom: {
-            interactive: false,
-            trigger: "dblclick", // or "click" for single click
-            amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out)
-        },
-        pan: {
-            interactive: false,
-            cursor: "move",
-            frameRate: 20
-        }
-    };
-
-    function init(plot) {
-        function onZoomClick(e, zoomOut) {
-            var c = plot.offset();
-            c.left = e.pageX - c.left;
-            c.top = e.pageY - c.top;
-            if (zoomOut)
-                plot.zoomOut({ center: c });
-            else
-                plot.zoom({ center: c });
-        }
-
-        function onMouseWheel(e, delta) {
-            e.preventDefault();
-            onZoomClick(e, delta < 0);
-            return false;
-        }
-        
-        var prevCursor = 'default', prevPageX = 0, prevPageY = 0,
-            panTimeout = null;
-
-        function onDragStart(e) {
-            if (e.which != 1)  // only accept left-click
-                return false;
-            var c = plot.getPlaceholder().css('cursor');
-            if (c)
-                prevCursor = c;
-            plot.getPlaceholder().css('cursor', plot.getOptions().pan.cursor);
-            prevPageX = e.pageX;
-            prevPageY = e.pageY;
-        }
-        
-        function onDrag(e) {
-            var frameRate = plot.getOptions().pan.frameRate;
-            if (panTimeout || !frameRate)
-                return;
-
-            panTimeout = setTimeout(function () {
-                plot.pan({ left: prevPageX - e.pageX,
-                           top: prevPageY - e.pageY });
-                prevPageX = e.pageX;
-                prevPageY = e.pageY;
-                                                    
-                panTimeout = null;
-            }, 1 / frameRate * 1000);
-        }
-
-        function onDragEnd(e) {
-            if (panTimeout) {
-                clearTimeout(panTimeout);
-                panTimeout = null;
-            }
-                    
-            plot.getPlaceholder().css('cursor', prevCursor);
-            plot.pan({ left: prevPageX - e.pageX,
-                       top: prevPageY - e.pageY });
-        }
-        
-        function bindEvents(plot, eventHolder) {
-            var o = plot.getOptions();
-            if (o.zoom.interactive) {
-                eventHolder[o.zoom.trigger](onZoomClick);
-                eventHolder.mousewheel(onMouseWheel);
-            }
-
-            if (o.pan.interactive) {
-                eventHolder.bind("dragstart", { distance: 10 }, onDragStart);
-                eventHolder.bind("drag", onDrag);
-                eventHolder.bind("dragend", onDragEnd);
-            }
-        }
-
-        plot.zoomOut = function (args) {
-            if (!args)
-                args = {};
-            
-            if (!args.amount)
-                args.amount = plot.getOptions().zoom.amount;
-
-            args.amount = 1 / args.amount;
-            plot.zoom(args);
-        };
-        
-        plot.zoom = function (args) {
-            if (!args)
-                args = {};
-            
-            var c = args.center,
-                amount = args.amount || plot.getOptions().zoom.amount,
-                w = plot.width(), h = plot.height();
-
-            if (!c)
-                c = { left: w / 2, top: h / 2 };
-                
-            var xf = c.left / w,
-                yf = c.top / h,
-                minmax = {
-                    x: {
-                        min: c.left - xf * w / amount,
-                        max: c.left + (1 - xf) * w / amount
-                    },
-                    y: {
-                        min: c.top - yf * h / amount,
-                        max: c.top + (1 - yf) * h / amount
-                    }
-                };
-
-            $.each(plot.getAxes(), function(_, axis) {
-                var opts = axis.options,
-                    min = minmax[axis.direction].min,
-                    max = minmax[axis.direction].max,
-                    zr = opts.zoomRange,
-                    pr = opts.panRange;
-
-                if (zr === false) // no zooming on this axis
-                    return;
-                    
-                min = axis.c2p(min);
-                max = axis.c2p(max);
-                if (min > max) {
-                    // make sure min < max
-                    var tmp = min;
-                    min = max;
-                    max = tmp;
-                }
-
-                //Check that we are in panRange
-                if (pr) {
-                    if (pr[0] != null && min < pr[0]) {
-                        min = pr[0];
-                    }
-                    if (pr[1] != null && max > pr[1]) {
-                        max = pr[1];
-                    }
-                }
-
-                var range = max - min;
-                if (zr &&
-                    ((zr[0] != null && range < zr[0] && amount >1) ||
-                     (zr[1] != null && range > zr[1] && amount <1)))
-                    return;
-            
-                opts.min = min;
-                opts.max = max;
-            });
-            
-            plot.setupGrid();
-            plot.draw();
-            
-            if (!args.preventEvent)
-                plot.getPlaceholder().trigger("plotzoom", [ plot, args ]);
-        };
-
-        plot.pan = function (args) {
-            var delta = {
-                x: +args.left,
-                y: +args.top
-            };
-
-            if (isNaN(delta.x))
-                delta.x = 0;
-            if (isNaN(delta.y))
-                delta.y = 0;
-
-            $.each(plot.getAxes(), function (_, axis) {
-                var opts = axis.options,
-                    min, max, d = delta[axis.direction];
-
-                min = axis.c2p(axis.p2c(axis.min) + d),
-                max = axis.c2p(axis.p2c(axis.max) + d);
-
-                var pr = opts.panRange;
-                if (pr === false) // no panning on this axis
-                    return;
-                
-                if (pr) {
-                    // check whether we hit the wall
-                    if (pr[0] != null && pr[0] > min) {
-                        d = pr[0] - min;
-                        min += d;
-                        max += d;
-                    }
-                    
-                    if (pr[1] != null && pr[1] < max) {
-                        d = pr[1] - max;
-                        min += d;
-                        max += d;
-                    }
-                }
-                
-                opts.min = min;
-                opts.max = max;
-            });
-            
-            plot.setupGrid();
-            plot.draw();
-            
-            if (!args.preventEvent)
-                plot.getPlaceholder().trigger("plotpan", [ plot, args ]);
-        };
-
-        function shutdown(plot, eventHolder) {
-            eventHolder.unbind(plot.getOptions().zoom.trigger, onZoomClick);
-            eventHolder.unbind("mousewheel", onMouseWheel);
-            eventHolder.unbind("dragstart", onDragStart);
-            eventHolder.unbind("drag", onDrag);
-            eventHolder.unbind("dragend", onDragEnd);
-            if (panTimeout)
-                clearTimeout(panTimeout);
-        }
-        
-        plot.hooks.bindEvents.push(bindEvents);
-        plot.hooks.shutdown.push(shutdown);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'navigate',
-        version: '1.3'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.navigate.min.js b/static/js/jquery.flot.navigate.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.navigate.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function(a){function e(h){var k,j=this,l=h.data||{};if(l.elem)j=h.dragTarget=l.elem,h.dragProxy=d.proxy||j,h.cursorOffsetX=l.pageX-l.left,h.cursorOffsetY=l.pageY-l.top,h.offsetX=h.pageX-h.cursorOffsetX,h.offsetY=h.pageY-h.cursorOffsetY;else if(d.dragging||l.which>0&&h.which!=l.which||a(h.target).is(l.not))return;switch(h.type){case"mousedown":return a.extend(l,a(j).offset(),{elem:j,target:h.target,pageX:h.pageX,pageY:h.pageY}),b.add(document,"mousemove mouseup",e,l),i(j,!1),d.dragging=null,!1;case!d.dragging&&"mousemove":if(g(h.pageX-l.pageX)+g(h.pageY-l.pageY)<l.distance)break;h.target=l.target,k=f(h,"dragstart",j),k!==!1&&(d.dragging=j,d.proxy=h.dragProxy=a(k||j)[0]);case"mousemove":if(d.dragging){if(k=f(h,"drag",j),c.drop&&(c.drop.allowed=k!==!1,c.drop.handler(h)),k!==!1)break;h.type="mouseup"}case"mouseup":b.remove(document,"mousemove mouseup",e),d.dragging&&(c.drop&&c.drop.handler(h),f(h,"dragend",j)),i(j,!0),d.dragging=d.proxy=l.elem=!1}return!0}function f(b,c,d){b.type=c;var e=a.event.dispatch.call(d,b);return e===!1?!1:e||b.result}function g(a){return Math.pow(a,2)}function h(){return d.dragging===!1}function i(a,b){a&&(a.unselectable=b?"off":"on",a.onselectstart=function(){return b},a.style&&(a.style.MozUserSelect=b?"":"none"))}a.fn.drag=function(a,b,c){return b&&this.bind("dragstart",a),c&&this.bind("dragend",c),a?this.bind("drag",b?b:a):this.trigger("drag")};var b=a.event,c=b.special,d=c.drag={not:":input",distance:0,which:1,dragging:!1,setup:function(c){c=a.extend({distance:d.distance,which:d.which,not:d.not},c||{}),c.distance=g(c.distance),b.add(this,"mousedown",e,c),this.attachEvent&&this.attachEvent("ondragstart",h)},teardown:function(){b.remove(this,"mousedown",e),this===d.dragging&&(d.dragging=d.proxy=!1),i(this,!0),this.detachEvent&&this.detachEvent("ondragstart",h)}};c.dragstart=c.dragend={setup:function(){},teardown:function(){}}})(jQuery);(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;void 0!==b.axis&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);void 0!==b.wheelDeltaY&&(g=b.wheelDeltaY/120);void 0!==b.wheelDeltaX&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,!1);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,!1);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);(function($){var options={xaxis:{zoomRange:null,panRange:null},zoom:{interactive:false,trigger:"dblclick",amount:1.5},pan:{interactive:false,cursor:"move",frameRate:20}};function init(plot){function onZoomClick(e,zoomOut){var c=plot.offset();c.left=e.pageX-c.left;c.top=e.pageY-c.top;if(zoomOut)plot.zoomOut({center:c});else plot.zoom({center:c})}function onMouseWheel(e,delta){e.preventDefault();onZoomClick(e,delta<0);return false}var prevCursor="default",prevPageX=0,prevPageY=0,panTimeout=null;function onDragStart(e){if(e.which!=1)return false;var c=plot.getPlaceholder().css("cursor");if(c)prevCursor=c;plot.getPlaceholder().css("cursor",plot.getOptions().pan.cursor);prevPageX=e.pageX;prevPageY=e.pageY}function onDrag(e){var frameRate=plot.getOptions().pan.frameRate;if(panTimeout||!frameRate)return;panTimeout=setTimeout(function(){plot.pan({left:prevPageX-e.pageX,top:prevPageY-e.pageY});prevPageX=e.pageX;prevPageY=e.pageY;panTimeout=null},1/frameRate*1e3)}function onDragEnd(e){if(panTimeout){clearTimeout(panTimeout);panTimeout=null}plot.getPlaceholder().css("cursor",prevCursor);plot.pan({left:prevPageX-e.pageX,top:prevPageY-e.pageY})}function bindEvents(plot,eventHolder){var o=plot.getOptions();if(o.zoom.interactive){eventHolder[o.zoom.trigger](onZoomClick);eventHolder.mousewheel(onMouseWheel)}if(o.pan.interactive){eventHolder.bind("dragstart",{distance:10},onDragStart);eventHolder.bind("drag",onDrag);eventHolder.bind("dragend",onDragEnd)}}plot.zoomOut=function(args){if(!args)args={};if(!args.amount)args.amount=plot.getOptions().zoom.amount;args.amount=1/args.amount;plot.zoom(args)};plot.zoom=function(args){if(!args)args={};var c=args.center,amount=args.amount||plot.getOptions().zoom.amount,w=plot.width(),h=plot.height();if(!c)c={left:w/2,top:h/2};var xf=c.left/w,yf=c.top/h,minmax={x:{min:c.left-xf*w/amount,max:c.left+(1-xf)*w/amount},y:{min:c.top-yf*h/amount,max:c.top+(1-yf)*h/amount}};$.each(plot.getAxes(),function(_,axis){var opts=axis.options,min=minmax[axis.direction].min,max=minmax[axis.direction].max,zr=opts.zoomRange,pr=opts.panRange;if(zr===false)return;min=axis.c2p(min);max=axis.c2p(max);if(min>max){var tmp=min;min=max;max=tmp}if(pr){if(pr[0]!=null&&min<pr[0]){min=pr[0]}if(pr[1]!=null&&max>pr[1]){max=pr[1]}}var range=max-min;if(zr&&(zr[0]!=null&&range<zr[0]&&amount>1||zr[1]!=null&&range>zr[1]&&amount<1))return;opts.min=min;opts.max=max});plot.setupGrid();plot.draw();if(!args.preventEvent)plot.getPlaceholder().trigger("plotzoom",[plot,args])};plot.pan=function(args){var delta={x:+args.left,y:+args.top};if(isNaN(delta.x))delta.x=0;if(isNaN(delta.y))delta.y=0;$.each(plot.getAxes(),function(_,axis){var opts=axis.options,min,max,d=delta[axis.direction];min=axis.c2p(axis.p2c(axis.min)+d),max=axis.c2p(axis.p2c(axis.max)+d);var pr=opts.panRange;if(pr===false)return;if(pr){if(pr[0]!=null&&pr[0]>min){d=pr[0]-min;min+=d;max+=d}if(pr[1]!=null&&pr[1]<max){d=pr[1]-max;min+=d;max+=d}}opts.min=min;opts.max=max});plot.setupGrid();plot.draw();if(!args.preventEvent)plot.getPlaceholder().trigger("plotpan",[plot,args])};function shutdown(plot,eventHolder){eventHolder.unbind(plot.getOptions().zoom.trigger,onZoomClick);eventHolder.unbind("mousewheel",onMouseWheel);eventHolder.unbind("dragstart",onDragStart);eventHolder.unbind("drag",onDrag);eventHolder.unbind("dragend",onDragEnd);if(panTimeout)clearTimeout(panTimeout)}plot.hooks.bindEvents.push(bindEvents);plot.hooks.shutdown.push(shutdown)}$.plot.plugins.push({init:init,options:options,name:"navigate",version:"1.3"})})(jQuery);
diff --git a/static/js/jquery.flot.pie.js b/static/js/jquery.flot.pie.js
deleted file mode 100644
--- a/static/js/jquery.flot.pie.js
+++ /dev/null
@@ -1,820 +0,0 @@
-/* Flot plugin for rendering pie charts.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The plugin assumes that each series has a single data value, and that each
-value is a positive integer or zero.  Negative numbers don't make sense for a
-pie chart, and have unpredictable results.  The values do NOT need to be
-passed in as percentages; the plugin will calculate the total and per-slice
-percentages internally.
-
-* Created by Brian Medendorp
-
-* Updated with contributions from btburnett3, Anthony Aragues and Xavi Ivars
-
-The plugin supports these options:
-
-	series: {
-		pie: {
-			show: true/false
-			radius: 0-1 for percentage of fullsize, or a specified pixel length, or 'auto'
-			innerRadius: 0-1 for percentage of fullsize or a specified pixel length, for creating a donut effect
-			startAngle: 0-2 factor of PI used for starting angle (in radians) i.e 3/2 starts at the top, 0 and 2 have the same result
-			tilt: 0-1 for percentage to tilt the pie, where 1 is no tilt, and 0 is completely flat (nothing will show)
-			offset: {
-				top: integer value to move the pie up or down
-				left: integer value to move the pie left or right, or 'auto'
-			},
-			stroke: {
-				color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#FFF')
-				width: integer pixel width of the stroke
-			},
-			label: {
-				show: true/false, or 'auto'
-				formatter:  a user-defined function that modifies the text/style of the label text
-				radius: 0-1 for percentage of fullsize, or a specified pixel length
-				background: {
-					color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#000')
-					opacity: 0-1
-				},
-				threshold: 0-1 for the percentage value at which to hide labels (if they're too small)
-			},
-			combine: {
-				threshold: 0-1 for the percentage value at which to combine slices (if they're too small)
-				color: any hexidecimal color value (other formats may or may not work, so best to stick with something like '#CCC'), if null, the plugin will automatically use the color of the first slice to be combined
-				label: any text value of what the combined slice should be labeled
-			}
-			highlight: {
-				opacity: 0-1
-			}
-		}
-	}
-
-More detail and specific examples can be found in the included HTML file.
-
-*/
-
-(function($) {
-
-	// Maximum redraw attempts when fitting labels within the plot
-
-	var REDRAW_ATTEMPTS = 10;
-
-	// Factor by which to shrink the pie when fitting labels within the plot
-
-	var REDRAW_SHRINK = 0.95;
-
-	function init(plot) {
-
-		var canvas = null,
-			target = null,
-			options = null,
-			maxRadius = null,
-			centerLeft = null,
-			centerTop = null,
-			processed = false,
-			ctx = null;
-
-		// interactive variables
-
-		var highlights = [];
-
-		// add hook to determine if pie plugin in enabled, and then perform necessary operations
-
-		plot.hooks.processOptions.push(function(plot, options) {
-			if (options.series.pie.show) {
-
-				options.grid.show = false;
-
-				// set labels.show
-
-				if (options.series.pie.label.show == "auto") {
-					if (options.legend.show) {
-						options.series.pie.label.show = false;
-					} else {
-						options.series.pie.label.show = true;
-					}
-				}
-
-				// set radius
-
-				if (options.series.pie.radius == "auto") {
-					if (options.series.pie.label.show) {
-						options.series.pie.radius = 3/4;
-					} else {
-						options.series.pie.radius = 1;
-					}
-				}
-
-				// ensure sane tilt
-
-				if (options.series.pie.tilt > 1) {
-					options.series.pie.tilt = 1;
-				} else if (options.series.pie.tilt < 0) {
-					options.series.pie.tilt = 0;
-				}
-			}
-		});
-
-		plot.hooks.bindEvents.push(function(plot, eventHolder) {
-			var options = plot.getOptions();
-			if (options.series.pie.show) {
-				if (options.grid.hoverable) {
-					eventHolder.unbind("mousemove").mousemove(onMouseMove);
-				}
-				if (options.grid.clickable) {
-					eventHolder.unbind("click").click(onClick);
-				}
-			}
-		});
-
-		plot.hooks.processDatapoints.push(function(plot, series, data, datapoints) {
-			var options = plot.getOptions();
-			if (options.series.pie.show) {
-				processDatapoints(plot, series, data, datapoints);
-			}
-		});
-
-		plot.hooks.drawOverlay.push(function(plot, octx) {
-			var options = plot.getOptions();
-			if (options.series.pie.show) {
-				drawOverlay(plot, octx);
-			}
-		});
-
-		plot.hooks.draw.push(function(plot, newCtx) {
-			var options = plot.getOptions();
-			if (options.series.pie.show) {
-				draw(plot, newCtx);
-			}
-		});
-
-		function processDatapoints(plot, series, datapoints) {
-			if (!processed)	{
-				processed = true;
-				canvas = plot.getCanvas();
-				target = $(canvas).parent();
-				options = plot.getOptions();
-				plot.setData(combine(plot.getData()));
-			}
-		}
-
-		function combine(data) {
-
-			var total = 0,
-				combined = 0,
-				numCombined = 0,
-				color = options.series.pie.combine.color,
-				newdata = [];
-
-			// Fix up the raw data from Flot, ensuring the data is numeric
-
-			for (var i = 0; i < data.length; ++i) {
-
-				var value = data[i].data;
-
-				// If the data is an array, we'll assume that it's a standard
-				// Flot x-y pair, and are concerned only with the second value.
-
-				// Note how we use the original array, rather than creating a
-				// new one; this is more efficient and preserves any extra data
-				// that the user may have stored in higher indexes.
-
-				if ($.isArray(value) && value.length == 1) {
-    				value = value[0];
-				}
-
-				if ($.isArray(value)) {
-					// Equivalent to $.isNumeric() but compatible with jQuery < 1.7
-					if (!isNaN(parseFloat(value[1])) && isFinite(value[1])) {
-						value[1] = +value[1];
-					} else {
-						value[1] = 0;
-					}
-				} else if (!isNaN(parseFloat(value)) && isFinite(value)) {
-					value = [1, +value];
-				} else {
-					value = [1, 0];
-				}
-
-				data[i].data = [value];
-			}
-
-			// Sum up all the slices, so we can calculate percentages for each
-
-			for (var i = 0; i < data.length; ++i) {
-				total += data[i].data[0][1];
-			}
-
-			// Count the number of slices with percentages below the combine
-			// threshold; if it turns out to be just one, we won't combine.
-
-			for (var i = 0; i < data.length; ++i) {
-				var value = data[i].data[0][1];
-				if (value / total <= options.series.pie.combine.threshold) {
-					combined += value;
-					numCombined++;
-					if (!color) {
-						color = data[i].color;
-					}
-				}
-			}
-
-			for (var i = 0; i < data.length; ++i) {
-				var value = data[i].data[0][1];
-				if (numCombined < 2 || value / total > options.series.pie.combine.threshold) {
-					newdata.push(
-						$.extend(data[i], {     /* extend to allow keeping all other original data values
-						                           and using them e.g. in labelFormatter. */
-							data: [[1, value]],
-							color: data[i].color,
-							label: data[i].label,
-							angle: value * Math.PI * 2 / total,
-							percent: value / (total / 100)
-						})
-					);
-				}
-			}
-
-			if (numCombined > 1) {
-				newdata.push({
-					data: [[1, combined]],
-					color: color,
-					label: options.series.pie.combine.label,
-					angle: combined * Math.PI * 2 / total,
-					percent: combined / (total / 100)
-				});
-			}
-
-			return newdata;
-		}
-
-		function draw(plot, newCtx) {
-
-			if (!target) {
-				return; // if no series were passed
-			}
-
-			var canvasWidth = plot.getPlaceholder().width(),
-				canvasHeight = plot.getPlaceholder().height(),
-				legendWidth = target.children().filter(".legend").children().width() || 0;
-
-			ctx = newCtx;
-
-			// WARNING: HACK! REWRITE THIS CODE AS SOON AS POSSIBLE!
-
-			// When combining smaller slices into an 'other' slice, we need to
-			// add a new series.  Since Flot gives plugins no way to modify the
-			// list of series, the pie plugin uses a hack where the first call
-			// to processDatapoints results in a call to setData with the new
-			// list of series, then subsequent processDatapoints do nothing.
-
-			// The plugin-global 'processed' flag is used to control this hack;
-			// it starts out false, and is set to true after the first call to
-			// processDatapoints.
-
-			// Unfortunately this turns future setData calls into no-ops; they
-			// call processDatapoints, the flag is true, and nothing happens.
-
-			// To fix this we'll set the flag back to false here in draw, when
-			// all series have been processed, so the next sequence of calls to
-			// processDatapoints once again starts out with a slice-combine.
-			// This is really a hack; in 0.9 we need to give plugins a proper
-			// way to modify series before any processing begins.
-
-			processed = false;
-
-			// calculate maximum radius and center point
-
-			maxRadius =  Math.min(canvasWidth, canvasHeight / options.series.pie.tilt) / 2;
-			centerTop = canvasHeight / 2 + options.series.pie.offset.top;
-			centerLeft = canvasWidth / 2;
-
-			if (options.series.pie.offset.left == "auto") {
-				if (options.legend.position.match("w")) {
-					centerLeft += legendWidth / 2;
-				} else {
-					centerLeft -= legendWidth / 2;
-				}
-				if (centerLeft < maxRadius) {
-					centerLeft = maxRadius;
-				} else if (centerLeft > canvasWidth - maxRadius) {
-					centerLeft = canvasWidth - maxRadius;
-				}
-			} else {
-				centerLeft += options.series.pie.offset.left;
-			}
-
-			var slices = plot.getData(),
-				attempts = 0;
-
-			// Keep shrinking the pie's radius until drawPie returns true,
-			// indicating that all the labels fit, or we try too many times.
-
-			do {
-				if (attempts > 0) {
-					maxRadius *= REDRAW_SHRINK;
-				}
-				attempts += 1;
-				clear();
-				if (options.series.pie.tilt <= 0.8) {
-					drawShadow();
-				}
-			} while (!drawPie() && attempts < REDRAW_ATTEMPTS)
-
-			if (attempts >= REDRAW_ATTEMPTS) {
-				clear();
-				target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>");
-			}
-
-			if (plot.setSeries && plot.insertLegend) {
-				plot.setSeries(slices);
-				plot.insertLegend();
-			}
-
-			// we're actually done at this point, just defining internal functions at this point
-
-			function clear() {
-				ctx.clearRect(0, 0, canvasWidth, canvasHeight);
-				target.children().filter(".pieLabel, .pieLabelBackground").remove();
-			}
-
-			function drawShadow() {
-
-				var shadowLeft = options.series.pie.shadow.left;
-				var shadowTop = options.series.pie.shadow.top;
-				var edge = 10;
-				var alpha = options.series.pie.shadow.alpha;
-				var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
-
-				if (radius >= canvasWidth / 2 - shadowLeft || radius * options.series.pie.tilt >= canvasHeight / 2 - shadowTop || radius <= edge) {
-					return;	// shadow would be outside canvas, so don't draw it
-				}
-
-				ctx.save();
-				ctx.translate(shadowLeft,shadowTop);
-				ctx.globalAlpha = alpha;
-				ctx.fillStyle = "#000";
-
-				// center and rotate to starting position
-
-				ctx.translate(centerLeft,centerTop);
-				ctx.scale(1, options.series.pie.tilt);
-
-				//radius -= edge;
-
-				for (var i = 1; i <= edge; i++) {
-					ctx.beginPath();
-					ctx.arc(0, 0, radius, 0, Math.PI * 2, false);
-					ctx.fill();
-					radius -= i;
-				}
-
-				ctx.restore();
-			}
-
-			function drawPie() {
-
-				var startAngle = Math.PI * options.series.pie.startAngle;
-				var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
-
-				// center and rotate to starting position
-
-				ctx.save();
-				ctx.translate(centerLeft,centerTop);
-				ctx.scale(1, options.series.pie.tilt);
-				//ctx.rotate(startAngle); // start at top; -- This doesn't work properly in Opera
-
-				// draw slices
-
-				ctx.save();
-				var currentAngle = startAngle;
-				for (var i = 0; i < slices.length; ++i) {
-					slices[i].startAngle = currentAngle;
-					drawSlice(slices[i].angle, slices[i].color, true);
-				}
-				ctx.restore();
-
-				// draw slice outlines
-
-				if (options.series.pie.stroke.width > 0) {
-					ctx.save();
-					ctx.lineWidth = options.series.pie.stroke.width;
-					currentAngle = startAngle;
-					for (var i = 0; i < slices.length; ++i) {
-						drawSlice(slices[i].angle, options.series.pie.stroke.color, false);
-					}
-					ctx.restore();
-				}
-
-				// draw donut hole
-
-				drawDonutHole(ctx);
-
-				ctx.restore();
-
-				// Draw the labels, returning true if they fit within the plot
-
-				if (options.series.pie.label.show) {
-					return drawLabels();
-				} else return true;
-
-				function drawSlice(angle, color, fill) {
-
-					if (angle <= 0 || isNaN(angle)) {
-						return;
-					}
-
-					if (fill) {
-						ctx.fillStyle = color;
-					} else {
-						ctx.strokeStyle = color;
-						ctx.lineJoin = "round";
-					}
-
-					ctx.beginPath();
-					if (Math.abs(angle - Math.PI * 2) > 0.000000001) {
-						ctx.moveTo(0, 0); // Center of the pie
-					}
-
-					//ctx.arc(0, 0, radius, 0, angle, false); // This doesn't work properly in Opera
-					ctx.arc(0, 0, radius,currentAngle, currentAngle + angle / 2, false);
-					ctx.arc(0, 0, radius,currentAngle + angle / 2, currentAngle + angle, false);
-					ctx.closePath();
-					//ctx.rotate(angle); // This doesn't work properly in Opera
-					currentAngle += angle;
-
-					if (fill) {
-						ctx.fill();
-					} else {
-						ctx.stroke();
-					}
-				}
-
-				function drawLabels() {
-
-					var currentAngle = startAngle;
-					var radius = options.series.pie.label.radius > 1 ? options.series.pie.label.radius : maxRadius * options.series.pie.label.radius;
-
-					for (var i = 0; i < slices.length; ++i) {
-						if (slices[i].percent >= options.series.pie.label.threshold * 100) {
-							if (!drawLabel(slices[i], currentAngle, i)) {
-								return false;
-							}
-						}
-						currentAngle += slices[i].angle;
-					}
-
-					return true;
-
-					function drawLabel(slice, startAngle, index) {
-
-						if (slice.data[0][1] == 0) {
-							return true;
-						}
-
-						// format label text
-
-						var lf = options.legend.labelFormatter, text, plf = options.series.pie.label.formatter;
-
-						if (lf) {
-							text = lf(slice.label, slice);
-						} else {
-							text = slice.label;
-						}
-
-						if (plf) {
-							text = plf(text, slice);
-						}
-
-						var halfAngle = ((startAngle + slice.angle) + startAngle) / 2;
-						var x = centerLeft + Math.round(Math.cos(halfAngle) * radius);
-						var y = centerTop + Math.round(Math.sin(halfAngle) * radius) * options.series.pie.tilt;
-
-						var html = "<span class='pieLabel' id='pieLabel" + index + "' style='position:absolute;top:" + y + "px;left:" + x + "px;'>" + text + "</span>";
-						target.append(html);
-
-						var label = target.children("#pieLabel" + index);
-						var labelTop = (y - label.height() / 2);
-						var labelLeft = (x - label.width() / 2);
-
-						label.css("top", labelTop);
-						label.css("left", labelLeft);
-
-						// check to make sure that the label is not outside the canvas
-
-						if (0 - labelTop > 0 || 0 - labelLeft > 0 || canvasHeight - (labelTop + label.height()) < 0 || canvasWidth - (labelLeft + label.width()) < 0) {
-							return false;
-						}
-
-						if (options.series.pie.label.background.opacity != 0) {
-
-							// put in the transparent background separately to avoid blended labels and label boxes
-
-							var c = options.series.pie.label.background.color;
-
-							if (c == null) {
-								c = slice.color;
-							}
-
-							var pos = "top:" + labelTop + "px;left:" + labelLeft + "px;";
-							$("<div class='pieLabelBackground' style='position:absolute;width:" + label.width() + "px;height:" + label.height() + "px;" + pos + "background-color:" + c + ";'></div>")
-								.css("opacity", options.series.pie.label.background.opacity)
-								.insertBefore(label);
-						}
-
-						return true;
-					} // end individual label function
-				} // end drawLabels function
-			} // end drawPie function
-		} // end draw function
-
-		// Placed here because it needs to be accessed from multiple locations
-
-		function drawDonutHole(layer) {
-			if (options.series.pie.innerRadius > 0) {
-
-				// subtract the center
-
-				layer.save();
-				var innerRadius = options.series.pie.innerRadius > 1 ? options.series.pie.innerRadius : maxRadius * options.series.pie.innerRadius;
-				layer.globalCompositeOperation = "destination-out"; // this does not work with excanvas, but it will fall back to using the stroke color
-				layer.beginPath();
-				layer.fillStyle = options.series.pie.stroke.color;
-				layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
-				layer.fill();
-				layer.closePath();
-				layer.restore();
-
-				// add inner stroke
-
-				layer.save();
-				layer.beginPath();
-				layer.strokeStyle = options.series.pie.stroke.color;
-				layer.arc(0, 0, innerRadius, 0, Math.PI * 2, false);
-				layer.stroke();
-				layer.closePath();
-				layer.restore();
-
-				// TODO: add extra shadow inside hole (with a mask) if the pie is tilted.
-			}
-		}
-
-		//-- Additional Interactive related functions --
-
-		function isPointInPoly(poly, pt) {
-			for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
-				((poly[i][1] <= pt[1] && pt[1] < poly[j][1]) || (poly[j][1] <= pt[1] && pt[1]< poly[i][1]))
-				&& (pt[0] < (poly[j][0] - poly[i][0]) * (pt[1] - poly[i][1]) / (poly[j][1] - poly[i][1]) + poly[i][0])
-				&& (c = !c);
-			return c;
-		}
-
-		function findNearbySlice(mouseX, mouseY) {
-
-			var slices = plot.getData(),
-				options = plot.getOptions(),
-				radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius,
-				x, y;
-
-			for (var i = 0; i < slices.length; ++i) {
-
-				var s = slices[i];
-
-				if (s.pie.show) {
-
-					ctx.save();
-					ctx.beginPath();
-					ctx.moveTo(0, 0); // Center of the pie
-					//ctx.scale(1, options.series.pie.tilt);	// this actually seems to break everything when here.
-					ctx.arc(0, 0, radius, s.startAngle, s.startAngle + s.angle / 2, false);
-					ctx.arc(0, 0, radius, s.startAngle + s.angle / 2, s.startAngle + s.angle, false);
-					ctx.closePath();
-					x = mouseX - centerLeft;
-					y = mouseY - centerTop;
-
-					if (ctx.isPointInPath) {
-						if (ctx.isPointInPath(mouseX - centerLeft, mouseY - centerTop)) {
-							ctx.restore();
-							return {
-								datapoint: [s.percent, s.data],
-								dataIndex: 0,
-								series: s,
-								seriesIndex: i
-							};
-						}
-					} else {
-
-						// excanvas for IE doesn;t support isPointInPath, this is a workaround.
-
-						var p1X = radius * Math.cos(s.startAngle),
-							p1Y = radius * Math.sin(s.startAngle),
-							p2X = radius * Math.cos(s.startAngle + s.angle / 4),
-							p2Y = radius * Math.sin(s.startAngle + s.angle / 4),
-							p3X = radius * Math.cos(s.startAngle + s.angle / 2),
-							p3Y = radius * Math.sin(s.startAngle + s.angle / 2),
-							p4X = radius * Math.cos(s.startAngle + s.angle / 1.5),
-							p4Y = radius * Math.sin(s.startAngle + s.angle / 1.5),
-							p5X = radius * Math.cos(s.startAngle + s.angle),
-							p5Y = radius * Math.sin(s.startAngle + s.angle),
-							arrPoly = [[0, 0], [p1X, p1Y], [p2X, p2Y], [p3X, p3Y], [p4X, p4Y], [p5X, p5Y]],
-							arrPoint = [x, y];
-
-						// TODO: perhaps do some mathmatical trickery here with the Y-coordinate to compensate for pie tilt?
-
-						if (isPointInPoly(arrPoly, arrPoint)) {
-							ctx.restore();
-							return {
-								datapoint: [s.percent, s.data],
-								dataIndex: 0,
-								series: s,
-								seriesIndex: i
-							};
-						}
-					}
-
-					ctx.restore();
-				}
-			}
-
-			return null;
-		}
-
-		function onMouseMove(e) {
-			triggerClickHoverEvent("plothover", e);
-		}
-
-		function onClick(e) {
-			triggerClickHoverEvent("plotclick", e);
-		}
-
-		// trigger click or hover event (they send the same parameters so we share their code)
-
-		function triggerClickHoverEvent(eventname, e) {
-
-			var offset = plot.offset();
-			var canvasX = parseInt(e.pageX - offset.left);
-			var canvasY =  parseInt(e.pageY - offset.top);
-			var item = findNearbySlice(canvasX, canvasY);
-
-			if (options.grid.autoHighlight) {
-
-				// clear auto-highlights
-
-				for (var i = 0; i < highlights.length; ++i) {
-					var h = highlights[i];
-					if (h.auto == eventname && !(item && h.series == item.series)) {
-						unhighlight(h.series);
-					}
-				}
-			}
-
-			// highlight the slice
-
-			if (item) {
-				highlight(item.series, eventname);
-			}
-
-			// trigger any hover bind events
-
-			var pos = { pageX: e.pageX, pageY: e.pageY };
-			target.trigger(eventname, [pos, item]);
-		}
-
-		function highlight(s, auto) {
-			//if (typeof s == "number") {
-			//	s = series[s];
-			//}
-
-			var i = indexOfHighlight(s);
-
-			if (i == -1) {
-				highlights.push({ series: s, auto: auto });
-				plot.triggerRedrawOverlay();
-			} else if (!auto) {
-				highlights[i].auto = false;
-			}
-		}
-
-		function unhighlight(s) {
-			if (s == null) {
-				highlights = [];
-				plot.triggerRedrawOverlay();
-			}
-
-			//if (typeof s == "number") {
-			//	s = series[s];
-			//}
-
-			var i = indexOfHighlight(s);
-
-			if (i != -1) {
-				highlights.splice(i, 1);
-				plot.triggerRedrawOverlay();
-			}
-		}
-
-		function indexOfHighlight(s) {
-			for (var i = 0; i < highlights.length; ++i) {
-				var h = highlights[i];
-				if (h.series == s)
-					return i;
-			}
-			return -1;
-		}
-
-		function drawOverlay(plot, octx) {
-
-			var options = plot.getOptions();
-
-			var radius = options.series.pie.radius > 1 ? options.series.pie.radius : maxRadius * options.series.pie.radius;
-
-			octx.save();
-			octx.translate(centerLeft, centerTop);
-			octx.scale(1, options.series.pie.tilt);
-
-			for (var i = 0; i < highlights.length; ++i) {
-				drawHighlight(highlights[i].series);
-			}
-
-			drawDonutHole(octx);
-
-			octx.restore();
-
-			function drawHighlight(series) {
-
-				if (series.angle <= 0 || isNaN(series.angle)) {
-					return;
-				}
-
-				//octx.fillStyle = parseColor(options.series.pie.highlight.color).scale(null, null, null, options.series.pie.highlight.opacity).toString();
-				octx.fillStyle = "rgba(255, 255, 255, " + options.series.pie.highlight.opacity + ")"; // this is temporary until we have access to parseColor
-				octx.beginPath();
-				if (Math.abs(series.angle - Math.PI * 2) > 0.000000001) {
-					octx.moveTo(0, 0); // Center of the pie
-				}
-				octx.arc(0, 0, radius, series.startAngle, series.startAngle + series.angle / 2, false);
-				octx.arc(0, 0, radius, series.startAngle + series.angle / 2, series.startAngle + series.angle, false);
-				octx.closePath();
-				octx.fill();
-			}
-		}
-	} // end init (plugin body)
-
-	// define pie specific options and their default values
-
-	var options = {
-		series: {
-			pie: {
-				show: false,
-				radius: "auto",	// actual radius of the visible pie (based on full calculated radius if <=1, or hard pixel value)
-				innerRadius: 0, /* for donut */
-				startAngle: 3/2,
-				tilt: 1,
-				shadow: {
-					left: 5,	// shadow left offset
-					top: 15,	// shadow top offset
-					alpha: 0.02	// shadow alpha
-				},
-				offset: {
-					top: 0,
-					left: "auto"
-				},
-				stroke: {
-					color: "#fff",
-					width: 1
-				},
-				label: {
-					show: "auto",
-					formatter: function(label, slice) {
-						return "<div style='font-size:x-small;text-align:center;padding:2px;color:" + slice.color + ";'>" + label + "<br/>" + Math.round(slice.percent) + "%</div>";
-					},	// formatter function
-					radius: 1,	// radius at which to place the labels (based on full calculated radius if <=1, or hard pixel value)
-					background: {
-						color: null,
-						opacity: 0
-					},
-					threshold: 0	// percentage at which to hide the label (i.e. the slice is too narrow)
-				},
-				combine: {
-					threshold: -1,	// percentage at which to combine little slices into one larger slice
-					color: null,	// color to give the new slice (auto-generated if null)
-					label: "Other"	// label to give the new slice
-				},
-				highlight: {
-					//color: "#fff",		// will add this functionality once parseColor is available
-					opacity: 0.5
-				}
-			}
-		}
-	};
-
-	$.plot.plugins.push({
-		init: init,
-		options: options,
-		name: "pie",
-		version: "1.1"
-	});
-
-})(jQuery);
diff --git a/static/js/jquery.flot.pie.min.js b/static/js/jquery.flot.pie.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.pie.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var REDRAW_ATTEMPTS=10;var REDRAW_SHRINK=.95;function init(plot){var canvas=null,target=null,options=null,maxRadius=null,centerLeft=null,centerTop=null,processed=false,ctx=null;var highlights=[];plot.hooks.processOptions.push(function(plot,options){if(options.series.pie.show){options.grid.show=false;if(options.series.pie.label.show=="auto"){if(options.legend.show){options.series.pie.label.show=false}else{options.series.pie.label.show=true}}if(options.series.pie.radius=="auto"){if(options.series.pie.label.show){options.series.pie.radius=3/4}else{options.series.pie.radius=1}}if(options.series.pie.tilt>1){options.series.pie.tilt=1}else if(options.series.pie.tilt<0){options.series.pie.tilt=0}}});plot.hooks.bindEvents.push(function(plot,eventHolder){var options=plot.getOptions();if(options.series.pie.show){if(options.grid.hoverable){eventHolder.unbind("mousemove").mousemove(onMouseMove)}if(options.grid.clickable){eventHolder.unbind("click").click(onClick)}}});plot.hooks.processDatapoints.push(function(plot,series,data,datapoints){var options=plot.getOptions();if(options.series.pie.show){processDatapoints(plot,series,data,datapoints)}});plot.hooks.drawOverlay.push(function(plot,octx){var options=plot.getOptions();if(options.series.pie.show){drawOverlay(plot,octx)}});plot.hooks.draw.push(function(plot,newCtx){var options=plot.getOptions();if(options.series.pie.show){draw(plot,newCtx)}});function processDatapoints(plot,series,datapoints){if(!processed){processed=true;canvas=plot.getCanvas();target=$(canvas).parent();options=plot.getOptions();plot.setData(combine(plot.getData()))}}function combine(data){var total=0,combined=0,numCombined=0,color=options.series.pie.combine.color,newdata=[];for(var i=0;i<data.length;++i){var value=data[i].data;if($.isArray(value)&&value.length==1){value=value[0]}if($.isArray(value)){if(!isNaN(parseFloat(value[1]))&&isFinite(value[1])){value[1]=+value[1]}else{value[1]=0}}else if(!isNaN(parseFloat(value))&&isFinite(value)){value=[1,+value]}else{value=[1,0]}data[i].data=[value]}for(var i=0;i<data.length;++i){total+=data[i].data[0][1]}for(var i=0;i<data.length;++i){var value=data[i].data[0][1];if(value/total<=options.series.pie.combine.threshold){combined+=value;numCombined++;if(!color){color=data[i].color}}}for(var i=0;i<data.length;++i){var value=data[i].data[0][1];if(numCombined<2||value/total>options.series.pie.combine.threshold){newdata.push($.extend(data[i],{data:[[1,value]],color:data[i].color,label:data[i].label,angle:value*Math.PI*2/total,percent:value/(total/100)}))}}if(numCombined>1){newdata.push({data:[[1,combined]],color:color,label:options.series.pie.combine.label,angle:combined*Math.PI*2/total,percent:combined/(total/100)})}return newdata}function draw(plot,newCtx){if(!target){return}var canvasWidth=plot.getPlaceholder().width(),canvasHeight=plot.getPlaceholder().height(),legendWidth=target.children().filter(".legend").children().width()||0;ctx=newCtx;processed=false;maxRadius=Math.min(canvasWidth,canvasHeight/options.series.pie.tilt)/2;centerTop=canvasHeight/2+options.series.pie.offset.top;centerLeft=canvasWidth/2;if(options.series.pie.offset.left=="auto"){if(options.legend.position.match("w")){centerLeft+=legendWidth/2}else{centerLeft-=legendWidth/2}if(centerLeft<maxRadius){centerLeft=maxRadius}else if(centerLeft>canvasWidth-maxRadius){centerLeft=canvasWidth-maxRadius}}else{centerLeft+=options.series.pie.offset.left}var slices=plot.getData(),attempts=0;do{if(attempts>0){maxRadius*=REDRAW_SHRINK}attempts+=1;clear();if(options.series.pie.tilt<=.8){drawShadow()}}while(!drawPie()&&attempts<REDRAW_ATTEMPTS);if(attempts>=REDRAW_ATTEMPTS){clear();target.prepend("<div class='error'>Could not draw pie with labels contained inside canvas</div>")}if(plot.setSeries&&plot.insertLegend){plot.setSeries(slices);plot.insertLegend()}function clear(){ctx.clearRect(0,0,canvasWidth,canvasHeight);target.children().filter(".pieLabel, .pieLabelBackground").remove()}function drawShadow(){var shadowLeft=options.series.pie.shadow.left;var shadowTop=options.series.pie.shadow.top;var edge=10;var alpha=options.series.pie.shadow.alpha;var radius=options.series.pie.radius>1?options.series.pie.radius:maxRadius*options.series.pie.radius;if(radius>=canvasWidth/2-shadowLeft||radius*options.series.pie.tilt>=canvasHeight/2-shadowTop||radius<=edge){return}ctx.save();ctx.translate(shadowLeft,shadowTop);ctx.globalAlpha=alpha;ctx.fillStyle="#000";ctx.translate(centerLeft,centerTop);ctx.scale(1,options.series.pie.tilt);for(var i=1;i<=edge;i++){ctx.beginPath();ctx.arc(0,0,radius,0,Math.PI*2,false);ctx.fill();radius-=i}ctx.restore()}function drawPie(){var startAngle=Math.PI*options.series.pie.startAngle;var radius=options.series.pie.radius>1?options.series.pie.radius:maxRadius*options.series.pie.radius;ctx.save();ctx.translate(centerLeft,centerTop);ctx.scale(1,options.series.pie.tilt);ctx.save();var currentAngle=startAngle;for(var i=0;i<slices.length;++i){slices[i].startAngle=currentAngle;drawSlice(slices[i].angle,slices[i].color,true)}ctx.restore();if(options.series.pie.stroke.width>0){ctx.save();ctx.lineWidth=options.series.pie.stroke.width;currentAngle=startAngle;for(var i=0;i<slices.length;++i){drawSlice(slices[i].angle,options.series.pie.stroke.color,false)}ctx.restore()}drawDonutHole(ctx);ctx.restore();if(options.series.pie.label.show){return drawLabels()}else return true;function drawSlice(angle,color,fill){if(angle<=0||isNaN(angle)){return}if(fill){ctx.fillStyle=color}else{ctx.strokeStyle=color;ctx.lineJoin="round"}ctx.beginPath();if(Math.abs(angle-Math.PI*2)>1e-9){ctx.moveTo(0,0)}ctx.arc(0,0,radius,currentAngle,currentAngle+angle/2,false);ctx.arc(0,0,radius,currentAngle+angle/2,currentAngle+angle,false);ctx.closePath();currentAngle+=angle;if(fill){ctx.fill()}else{ctx.stroke()}}function drawLabels(){var currentAngle=startAngle;var radius=options.series.pie.label.radius>1?options.series.pie.label.radius:maxRadius*options.series.pie.label.radius;for(var i=0;i<slices.length;++i){if(slices[i].percent>=options.series.pie.label.threshold*100){if(!drawLabel(slices[i],currentAngle,i)){return false}}currentAngle+=slices[i].angle}return true;function drawLabel(slice,startAngle,index){if(slice.data[0][1]==0){return true}var lf=options.legend.labelFormatter,text,plf=options.series.pie.label.formatter;if(lf){text=lf(slice.label,slice)}else{text=slice.label}if(plf){text=plf(text,slice)}var halfAngle=(startAngle+slice.angle+startAngle)/2;var x=centerLeft+Math.round(Math.cos(halfAngle)*radius);var y=centerTop+Math.round(Math.sin(halfAngle)*radius)*options.series.pie.tilt;var html="<span class='pieLabel' id='pieLabel"+index+"' style='position:absolute;top:"+y+"px;left:"+x+"px;'>"+text+"</span>";target.append(html);var label=target.children("#pieLabel"+index);var labelTop=y-label.height()/2;var labelLeft=x-label.width()/2;label.css("top",labelTop);label.css("left",labelLeft);if(0-labelTop>0||0-labelLeft>0||canvasHeight-(labelTop+label.height())<0||canvasWidth-(labelLeft+label.width())<0){return false}if(options.series.pie.label.background.opacity!=0){var c=options.series.pie.label.background.color;if(c==null){c=slice.color}var pos="top:"+labelTop+"px;left:"+labelLeft+"px;";$("<div class='pieLabelBackground' style='position:absolute;width:"+label.width()+"px;height:"+label.height()+"px;"+pos+"background-color:"+c+";'></div>").css("opacity",options.series.pie.label.background.opacity).insertBefore(label)}return true}}}}function drawDonutHole(layer){if(options.series.pie.innerRadius>0){layer.save();var innerRadius=options.series.pie.innerRadius>1?options.series.pie.innerRadius:maxRadius*options.series.pie.innerRadius;layer.globalCompositeOperation="destination-out";layer.beginPath();layer.fillStyle=options.series.pie.stroke.color;layer.arc(0,0,innerRadius,0,Math.PI*2,false);layer.fill();layer.closePath();layer.restore();layer.save();layer.beginPath();layer.strokeStyle=options.series.pie.stroke.color;layer.arc(0,0,innerRadius,0,Math.PI*2,false);layer.stroke();layer.closePath();layer.restore()}}function isPointInPoly(poly,pt){for(var c=false,i=-1,l=poly.length,j=l-1;++i<l;j=i)(poly[i][1]<=pt[1]&&pt[1]<poly[j][1]||poly[j][1]<=pt[1]&&pt[1]<poly[i][1])&&pt[0]<(poly[j][0]-poly[i][0])*(pt[1]-poly[i][1])/(poly[j][1]-poly[i][1])+poly[i][0]&&(c=!c);return c}function findNearbySlice(mouseX,mouseY){var slices=plot.getData(),options=plot.getOptions(),radius=options.series.pie.radius>1?options.series.pie.radius:maxRadius*options.series.pie.radius,x,y;for(var i=0;i<slices.length;++i){var s=slices[i];if(s.pie.show){ctx.save();ctx.beginPath();ctx.moveTo(0,0);ctx.arc(0,0,radius,s.startAngle,s.startAngle+s.angle/2,false);ctx.arc(0,0,radius,s.startAngle+s.angle/2,s.startAngle+s.angle,false);ctx.closePath();x=mouseX-centerLeft;y=mouseY-centerTop;if(ctx.isPointInPath){if(ctx.isPointInPath(mouseX-centerLeft,mouseY-centerTop)){ctx.restore();return{datapoint:[s.percent,s.data],dataIndex:0,series:s,seriesIndex:i}}}else{var p1X=radius*Math.cos(s.startAngle),p1Y=radius*Math.sin(s.startAngle),p2X=radius*Math.cos(s.startAngle+s.angle/4),p2Y=radius*Math.sin(s.startAngle+s.angle/4),p3X=radius*Math.cos(s.startAngle+s.angle/2),p3Y=radius*Math.sin(s.startAngle+s.angle/2),p4X=radius*Math.cos(s.startAngle+s.angle/1.5),p4Y=radius*Math.sin(s.startAngle+s.angle/1.5),p5X=radius*Math.cos(s.startAngle+s.angle),p5Y=radius*Math.sin(s.startAngle+s.angle),arrPoly=[[0,0],[p1X,p1Y],[p2X,p2Y],[p3X,p3Y],[p4X,p4Y],[p5X,p5Y]],arrPoint=[x,y];if(isPointInPoly(arrPoly,arrPoint)){ctx.restore();return{datapoint:[s.percent,s.data],dataIndex:0,series:s,seriesIndex:i}}}ctx.restore()}}return null}function onMouseMove(e){triggerClickHoverEvent("plothover",e)}function onClick(e){triggerClickHoverEvent("plotclick",e)}function triggerClickHoverEvent(eventname,e){var offset=plot.offset();var canvasX=parseInt(e.pageX-offset.left);var canvasY=parseInt(e.pageY-offset.top);var item=findNearbySlice(canvasX,canvasY);if(options.grid.autoHighlight){for(var i=0;i<highlights.length;++i){var h=highlights[i];if(h.auto==eventname&&!(item&&h.series==item.series)){unhighlight(h.series)}}}if(item){highlight(item.series,eventname)}var pos={pageX:e.pageX,pageY:e.pageY};target.trigger(eventname,[pos,item])}function highlight(s,auto){var i=indexOfHighlight(s);if(i==-1){highlights.push({series:s,auto:auto});plot.triggerRedrawOverlay()}else if(!auto){highlights[i].auto=false}}function unhighlight(s){if(s==null){highlights=[];plot.triggerRedrawOverlay()}var i=indexOfHighlight(s);if(i!=-1){highlights.splice(i,1);plot.triggerRedrawOverlay()}}function indexOfHighlight(s){for(var i=0;i<highlights.length;++i){var h=highlights[i];if(h.series==s)return i}return-1}function drawOverlay(plot,octx){var options=plot.getOptions();var radius=options.series.pie.radius>1?options.series.pie.radius:maxRadius*options.series.pie.radius;octx.save();octx.translate(centerLeft,centerTop);octx.scale(1,options.series.pie.tilt);for(var i=0;i<highlights.length;++i){drawHighlight(highlights[i].series)}drawDonutHole(octx);octx.restore();function drawHighlight(series){if(series.angle<=0||isNaN(series.angle)){return}octx.fillStyle="rgba(255, 255, 255, "+options.series.pie.highlight.opacity+")";octx.beginPath();if(Math.abs(series.angle-Math.PI*2)>1e-9){octx.moveTo(0,0)}octx.arc(0,0,radius,series.startAngle,series.startAngle+series.angle/2,false);octx.arc(0,0,radius,series.startAngle+series.angle/2,series.startAngle+series.angle,false);octx.closePath();octx.fill()}}}var options={series:{pie:{show:false,radius:"auto",innerRadius:0,startAngle:3/2,tilt:1,shadow:{left:5,top:15,alpha:.02},offset:{top:0,left:"auto"},stroke:{color:"#fff",width:1},label:{show:"auto",formatter:function(label,slice){return"<div style='font-size:x-small;text-align:center;padding:2px;color:"+slice.color+";'>"+label+"<br/>"+Math.round(slice.percent)+"%</div>"},radius:1,background:{color:null,opacity:0},threshold:0},combine:{threshold:-1,color:null,label:"Other"},highlight:{opacity:.5}}}};$.plot.plugins.push({init:init,options:options,name:"pie",version:"1.1"})})(jQuery);
diff --git a/static/js/jquery.flot.resize.js b/static/js/jquery.flot.resize.js
deleted file mode 100644
--- a/static/js/jquery.flot.resize.js
+++ /dev/null
@@ -1,59 +0,0 @@
-/* Flot plugin for automatically redrawing plots as the placeholder resizes.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-It works by listening for changes on the placeholder div (through the jQuery
-resize event plugin) - if the size changes, it will redraw the plot.
-
-There are no options. If you need to disable the plugin for some plots, you
-can just fix the size of their placeholders.
-
-*/
-
-/* Inline dependency:
- * jQuery resize event - v1.1 - 3/14/2010
- * http://benalman.com/projects/jquery-resize-plugin/
- *
- * Copyright (c) 2010 "Cowboy" Ben Alman
- * Dual licensed under the MIT and GPL licenses.
- * http://benalman.com/about/license/
- */
-(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);
-
-(function ($) {
-    var options = { }; // no options
-
-    function init(plot) {
-        function onResize() {
-            var placeholder = plot.getPlaceholder();
-
-            // somebody might have hidden us and we can't plot
-            // when we don't have the dimensions
-            if (placeholder.width() == 0 || placeholder.height() == 0)
-                return;
-
-            plot.resize();
-            plot.setupGrid();
-            plot.draw();
-        }
-        
-        function bindEvents(plot, eventHolder) {
-            plot.getPlaceholder().resize(onResize);
-        }
-
-        function shutdown(plot, eventHolder) {
-            plot.getPlaceholder().unbind("resize", onResize);
-        }
-        
-        plot.hooks.bindEvents.push(bindEvents);
-        plot.hooks.shutdown.push(shutdown);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'resize',
-        version: '1.0'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.resize.min.js b/static/js/jquery.flot.resize.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.resize.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($,e,t){"$:nomunge";var i=[],n=$.resize=$.extend($.resize,{}),a,r=false,s="setTimeout",u="resize",m=u+"-special-event",o="pendingDelay",l="activeDelay",f="throttleWindow";n[o]=200;n[l]=20;n[f]=true;$.event.special[u]={setup:function(){if(!n[f]&&this[s]){return false}var e=$(this);i.push(this);e.data(m,{w:e.width(),h:e.height()});if(i.length===1){a=t;h()}},teardown:function(){if(!n[f]&&this[s]){return false}var e=$(this);for(var t=i.length-1;t>=0;t--){if(i[t]==this){i.splice(t,1);break}}e.removeData(m);if(!i.length){if(r){cancelAnimationFrame(a)}else{clearTimeout(a)}a=null}},add:function(e){if(!n[f]&&this[s]){return false}var i;function a(e,n,a){var r=$(this),s=r.data(m)||{};s.w=n!==t?n:r.width();s.h=a!==t?a:r.height();i.apply(this,arguments)}if($.isFunction(e)){i=e;return a}else{i=e.handler;e.handler=a}}};function h(t){if(r===true){r=t||1}for(var s=i.length-1;s>=0;s--){var l=$(i[s]);if(l[0]==e||l.is(":visible")){var f=l.width(),c=l.height(),d=l.data(m);if(d&&(f!==d.w||c!==d.h)){l.trigger(u,[d.w=f,d.h=c]);r=t||true}}else{d=l.data(m);d.w=0;d.h=0}}if(a!==null){if(r&&(t==null||t-r<1e3)){a=e.requestAnimationFrame(h)}else{a=setTimeout(h,n[o]);r=false}}}if(!e.requestAnimationFrame){e.requestAnimationFrame=function(){return e.webkitRequestAnimationFrame||e.mozRequestAnimationFrame||e.oRequestAnimationFrame||e.msRequestAnimationFrame||function(t,i){return e.setTimeout(function(){t((new Date).getTime())},n[l])}}()}if(!e.cancelAnimationFrame){e.cancelAnimationFrame=function(){return e.webkitCancelRequestAnimationFrame||e.mozCancelRequestAnimationFrame||e.oCancelRequestAnimationFrame||e.msCancelRequestAnimationFrame||clearTimeout}()}})(jQuery,this);(function($){var options={};function init(plot){function onResize(){var placeholder=plot.getPlaceholder();if(placeholder.width()==0||placeholder.height()==0)return;plot.resize();plot.setupGrid();plot.draw()}function bindEvents(plot,eventHolder){plot.getPlaceholder().resize(onResize)}function shutdown(plot,eventHolder){plot.getPlaceholder().unbind("resize",onResize)}plot.hooks.bindEvents.push(bindEvents);plot.hooks.shutdown.push(shutdown)}$.plot.plugins.push({init:init,options:options,name:"resize",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.selection.js b/static/js/jquery.flot.selection.js
deleted file mode 100644
--- a/static/js/jquery.flot.selection.js
+++ /dev/null
@@ -1,360 +0,0 @@
-/* Flot plugin for selecting regions of a plot.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The plugin supports these options:
-
-selection: {
-	mode: null or "x" or "y" or "xy",
-	color: color,
-	shape: "round" or "miter" or "bevel",
-	minSize: number of pixels
-}
-
-Selection support is enabled by setting the mode to one of "x", "y" or "xy".
-In "x" mode, the user will only be able to specify the x range, similarly for
-"y" mode. For "xy", the selection becomes a rectangle where both ranges can be
-specified. "color" is color of the selection (if you need to change the color
-later on, you can get to it with plot.getOptions().selection.color). "shape"
-is the shape of the corners of the selection.
-
-"minSize" is the minimum size a selection can be in pixels. This value can
-be customized to determine the smallest size a selection can be and still
-have the selection rectangle be displayed. When customizing this value, the
-fact that it refers to pixels, not axis units must be taken into account.
-Thus, for example, if there is a bar graph in time mode with BarWidth set to 1
-minute, setting "minSize" to 1 will not make the minimum selection size 1
-minute, but rather 1 pixel. Note also that setting "minSize" to 0 will prevent
-"plotunselected" events from being fired when the user clicks the mouse without
-dragging.
-
-When selection support is enabled, a "plotselected" event will be emitted on
-the DOM element you passed into the plot function. The event handler gets a
-parameter with the ranges selected on the axes, like this:
-
-	placeholder.bind( "plotselected", function( event, ranges ) {
-		alert("You selected " + ranges.xaxis.from + " to " + ranges.xaxis.to)
-		// similar for yaxis - with multiple axes, the extra ones are in
-		// x2axis, x3axis, ...
-	});
-
-The "plotselected" event is only fired when the user has finished making the
-selection. A "plotselecting" event is fired during the process with the same
-parameters as the "plotselected" event, in case you want to know what's
-happening while it's happening,
-
-A "plotunselected" event with no arguments is emitted when the user clicks the
-mouse to remove the selection. As stated above, setting "minSize" to 0 will
-destroy this behavior.
-
-The plugin allso adds the following methods to the plot object:
-
-- setSelection( ranges, preventEvent )
-
-  Set the selection rectangle. The passed in ranges is on the same form as
-  returned in the "plotselected" event. If the selection mode is "x", you
-  should put in either an xaxis range, if the mode is "y" you need to put in
-  an yaxis range and both xaxis and yaxis if the selection mode is "xy", like
-  this:
-
-	setSelection({ xaxis: { from: 0, to: 10 }, yaxis: { from: 40, to: 60 } });
-
-  setSelection will trigger the "plotselected" event when called. If you don't
-  want that to happen, e.g. if you're inside a "plotselected" handler, pass
-  true as the second parameter. If you are using multiple axes, you can
-  specify the ranges on any of those, e.g. as x2axis/x3axis/... instead of
-  xaxis, the plugin picks the first one it sees.
-
-- clearSelection( preventEvent )
-
-  Clear the selection rectangle. Pass in true to avoid getting a
-  "plotunselected" event.
-
-- getSelection()
-
-  Returns the current selection in the same format as the "plotselected"
-  event. If there's currently no selection, the function returns null.
-
-*/
-
-(function ($) {
-    function init(plot) {
-        var selection = {
-                first: { x: -1, y: -1}, second: { x: -1, y: -1},
-                show: false,
-                active: false
-            };
-
-        // FIXME: The drag handling implemented here should be
-        // abstracted out, there's some similar code from a library in
-        // the navigation plugin, this should be massaged a bit to fit
-        // the Flot cases here better and reused. Doing this would
-        // make this plugin much slimmer.
-        var savedhandlers = {};
-
-        var mouseUpHandler = null;
-        
-        function onMouseMove(e) {
-            if (selection.active) {
-                updateSelection(e);
-                
-                plot.getPlaceholder().trigger("plotselecting", [ getSelection() ]);
-            }
-        }
-
-        function onMouseDown(e) {
-            if (e.which != 1)  // only accept left-click
-                return;
-            
-            // cancel out any text selections
-            document.body.focus();
-
-            // prevent text selection and drag in old-school browsers
-            if (document.onselectstart !== undefined && savedhandlers.onselectstart == null) {
-                savedhandlers.onselectstart = document.onselectstart;
-                document.onselectstart = function () { return false; };
-            }
-            if (document.ondrag !== undefined && savedhandlers.ondrag == null) {
-                savedhandlers.ondrag = document.ondrag;
-                document.ondrag = function () { return false; };
-            }
-
-            setSelectionPos(selection.first, e);
-
-            selection.active = true;
-
-            // this is a bit silly, but we have to use a closure to be
-            // able to whack the same handler again
-            mouseUpHandler = function (e) { onMouseUp(e); };
-            
-            $(document).one("mouseup", mouseUpHandler);
-        }
-
-        function onMouseUp(e) {
-            mouseUpHandler = null;
-            
-            // revert drag stuff for old-school browsers
-            if (document.onselectstart !== undefined)
-                document.onselectstart = savedhandlers.onselectstart;
-            if (document.ondrag !== undefined)
-                document.ondrag = savedhandlers.ondrag;
-
-            // no more dragging
-            selection.active = false;
-            updateSelection(e);
-
-            if (selectionIsSane())
-                triggerSelectedEvent();
-            else {
-                // this counts as a clear
-                plot.getPlaceholder().trigger("plotunselected", [ ]);
-                plot.getPlaceholder().trigger("plotselecting", [ null ]);
-            }
-
-            return false;
-        }
-
-        function getSelection() {
-            if (!selectionIsSane())
-                return null;
-            
-            if (!selection.show) return null;
-
-            var r = {}, c1 = selection.first, c2 = selection.second;
-            $.each(plot.getAxes(), function (name, axis) {
-                if (axis.used) {
-                    var p1 = axis.c2p(c1[axis.direction]), p2 = axis.c2p(c2[axis.direction]); 
-                    r[name] = { from: Math.min(p1, p2), to: Math.max(p1, p2) };
-                }
-            });
-            return r;
-        }
-
-        function triggerSelectedEvent() {
-            var r = getSelection();
-
-            plot.getPlaceholder().trigger("plotselected", [ r ]);
-
-            // backwards-compat stuff, to be removed in future
-            if (r.xaxis && r.yaxis)
-                plot.getPlaceholder().trigger("selected", [ { x1: r.xaxis.from, y1: r.yaxis.from, x2: r.xaxis.to, y2: r.yaxis.to } ]);
-        }
-
-        function clamp(min, value, max) {
-            return value < min ? min: (value > max ? max: value);
-        }
-
-        function setSelectionPos(pos, e) {
-            var o = plot.getOptions();
-            var offset = plot.getPlaceholder().offset();
-            var plotOffset = plot.getPlotOffset();
-            pos.x = clamp(0, e.pageX - offset.left - plotOffset.left, plot.width());
-            pos.y = clamp(0, e.pageY - offset.top - plotOffset.top, plot.height());
-
-            if (o.selection.mode == "y")
-                pos.x = pos == selection.first ? 0 : plot.width();
-
-            if (o.selection.mode == "x")
-                pos.y = pos == selection.first ? 0 : plot.height();
-        }
-
-        function updateSelection(pos) {
-            if (pos.pageX == null)
-                return;
-
-            setSelectionPos(selection.second, pos);
-            if (selectionIsSane()) {
-                selection.show = true;
-                plot.triggerRedrawOverlay();
-            }
-            else
-                clearSelection(true);
-        }
-
-        function clearSelection(preventEvent) {
-            if (selection.show) {
-                selection.show = false;
-                plot.triggerRedrawOverlay();
-                if (!preventEvent)
-                    plot.getPlaceholder().trigger("plotunselected", [ ]);
-            }
-        }
-
-        // function taken from markings support in Flot
-        function extractRange(ranges, coord) {
-            var axis, from, to, key, axes = plot.getAxes();
-
-            for (var k in axes) {
-                axis = axes[k];
-                if (axis.direction == coord) {
-                    key = coord + axis.n + "axis";
-                    if (!ranges[key] && axis.n == 1)
-                        key = coord + "axis"; // support x1axis as xaxis
-                    if (ranges[key]) {
-                        from = ranges[key].from;
-                        to = ranges[key].to;
-                        break;
-                    }
-                }
-            }
-
-            // backwards-compat stuff - to be removed in future
-            if (!ranges[key]) {
-                axis = coord == "x" ? plot.getXAxes()[0] : plot.getYAxes()[0];
-                from = ranges[coord + "1"];
-                to = ranges[coord + "2"];
-            }
-
-            // auto-reverse as an added bonus
-            if (from != null && to != null && from > to) {
-                var tmp = from;
-                from = to;
-                to = tmp;
-            }
-            
-            return { from: from, to: to, axis: axis };
-        }
-        
-        function setSelection(ranges, preventEvent) {
-            var axis, range, o = plot.getOptions();
-
-            if (o.selection.mode == "y") {
-                selection.first.x = 0;
-                selection.second.x = plot.width();
-            }
-            else {
-                range = extractRange(ranges, "x");
-
-                selection.first.x = range.axis.p2c(range.from);
-                selection.second.x = range.axis.p2c(range.to);
-            }
-
-            if (o.selection.mode == "x") {
-                selection.first.y = 0;
-                selection.second.y = plot.height();
-            }
-            else {
-                range = extractRange(ranges, "y");
-
-                selection.first.y = range.axis.p2c(range.from);
-                selection.second.y = range.axis.p2c(range.to);
-            }
-
-            selection.show = true;
-            plot.triggerRedrawOverlay();
-            if (!preventEvent && selectionIsSane())
-                triggerSelectedEvent();
-        }
-
-        function selectionIsSane() {
-            var minSize = plot.getOptions().selection.minSize;
-            return Math.abs(selection.second.x - selection.first.x) >= minSize &&
-                Math.abs(selection.second.y - selection.first.y) >= minSize;
-        }
-
-        plot.clearSelection = clearSelection;
-        plot.setSelection = setSelection;
-        plot.getSelection = getSelection;
-
-        plot.hooks.bindEvents.push(function(plot, eventHolder) {
-            var o = plot.getOptions();
-            if (o.selection.mode != null) {
-                eventHolder.mousemove(onMouseMove);
-                eventHolder.mousedown(onMouseDown);
-            }
-        });
-
-
-        plot.hooks.drawOverlay.push(function (plot, ctx) {
-            // draw selection
-            if (selection.show && selectionIsSane()) {
-                var plotOffset = plot.getPlotOffset();
-                var o = plot.getOptions();
-
-                ctx.save();
-                ctx.translate(plotOffset.left, plotOffset.top);
-
-                var c = $.color.parse(o.selection.color);
-
-                ctx.strokeStyle = c.scale('a', 0.8).toString();
-                ctx.lineWidth = 1;
-                ctx.lineJoin = o.selection.shape;
-                ctx.fillStyle = c.scale('a', 0.4).toString();
-
-                var x = Math.min(selection.first.x, selection.second.x) + 0.5,
-                    y = Math.min(selection.first.y, selection.second.y) + 0.5,
-                    w = Math.abs(selection.second.x - selection.first.x) - 1,
-                    h = Math.abs(selection.second.y - selection.first.y) - 1;
-
-                ctx.fillRect(x, y, w, h);
-                ctx.strokeRect(x, y, w, h);
-
-                ctx.restore();
-            }
-        });
-        
-        plot.hooks.shutdown.push(function (plot, eventHolder) {
-            eventHolder.unbind("mousemove", onMouseMove);
-            eventHolder.unbind("mousedown", onMouseDown);
-            
-            if (mouseUpHandler)
-                $(document).unbind("mouseup", mouseUpHandler);
-        });
-
-    }
-
-    $.plot.plugins.push({
-        init: init,
-        options: {
-            selection: {
-                mode: null, // one of null, "x", "y" or "xy"
-                color: "#e8cfac",
-                shape: "round", // one of "round", "miter", or "bevel"
-                minSize: 5 // minimum number of pixels
-            }
-        },
-        name: 'selection',
-        version: '1.1'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.selection.min.js b/static/js/jquery.flot.selection.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.selection.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){function init(plot){var selection={first:{x:-1,y:-1},second:{x:-1,y:-1},show:false,active:false};var savedhandlers={};var mouseUpHandler=null;function onMouseMove(e){if(selection.active){updateSelection(e);plot.getPlaceholder().trigger("plotselecting",[getSelection()])}}function onMouseDown(e){if(e.which!=1)return;document.body.focus();if(document.onselectstart!==undefined&&savedhandlers.onselectstart==null){savedhandlers.onselectstart=document.onselectstart;document.onselectstart=function(){return false}}if(document.ondrag!==undefined&&savedhandlers.ondrag==null){savedhandlers.ondrag=document.ondrag;document.ondrag=function(){return false}}setSelectionPos(selection.first,e);selection.active=true;mouseUpHandler=function(e){onMouseUp(e)};$(document).one("mouseup",mouseUpHandler)}function onMouseUp(e){mouseUpHandler=null;if(document.onselectstart!==undefined)document.onselectstart=savedhandlers.onselectstart;if(document.ondrag!==undefined)document.ondrag=savedhandlers.ondrag;selection.active=false;updateSelection(e);if(selectionIsSane())triggerSelectedEvent();else{plot.getPlaceholder().trigger("plotunselected",[]);plot.getPlaceholder().trigger("plotselecting",[null])}return false}function getSelection(){if(!selectionIsSane())return null;if(!selection.show)return null;var r={},c1=selection.first,c2=selection.second;$.each(plot.getAxes(),function(name,axis){if(axis.used){var p1=axis.c2p(c1[axis.direction]),p2=axis.c2p(c2[axis.direction]);r[name]={from:Math.min(p1,p2),to:Math.max(p1,p2)}}});return r}function triggerSelectedEvent(){var r=getSelection();plot.getPlaceholder().trigger("plotselected",[r]);if(r.xaxis&&r.yaxis)plot.getPlaceholder().trigger("selected",[{x1:r.xaxis.from,y1:r.yaxis.from,x2:r.xaxis.to,y2:r.yaxis.to}])}function clamp(min,value,max){return value<min?min:value>max?max:value}function setSelectionPos(pos,e){var o=plot.getOptions();var offset=plot.getPlaceholder().offset();var plotOffset=plot.getPlotOffset();pos.x=clamp(0,e.pageX-offset.left-plotOffset.left,plot.width());pos.y=clamp(0,e.pageY-offset.top-plotOffset.top,plot.height());if(o.selection.mode=="y")pos.x=pos==selection.first?0:plot.width();if(o.selection.mode=="x")pos.y=pos==selection.first?0:plot.height()}function updateSelection(pos){if(pos.pageX==null)return;setSelectionPos(selection.second,pos);if(selectionIsSane()){selection.show=true;plot.triggerRedrawOverlay()}else clearSelection(true)}function clearSelection(preventEvent){if(selection.show){selection.show=false;plot.triggerRedrawOverlay();if(!preventEvent)plot.getPlaceholder().trigger("plotunselected",[])}}function extractRange(ranges,coord){var axis,from,to,key,axes=plot.getAxes();for(var k in axes){axis=axes[k];if(axis.direction==coord){key=coord+axis.n+"axis";if(!ranges[key]&&axis.n==1)key=coord+"axis";if(ranges[key]){from=ranges[key].from;to=ranges[key].to;break}}}if(!ranges[key]){axis=coord=="x"?plot.getXAxes()[0]:plot.getYAxes()[0];from=ranges[coord+"1"];to=ranges[coord+"2"]}if(from!=null&&to!=null&&from>to){var tmp=from;from=to;to=tmp}return{from:from,to:to,axis:axis}}function setSelection(ranges,preventEvent){var axis,range,o=plot.getOptions();if(o.selection.mode=="y"){selection.first.x=0;selection.second.x=plot.width()}else{range=extractRange(ranges,"x");selection.first.x=range.axis.p2c(range.from);selection.second.x=range.axis.p2c(range.to)}if(o.selection.mode=="x"){selection.first.y=0;selection.second.y=plot.height()}else{range=extractRange(ranges,"y");selection.first.y=range.axis.p2c(range.from);selection.second.y=range.axis.p2c(range.to)}selection.show=true;plot.triggerRedrawOverlay();if(!preventEvent&&selectionIsSane())triggerSelectedEvent()}function selectionIsSane(){var minSize=plot.getOptions().selection.minSize;return Math.abs(selection.second.x-selection.first.x)>=minSize&&Math.abs(selection.second.y-selection.first.y)>=minSize}plot.clearSelection=clearSelection;plot.setSelection=setSelection;plot.getSelection=getSelection;plot.hooks.bindEvents.push(function(plot,eventHolder){var o=plot.getOptions();if(o.selection.mode!=null){eventHolder.mousemove(onMouseMove);eventHolder.mousedown(onMouseDown)}});plot.hooks.drawOverlay.push(function(plot,ctx){if(selection.show&&selectionIsSane()){var plotOffset=plot.getPlotOffset();var o=plot.getOptions();ctx.save();ctx.translate(plotOffset.left,plotOffset.top);var c=$.color.parse(o.selection.color);ctx.strokeStyle=c.scale("a",.8).toString();ctx.lineWidth=1;ctx.lineJoin=o.selection.shape;ctx.fillStyle=c.scale("a",.4).toString();var x=Math.min(selection.first.x,selection.second.x)+.5,y=Math.min(selection.first.y,selection.second.y)+.5,w=Math.abs(selection.second.x-selection.first.x)-1,h=Math.abs(selection.second.y-selection.first.y)-1;ctx.fillRect(x,y,w,h);ctx.strokeRect(x,y,w,h);ctx.restore()}});plot.hooks.shutdown.push(function(plot,eventHolder){eventHolder.unbind("mousemove",onMouseMove);eventHolder.unbind("mousedown",onMouseDown);if(mouseUpHandler)$(document).unbind("mouseup",mouseUpHandler)})}$.plot.plugins.push({init:init,options:{selection:{mode:null,color:"#e8cfac",shape:"round",minSize:5}},name:"selection",version:"1.1"})})(jQuery);
diff --git a/static/js/jquery.flot.stack.js b/static/js/jquery.flot.stack.js
deleted file mode 100644
--- a/static/js/jquery.flot.stack.js
+++ /dev/null
@@ -1,188 +0,0 @@
-/* Flot plugin for stacking data sets rather than overlyaing them.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The plugin assumes the data is sorted on x (or y if stacking horizontally).
-For line charts, it is assumed that if a line has an undefined gap (from a
-null point), then the line above it should have the same gap - insert zeros
-instead of "null" if you want another behaviour. This also holds for the start
-and end of the chart. Note that stacking a mix of positive and negative values
-in most instances doesn't make sense (so it looks weird).
-
-Two or more series are stacked when their "stack" attribute is set to the same
-key (which can be any number or string or just "true"). To specify the default
-stack, you can set the stack option like this:
-
-	series: {
-		stack: null/false, true, or a key (number/string)
-	}
-
-You can also specify it for a single series, like this:
-
-	$.plot( $("#placeholder"), [{
-		data: [ ... ],
-		stack: true
-	}])
-
-The stacking order is determined by the order of the data series in the array
-(later series end up on top of the previous).
-
-Internally, the plugin modifies the datapoints in each series, adding an
-offset to the y value. For line series, extra data points are inserted through
-interpolation. If there's a second y value, it's also adjusted (e.g for bar
-charts or filled areas).
-
-*/
-
-(function ($) {
-    var options = {
-        series: { stack: null } // or number/string
-    };
-    
-    function init(plot) {
-        function findMatchingSeries(s, allseries) {
-            var res = null;
-            for (var i = 0; i < allseries.length; ++i) {
-                if (s == allseries[i])
-                    break;
-                
-                if (allseries[i].stack == s.stack)
-                    res = allseries[i];
-            }
-            
-            return res;
-        }
-        
-        function stackData(plot, s, datapoints) {
-            if (s.stack == null || s.stack === false)
-                return;
-
-            var other = findMatchingSeries(s, plot.getData());
-            if (!other)
-                return;
-
-            var ps = datapoints.pointsize,
-                points = datapoints.points,
-                otherps = other.datapoints.pointsize,
-                otherpoints = other.datapoints.points,
-                newpoints = [],
-                px, py, intery, qx, qy, bottom,
-                withlines = s.lines.show,
-                horizontal = s.bars.horizontal,
-                withbottom = ps > 2 && (horizontal ? datapoints.format[2].x : datapoints.format[2].y),
-                withsteps = withlines && s.lines.steps,
-                fromgap = true,
-                keyOffset = horizontal ? 1 : 0,
-                accumulateOffset = horizontal ? 0 : 1,
-                i = 0, j = 0, l, m;
-
-            while (true) {
-                if (i >= points.length)
-                    break;
-
-                l = newpoints.length;
-
-                if (points[i] == null) {
-                    // copy gaps
-                    for (m = 0; m < ps; ++m)
-                        newpoints.push(points[i + m]);
-                    i += ps;
-                }
-                else if (j >= otherpoints.length) {
-                    // for lines, we can't use the rest of the points
-                    if (!withlines) {
-                        for (m = 0; m < ps; ++m)
-                            newpoints.push(points[i + m]);
-                    }
-                    i += ps;
-                }
-                else if (otherpoints[j] == null) {
-                    // oops, got a gap
-                    for (m = 0; m < ps; ++m)
-                        newpoints.push(null);
-                    fromgap = true;
-                    j += otherps;
-                }
-                else {
-                    // cases where we actually got two points
-                    px = points[i + keyOffset];
-                    py = points[i + accumulateOffset];
-                    qx = otherpoints[j + keyOffset];
-                    qy = otherpoints[j + accumulateOffset];
-                    bottom = 0;
-
-                    if (px == qx) {
-                        for (m = 0; m < ps; ++m)
-                            newpoints.push(points[i + m]);
-
-                        newpoints[l + accumulateOffset] += qy;
-                        bottom = qy;
-                        
-                        i += ps;
-                        j += otherps;
-                    }
-                    else if (px > qx) {
-                        // we got past point below, might need to
-                        // insert interpolated extra point
-                        if (withlines && i > 0 && points[i - ps] != null) {
-                            intery = py + (points[i - ps + accumulateOffset] - py) * (qx - px) / (points[i - ps + keyOffset] - px);
-                            newpoints.push(qx);
-                            newpoints.push(intery + qy);
-                            for (m = 2; m < ps; ++m)
-                                newpoints.push(points[i + m]);
-                            bottom = qy; 
-                        }
-
-                        j += otherps;
-                    }
-                    else { // px < qx
-                        if (fromgap && withlines) {
-                            // if we come from a gap, we just skip this point
-                            i += ps;
-                            continue;
-                        }
-                            
-                        for (m = 0; m < ps; ++m)
-                            newpoints.push(points[i + m]);
-                        
-                        // we might be able to interpolate a point below,
-                        // this can give us a better y
-                        if (withlines && j > 0 && otherpoints[j - otherps] != null)
-                            bottom = qy + (otherpoints[j - otherps + accumulateOffset] - qy) * (px - qx) / (otherpoints[j - otherps + keyOffset] - qx);
-
-                        newpoints[l + accumulateOffset] += bottom;
-                        
-                        i += ps;
-                    }
-
-                    fromgap = false;
-                    
-                    if (l != newpoints.length && withbottom)
-                        newpoints[l + 2] += bottom;
-                }
-
-                // maintain the line steps invariant
-                if (withsteps && l != newpoints.length && l > 0
-                    && newpoints[l] != null
-                    && newpoints[l] != newpoints[l - ps]
-                    && newpoints[l + 1] != newpoints[l - ps + 1]) {
-                    for (m = 0; m < ps; ++m)
-                        newpoints[l + ps + m] = newpoints[l + m];
-                    newpoints[l + 1] = newpoints[l - ps + 1];
-                }
-            }
-
-            datapoints.points = newpoints;
-        }
-        
-        plot.hooks.processDatapoints.push(stackData);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'stack',
-        version: '1.2'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.stack.min.js b/static/js/jquery.flot.stack.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.stack.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={series:{stack:null}};function init(plot){function findMatchingSeries(s,allseries){var res=null;for(var i=0;i<allseries.length;++i){if(s==allseries[i])break;if(allseries[i].stack==s.stack)res=allseries[i]}return res}function stackData(plot,s,datapoints){if(s.stack==null||s.stack===false)return;var other=findMatchingSeries(s,plot.getData());if(!other)return;var ps=datapoints.pointsize,points=datapoints.points,otherps=other.datapoints.pointsize,otherpoints=other.datapoints.points,newpoints=[],px,py,intery,qx,qy,bottom,withlines=s.lines.show,horizontal=s.bars.horizontal,withbottom=ps>2&&(horizontal?datapoints.format[2].x:datapoints.format[2].y),withsteps=withlines&&s.lines.steps,fromgap=true,keyOffset=horizontal?1:0,accumulateOffset=horizontal?0:1,i=0,j=0,l,m;while(true){if(i>=points.length)break;l=newpoints.length;if(points[i]==null){for(m=0;m<ps;++m)newpoints.push(points[i+m]);i+=ps}else if(j>=otherpoints.length){if(!withlines){for(m=0;m<ps;++m)newpoints.push(points[i+m])}i+=ps}else if(otherpoints[j]==null){for(m=0;m<ps;++m)newpoints.push(null);fromgap=true;j+=otherps}else{px=points[i+keyOffset];py=points[i+accumulateOffset];qx=otherpoints[j+keyOffset];qy=otherpoints[j+accumulateOffset];bottom=0;if(px==qx){for(m=0;m<ps;++m)newpoints.push(points[i+m]);newpoints[l+accumulateOffset]+=qy;bottom=qy;i+=ps;j+=otherps}else if(px>qx){if(withlines&&i>0&&points[i-ps]!=null){intery=py+(points[i-ps+accumulateOffset]-py)*(qx-px)/(points[i-ps+keyOffset]-px);newpoints.push(qx);newpoints.push(intery+qy);for(m=2;m<ps;++m)newpoints.push(points[i+m]);bottom=qy}j+=otherps}else{if(fromgap&&withlines){i+=ps;continue}for(m=0;m<ps;++m)newpoints.push(points[i+m]);if(withlines&&j>0&&otherpoints[j-otherps]!=null)bottom=qy+(otherpoints[j-otherps+accumulateOffset]-qy)*(px-qx)/(otherpoints[j-otherps+keyOffset]-qx);newpoints[l+accumulateOffset]+=bottom;i+=ps}fromgap=false;if(l!=newpoints.length&&withbottom)newpoints[l+2]+=bottom}if(withsteps&&l!=newpoints.length&&l>0&&newpoints[l]!=null&&newpoints[l]!=newpoints[l-ps]&&newpoints[l+1]!=newpoints[l-ps+1]){for(m=0;m<ps;++m)newpoints[l+ps+m]=newpoints[l+m];newpoints[l+1]=newpoints[l-ps+1]}}datapoints.points=newpoints}plot.hooks.processDatapoints.push(stackData)}$.plot.plugins.push({init:init,options:options,name:"stack",version:"1.2"})})(jQuery);
diff --git a/static/js/jquery.flot.symbol.js b/static/js/jquery.flot.symbol.js
deleted file mode 100644
--- a/static/js/jquery.flot.symbol.js
+++ /dev/null
@@ -1,71 +0,0 @@
-/* Flot plugin that adds some extra symbols for plotting points.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The symbols are accessed as strings through the standard symbol options:
-
-	series: {
-		points: {
-			symbol: "square" // or "diamond", "triangle", "cross"
-		}
-	}
-
-*/
-
-(function ($) {
-    function processRawData(plot, series, datapoints) {
-        // we normalize the area of each symbol so it is approximately the
-        // same as a circle of the given radius
-
-        var handlers = {
-            square: function (ctx, x, y, radius, shadow) {
-                // pi * r^2 = (2s)^2  =>  s = r * sqrt(pi)/2
-                var size = radius * Math.sqrt(Math.PI) / 2;
-                ctx.rect(x - size, y - size, size + size, size + size);
-            },
-            diamond: function (ctx, x, y, radius, shadow) {
-                // pi * r^2 = 2s^2  =>  s = r * sqrt(pi/2)
-                var size = radius * Math.sqrt(Math.PI / 2);
-                ctx.moveTo(x - size, y);
-                ctx.lineTo(x, y - size);
-                ctx.lineTo(x + size, y);
-                ctx.lineTo(x, y + size);
-                ctx.lineTo(x - size, y);
-            },
-            triangle: function (ctx, x, y, radius, shadow) {
-                // pi * r^2 = 1/2 * s^2 * sin (pi / 3)  =>  s = r * sqrt(2 * pi / sin(pi / 3))
-                var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3));
-                var height = size * Math.sin(Math.PI / 3);
-                ctx.moveTo(x - size/2, y + height/2);
-                ctx.lineTo(x + size/2, y + height/2);
-                if (!shadow) {
-                    ctx.lineTo(x, y - height/2);
-                    ctx.lineTo(x - size/2, y + height/2);
-                }
-            },
-            cross: function (ctx, x, y, radius, shadow) {
-                // pi * r^2 = (2s)^2  =>  s = r * sqrt(pi)/2
-                var size = radius * Math.sqrt(Math.PI) / 2;
-                ctx.moveTo(x - size, y - size);
-                ctx.lineTo(x + size, y + size);
-                ctx.moveTo(x - size, y + size);
-                ctx.lineTo(x + size, y - size);
-            }
-        };
-
-        var s = series.points.symbol;
-        if (handlers[s])
-            series.points.symbol = handlers[s];
-    }
-    
-    function init(plot) {
-        plot.hooks.processDatapoints.push(processRawData);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        name: 'symbols',
-        version: '1.0'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.symbol.min.js b/static/js/jquery.flot.symbol.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.symbol.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){function processRawData(plot,series,datapoints){var handlers={square:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(Math.PI)/2;ctx.rect(x-size,y-size,size+size,size+size)},diamond:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(Math.PI/2);ctx.moveTo(x-size,y);ctx.lineTo(x,y-size);ctx.lineTo(x+size,y);ctx.lineTo(x,y+size);ctx.lineTo(x-size,y)},triangle:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(2*Math.PI/Math.sin(Math.PI/3));var height=size*Math.sin(Math.PI/3);ctx.moveTo(x-size/2,y+height/2);ctx.lineTo(x+size/2,y+height/2);if(!shadow){ctx.lineTo(x,y-height/2);ctx.lineTo(x-size/2,y+height/2)}},cross:function(ctx,x,y,radius,shadow){var size=radius*Math.sqrt(Math.PI)/2;ctx.moveTo(x-size,y-size);ctx.lineTo(x+size,y+size);ctx.moveTo(x-size,y+size);ctx.lineTo(x+size,y-size)}};var s=series.points.symbol;if(handlers[s])series.points.symbol=handlers[s]}function init(plot){plot.hooks.processDatapoints.push(processRawData)}$.plot.plugins.push({init:init,name:"symbols",version:"1.0"})})(jQuery);
diff --git a/static/js/jquery.flot.threshold.js b/static/js/jquery.flot.threshold.js
deleted file mode 100644
--- a/static/js/jquery.flot.threshold.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/* Flot plugin for thresholding data.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-The plugin supports these options:
-
-	series: {
-		threshold: {
-			below: number
-			color: colorspec
-		}
-	}
-
-It can also be applied to a single series, like this:
-
-	$.plot( $("#placeholder"), [{
-		data: [ ... ],
-		threshold: { ... }
-	}])
-
-An array can be passed for multiple thresholding, like this:
-
-	threshold: [{
-		below: number1
-		color: color1
-	},{
-		below: number2
-		color: color2
-	}]
-
-These multiple threshold objects can be passed in any order since they are
-sorted by the processing function.
-
-The data points below "below" are drawn with the specified color. This makes
-it easy to mark points below 0, e.g. for budget data.
-
-Internally, the plugin works by splitting the data into two series, above and
-below the threshold. The extra series below the threshold will have its label
-cleared and the special "originSeries" attribute set to the original series.
-You may need to check for this in hover events.
-
-*/
-
-(function ($) {
-    var options = {
-        series: { threshold: null } // or { below: number, color: color spec}
-    };
-    
-    function init(plot) {
-        function thresholdData(plot, s, datapoints, below, color) {
-            var ps = datapoints.pointsize, i, x, y, p, prevp,
-                thresholded = $.extend({}, s); // note: shallow copy
-
-            thresholded.datapoints = { points: [], pointsize: ps, format: datapoints.format };
-            thresholded.label = null;
-            thresholded.color = color;
-            thresholded.threshold = null;
-            thresholded.originSeries = s;
-            thresholded.data = [];
- 
-            var origpoints = datapoints.points,
-                addCrossingPoints = s.lines.show;
-
-            var threspoints = [];
-            var newpoints = [];
-            var m;
-
-            for (i = 0; i < origpoints.length; i += ps) {
-                x = origpoints[i];
-                y = origpoints[i + 1];
-
-                prevp = p;
-                if (y < below)
-                    p = threspoints;
-                else
-                    p = newpoints;
-
-                if (addCrossingPoints && prevp != p && x != null
-                    && i > 0 && origpoints[i - ps] != null) {
-                    var interx = x + (below - y) * (x - origpoints[i - ps]) / (y - origpoints[i - ps + 1]);
-                    prevp.push(interx);
-                    prevp.push(below);
-                    for (m = 2; m < ps; ++m)
-                        prevp.push(origpoints[i + m]);
-                    
-                    p.push(null); // start new segment
-                    p.push(null);
-                    for (m = 2; m < ps; ++m)
-                        p.push(origpoints[i + m]);
-                    p.push(interx);
-                    p.push(below);
-                    for (m = 2; m < ps; ++m)
-                        p.push(origpoints[i + m]);
-                }
-
-                p.push(x);
-                p.push(y);
-                for (m = 2; m < ps; ++m)
-                    p.push(origpoints[i + m]);
-            }
-
-            datapoints.points = newpoints;
-            thresholded.datapoints.points = threspoints;
-            
-            if (thresholded.datapoints.points.length > 0) {
-                var origIndex = $.inArray(s, plot.getData());
-                // Insert newly-generated series right after original one (to prevent it from becoming top-most)
-                plot.getData().splice(origIndex + 1, 0, thresholded);
-            }
-                
-            // FIXME: there are probably some edge cases left in bars
-        }
-        
-        function processThresholds(plot, s, datapoints) {
-            if (!s.threshold)
-                return;
-            
-            if (s.threshold instanceof Array) {
-                s.threshold.sort(function(a, b) {
-                    return a.below - b.below;
-                });
-                
-                $(s.threshold).each(function(i, th) {
-                    thresholdData(plot, s, datapoints, th.below, th.color);
-                });
-            }
-            else {
-                thresholdData(plot, s, datapoints, s.threshold.below, s.threshold.color);
-            }
-        }
-        
-        plot.hooks.processDatapoints.push(processThresholds);
-    }
-    
-    $.plot.plugins.push({
-        init: init,
-        options: options,
-        name: 'threshold',
-        version: '1.2'
-    });
-})(jQuery);
diff --git a/static/js/jquery.flot.threshold.min.js b/static/js/jquery.flot.threshold.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.threshold.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={series:{threshold:null}};function init(plot){function thresholdData(plot,s,datapoints,below,color){var ps=datapoints.pointsize,i,x,y,p,prevp,thresholded=$.extend({},s);thresholded.datapoints={points:[],pointsize:ps,format:datapoints.format};thresholded.label=null;thresholded.color=color;thresholded.threshold=null;thresholded.originSeries=s;thresholded.data=[];var origpoints=datapoints.points,addCrossingPoints=s.lines.show;var threspoints=[];var newpoints=[];var m;for(i=0;i<origpoints.length;i+=ps){x=origpoints[i];y=origpoints[i+1];prevp=p;if(y<below)p=threspoints;else p=newpoints;if(addCrossingPoints&&prevp!=p&&x!=null&&i>0&&origpoints[i-ps]!=null){var interx=x+(below-y)*(x-origpoints[i-ps])/(y-origpoints[i-ps+1]);prevp.push(interx);prevp.push(below);for(m=2;m<ps;++m)prevp.push(origpoints[i+m]);p.push(null);p.push(null);for(m=2;m<ps;++m)p.push(origpoints[i+m]);p.push(interx);p.push(below);for(m=2;m<ps;++m)p.push(origpoints[i+m])}p.push(x);p.push(y);for(m=2;m<ps;++m)p.push(origpoints[i+m])}datapoints.points=newpoints;thresholded.datapoints.points=threspoints;if(thresholded.datapoints.points.length>0){var origIndex=$.inArray(s,plot.getData());plot.getData().splice(origIndex+1,0,thresholded)}}function processThresholds(plot,s,datapoints){if(!s.threshold)return;if(s.threshold instanceof Array){s.threshold.sort(function(a,b){return a.below-b.below});$(s.threshold).each(function(i,th){thresholdData(plot,s,datapoints,th.below,th.color)})}else{thresholdData(plot,s,datapoints,s.threshold.below,s.threshold.color)}}plot.hooks.processDatapoints.push(processThresholds)}$.plot.plugins.push({init:init,options:options,name:"threshold",version:"1.2"})})(jQuery);
diff --git a/static/js/jquery.flot.time.js b/static/js/jquery.flot.time.js
deleted file mode 100644
--- a/static/js/jquery.flot.time.js
+++ /dev/null
@@ -1,432 +0,0 @@
-/* Pretty handling of time axes.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-Set axis.mode to "time" to enable. See the section "Time series data" in
-API.txt for details.
-
-*/
-
-(function($) {
-
-	var options = {
-		xaxis: {
-			timezone: null,		// "browser" for local to the client or timezone for timezone-js
-			timeformat: null,	// format string to use
-			twelveHourClock: false,	// 12 or 24 time in time mode
-			monthNames: null	// list of names of months
-		}
-	};
-
-	// round to nearby lower multiple of base
-
-	function floorInBase(n, base) {
-		return base * Math.floor(n / base);
-	}
-
-	// Returns a string with the date d formatted according to fmt.
-	// A subset of the Open Group's strftime format is supported.
-
-	function formatDate(d, fmt, monthNames, dayNames) {
-
-		if (typeof d.strftime == "function") {
-			return d.strftime(fmt);
-		}
-
-		var leftPad = function(n, pad) {
-			n = "" + n;
-			pad = "" + (pad == null ? "0" : pad);
-			return n.length == 1 ? pad + n : n;
-		};
-
-		var r = [];
-		var escape = false;
-		var hours = d.getHours();
-		var isAM = hours < 12;
-
-		if (monthNames == null) {
-			monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
-		}
-
-		if (dayNames == null) {
-			dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
-		}
-
-		var hours12;
-
-		if (hours > 12) {
-			hours12 = hours - 12;
-		} else if (hours == 0) {
-			hours12 = 12;
-		} else {
-			hours12 = hours;
-		}
-
-		for (var i = 0; i < fmt.length; ++i) {
-
-			var c = fmt.charAt(i);
-
-			if (escape) {
-				switch (c) {
-					case 'a': c = "" + dayNames[d.getDay()]; break;
-					case 'b': c = "" + monthNames[d.getMonth()]; break;
-					case 'd': c = leftPad(d.getDate()); break;
-					case 'e': c = leftPad(d.getDate(), " "); break;
-					case 'h':	// For back-compat with 0.7; remove in 1.0
-					case 'H': c = leftPad(hours); break;
-					case 'I': c = leftPad(hours12); break;
-					case 'l': c = leftPad(hours12, " "); break;
-					case 'm': c = leftPad(d.getMonth() + 1); break;
-					case 'M': c = leftPad(d.getMinutes()); break;
-					// quarters not in Open Group's strftime specification
-					case 'q':
-						c = "" + (Math.floor(d.getMonth() / 3) + 1); break;
-					case 'S': c = leftPad(d.getSeconds()); break;
-					case 'y': c = leftPad(d.getFullYear() % 100); break;
-					case 'Y': c = "" + d.getFullYear(); break;
-					case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break;
-					case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break;
-					case 'w': c = "" + d.getDay(); break;
-				}
-				r.push(c);
-				escape = false;
-			} else {
-				if (c == "%") {
-					escape = true;
-				} else {
-					r.push(c);
-				}
-			}
-		}
-
-		return r.join("");
-	}
-
-	// To have a consistent view of time-based data independent of which time
-	// zone the client happens to be in we need a date-like object independent
-	// of time zones.  This is done through a wrapper that only calls the UTC
-	// versions of the accessor methods.
-
-	function makeUtcWrapper(d) {
-
-		function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) {
-			sourceObj[sourceMethod] = function() {
-				return targetObj[targetMethod].apply(targetObj, arguments);
-			};
-		};
-
-		var utc = {
-			date: d
-		};
-
-		// support strftime, if found
-
-		if (d.strftime != undefined) {
-			addProxyMethod(utc, "strftime", d, "strftime");
-		}
-
-		addProxyMethod(utc, "getTime", d, "getTime");
-		addProxyMethod(utc, "setTime", d, "setTime");
-
-		var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"];
-
-		for (var p = 0; p < props.length; p++) {
-			addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]);
-			addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]);
-		}
-
-		return utc;
-	};
-
-	// select time zone strategy.  This returns a date-like object tied to the
-	// desired timezone
-
-	function dateGenerator(ts, opts) {
-		if (opts.timezone == "browser") {
-			return new Date(ts);
-		} else if (!opts.timezone || opts.timezone == "utc") {
-			return makeUtcWrapper(new Date(ts));
-		} else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") {
-			var d = new timezoneJS.Date();
-			// timezone-js is fickle, so be sure to set the time zone before
-			// setting the time.
-			d.setTimezone(opts.timezone);
-			d.setTime(ts);
-			return d;
-		} else {
-			return makeUtcWrapper(new Date(ts));
-		}
-	}
-	
-	// map of app. size of time units in milliseconds
-
-	var timeUnitSize = {
-		"second": 1000,
-		"minute": 60 * 1000,
-		"hour": 60 * 60 * 1000,
-		"day": 24 * 60 * 60 * 1000,
-		"month": 30 * 24 * 60 * 60 * 1000,
-		"quarter": 3 * 30 * 24 * 60 * 60 * 1000,
-		"year": 365.2425 * 24 * 60 * 60 * 1000
-	};
-
-	// the allowed tick sizes, after 1 year we use
-	// an integer algorithm
-
-	var baseSpec = [
-		[1, "second"], [2, "second"], [5, "second"], [10, "second"],
-		[30, "second"], 
-		[1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"],
-		[30, "minute"], 
-		[1, "hour"], [2, "hour"], [4, "hour"],
-		[8, "hour"], [12, "hour"],
-		[1, "day"], [2, "day"], [3, "day"],
-		[0.25, "month"], [0.5, "month"], [1, "month"],
-		[2, "month"]
-	];
-
-	// we don't know which variant(s) we'll need yet, but generating both is
-	// cheap
-
-	var specMonths = baseSpec.concat([[3, "month"], [6, "month"],
-		[1, "year"]]);
-	var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"],
-		[1, "year"]]);
-
-	function init(plot) {
-		plot.hooks.processOptions.push(function (plot, options) {
-			$.each(plot.getAxes(), function(axisName, axis) {
-
-				var opts = axis.options;
-
-				if (opts.mode == "time") {
-					axis.tickGenerator = function(axis) {
-
-						var ticks = [];
-						var d = dateGenerator(axis.min, opts);
-						var minSize = 0;
-
-						// make quarter use a possibility if quarters are
-						// mentioned in either of these options
-
-						var spec = (opts.tickSize && opts.tickSize[1] ===
-							"quarter") ||
-							(opts.minTickSize && opts.minTickSize[1] ===
-							"quarter") ? specQuarters : specMonths;
-
-						if (opts.minTickSize != null) {
-							if (typeof opts.tickSize == "number") {
-								minSize = opts.tickSize;
-							} else {
-								minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]];
-							}
-						}
-
-						for (var i = 0; i < spec.length - 1; ++i) {
-							if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]]
-											  + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2
-								&& spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) {
-								break;
-							}
-						}
-
-						var size = spec[i][0];
-						var unit = spec[i][1];
-
-						// special-case the possibility of several years
-
-						if (unit == "year") {
-
-							// if given a minTickSize in years, just use it,
-							// ensuring that it's an integer
-
-							if (opts.minTickSize != null && opts.minTickSize[1] == "year") {
-								size = Math.floor(opts.minTickSize[0]);
-							} else {
-
-								var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10));
-								var norm = (axis.delta / timeUnitSize.year) / magn;
-
-								if (norm < 1.5) {
-									size = 1;
-								} else if (norm < 3) {
-									size = 2;
-								} else if (norm < 7.5) {
-									size = 5;
-								} else {
-									size = 10;
-								}
-
-								size *= magn;
-							}
-
-							// minimum size for years is 1
-
-							if (size < 1) {
-								size = 1;
-							}
-						}
-
-						axis.tickSize = opts.tickSize || [size, unit];
-						var tickSize = axis.tickSize[0];
-						unit = axis.tickSize[1];
-
-						var step = tickSize * timeUnitSize[unit];
-
-						if (unit == "second") {
-							d.setSeconds(floorInBase(d.getSeconds(), tickSize));
-						} else if (unit == "minute") {
-							d.setMinutes(floorInBase(d.getMinutes(), tickSize));
-						} else if (unit == "hour") {
-							d.setHours(floorInBase(d.getHours(), tickSize));
-						} else if (unit == "month") {
-							d.setMonth(floorInBase(d.getMonth(), tickSize));
-						} else if (unit == "quarter") {
-							d.setMonth(3 * floorInBase(d.getMonth() / 3,
-								tickSize));
-						} else if (unit == "year") {
-							d.setFullYear(floorInBase(d.getFullYear(), tickSize));
-						}
-
-						// reset smaller components
-
-						d.setMilliseconds(0);
-
-						if (step >= timeUnitSize.minute) {
-							d.setSeconds(0);
-						}
-						if (step >= timeUnitSize.hour) {
-							d.setMinutes(0);
-						}
-						if (step >= timeUnitSize.day) {
-							d.setHours(0);
-						}
-						if (step >= timeUnitSize.day * 4) {
-							d.setDate(1);
-						}
-						if (step >= timeUnitSize.month * 2) {
-							d.setMonth(floorInBase(d.getMonth(), 3));
-						}
-						if (step >= timeUnitSize.quarter * 2) {
-							d.setMonth(floorInBase(d.getMonth(), 6));
-						}
-						if (step >= timeUnitSize.year) {
-							d.setMonth(0);
-						}
-
-						var carry = 0;
-						var v = Number.NaN;
-						var prev;
-
-						do {
-
-							prev = v;
-							v = d.getTime();
-							ticks.push(v);
-
-							if (unit == "month" || unit == "quarter") {
-								if (tickSize < 1) {
-
-									// a bit complicated - we'll divide the
-									// month/quarter up but we need to take
-									// care of fractions so we don't end up in
-									// the middle of a day
-
-									d.setDate(1);
-									var start = d.getTime();
-									d.setMonth(d.getMonth() +
-										(unit == "quarter" ? 3 : 1));
-									var end = d.getTime();
-									d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize);
-									carry = d.getHours();
-									d.setHours(0);
-								} else {
-									d.setMonth(d.getMonth() +
-										tickSize * (unit == "quarter" ? 3 : 1));
-								}
-							} else if (unit == "year") {
-								d.setFullYear(d.getFullYear() + tickSize);
-							} else {
-								d.setTime(v + step);
-							}
-						} while (v < axis.max && v != prev);
-
-						return ticks;
-					};
-
-					axis.tickFormatter = function (v, axis) {
-
-						var d = dateGenerator(v, axis.options);
-
-						// first check global format
-
-						if (opts.timeformat != null) {
-							return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames);
-						}
-
-						// possibly use quarters if quarters are mentioned in
-						// any of these places
-
-						var useQuarters = (axis.options.tickSize &&
-								axis.options.tickSize[1] == "quarter") ||
-							(axis.options.minTickSize &&
-								axis.options.minTickSize[1] == "quarter");
-
-						var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]];
-						var span = axis.max - axis.min;
-						var suffix = (opts.twelveHourClock) ? " %p" : "";
-						var hourCode = (opts.twelveHourClock) ? "%I" : "%H";
-						var fmt;
-
-						if (t < timeUnitSize.minute) {
-							fmt = hourCode + ":%M:%S" + suffix;
-						} else if (t < timeUnitSize.day) {
-							if (span < 2 * timeUnitSize.day) {
-								fmt = hourCode + ":%M" + suffix;
-							} else {
-								fmt = "%b %d " + hourCode + ":%M" + suffix;
-							}
-						} else if (t < timeUnitSize.month) {
-							fmt = "%b %d";
-						} else if ((useQuarters && t < timeUnitSize.quarter) ||
-							(!useQuarters && t < timeUnitSize.year)) {
-							if (span < timeUnitSize.year) {
-								fmt = "%b";
-							} else {
-								fmt = "%b %Y";
-							}
-						} else if (useQuarters && t < timeUnitSize.year) {
-							if (span < timeUnitSize.year) {
-								fmt = "Q%q";
-							} else {
-								fmt = "Q%q %Y";
-							}
-						} else {
-							fmt = "%Y";
-						}
-
-						var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames);
-
-						return rt;
-					};
-				}
-			});
-		});
-	}
-
-	$.plot.plugins.push({
-		init: init,
-		options: options,
-		name: 'time',
-		version: '1.0'
-	});
-
-	// Time-axis support used to be in Flot core, which exposed the
-	// formatDate function on the plot object.  Various plugins depend
-	// on the function, so we need to re-expose it here.
-
-	$.plot.formatDate = formatDate;
-	$.plot.dateGenerator = dateGenerator;
-
-})(jQuery);
diff --git a/static/js/jquery.flot.time.min.js b/static/js/jquery.flot.time.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.time.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/* Javascript plotting library for jQuery, version 0.8.3.
-
-Copyright (c) 2007-2014 IOLA and Ole Laursen.
-Licensed under the MIT license.
-
-*/
-(function($){var options={xaxis:{timezone:null,timeformat:null,twelveHourClock:false,monthNames:null}};function floorInBase(n,base){return base*Math.floor(n/base)}function formatDate(d,fmt,monthNames,dayNames){if(typeof d.strftime=="function"){return d.strftime(fmt)}var leftPad=function(n,pad){n=""+n;pad=""+(pad==null?"0":pad);return n.length==1?pad+n:n};var r=[];var escape=false;var hours=d.getHours();var isAM=hours<12;if(monthNames==null){monthNames=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]}if(dayNames==null){dayNames=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]}var hours12;if(hours>12){hours12=hours-12}else if(hours==0){hours12=12}else{hours12=hours}for(var i=0;i<fmt.length;++i){var c=fmt.charAt(i);if(escape){switch(c){case"a":c=""+dayNames[d.getDay()];break;case"b":c=""+monthNames[d.getMonth()];break;case"d":c=leftPad(d.getDate());break;case"e":c=leftPad(d.getDate()," ");break;case"h":case"H":c=leftPad(hours);break;case"I":c=leftPad(hours12);break;case"l":c=leftPad(hours12," ");break;case"m":c=leftPad(d.getMonth()+1);break;case"M":c=leftPad(d.getMinutes());break;case"q":c=""+(Math.floor(d.getMonth()/3)+1);break;case"S":c=leftPad(d.getSeconds());break;case"y":c=leftPad(d.getFullYear()%100);break;case"Y":c=""+d.getFullYear();break;case"p":c=isAM?""+"am":""+"pm";break;case"P":c=isAM?""+"AM":""+"PM";break;case"w":c=""+d.getDay();break}r.push(c);escape=false}else{if(c=="%"){escape=true}else{r.push(c)}}}return r.join("")}function makeUtcWrapper(d){function addProxyMethod(sourceObj,sourceMethod,targetObj,targetMethod){sourceObj[sourceMethod]=function(){return targetObj[targetMethod].apply(targetObj,arguments)}}var utc={date:d};if(d.strftime!=undefined){addProxyMethod(utc,"strftime",d,"strftime")}addProxyMethod(utc,"getTime",d,"getTime");addProxyMethod(utc,"setTime",d,"setTime");var props=["Date","Day","FullYear","Hours","Milliseconds","Minutes","Month","Seconds"];for(var p=0;p<props.length;p++){addProxyMethod(utc,"get"+props[p],d,"getUTC"+props[p]);addProxyMethod(utc,"set"+props[p],d,"setUTC"+props[p])}return utc}function dateGenerator(ts,opts){if(opts.timezone=="browser"){return new Date(ts)}else if(!opts.timezone||opts.timezone=="utc"){return makeUtcWrapper(new Date(ts))}else if(typeof timezoneJS!="undefined"&&typeof timezoneJS.Date!="undefined"){var d=new timezoneJS.Date;d.setTimezone(opts.timezone);d.setTime(ts);return d}else{return makeUtcWrapper(new Date(ts))}}var timeUnitSize={second:1e3,minute:60*1e3,hour:60*60*1e3,day:24*60*60*1e3,month:30*24*60*60*1e3,quarter:3*30*24*60*60*1e3,year:365.2425*24*60*60*1e3};var baseSpec=[[1,"second"],[2,"second"],[5,"second"],[10,"second"],[30,"second"],[1,"minute"],[2,"minute"],[5,"minute"],[10,"minute"],[30,"minute"],[1,"hour"],[2,"hour"],[4,"hour"],[8,"hour"],[12,"hour"],[1,"day"],[2,"day"],[3,"day"],[.25,"month"],[.5,"month"],[1,"month"],[2,"month"]];var specMonths=baseSpec.concat([[3,"month"],[6,"month"],[1,"year"]]);var specQuarters=baseSpec.concat([[1,"quarter"],[2,"quarter"],[1,"year"]]);function init(plot){plot.hooks.processOptions.push(function(plot,options){$.each(plot.getAxes(),function(axisName,axis){var opts=axis.options;if(opts.mode=="time"){axis.tickGenerator=function(axis){var ticks=[];var d=dateGenerator(axis.min,opts);var minSize=0;var spec=opts.tickSize&&opts.tickSize[1]==="quarter"||opts.minTickSize&&opts.minTickSize[1]==="quarter"?specQuarters:specMonths;if(opts.minTickSize!=null){if(typeof opts.tickSize=="number"){minSize=opts.tickSize}else{minSize=opts.minTickSize[0]*timeUnitSize[opts.minTickSize[1]]}}for(var i=0;i<spec.length-1;++i){if(axis.delta<(spec[i][0]*timeUnitSize[spec[i][1]]+spec[i+1][0]*timeUnitSize[spec[i+1][1]])/2&&spec[i][0]*timeUnitSize[spec[i][1]]>=minSize){break}}var size=spec[i][0];var unit=spec[i][1];if(unit=="year"){if(opts.minTickSize!=null&&opts.minTickSize[1]=="year"){size=Math.floor(opts.minTickSize[0])}else{var magn=Math.pow(10,Math.floor(Math.log(axis.delta/timeUnitSize.year)/Math.LN10));var norm=axis.delta/timeUnitSize.year/magn;if(norm<1.5){size=1}else if(norm<3){size=2}else if(norm<7.5){size=5}else{size=10}size*=magn}if(size<1){size=1}}axis.tickSize=opts.tickSize||[size,unit];var tickSize=axis.tickSize[0];unit=axis.tickSize[1];var step=tickSize*timeUnitSize[unit];if(unit=="second"){d.setSeconds(floorInBase(d.getSeconds(),tickSize))}else if(unit=="minute"){d.setMinutes(floorInBase(d.getMinutes(),tickSize))}else if(unit=="hour"){d.setHours(floorInBase(d.getHours(),tickSize))}else if(unit=="month"){d.setMonth(floorInBase(d.getMonth(),tickSize))}else if(unit=="quarter"){d.setMonth(3*floorInBase(d.getMonth()/3,tickSize))}else if(unit=="year"){d.setFullYear(floorInBase(d.getFullYear(),tickSize))}d.setMilliseconds(0);if(step>=timeUnitSize.minute){d.setSeconds(0)}if(step>=timeUnitSize.hour){d.setMinutes(0)}if(step>=timeUnitSize.day){d.setHours(0)}if(step>=timeUnitSize.day*4){d.setDate(1)}if(step>=timeUnitSize.month*2){d.setMonth(floorInBase(d.getMonth(),3))}if(step>=timeUnitSize.quarter*2){d.setMonth(floorInBase(d.getMonth(),6))}if(step>=timeUnitSize.year){d.setMonth(0)}var carry=0;var v=Number.NaN;var prev;do{prev=v;v=d.getTime();ticks.push(v);if(unit=="month"||unit=="quarter"){if(tickSize<1){d.setDate(1);var start=d.getTime();d.setMonth(d.getMonth()+(unit=="quarter"?3:1));var end=d.getTime();d.setTime(v+carry*timeUnitSize.hour+(end-start)*tickSize);carry=d.getHours();d.setHours(0)}else{d.setMonth(d.getMonth()+tickSize*(unit=="quarter"?3:1))}}else if(unit=="year"){d.setFullYear(d.getFullYear()+tickSize)}else{d.setTime(v+step)}}while(v<axis.max&&v!=prev);return ticks};axis.tickFormatter=function(v,axis){var d=dateGenerator(v,axis.options);if(opts.timeformat!=null){return formatDate(d,opts.timeformat,opts.monthNames,opts.dayNames)}var useQuarters=axis.options.tickSize&&axis.options.tickSize[1]=="quarter"||axis.options.minTickSize&&axis.options.minTickSize[1]=="quarter";var t=axis.tickSize[0]*timeUnitSize[axis.tickSize[1]];var span=axis.max-axis.min;var suffix=opts.twelveHourClock?" %p":"";var hourCode=opts.twelveHourClock?"%I":"%H";var fmt;if(t<timeUnitSize.minute){fmt=hourCode+":%M:%S"+suffix}else if(t<timeUnitSize.day){if(span<2*timeUnitSize.day){fmt=hourCode+":%M"+suffix}else{fmt="%b %d "+hourCode+":%M"+suffix}}else if(t<timeUnitSize.month){fmt="%b %d"}else if(useQuarters&&t<timeUnitSize.quarter||!useQuarters&&t<timeUnitSize.year){if(span<timeUnitSize.year){fmt="%b"}else{fmt="%b %Y"}}else if(useQuarters&&t<timeUnitSize.year){if(span<timeUnitSize.year){fmt="Q%q"}else{fmt="Q%q %Y"}}else{fmt="%Y"}var rt=formatDate(d,fmt,opts.monthNames,opts.dayNames);return rt}}})})}$.plot.plugins.push({init:init,options:options,name:"time",version:"1.0"});$.plot.formatDate=formatDate;$.plot.dateGenerator=dateGenerator})(jQuery);
diff --git a/static/js/jquery.flot.tooltip.js b/static/js/jquery.flot.tooltip.js
deleted file mode 100644
--- a/static/js/jquery.flot.tooltip.js
+++ /dev/null
@@ -1,409 +0,0 @@
-/*
- * jquery.flot.tooltip
- * 
- * description: easy-to-use tooltips for Flot charts
- * version: 0.7.1
- * author: Krzysztof Urbas @krzysu [myviews.pl]
- * website: https://github.com/krzysu/flot.tooltip
- * 
- * build on 2014-06-22
- * released under MIT License, 2012
-*/ 
-// IE8 polyfill for Array.indexOf
-if (!Array.prototype.indexOf) {
-    Array.prototype.indexOf = function (searchElement, fromIndex) {
-        if ( this === undefined || this === null ) {
-            throw new TypeError( '"this" is null or not defined' );
-        }
-        var length = this.length >>> 0; // Hack to convert object.length to a UInt32
-        fromIndex = +fromIndex || 0;
-        if (Math.abs(fromIndex) === Infinity) {
-            fromIndex = 0;
-        }
-        if (fromIndex < 0) {
-            fromIndex += length;
-            if (fromIndex < 0) {
-                fromIndex = 0;
-            }
-        }
-
-        for (;fromIndex < length; fromIndex++) {
-            if (this[fromIndex] === searchElement) {
-                return fromIndex;
-            }
-        }
-
-        return -1;
-    };
-}
-
-(function ($) {
-
-    // plugin options, default values
-    var defaultOptions = {
-        tooltip: false,
-        tooltipOpts: {
-            content: "%s | X: %x | Y: %y",
-            // allowed templates are:
-            // %s -> series label,
-            // %lx -> x axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
-            // %ly -> y axis label (requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels),
-            // %x -> X value,
-            // %y -> Y value,
-            // %x.2 -> precision of X value,
-            // %p -> percent
-            xDateFormat: null,
-            yDateFormat: null,
-            monthNames: null,
-            dayNames: null,
-            shifts: {
-                x: 10,
-                y: 20
-            },
-            defaultTheme: true,
-
-            // callbacks
-            onHover: function(flotItem, $tooltipEl) {}
-        }
-    };
-
-    // object
-    var FlotTooltip = function(plot) {
-
-        // variables
-        this.tipPosition = {x: 0, y: 0};
-
-        this.init(plot);
-    };
-
-    // main plugin function
-    FlotTooltip.prototype.init = function(plot) {
-
-        var that = this;
-
-        // detect other flot plugins
-        var plotPluginsLength = $.plot.plugins.length;
-        this.plotPlugins = [];
-
-        if (plotPluginsLength) {
-            for (var p = 0; p < plotPluginsLength; p++) {
-                this.plotPlugins.push($.plot.plugins[p].name);
-            }
-        }
-
-        plot.hooks.bindEvents.push(function (plot, eventHolder) {
-
-            // get plot options
-            that.plotOptions = plot.getOptions();
-
-            // if not enabled return
-            if (that.plotOptions.tooltip === false || typeof that.plotOptions.tooltip === 'undefined') return;
-
-            // shortcut to access tooltip options
-            that.tooltipOptions = that.plotOptions.tooltipOpts;
-
-            // create tooltip DOM element
-            var $tip = that.getDomElement();
-
-            // bind event
-            $( plot.getPlaceholder() ).bind("plothover", plothover);
-
-            $(eventHolder).bind('mousemove', mouseMove);
-        });
-
-        plot.hooks.shutdown.push(function (plot, eventHolder){
-            $(plot.getPlaceholder()).unbind("plothover", plothover);
-            $(eventHolder).unbind("mousemove", mouseMove);
-        });
-
-        function mouseMove(e){
-            var pos = {};
-            pos.x = e.pageX;
-            pos.y = e.pageY;
-            that.updateTooltipPosition(pos);
-        }
-
-        function plothover(event, pos, item) {
-            var $tip = that.getDomElement();
-            if (item) {
-                var tipText;
-
-                // convert tooltip content template to real tipText
-                tipText = that.stringFormat(that.tooltipOptions.content, item);
-
-                $tip.html( tipText );
-                that.updateTooltipPosition({ x: pos.pageX, y: pos.pageY });
-                $tip.css({
-                        left: that.tipPosition.x + that.tooltipOptions.shifts.x,
-                        top: that.tipPosition.y + that.tooltipOptions.shifts.y
-                    })
-                    .show();
-
-                // run callback
-                if(typeof that.tooltipOptions.onHover === 'function') {
-                    that.tooltipOptions.onHover(item, $tip);
-                }
-            }
-            else {
-                $tip.hide().html('');
-            }
-        }
-    };
-
-    /**
-     * get or create tooltip DOM element
-     * @return jQuery object
-     */
-    FlotTooltip.prototype.getDomElement = function() {
-        var $tip = $('#flotTip');
-
-        if( $tip.length === 0 ){
-            $tip = $('<div />').attr('id', 'flotTip');
-            $tip.appendTo('body').hide().css({position: 'absolute'});
-
-            if(this.tooltipOptions.defaultTheme) {
-                $tip.css({
-                    'background': '#fff',
-                    'z-index': '1040',
-                    'padding': '0.4em 0.6em',
-                    'border-radius': '0.5em',
-                    'font-size': '0.8em',
-                    'border': '1px solid #111',
-                    'display': 'none',
-                    'white-space': 'nowrap'
-                });
-            }
-        }
-
-        return $tip;
-    };
-
-    // as the name says
-    FlotTooltip.prototype.updateTooltipPosition = function(pos) {
-        var $tip = $('#flotTip');
-
-        var totalTipWidth = $tip.outerWidth() + this.tooltipOptions.shifts.x;
-        var totalTipHeight = $tip.outerHeight() + this.tooltipOptions.shifts.y;
-        if ((pos.x - $(window).scrollLeft()) > ($(window).innerWidth() - totalTipWidth)) {
-            pos.x -= totalTipWidth;
-        }
-        if ((pos.y - $(window).scrollTop()) > ($(window).innerHeight() - totalTipHeight)) {
-            pos.y -= totalTipHeight;
-        }
-        this.tipPosition.x = pos.x;
-        this.tipPosition.y = pos.y;
-    };
-
-    /**
-     * core function, create tooltip content
-     * @param  {string} content - template with tooltip content
-     * @param  {object} item - Flot item
-     * @return {string} real tooltip content for current item
-     */
-    FlotTooltip.prototype.stringFormat = function(content, item) {
-
-        var percentPattern = /%p\.{0,1}(\d{0,})/;
-        var seriesPattern = /%s/;
-        var xLabelPattern = /%lx/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
-        var yLabelPattern = /%ly/; // requires flot-axislabels plugin https://github.com/markrcote/flot-axislabels, will be ignored if plugin isn't loaded
-        var xPattern = /%x\.{0,1}(\d{0,})/;
-        var yPattern = /%y\.{0,1}(\d{0,})/;
-        var xPatternWithoutPrecision = "%x";
-        var yPatternWithoutPrecision = "%y";
-        var customTextPattern = "%ct";
-
-        var x, y, customText;
-
-        // for threshold plugin we need to read data from different place
-        if (typeof item.series.threshold !== "undefined") {
-            x = item.datapoint[0];
-            y = item.datapoint[1];
-            customText = item.datapoint[2];
-        } else if (typeof item.series.lines !== "undefined" && item.series.lines.steps) {
-            x = item.series.datapoints.points[item.dataIndex * 2];
-            y = item.series.datapoints.points[item.dataIndex * 2 + 1];
-            // TODO: where to find custom text in this variant?
-            customText = "";
-        } else {
-            x = item.series.data[item.dataIndex][0];
-            y = item.series.data[item.dataIndex][1];
-            customText = item.series.data[item.dataIndex][2];
-        }
-
-        // I think this is only in case of threshold plugin
-        if (item.series.label === null && item.series.originSeries) {
-            item.series.label = item.series.originSeries.label;
-        }
-
-        // if it is a function callback get the content string
-        if( typeof(content) === 'function' ) {
-            content = content(item.series.label, x, y, item);
-        }
-
-        // percent match for pie charts
-        if( typeof (item.series.percent) !== 'undefined' ) {
-            content = this.adjustValPrecision(percentPattern, content, item.series.percent);
-        }
-
-        // series match
-        if( typeof(item.series.label) !== 'undefined' ) {
-            content = content.replace(seriesPattern, item.series.label);
-        }
-        else {
-            //remove %s if label is undefined
-            content = content.replace(seriesPattern, "");
-        }
-
-        // x axis label match
-        if( this.hasAxisLabel('xaxis', item) ) {
-            content = content.replace(xLabelPattern, item.series.xaxis.options.axisLabel);
-        }
-        else {
-            //remove %lx if axis label is undefined or axislabels plugin not present
-            content = content.replace(xLabelPattern, "");
-        }
-
-        // y axis label match
-        if( this.hasAxisLabel('yaxis', item) ) {
-            content = content.replace(yLabelPattern, item.series.yaxis.options.axisLabel);
-        }
-        else {
-            //remove %ly if axis label is undefined or axislabels plugin not present
-            content = content.replace(yLabelPattern, "");
-        }
-
-        // time mode axes with custom dateFormat
-        if(this.isTimeMode('xaxis', item) && this.isXDateFormat(item)) {
-            content = content.replace(xPattern, this.timestampToDate(x, this.tooltipOptions.xDateFormat, item.series.xaxis.options));
-        }
-
-        if(this.isTimeMode('yaxis', item) && this.isYDateFormat(item)) {
-            content = content.replace(yPattern, this.timestampToDate(y, this.tooltipOptions.yDateFormat, item.series.yaxis.options));
-        }
-
-        // set precision if defined
-        if(typeof x === 'number') {
-            content = this.adjustValPrecision(xPattern, content, x);
-        }
-        if(typeof y === 'number') {
-            content = this.adjustValPrecision(yPattern, content, y);
-        }
-
-        // change x from number to given label, if given
-        if(typeof item.series.xaxis.ticks !== 'undefined') {
-
-            var ticks;
-            if(this.hasRotatedXAxisTicks(item)) {
-                // xaxis.ticks will be an empty array if tickRotor is being used, but the values are available in rotatedTicks
-                ticks = 'rotatedTicks';
-            }
-            else {
-                ticks = 'ticks';
-            }
-
-            // see https://github.com/krzysu/flot.tooltip/issues/65
-            var tickIndex = item.dataIndex + item.seriesIndex;
-
-            if(item.series.xaxis[ticks].length > tickIndex && !this.isTimeMode('xaxis', item)) {
-                var valueX = (this.isCategoriesMode('xaxis', item)) ? item.series.xaxis[ticks][tickIndex].label : item.series.xaxis[ticks][tickIndex].v;
-                if (valueX === x) {
-                    content = content.replace(xPattern, item.series.xaxis[ticks][tickIndex].label);
-                }
-            }
-        }
-
-        // change y from number to given label, if given
-        if(typeof item.series.yaxis.ticks !== 'undefined') {
-            for (var index in item.series.yaxis.ticks) {
-                if (item.series.yaxis.ticks.hasOwnProperty(index)) {
-                    var valueY = (this.isCategoriesMode('yaxis', item)) ? item.series.yaxis.ticks[index].label : item.series.yaxis.ticks[index].v;
-                    if (valueY === y) {
-                        content = content.replace(yPattern, item.series.yaxis.ticks[index].label);
-                    }
-                }
-            }
-        }
-
-        // if no value customization, use tickFormatter by default
-        if(typeof item.series.xaxis.tickFormatter !== 'undefined') {
-            //escape dollar
-            content = content.replace(xPatternWithoutPrecision, item.series.xaxis.tickFormatter(x, item.series.xaxis).replace(/\$/g, '$$'));
-        }
-        if(typeof item.series.yaxis.tickFormatter !== 'undefined') {
-            //escape dollar
-            content = content.replace(yPatternWithoutPrecision, item.series.yaxis.tickFormatter(y, item.series.yaxis).replace(/\$/g, '$$'));
-        }
-
-        if(customText) {
-            content = content.replace(customTextPattern, customText);
-        }
-
-        return content;
-    };
-
-    // helpers just for readability
-    FlotTooltip.prototype.isTimeMode = function(axisName, item) {
-        return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'time');
-    };
-
-    FlotTooltip.prototype.isXDateFormat = function(item) {
-        return (typeof this.tooltipOptions.xDateFormat !== 'undefined' && this.tooltipOptions.xDateFormat !== null);
-    };
-
-    FlotTooltip.prototype.isYDateFormat = function(item) {
-        return (typeof this.tooltipOptions.yDateFormat !== 'undefined' && this.tooltipOptions.yDateFormat !== null);
-    };
-
-    FlotTooltip.prototype.isCategoriesMode = function(axisName, item) {
-        return (typeof item.series[axisName].options.mode !== 'undefined' && item.series[axisName].options.mode === 'categories');
-    };
-
-    //
-    FlotTooltip.prototype.timestampToDate = function(tmst, dateFormat, options) {
-        var theDate = $.plot.dateGenerator(tmst, options);
-        return $.plot.formatDate(theDate, dateFormat, this.tooltipOptions.monthNames, this.tooltipOptions.dayNames);
-    };
-
-    //
-    FlotTooltip.prototype.adjustValPrecision = function(pattern, content, value) {
-
-        var precision;
-        var matchResult = content.match(pattern);
-        if( matchResult !== null ) {
-            if(RegExp.$1 !== '') {
-                precision = RegExp.$1;
-                value = value.toFixed(precision);
-
-                // only replace content if precision exists, in other case use thickformater
-                content = content.replace(pattern, value);
-            }
-        }
-        return content;
-    };
-
-    // other plugins detection below
-
-    // check if flot-axislabels plugin (https://github.com/markrcote/flot-axislabels) is used and that an axis label is given
-    FlotTooltip.prototype.hasAxisLabel = function(axisName, item) {
-        return (this.plotPlugins.indexOf('axisLabels') !== -1 && typeof item.series[axisName].options.axisLabel !== 'undefined' && item.series[axisName].options.axisLabel.length > 0);
-    };
-
-    // check whether flot-tickRotor, a plugin which allows rotation of X-axis ticks, is being used
-    FlotTooltip.prototype.hasRotatedXAxisTicks = function(item) {
-        return ($.grep($.plot.plugins, function(p){ return p.name === "tickRotor"; }).length === 1 && typeof item.series.xaxis.rotatedTicks !== 'undefined');
-    };
-
-    //
-    var init = function(plot) {
-      new FlotTooltip(plot);
-    };
-
-    // define Flot plugin
-    $.plot.plugins.push({
-        init: init,
-        options: defaultOptions,
-        name: 'tooltip',
-        version: '0.6.7'
-    });
-
-})(jQuery);
diff --git a/static/js/jquery.flot.tooltip.min.js b/static/js/jquery.flot.tooltip.min.js
deleted file mode 100644
--- a/static/js/jquery.flot.tooltip.min.js
+++ /dev/null
@@ -1,12 +0,0 @@
-/*
- * jquery.flot.tooltip
- * 
- * description: easy-to-use tooltips for Flot charts
- * version: 0.7.1
- * author: Krzysztof Urbas @krzysu [myviews.pl]
- * website: https://github.com/krzysu/flot.tooltip
- * 
- * build on 2014-06-22
- * released under MIT License, 2012
-*/ 
-Array.prototype.indexOf||(Array.prototype.indexOf=function(t,i){if(void 0===this||null===this)throw new TypeError('"this" is null or not defined');var e=this.length>>>0;for(i=+i||0,1/0===Math.abs(i)&&(i=0),0>i&&(i+=e,0>i&&(i=0));e>i;i++)if(this[i]===t)return i;return-1}),function(t){var i={tooltip:!1,tooltipOpts:{content:"%s | X: %x | Y: %y",xDateFormat:null,yDateFormat:null,monthNames:null,dayNames:null,shifts:{x:10,y:20},defaultTheme:!0,onHover:function(){}}},e=function(t){this.tipPosition={x:0,y:0},this.init(t)};e.prototype.init=function(i){function e(t){var i={};i.x=t.pageX,i.y=t.pageY,o.updateTooltipPosition(i)}function s(t,i,e){var s=o.getDomElement();if(e){var a;a=o.stringFormat(o.tooltipOptions.content,e),s.html(a),o.updateTooltipPosition({x:i.pageX,y:i.pageY}),s.css({left:o.tipPosition.x+o.tooltipOptions.shifts.x,top:o.tipPosition.y+o.tooltipOptions.shifts.y}).show(),"function"==typeof o.tooltipOptions.onHover&&o.tooltipOptions.onHover(e,s)}else s.hide().html("")}var o=this,a=t.plot.plugins.length;if(this.plotPlugins=[],a)for(var n=0;a>n;n++)this.plotPlugins.push(t.plot.plugins[n].name);i.hooks.bindEvents.push(function(i,a){o.plotOptions=i.getOptions(),o.plotOptions.tooltip!==!1&&void 0!==o.plotOptions.tooltip&&(o.tooltipOptions=o.plotOptions.tooltipOpts,o.getDomElement(),t(i.getPlaceholder()).bind("plothover",s),t(a).bind("mousemove",e))}),i.hooks.shutdown.push(function(i,o){t(i.getPlaceholder()).unbind("plothover",s),t(o).unbind("mousemove",e)})},e.prototype.getDomElement=function(){var i=t("#flotTip");return 0===i.length&&(i=t("<div />").attr("id","flotTip"),i.appendTo("body").hide().css({position:"absolute"}),this.tooltipOptions.defaultTheme&&i.css({background:"#fff","z-index":"1040",padding:"0.4em 0.6em","border-radius":"0.5em","font-size":"0.8em",border:"1px solid #111",display:"none","white-space":"nowrap"})),i},e.prototype.updateTooltipPosition=function(i){var e=t("#flotTip"),s=e.outerWidth()+this.tooltipOptions.shifts.x,o=e.outerHeight()+this.tooltipOptions.shifts.y;i.x-t(window).scrollLeft()>t(window).innerWidth()-s&&(i.x-=s),i.y-t(window).scrollTop()>t(window).innerHeight()-o&&(i.y-=o),this.tipPosition.x=i.x,this.tipPosition.y=i.y},e.prototype.stringFormat=function(t,i){var e,s,o,a=/%p\.{0,1}(\d{0,})/,n=/%s/,r=/%lx/,p=/%ly/,l=/%x\.{0,1}(\d{0,})/,d=/%y\.{0,1}(\d{0,})/,x="%x",h="%y",u="%ct";if(i.series.threshold!==void 0?(e=i.datapoint[0],s=i.datapoint[1],o=i.datapoint[2]):i.series.lines!==void 0&&i.series.lines.steps?(e=i.series.datapoints.points[2*i.dataIndex],s=i.series.datapoints.points[2*i.dataIndex+1],o=""):(e=i.series.data[i.dataIndex][0],s=i.series.data[i.dataIndex][1],o=i.series.data[i.dataIndex][2]),null===i.series.label&&i.series.originSeries&&(i.series.label=i.series.originSeries.label),"function"==typeof t&&(t=t(i.series.label,e,s,i)),i.series.percent!==void 0&&(t=this.adjustValPrecision(a,t,i.series.percent)),t=i.series.label!==void 0?t.replace(n,i.series.label):t.replace(n,""),t=this.hasAxisLabel("xaxis",i)?t.replace(r,i.series.xaxis.options.axisLabel):t.replace(r,""),t=this.hasAxisLabel("yaxis",i)?t.replace(p,i.series.yaxis.options.axisLabel):t.replace(p,""),this.isTimeMode("xaxis",i)&&this.isXDateFormat(i)&&(t=t.replace(l,this.timestampToDate(e,this.tooltipOptions.xDateFormat,i.series.xaxis.options))),this.isTimeMode("yaxis",i)&&this.isYDateFormat(i)&&(t=t.replace(d,this.timestampToDate(s,this.tooltipOptions.yDateFormat,i.series.yaxis.options))),"number"==typeof e&&(t=this.adjustValPrecision(l,t,e)),"number"==typeof s&&(t=this.adjustValPrecision(d,t,s)),i.series.xaxis.ticks!==void 0){var c;c=this.hasRotatedXAxisTicks(i)?"rotatedTicks":"ticks";var m=i.dataIndex+i.seriesIndex;if(i.series.xaxis[c].length>m&&!this.isTimeMode("xaxis",i)){var f=this.isCategoriesMode("xaxis",i)?i.series.xaxis[c][m].label:i.series.xaxis[c][m].v;f===e&&(t=t.replace(l,i.series.xaxis[c][m].label))}}if(i.series.yaxis.ticks!==void 0)for(var y in i.series.yaxis.ticks)if(i.series.yaxis.ticks.hasOwnProperty(y)){var v=this.isCategoriesMode("yaxis",i)?i.series.yaxis.ticks[y].label:i.series.yaxis.ticks[y].v;v===s&&(t=t.replace(d,i.series.yaxis.ticks[y].label))}return i.series.xaxis.tickFormatter!==void 0&&(t=t.replace(x,i.series.xaxis.tickFormatter(e,i.series.xaxis).replace(/\$/g,"$$"))),i.series.yaxis.tickFormatter!==void 0&&(t=t.replace(h,i.series.yaxis.tickFormatter(s,i.series.yaxis).replace(/\$/g,"$$"))),o&&(t=t.replace(u,o)),t},e.prototype.isTimeMode=function(t,i){return i.series[t].options.mode!==void 0&&"time"===i.series[t].options.mode},e.prototype.isXDateFormat=function(){return this.tooltipOptions.xDateFormat!==void 0&&null!==this.tooltipOptions.xDateFormat},e.prototype.isYDateFormat=function(){return this.tooltipOptions.yDateFormat!==void 0&&null!==this.tooltipOptions.yDateFormat},e.prototype.isCategoriesMode=function(t,i){return i.series[t].options.mode!==void 0&&"categories"===i.series[t].options.mode},e.prototype.timestampToDate=function(i,e,s){var o=t.plot.dateGenerator(i,s);return t.plot.formatDate(o,e,this.tooltipOptions.monthNames,this.tooltipOptions.dayNames)},e.prototype.adjustValPrecision=function(t,i,e){var s,o=i.match(t);return null!==o&&""!==RegExp.$1&&(s=RegExp.$1,e=e.toFixed(s),i=i.replace(t,e)),i},e.prototype.hasAxisLabel=function(t,i){return-1!==this.plotPlugins.indexOf("axisLabels")&&i.series[t].options.axisLabel!==void 0&&i.series[t].options.axisLabel.length>0},e.prototype.hasRotatedXAxisTicks=function(i){return 1===t.grep(t.plot.plugins,function(t){return"tickRotor"===t.name}).length&&i.series.xaxis.rotatedTicks!==void 0};var s=function(t){new e(t)};t.plot.plugins.push({init:s,options:i,name:"tooltip",version:"0.6.7"})}(jQuery);
diff --git a/static/js/jquery.hotkeys.js b/static/js/jquery.hotkeys.js
deleted file mode 100644
--- a/static/js/jquery.hotkeys.js
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * jQuery Hotkeys Plugin
- * Copyright 2010, John Resig
- * Dual licensed under the MIT or GPL Version 2 licenses.
- *
- * Based upon the plugin by Tzury Bar Yochay:
- * http://github.com/tzuryby/hotkeys
- *
- * Original idea by:
- * Binny V A, http://www.openjs.com/scripts/events/keyboard_shortcuts/
-*/
-
-/*
- * One small change is: now keys are passed by object { keys: '...' }
- * Might be useful, when you want to pass some other data to your handler
- */
-
-(function(jQuery){
-
-	jQuery.hotkeys = {
-		version: "0.8",
-
-		specialKeys: {
-			8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
-			20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
-			37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=",
-			96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
-			104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
-			112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
-			120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=",
-			188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"
-		},
-
-		shiftNums: {
-			"`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
-			"8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<",
-			".": ">",  "/": "?",  "\\": "|"
-		}
-	};
-
-	function keyHandler( handleObj ) {
-		if ( typeof handleObj.data === "string" ) {
-			handleObj.data = { keys: handleObj.data };
-		}
-
-		// Only care when a possible input has been specified
-		if ( !handleObj.data || !handleObj.data.keys || typeof handleObj.data.keys !== "string" ) {
-			return;
-		}
-
-		var origHandler = handleObj.handler,
-			keys = handleObj.data.keys.toLowerCase().split(" "),
-			textAcceptingInputTypes = ["text", "password", "number", "email", "url", "range", "date", "month", "week",
-        "time", "datetime", "datetime-local", "search", "color", "tel"];
-
-		handleObj.handler = function( event ) {
-			// Don't fire in text-accepting inputs that we didn't directly bind to
-			if ( this !== event.target && (/textarea|select/i.test( event.target.nodeName ) ||
-				jQuery.inArray(event.target.type, textAcceptingInputTypes) > -1 ) ) {
-				return;
-			}
-
-			var special = jQuery.hotkeys.specialKeys[ event.keyCode ],
-				character = String.fromCharCode( event.which ).toLowerCase(),
-				modif = "", possible = {};
-
-      jQuery.each([ "alt", "ctrl", "meta", "shift" ], function(index, specialKey) {
-        if (event[specialKey + 'Key'] && special !== specialKey) {
-          modif += specialKey + '+';
-        }
-      });
-
-
-      modif = modif.replace('alt+ctrl+meta+shift', 'hyper');
-
-			if ( special ) {
-				possible[ modif + special ] = true;
-			}
-
-			if ( character ) {
-				possible[ modif + character ] = true;
-				possible[ modif + jQuery.hotkeys.shiftNums[ character ] ] = true;
-
-				// "$" can be triggered as "Shift+4" or "Shift+$" or just "$"
-				if ( modif === "shift+" ) {
-					possible[ jQuery.hotkeys.shiftNums[ character ] ] = true;
-				}
-			}
-
-			for ( var i = 0, l = keys.length; i < l; i++ ) {
-				if ( possible[ keys[i] ] ) {
-					return origHandler.apply( this, arguments );
-				}
-			}
-		};
-	}
-
-	jQuery.each([ "keydown", "keyup", "keypress" ], function() {
-		jQuery.event.special[ this ] = { add: keyHandler };
-	});
-
-})( this.jQuery );
diff --git a/static/js/jquery.js b/static/js/jquery.js
deleted file mode 100644
--- a/static/js/jquery.js
+++ /dev/null
@@ -1,9190 +0,0 @@
-/*!
- * jQuery JavaScript Library v2.1.1
- * http://jquery.com/
- *
- * Includes Sizzle.js
- * http://sizzlejs.com/
- *
- * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2014-05-01T17:11Z
- */
-
-(function( global, factory ) {
-
-	if ( typeof module === "object" && typeof module.exports === "object" ) {
-		// For CommonJS and CommonJS-like environments where a proper window is present,
-		// execute the factory and get jQuery
-		// For environments that do not inherently posses a window with a document
-		// (such as Node.js), expose a jQuery-making factory as module.exports
-		// This accentuates the need for the creation of a real window
-		// e.g. var jQuery = require("jquery")(window);
-		// See ticket #14549 for more info
-		module.exports = global.document ?
-			factory( global, true ) :
-			function( w ) {
-				if ( !w.document ) {
-					throw new Error( "jQuery requires a window with a document" );
-				}
-				return factory( w );
-			};
-	} else {
-		factory( global );
-	}
-
-// Pass this if window is not defined yet
-}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
-
-// Can't do this because several apps including ASP.NET trace
-// the stack via arguments.caller.callee and Firefox dies if
-// you try to trace through "use strict" call chains. (#13335)
-// Support: Firefox 18+
-//
-
-var arr = [];
-
-var slice = arr.slice;
-
-var concat = arr.concat;
-
-var push = arr.push;
-
-var indexOf = arr.indexOf;
-
-var class2type = {};
-
-var toString = class2type.toString;
-
-var hasOwn = class2type.hasOwnProperty;
-
-var support = {};
-
-
-
-var
-	// Use the correct document accordingly with window argument (sandbox)
-	document = window.document,
-
-	version = "2.1.1",
-
-	// Define a local copy of jQuery
-	jQuery = function( selector, context ) {
-		// The jQuery object is actually just the init constructor 'enhanced'
-		// Need init if jQuery is called (just allow error to be thrown if not included)
-		return new jQuery.fn.init( selector, context );
-	},
-
-	// Support: Android<4.1
-	// Make sure we trim BOM and NBSP
-	rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
-
-	// Matches dashed string for camelizing
-	rmsPrefix = /^-ms-/,
-	rdashAlpha = /-([\da-z])/gi,
-
-	// Used by jQuery.camelCase as callback to replace()
-	fcamelCase = function( all, letter ) {
-		return letter.toUpperCase();
-	};
-
-jQuery.fn = jQuery.prototype = {
-	// The current version of jQuery being used
-	jquery: version,
-
-	constructor: jQuery,
-
-	// Start with an empty selector
-	selector: "",
-
-	// The default length of a jQuery object is 0
-	length: 0,
-
-	toArray: function() {
-		return slice.call( this );
-	},
-
-	// 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 != null ?
-
-			// Return just the one element from the set
-			( num < 0 ? this[ num + this.length ] : this[ num ] ) :
-
-			// Return all the elements in a clean array
-			slice.call( this );
-	},
-
-	// Take an array of elements and push it onto the stack
-	// (returning the new matched element set)
-	pushStack: function( elems ) {
-
-		// Build a new jQuery matched element set
-		var ret = jQuery.merge( this.constructor(), elems );
-
-		// Add the old object onto the stack (as a reference)
-		ret.prevObject = this;
-		ret.context = this.context;
-
-		// Return the newly-formed element set
-		return ret;
-	},
-
-	// 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 );
-	},
-
-	map: function( callback ) {
-		return this.pushStack( jQuery.map(this, function( elem, i ) {
-			return callback.call( elem, i, elem );
-		}));
-	},
-
-	slice: function() {
-		return this.pushStack( slice.apply( this, arguments ) );
-	},
-
-	first: function() {
-		return this.eq( 0 );
-	},
-
-	last: function() {
-		return this.eq( -1 );
-	},
-
-	eq: function( i ) {
-		var len = this.length,
-			j = +i + ( i < 0 ? len : 0 );
-		return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
-	},
-
-	end: function() {
-		return this.prevObject || this.constructor(null);
-	},
-
-	// For internal use only.
-	// Behaves like an Array's method, not like a jQuery method.
-	push: push,
-	sort: arr.sort,
-	splice: arr.splice
-};
-
-jQuery.extend = jQuery.fn.extend = function() {
-	var options, name, src, copy, copyIsArray, clone,
-		target = arguments[0] || {},
-		i = 1,
-		length = arguments.length,
-		deep = false;
-
-	// Handle a deep copy situation
-	if ( typeof target === "boolean" ) {
-		deep = target;
-
-		// skip the boolean and the target
-		target = arguments[ i ] || {};
-		i++;
-	}
-
-	// 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 ( i === length ) {
-		target = this;
-		i--;
-	}
-
-	for ( ; i < length; i++ ) {
-		// Only deal with non-null/undefined values
-		if ( (options = arguments[ i ]) != null ) {
-			// Extend the base object
-			for ( name in options ) {
-				src = target[ name ];
-				copy = options[ name ];
-
-				// Prevent never-ending loop
-				if ( target === copy ) {
-					continue;
-				}
-
-				// Recurse if we're merging plain objects or arrays
-				if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
-					if ( copyIsArray ) {
-						copyIsArray = false;
-						clone = src && jQuery.isArray(src) ? src : [];
-
-					} else {
-						clone = src && jQuery.isPlainObject(src) ? src : {};
-					}
-
-					// Never move original objects, clone them
-					target[ name ] = jQuery.extend( deep, clone, copy );
-
-				// Don't bring in undefined values
-				} else if ( copy !== undefined ) {
-					target[ name ] = copy;
-				}
-			}
-		}
-	}
-
-	// Return the modified object
-	return target;
-};
-
-jQuery.extend({
-	// Unique for each copy of jQuery on the page
-	expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
-
-	// Assume jQuery is ready without the ready module
-	isReady: true,
-
-	error: function( msg ) {
-		throw new Error( msg );
-	},
-
-	noop: function() {},
-
-	// 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 jQuery.type(obj) === "function";
-	},
-
-	isArray: Array.isArray,
-
-	isWindow: function( obj ) {
-		return obj != null && obj === obj.window;
-	},
-
-	isNumeric: function( obj ) {
-		// parseFloat NaNs numeric-cast false positives (null|true|false|"")
-		// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
-		// subtraction forces infinities to NaN
-		return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
-	},
-
-	isPlainObject: function( obj ) {
-		// Not plain objects:
-		// - Any object or value whose internal [[Class]] property is not "[object Object]"
-		// - DOM nodes
-		// - window
-		if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
-			return false;
-		}
-
-		if ( obj.constructor &&
-				!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
-			return false;
-		}
-
-		// If the function hasn't returned already, we're confident that
-		// |obj| is a plain object, created by {} or constructed with new Object
-		return true;
-	},
-
-	isEmptyObject: function( obj ) {
-		var name;
-		for ( name in obj ) {
-			return false;
-		}
-		return true;
-	},
-
-	type: function( obj ) {
-		if ( obj == null ) {
-			return obj + "";
-		}
-		// Support: Android < 4.0, iOS < 6 (functionish RegExp)
-		return typeof obj === "object" || typeof obj === "function" ?
-			class2type[ toString.call(obj) ] || "object" :
-			typeof obj;
-	},
-
-	// Evaluates a script in a global context
-	globalEval: function( code ) {
-		var script,
-			indirect = eval;
-
-		code = jQuery.trim( code );
-
-		if ( code ) {
-			// If the code includes a valid, prologue position
-			// strict mode pragma, execute code by injecting a
-			// script tag into the document.
-			if ( code.indexOf("use strict") === 1 ) {
-				script = document.createElement("script");
-				script.text = code;
-				document.head.appendChild( script ).parentNode.removeChild( script );
-			} else {
-			// Otherwise, avoid the DOM node creation, insertion
-			// and removal by using an indirect global eval
-				indirect( code );
-			}
-		}
-	},
-
-	// Convert dashed to camelCase; used by the css and data modules
-	// Microsoft forgot to hump their vendor prefix (#9572)
-	camelCase: function( string ) {
-		return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
-	},
-
-	nodeName: function( elem, name ) {
-		return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
-	},
-
-	// args is for internal usage only
-	each: function( obj, callback, args ) {
-		var value,
-			i = 0,
-			length = obj.length,
-			isArray = isArraylike( obj );
-
-		if ( args ) {
-			if ( isArray ) {
-				for ( ; i < length; i++ ) {
-					value = callback.apply( obj[ i ], args );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			} else {
-				for ( i in obj ) {
-					value = callback.apply( obj[ i ], args );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			}
-
-		// A special, fast, case for the most common use of each
-		} else {
-			if ( isArray ) {
-				for ( ; i < length; i++ ) {
-					value = callback.call( obj[ i ], i, obj[ i ] );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			} else {
-				for ( i in obj ) {
-					value = callback.call( obj[ i ], i, obj[ i ] );
-
-					if ( value === false ) {
-						break;
-					}
-				}
-			}
-		}
-
-		return obj;
-	},
-
-	// Support: Android<4.1
-	trim: function( text ) {
-		return text == null ?
-			"" :
-			( text + "" ).replace( rtrim, "" );
-	},
-
-	// results is for internal usage only
-	makeArray: function( arr, results ) {
-		var ret = results || [];
-
-		if ( arr != null ) {
-			if ( isArraylike( Object(arr) ) ) {
-				jQuery.merge( ret,
-					typeof arr === "string" ?
-					[ arr ] : arr
-				);
-			} else {
-				push.call( ret, arr );
-			}
-		}
-
-		return ret;
-	},
-
-	inArray: function( elem, arr, i ) {
-		return arr == null ? -1 : indexOf.call( arr, elem, i );
-	},
-
-	merge: function( first, second ) {
-		var len = +second.length,
-			j = 0,
-			i = first.length;
-
-		for ( ; j < len; j++ ) {
-			first[ i++ ] = second[ j ];
-		}
-
-		first.length = i;
-
-		return first;
-	},
-
-	grep: function( elems, callback, invert ) {
-		var callbackInverse,
-			matches = [],
-			i = 0,
-			length = elems.length,
-			callbackExpect = !invert;
-
-		// Go through the array, only saving the items
-		// that pass the validator function
-		for ( ; i < length; i++ ) {
-			callbackInverse = !callback( elems[ i ], i );
-			if ( callbackInverse !== callbackExpect ) {
-				matches.push( elems[ i ] );
-			}
-		}
-
-		return matches;
-	},
-
-	// arg is for internal usage only
-	map: function( elems, callback, arg ) {
-		var value,
-			i = 0,
-			length = elems.length,
-			isArray = isArraylike( elems ),
-			ret = [];
-
-		// Go through the array, translating each of the items to their new values
-		if ( isArray ) {
-			for ( ; i < length; i++ ) {
-				value = callback( elems[ i ], i, arg );
-
-				if ( value != null ) {
-					ret.push( value );
-				}
-			}
-
-		// Go through every key on the object,
-		} else {
-			for ( i in elems ) {
-				value = callback( elems[ i ], i, arg );
-
-				if ( value != null ) {
-					ret.push( value );
-				}
-			}
-		}
-
-		// Flatten any nested arrays
-		return concat.apply( [], ret );
-	},
-
-	// A global GUID counter for objects
-	guid: 1,
-
-	// Bind a function to a context, optionally partially applying any
-	// arguments.
-	proxy: function( fn, context ) {
-		var tmp, args, proxy;
-
-		if ( typeof context === "string" ) {
-			tmp = fn[ context ];
-			context = fn;
-			fn = tmp;
-		}
-
-		// Quick check to determine if target is callable, in the spec
-		// this throws a TypeError, but we will just return undefined.
-		if ( !jQuery.isFunction( fn ) ) {
-			return undefined;
-		}
-
-		// Simulated bind
-		args = slice.call( arguments, 2 );
-		proxy = function() {
-			return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
-		};
-
-		// Set the guid of unique handler to the same of original handler, so it can be removed
-		proxy.guid = fn.guid = fn.guid || jQuery.guid++;
-
-		return proxy;
-	},
-
-	now: Date.now,
-
-	// jQuery.support is not used in Core but other projects attach their
-	// properties to it so it needs to exist.
-	support: support
-});
-
-// Populate the class2type map
-jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
-	class2type[ "[object " + name + "]" ] = name.toLowerCase();
-});
-
-function isArraylike( obj ) {
-	var length = obj.length,
-		type = jQuery.type( obj );
-
-	if ( type === "function" || jQuery.isWindow( obj ) ) {
-		return false;
-	}
-
-	if ( obj.nodeType === 1 && length ) {
-		return true;
-	}
-
-	return type === "array" || length === 0 ||
-		typeof length === "number" && length > 0 && ( length - 1 ) in obj;
-}
-var Sizzle =
-/*!
- * Sizzle CSS Selector Engine v1.10.19
- * http://sizzlejs.com/
- *
- * Copyright 2013 jQuery Foundation, Inc. and other contributors
- * Released under the MIT license
- * http://jquery.org/license
- *
- * Date: 2014-04-18
- */
-(function( window ) {
-
-var i,
-	support,
-	Expr,
-	getText,
-	isXML,
-	tokenize,
-	compile,
-	select,
-	outermostContext,
-	sortInput,
-	hasDuplicate,
-
-	// Local document vars
-	setDocument,
-	document,
-	docElem,
-	documentIsHTML,
-	rbuggyQSA,
-	rbuggyMatches,
-	matches,
-	contains,
-
-	// Instance-specific data
-	expando = "sizzle" + -(new Date()),
-	preferredDoc = window.document,
-	dirruns = 0,
-	done = 0,
-	classCache = createCache(),
-	tokenCache = createCache(),
-	compilerCache = createCache(),
-	sortOrder = function( a, b ) {
-		if ( a === b ) {
-			hasDuplicate = true;
-		}
-		return 0;
-	},
-
-	// General-purpose constants
-	strundefined = typeof undefined,
-	MAX_NEGATIVE = 1 << 31,
-
-	// Instance methods
-	hasOwn = ({}).hasOwnProperty,
-	arr = [],
-	pop = arr.pop,
-	push_native = arr.push,
-	push = arr.push,
-	slice = arr.slice,
-	// Use a stripped-down indexOf if we can't use a native one
-	indexOf = arr.indexOf || function( elem ) {
-		var i = 0,
-			len = this.length;
-		for ( ; i < len; i++ ) {
-			if ( this[i] === elem ) {
-				return i;
-			}
-		}
-		return -1;
-	},
-
-	booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
-
-	// Regular expressions
-
-	// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
-	whitespace = "[\\x20\\t\\r\\n\\f]",
-	// http://www.w3.org/TR/css3-syntax/#characters
-	characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
-
-	// Loosely modeled on CSS identifier characters
-	// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
-	// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
-	identifier = characterEncoding.replace( "w", "w#" ),
-
-	// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
-	attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
-		// Operator (capture 2)
-		"*([*^$|!~]?=)" + whitespace +
-		// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
-		"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
-		"*\\]",
-
-	pseudos = ":(" + characterEncoding + ")(?:\\((" +
-		// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
-		// 1. quoted (capture 3; capture 4 or capture 5)
-		"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
-		// 2. simple (capture 6)
-		"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
-		// 3. anything else (capture 2)
-		".*" +
-		")\\)|)",
-
-	// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
-	rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
-
-	rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
-	rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
-
-	rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
-
-	rpseudo = new RegExp( pseudos ),
-	ridentifier = new RegExp( "^" + identifier + "$" ),
-
-	matchExpr = {
-		"ID": new RegExp( "^#(" + characterEncoding + ")" ),
-		"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
-		"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
-		"ATTR": new RegExp( "^" + attributes ),
-		"PSEUDO": new RegExp( "^" + pseudos ),
-		"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
-			"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
-			"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
-		"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
-		// For use in libraries implementing .is()
-		// We use this for POS matching in `select`
-		"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
-			whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
-	},
-
-	rinputs = /^(?:input|select|textarea|button)$/i,
-	rheader = /^h\d$/i,
-
-	rnative = /^[^{]+\{\s*\[native \w/,
-
-	// Easily-parseable/retrievable ID or TAG or CLASS selectors
-	rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
-
-	rsibling = /[+~]/,
-	rescape = /'|\\/g,
-
-	// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
-	runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
-	funescape = function( _, escaped, escapedWhitespace ) {
-		var high = "0x" + escaped - 0x10000;
-		// NaN means non-codepoint
-		// Support: Firefox<24
-		// Workaround erroneous numeric interpretation of +"0x"
-		return high !== high || escapedWhitespace ?
-			escaped :
-			high < 0 ?
-				// BMP codepoint
-				String.fromCharCode( high + 0x10000 ) :
-				// Supplemental Plane codepoint (surrogate pair)
-				String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
-	};
-
-// Optimize for push.apply( _, NodeList )
-try {
-	push.apply(
-		(arr = slice.call( preferredDoc.childNodes )),
-		preferredDoc.childNodes
-	);
-	// Support: Android<4.0
-	// Detect silently failing push.apply
-	arr[ preferredDoc.childNodes.length ].nodeType;
-} catch ( e ) {
-	push = { apply: arr.length ?
-
-		// Leverage slice if possible
-		function( target, els ) {
-			push_native.apply( target, slice.call(els) );
-		} :
-
-		// Support: IE<9
-		// Otherwise append directly
-		function( target, els ) {
-			var j = target.length,
-				i = 0;
-			// Can't trust NodeList.length
-			while ( (target[j++] = els[i++]) ) {}
-			target.length = j - 1;
-		}
-	};
-}
-
-function Sizzle( selector, context, results, seed ) {
-	var match, elem, m, nodeType,
-		// QSA vars
-		i, groups, old, nid, newContext, newSelector;
-
-	if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
-		setDocument( context );
-	}
-
-	context = context || document;
-	results = results || [];
-
-	if ( !selector || typeof selector !== "string" ) {
-		return results;
-	}
-
-	if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
-		return [];
-	}
-
-	if ( documentIsHTML && !seed ) {
-
-		// Shortcuts
-		if ( (match = rquickExpr.exec( selector )) ) {
-			// Speed-up: Sizzle("#ID")
-			if ( (m = match[1]) ) {
-				if ( nodeType === 9 ) {
-					elem = context.getElementById( m );
-					// Check parentNode to catch when Blackberry 4.6 returns
-					// nodes that are no longer in the document (jQuery #6963)
-					if ( elem && elem.parentNode ) {
-						// Handle the case where IE, Opera, and Webkit return items
-						// by name instead of ID
-						if ( elem.id === m ) {
-							results.push( elem );
-							return results;
-						}
-					} else {
-						return results;
-					}
-				} else {
-					// Context is not a document
-					if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
-						contains( context, elem ) && elem.id === m ) {
-						results.push( elem );
-						return results;
-					}
-				}
-
-			// Speed-up: Sizzle("TAG")
-			} else if ( match[2] ) {
-				push.apply( results, context.getElementsByTagName( selector ) );
-				return results;
-
-			// Speed-up: Sizzle(".CLASS")
-			} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
-				push.apply( results, context.getElementsByClassName( m ) );
-				return results;
-			}
-		}
-
-		// QSA path
-		if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
-			nid = old = expando;
-			newContext = context;
-			newSelector = nodeType === 9 && selector;
-
-			// qSA works strangely on Element-rooted queries
-			// We can work around this by specifying an extra ID on the root
-			// and working up from there (Thanks to Andrew Dupont for the technique)
-			// IE 8 doesn't work on object elements
-			if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
-				groups = tokenize( selector );
-
-				if ( (old = context.getAttribute("id")) ) {
-					nid = old.replace( rescape, "\\$&" );
-				} else {
-					context.setAttribute( "id", nid );
-				}
-				nid = "[id='" + nid + "'] ";
-
-				i = groups.length;
-				while ( i-- ) {
-					groups[i] = nid + toSelector( groups[i] );
-				}
-				newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
-				newSelector = groups.join(",");
-			}
-
-			if ( newSelector ) {
-				try {
-					push.apply( results,
-						newContext.querySelectorAll( newSelector )
-					);
-					return results;
-				} catch(qsaError) {
-				} finally {
-					if ( !old ) {
-						context.removeAttribute("id");
-					}
-				}
-			}
-		}
-	}
-
-	// All others
-	return select( selector.replace( rtrim, "$1" ), context, results, seed );
-}
-
-/**
- * Create key-value caches of limited size
- * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
- *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
- *	deleting the oldest entry
- */
-function createCache() {
-	var keys = [];
-
-	function cache( key, value ) {
-		// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
-		if ( keys.push( key + " " ) > Expr.cacheLength ) {
-			// Only keep the most recent entries
-			delete cache[ keys.shift() ];
-		}
-		return (cache[ key + " " ] = value);
-	}
-	return cache;
-}
-
-/**
- * Mark a function for special use by Sizzle
- * @param {Function} fn The function to mark
- */
-function markFunction( fn ) {
-	fn[ expando ] = true;
-	return fn;
-}
-
-/**
- * Support testing using an element
- * @param {Function} fn Passed the created div and expects a boolean result
- */
-function assert( fn ) {
-	var div = document.createElement("div");
-
-	try {
-		return !!fn( div );
-	} catch (e) {
-		return false;
-	} finally {
-		// Remove from its parent by default
-		if ( div.parentNode ) {
-			div.parentNode.removeChild( div );
-		}
-		// release memory in IE
-		div = null;
-	}
-}
-
-/**
- * Adds the same handler for all of the specified attrs
- * @param {String} attrs Pipe-separated list of attributes
- * @param {Function} handler The method that will be applied
- */
-function addHandle( attrs, handler ) {
-	var arr = attrs.split("|"),
-		i = attrs.length;
-
-	while ( i-- ) {
-		Expr.attrHandle[ arr[i] ] = handler;
-	}
-}
-
-/**
- * Checks document order of two siblings
- * @param {Element} a
- * @param {Element} b
- * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
- */
-function siblingCheck( a, b ) {
-	var cur = b && a,
-		diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
-			( ~b.sourceIndex || MAX_NEGATIVE ) -
-			( ~a.sourceIndex || MAX_NEGATIVE );
-
-	// Use IE sourceIndex if available on both nodes
-	if ( diff ) {
-		return diff;
-	}
-
-	// Check if b follows a
-	if ( cur ) {
-		while ( (cur = cur.nextSibling) ) {
-			if ( cur === b ) {
-				return -1;
-			}
-		}
-	}
-
-	return a ? 1 : -1;
-}
-
-/**
- * Returns a function to use in pseudos for input types
- * @param {String} type
- */
-function createInputPseudo( type ) {
-	return function( elem ) {
-		var name = elem.nodeName.toLowerCase();
-		return name === "input" && elem.type === type;
-	};
-}
-
-/**
- * Returns a function to use in pseudos for buttons
- * @param {String} type
- */
-function createButtonPseudo( type ) {
-	return function( elem ) {
-		var name = elem.nodeName.toLowerCase();
-		return (name === "input" || name === "button") && elem.type === type;
-	};
-}
-
-/**
- * Returns a function to use in pseudos for positionals
- * @param {Function} fn
- */
-function createPositionalPseudo( fn ) {
-	return markFunction(function( argument ) {
-		argument = +argument;
-		return markFunction(function( seed, matches ) {
-			var j,
-				matchIndexes = fn( [], seed.length, argument ),
-				i = matchIndexes.length;
-
-			// Match elements found at the specified indexes
-			while ( i-- ) {
-				if ( seed[ (j = matchIndexes[i]) ] ) {
-					seed[j] = !(matches[j] = seed[j]);
-				}
-			}
-		});
-	});
-}
-
-/**
- * Checks a node for validity as a Sizzle context
- * @param {Element|Object=} context
- * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
- */
-function testContext( context ) {
-	return context && typeof context.getElementsByTagName !== strundefined && context;
-}
-
-// Expose support vars for convenience
-support = Sizzle.support = {};
-
-/**
- * Detects XML nodes
- * @param {Element|Object} elem An element or a document
- * @returns {Boolean} True iff elem is a non-HTML XML node
- */
-isXML = Sizzle.isXML = function( elem ) {
-	// documentElement is verified for cases where it doesn't yet exist
-	// (such as loading iframes in IE - #4833)
-	var documentElement = elem && (elem.ownerDocument || elem).documentElement;
-	return documentElement ? documentElement.nodeName !== "HTML" : false;
-};
-
-/**
- * Sets document-related variables once based on the current document
- * @param {Element|Object} [doc] An element or document object to use to set the document
- * @returns {Object} Returns the current document
- */
-setDocument = Sizzle.setDocument = function( node ) {
-	var hasCompare,
-		doc = node ? node.ownerDocument || node : preferredDoc,
-		parent = doc.defaultView;
-
-	// If no document and documentElement is available, return
-	if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
-		return document;
-	}
-
-	// Set our document
-	document = doc;
-	docElem = doc.documentElement;
-
-	// Support tests
-	documentIsHTML = !isXML( doc );
-
-	// Support: IE>8
-	// If iframe document is assigned to "document" variable and if iframe has been reloaded,
-	// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
-	// IE6-8 do not support the defaultView property so parent will be undefined
-	if ( parent && parent !== parent.top ) {
-		// IE11 does not have attachEvent, so all must suffer
-		if ( parent.addEventListener ) {
-			parent.addEventListener( "unload", function() {
-				setDocument();
-			}, false );
-		} else if ( parent.attachEvent ) {
-			parent.attachEvent( "onunload", function() {
-				setDocument();
-			});
-		}
-	}
-
-	/* Attributes
-	---------------------------------------------------------------------- */
-
-	// Support: IE<8
-	// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
-	support.attributes = assert(function( div ) {
-		div.className = "i";
-		return !div.getAttribute("className");
-	});
-
-	/* getElement(s)By*
-	---------------------------------------------------------------------- */
-
-	// Check if getElementsByTagName("*") returns only elements
-	support.getElementsByTagName = assert(function( div ) {
-		div.appendChild( doc.createComment("") );
-		return !div.getElementsByTagName("*").length;
-	});
-
-	// Check if getElementsByClassName can be trusted
-	support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
-		div.innerHTML = "<div class='a'></div><div class='a i'></div>";
-
-		// Support: Safari<4
-		// Catch class over-caching
-		div.firstChild.className = "i";
-		// Support: Opera<10
-		// Catch gEBCN failure to find non-leading classes
-		return div.getElementsByClassName("i").length === 2;
-	});
-
-	// Support: IE<10
-	// Check if getElementById returns elements by name
-	// The broken getElementById methods don't pick up programatically-set names,
-	// so use a roundabout getElementsByName test
-	support.getById = assert(function( div ) {
-		docElem.appendChild( div ).id = expando;
-		return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
-	});
-
-	// ID find and filter
-	if ( support.getById ) {
-		Expr.find["ID"] = function( id, context ) {
-			if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
-				var m = context.getElementById( id );
-				// Check parentNode to catch when Blackberry 4.6 returns
-				// nodes that are no longer in the document #6963
-				return m && m.parentNode ? [ m ] : [];
-			}
-		};
-		Expr.filter["ID"] = function( id ) {
-			var attrId = id.replace( runescape, funescape );
-			return function( elem ) {
-				return elem.getAttribute("id") === attrId;
-			};
-		};
-	} else {
-		// Support: IE6/7
-		// getElementById is not reliable as a find shortcut
-		delete Expr.find["ID"];
-
-		Expr.filter["ID"] =  function( id ) {
-			var attrId = id.replace( runescape, funescape );
-			return function( elem ) {
-				var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
-				return node && node.value === attrId;
-			};
-		};
-	}
-
-	// Tag
-	Expr.find["TAG"] = support.getElementsByTagName ?
-		function( tag, context ) {
-			if ( typeof context.getElementsByTagName !== strundefined ) {
-				return context.getElementsByTagName( tag );
-			}
-		} :
-		function( tag, context ) {
-			var elem,
-				tmp = [],
-				i = 0,
-				results = context.getElementsByTagName( tag );
-
-			// Filter out possible comments
-			if ( tag === "*" ) {
-				while ( (elem = results[i++]) ) {
-					if ( elem.nodeType === 1 ) {
-						tmp.push( elem );
-					}
-				}
-
-				return tmp;
-			}
-			return results;
-		};
-
-	// Class
-	Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
-		if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
-			return context.getElementsByClassName( className );
-		}
-	};
-
-	/* QSA/matchesSelector
-	---------------------------------------------------------------------- */
-
-	// QSA and matchesSelector support
-
-	// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
-	rbuggyMatches = [];
-
-	// qSa(:focus) reports false when true (Chrome 21)
-	// We allow this because of a bug in IE8/9 that throws an error
-	// whenever `document.activeElement` is accessed on an iframe
-	// So, we allow :focus to pass through QSA all the time to avoid the IE error
-	// See http://bugs.jquery.com/ticket/13378
-	rbuggyQSA = [];
-
-	if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
-		// Build QSA regex
-		// Regex strategy adopted from Diego Perini
-		assert(function( div ) {
-			// Select is set to empty string on purpose
-			// This is to test IE's treatment of not explicitly
-			// setting a boolean content attribute,
-			// since its presence should be enough
-			// http://bugs.jquery.com/ticket/12359
-			div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
-
-			// Support: IE8, Opera 11-12.16
-			// Nothing should be selected when empty strings follow ^= or $= or *=
-			// The test attribute must be unknown in Opera but "safe" for WinRT
-			// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
-			if ( div.querySelectorAll("[msallowclip^='']").length ) {
-				rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
-			}
-
-			// Support: IE8
-			// Boolean attributes and "value" are not treated correctly
-			if ( !div.querySelectorAll("[selected]").length ) {
-				rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
-			}
-
-			// Webkit/Opera - :checked should return selected option elements
-			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
-			// IE8 throws error here and will not see later tests
-			if ( !div.querySelectorAll(":checked").length ) {
-				rbuggyQSA.push(":checked");
-			}
-		});
-
-		assert(function( div ) {
-			// Support: Windows 8 Native Apps
-			// The type and name attributes are restricted during .innerHTML assignment
-			var input = doc.createElement("input");
-			input.setAttribute( "type", "hidden" );
-			div.appendChild( input ).setAttribute( "name", "D" );
-
-			// Support: IE8
-			// Enforce case-sensitivity of name attribute
-			if ( div.querySelectorAll("[name=d]").length ) {
-				rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
-			}
-
-			// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
-			// IE8 throws error here and will not see later tests
-			if ( !div.querySelectorAll(":enabled").length ) {
-				rbuggyQSA.push( ":enabled", ":disabled" );
-			}
-
-			// Opera 10-11 does not throw on post-comma invalid pseudos
-			div.querySelectorAll("*,:x");
-			rbuggyQSA.push(",.*:");
-		});
-	}
-
-	if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
-		docElem.webkitMatchesSelector ||
-		docElem.mozMatchesSelector ||
-		docElem.oMatchesSelector ||
-		docElem.msMatchesSelector) )) ) {
-
-		assert(function( div ) {
-			// Check to see if it's possible to do matchesSelector
-			// on a disconnected node (IE 9)
-			support.disconnectedMatch = matches.call( div, "div" );
-
-			// This should fail with an exception
-			// Gecko does not error, returns false instead
-			matches.call( div, "[s!='']:x" );
-			rbuggyMatches.push( "!=", pseudos );
-		});
-	}
-
-	rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
-	rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
-
-	/* Contains
-	---------------------------------------------------------------------- */
-	hasCompare = rnative.test( docElem.compareDocumentPosition );
-
-	// Element contains another
-	// Purposefully does not implement inclusive descendent
-	// As in, an element does not contain itself
-	contains = hasCompare || rnative.test( docElem.contains ) ?
-		function( a, b ) {
-			var adown = a.nodeType === 9 ? a.documentElement : a,
-				bup = b && b.parentNode;
-			return a === bup || !!( bup && bup.nodeType === 1 && (
-				adown.contains ?
-					adown.contains( bup ) :
-					a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
-			));
-		} :
-		function( a, b ) {
-			if ( b ) {
-				while ( (b = b.parentNode) ) {
-					if ( b === a ) {
-						return true;
-					}
-				}
-			}
-			return false;
-		};
-
-	/* Sorting
-	---------------------------------------------------------------------- */
-
-	// Document order sorting
-	sortOrder = hasCompare ?
-	function( a, b ) {
-
-		// Flag for duplicate removal
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-		}
-
-		// Sort on method existence if only one input has compareDocumentPosition
-		var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
-		if ( compare ) {
-			return compare;
-		}
-
-		// Calculate position if both inputs belong to the same document
-		compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
-			a.compareDocumentPosition( b ) :
-
-			// Otherwise we know they are disconnected
-			1;
-
-		// Disconnected nodes
-		if ( compare & 1 ||
-			(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
-
-			// Choose the first element that is related to our preferred document
-			if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
-				return -1;
-			}
-			if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
-				return 1;
-			}
-
-			// Maintain original order
-			return sortInput ?
-				( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
-				0;
-		}
-
-		return compare & 4 ? -1 : 1;
-	} :
-	function( a, b ) {
-		// Exit early if the nodes are identical
-		if ( a === b ) {
-			hasDuplicate = true;
-			return 0;
-		}
-
-		var cur,
-			i = 0,
-			aup = a.parentNode,
-			bup = b.parentNode,
-			ap = [ a ],
-			bp = [ b ];
-
-		// Parentless nodes are either documents or disconnected
-		if ( !aup || !bup ) {
-			return a === doc ? -1 :
-				b === doc ? 1 :
-				aup ? -1 :
-				bup ? 1 :
-				sortInput ?
-				( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
-				0;
-
-		// If the nodes are siblings, we can do a quick check
-		} else if ( aup === bup ) {
-			return siblingCheck( a, b );
-		}
-
-		// Otherwise we need full lists of their ancestors for comparison
-		cur = a;
-		while ( (cur = cur.parentNode) ) {
-			ap.unshift( cur );
-		}
-		cur = b;
-		while ( (cur = cur.parentNode) ) {
-			bp.unshift( cur );
-		}
-
-		// Walk down the tree looking for a discrepancy
-		while ( ap[i] === bp[i] ) {
-			i++;
-		}
-
-		return i ?
-			// Do a sibling check if the nodes have a common ancestor
-			siblingCheck( ap[i], bp[i] ) :
-
-			// Otherwise nodes in our document sort first
-			ap[i] === preferredDoc ? -1 :
-			bp[i] === preferredDoc ? 1 :
-			0;
-	};
-
-	return doc;
-};
-
-Sizzle.matches = function( expr, elements ) {
-	return Sizzle( expr, null, null, elements );
-};
-
-Sizzle.matchesSelector = function( elem, expr ) {
-	// Set document vars if needed
-	if ( ( elem.ownerDocument || elem ) !== document ) {
-		setDocument( elem );
-	}
-
-	// Make sure that attribute selectors are quoted
-	expr = expr.replace( rattributeQuotes, "='$1']" );
-
-	if ( support.matchesSelector && documentIsHTML &&
-		( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
-		( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {
-
-		try {
-			var ret = matches.call( elem, expr );
-
-			// IE 9's matchesSelector returns false on disconnected nodes
-			if ( ret || support.disconnectedMatch ||
-					// As well, disconnected nodes are said to be in a document
-					// fragment in IE 9
-					elem.document && elem.document.nodeType !== 11 ) {
-				return ret;
-			}
-		} catch(e) {}
-	}
-
-	return Sizzle( expr, document, null, [ elem ] ).length > 0;
-};
-
-Sizzle.contains = function( context, elem ) {
-	// Set document vars if needed
-	if ( ( context.ownerDocument || context ) !== document ) {
-		setDocument( context );
-	}
-	return contains( context, elem );
-};
-
-Sizzle.attr = function( elem, name ) {
-	// Set document vars if needed
-	if ( ( elem.ownerDocument || elem ) !== document ) {
-		setDocument( elem );
-	}
-
-	var fn = Expr.attrHandle[ name.toLowerCase() ],
-		// Don't get fooled by Object.prototype properties (jQuery #13807)
-		val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
-			fn( elem, name, !documentIsHTML ) :
-			undefined;
-
-	return val !== undefined ?
-		val :
-		support.attributes || !documentIsHTML ?
-			elem.getAttribute( name ) :
-			(val = elem.getAttributeNode(name)) && val.specified ?
-				val.value :
-				null;
-};
-
-Sizzle.error = function( msg ) {
-	throw new Error( "Syntax error, unrecognized expression: " + msg );
-};
-
-/**
- * Document sorting and removing duplicates
- * @param {ArrayLike} results
- */
-Sizzle.uniqueSort = function( results ) {
-	var elem,
-		duplicates = [],
-		j = 0,
-		i = 0;
-
-	// Unless we *know* we can detect duplicates, assume their presence
-	hasDuplicate = !support.detectDuplicates;
-	sortInput = !support.sortStable && results.slice( 0 );
-	results.sort( sortOrder );
-
-	if ( hasDuplicate ) {
-		while ( (elem = results[i++]) ) {
-			if ( elem === results[ i ] ) {
-				j = duplicates.push( i );
-			}
-		}
-		while ( j-- ) {
-			results.splice( duplicates[ j ], 1 );
-		}
-	}
-
-	// Clear input after sorting to release objects
-	// See https://github.com/jquery/sizzle/pull/225
-	sortInput = null;
-
-	return results;
-};
-
-/**
- * Utility function for retrieving the text value of an array of DOM nodes
- * @param {Array|Element} elem
- */
-getText = Sizzle.getText = function( elem ) {
-	var node,
-		ret = "",
-		i = 0,
-		nodeType = elem.nodeType;
-
-	if ( !nodeType ) {
-		// If no nodeType, this is expected to be an array
-		while ( (node = elem[i++]) ) {
-			// Do not traverse comment nodes
-			ret += getText( node );
-		}
-	} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
-		// Use textContent for elements
-		// innerText usage removed for consistency of new lines (jQuery #11153)
-		if ( typeof elem.textContent === "string" ) {
-			return elem.textContent;
-		} else {
-			// Traverse its children
-			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
-				ret += getText( elem );
-			}
-		}
-	} else if ( nodeType === 3 || nodeType === 4 ) {
-		return elem.nodeValue;
-	}
-	// Do not include comment or processing instruction nodes
-
-	return ret;
-};
-
-Expr = Sizzle.selectors = {
-
-	// Can be adjusted by the user
-	cacheLength: 50,
-
-	createPseudo: markFunction,
-
-	match: matchExpr,
-
-	attrHandle: {},
-
-	find: {},
-
-	relative: {
-		">": { dir: "parentNode", first: true },
-		" ": { dir: "parentNode" },
-		"+": { dir: "previousSibling", first: true },
-		"~": { dir: "previousSibling" }
-	},
-
-	preFilter: {
-		"ATTR": function( match ) {
-			match[1] = match[1].replace( runescape, funescape );
-
-			// Move the given value to match[3] whether quoted or unquoted
-			match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
-
-			if ( match[2] === "~=" ) {
-				match[3] = " " + match[3] + " ";
-			}
-
-			return match.slice( 0, 4 );
-		},
-
-		"CHILD": function( match ) {
-			/* matches from matchExpr["CHILD"]
-				1 type (only|nth|...)
-				2 what (child|of-type)
-				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
-				4 xn-component of xn+y argument ([+-]?\d*n|)
-				5 sign of xn-component
-				6 x of xn-component
-				7 sign of y-component
-				8 y of y-component
-			*/
-			match[1] = match[1].toLowerCase();
-
-			if ( match[1].slice( 0, 3 ) === "nth" ) {
-				// nth-* requires argument
-				if ( !match[3] ) {
-					Sizzle.error( match[0] );
-				}
-
-				// numeric x and y parameters for Expr.filter.CHILD
-				// remember that false/true cast respectively to 0/1
-				match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
-				match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
-
-			// other types prohibit arguments
-			} else if ( match[3] ) {
-				Sizzle.error( match[0] );
-			}
-
-			return match;
-		},
-
-		"PSEUDO": function( match ) {
-			var excess,
-				unquoted = !match[6] && match[2];
-
-			if ( matchExpr["CHILD"].test( match[0] ) ) {
-				return null;
-			}
-
-			// Accept quoted arguments as-is
-			if ( match[3] ) {
-				match[2] = match[4] || match[5] || "";
-
-			// Strip excess characters from unquoted arguments
-			} else if ( unquoted && rpseudo.test( unquoted ) &&
-				// Get excess from tokenize (recursively)
-				(excess = tokenize( unquoted, true )) &&
-				// advance to the next closing parenthesis
-				(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
-
-				// excess is a negative index
-				match[0] = match[0].slice( 0, excess );
-				match[2] = unquoted.slice( 0, excess );
-			}
-
-			// Return only captures needed by the pseudo filter method (type and argument)
-			return match.slice( 0, 3 );
-		}
-	},
-
-	filter: {
-
-		"TAG": function( nodeNameSelector ) {
-			var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
-			return nodeNameSelector === "*" ?
-				function() { return true; } :
-				function( elem ) {
-					return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
-				};
-		},
-
-		"CLASS": function( className ) {
-			var pattern = classCache[ className + " " ];
-
-			return pattern ||
-				(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
-				classCache( className, function( elem ) {
-					return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
-				});
-		},
-
-		"ATTR": function( name, operator, check ) {
-			return function( elem ) {
-				var result = Sizzle.attr( elem, name );
-
-				if ( result == null ) {
-					return operator === "!=";
-				}
-				if ( !operator ) {
-					return true;
-				}
-
-				result += "";
-
-				return operator === "=" ? result === check :
-					operator === "!=" ? result !== check :
-					operator === "^=" ? check && result.indexOf( check ) === 0 :
-					operator === "*=" ? check && result.indexOf( check ) > -1 :
-					operator === "$=" ? check && result.slice( -check.length ) === check :
-					operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
-					operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
-					false;
-			};
-		},
-
-		"CHILD": function( type, what, argument, first, last ) {
-			var simple = type.slice( 0, 3 ) !== "nth",
-				forward = type.slice( -4 ) !== "last",
-				ofType = what === "of-type";
-
-			return first === 1 && last === 0 ?
-
-				// Shortcut for :nth-*(n)
-				function( elem ) {
-					return !!elem.parentNode;
-				} :
-
-				function( elem, context, xml ) {
-					var cache, outerCache, node, diff, nodeIndex, start,
-						dir = simple !== forward ? "nextSibling" : "previousSibling",
-						parent = elem.parentNode,
-						name = ofType && elem.nodeName.toLowerCase(),
-						useCache = !xml && !ofType;
-
-					if ( parent ) {
-
-						// :(first|last|only)-(child|of-type)
-						if ( simple ) {
-							while ( dir ) {
-								node = elem;
-								while ( (node = node[ dir ]) ) {
-									if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
-										return false;
-									}
-								}
-								// Reverse direction for :only-* (if we haven't yet done so)
-								start = dir = type === "only" && !start && "nextSibling";
-							}
-							return true;
-						}
-
-						start = [ forward ? parent.firstChild : parent.lastChild ];
-
-						// non-xml :nth-child(...) stores cache data on `parent`
-						if ( forward && useCache ) {
-							// Seek `elem` from a previously-cached index
-							outerCache = parent[ expando ] || (parent[ expando ] = {});
-							cache = outerCache[ type ] || [];
-							nodeIndex = cache[0] === dirruns && cache[1];
-							diff = cache[0] === dirruns && cache[2];
-							node = nodeIndex && parent.childNodes[ nodeIndex ];
-
-							while ( (node = ++nodeIndex && node && node[ dir ] ||
-
-								// Fallback to seeking `elem` from the start
-								(diff = nodeIndex = 0) || start.pop()) ) {
-
-								// When found, cache indexes on `parent` and break
-								if ( node.nodeType === 1 && ++diff && node === elem ) {
-									outerCache[ type ] = [ dirruns, nodeIndex, diff ];
-									break;
-								}
-							}
-
-						// Use previously-cached element index if available
-						} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
-							diff = cache[1];
-
-						// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
-						} else {
-							// Use the same loop as above to seek `elem` from the start
-							while ( (node = ++nodeIndex && node && node[ dir ] ||
-								(diff = nodeIndex = 0) || start.pop()) ) {
-
-								if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
-									// Cache the index of each encountered element
-									if ( useCache ) {
-										(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
-									}
-
-									if ( node === elem ) {
-										break;
-									}
-								}
-							}
-						}
-
-						// Incorporate the offset, then check against cycle size
-						diff -= last;
-						return diff === first || ( diff % first === 0 && diff / first >= 0 );
-					}
-				};
-		},
-
-		"PSEUDO": function( pseudo, argument ) {
-			// pseudo-class names are case-insensitive
-			// http://www.w3.org/TR/selectors/#pseudo-classes
-			// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
-			// Remember that setFilters inherits from pseudos
-			var args,
-				fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
-					Sizzle.error( "unsupported pseudo: " + pseudo );
-
-			// The user may use createPseudo to indicate that
-			// arguments are needed to create the filter function
-			// just as Sizzle does
-			if ( fn[ expando ] ) {
-				return fn( argument );
-			}
-
-			// But maintain support for old signatures
-			if ( fn.length > 1 ) {
-				args = [ pseudo, pseudo, "", argument ];
-				return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
-					markFunction(function( seed, matches ) {
-						var idx,
-							matched = fn( seed, argument ),
-							i = matched.length;
-						while ( i-- ) {
-							idx = indexOf.call( seed, matched[i] );
-							seed[ idx ] = !( matches[ idx ] = matched[i] );
-						}
-					}) :
-					function( elem ) {
-						return fn( elem, 0, args );
-					};
-			}
-
-			return fn;
-		}
-	},
-
-	pseudos: {
-		// Potentially complex pseudos
-		"not": markFunction(function( selector ) {
-			// Trim the selector passed to compile
-			// to avoid treating leading and trailing
-			// spaces as combinators
-			var input = [],
-				results = [],
-				matcher = compile( selector.replace( rtrim, "$1" ) );
-
-			return matcher[ expando ] ?
-				markFunction(function( seed, matches, context, xml ) {
-					var elem,
-						unmatched = matcher( seed, null, xml, [] ),
-						i = seed.length;
-
-					// Match elements unmatched by `matcher`
-					while ( i-- ) {
-						if ( (elem = unmatched[i]) ) {
-							seed[i] = !(matches[i] = elem);
-						}
-					}
-				}) :
-				function( elem, context, xml ) {
-					input[0] = elem;
-					matcher( input, null, xml, results );
-					return !results.pop();
-				};
-		}),
-
-		"has": markFunction(function( selector ) {
-			return function( elem ) {
-				return Sizzle( selector, elem ).length > 0;
-			};
-		}),
-
-		"contains": markFunction(function( text ) {
-			return function( elem ) {
-				return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
-			};
-		}),
-
-		// "Whether an element is represented by a :lang() selector
-		// is based solely on the element's language value
-		// being equal to the identifier C,
-		// or beginning with the identifier C immediately followed by "-".
-		// The matching of C against the element's language value is performed case-insensitively.
-		// The identifier C does not have to be a valid language name."
-		// http://www.w3.org/TR/selectors/#lang-pseudo
-		"lang": markFunction( function( lang ) {
-			// lang value must be a valid identifier
-			if ( !ridentifier.test(lang || "") ) {
-				Sizzle.error( "unsupported lang: " + lang );
-			}
-			lang = lang.replace( runescape, funescape ).toLowerCase();
-			return function( elem ) {
-				var elemLang;
-				do {
-					if ( (elemLang = documentIsHTML ?
-						elem.lang :
-						elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
-
-						elemLang = elemLang.toLowerCase();
-						return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
-					}
-				} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
-				return false;
-			};
-		}),
-
-		// Miscellaneous
-		"target": function( elem ) {
-			var hash = window.location && window.location.hash;
-			return hash && hash.slice( 1 ) === elem.id;
-		},
-
-		"root": function( elem ) {
-			return elem === docElem;
-		},
-
-		"focus": function( elem ) {
-			return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
-		},
-
-		// Boolean properties
-		"enabled": function( elem ) {
-			return elem.disabled === false;
-		},
-
-		"disabled": function( elem ) {
-			return elem.disabled === true;
-		},
-
-		"checked": function( elem ) {
-			// In CSS3, :checked should return both checked and selected elements
-			// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
-			var nodeName = elem.nodeName.toLowerCase();
-			return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
-		},
-
-		"selected": function( elem ) {
-			// Accessing this property makes selected-by-default
-			// options in Safari work properly
-			if ( elem.parentNode ) {
-				elem.parentNode.selectedIndex;
-			}
-
-			return elem.selected === true;
-		},
-
-		// Contents
-		"empty": function( elem ) {
-			// http://www.w3.org/TR/selectors/#empty-pseudo
-			// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
-			//   but not by others (comment: 8; processing instruction: 7; etc.)
-			// nodeType < 6 works because attributes (2) do not appear as children
-			for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
-				if ( elem.nodeType < 6 ) {
-					return false;
-				}
-			}
-			return true;
-		},
-
-		"parent": function( elem ) {
-			return !Expr.pseudos["empty"]( elem );
-		},
-
-		// Element/input types
-		"header": function( elem ) {
-			return rheader.test( elem.nodeName );
-		},
-
-		"input": function( elem ) {
-			return rinputs.test( elem.nodeName );
-		},
-
-		"button": function( elem ) {
-			var name = elem.nodeName.toLowerCase();
-			return name === "input" && elem.type === "button" || name === "button";
-		},
-
-		"text": function( elem ) {
-			var attr;
-			return elem.nodeName.toLowerCase() === "input" &&
-				elem.type === "text" &&
-
-				// Support: IE<8
-				// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
-				( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
-		},
-
-		// Position-in-collection
-		"first": createPositionalPseudo(function() {
-			return [ 0 ];
-		}),
-
-		"last": createPositionalPseudo(function( matchIndexes, length ) {
-			return [ length - 1 ];
-		}),
-
-		"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
-			return [ argument < 0 ? argument + length : argument ];
-		}),
-
-		"even": createPositionalPseudo(function( matchIndexes, length ) {
-			var i = 0;
-			for ( ; i < length; i += 2 ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		}),
-
-		"odd": createPositionalPseudo(function( matchIndexes, length ) {
-			var i = 1;
-			for ( ; i < length; i += 2 ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		}),
-
-		"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
-			var i = argument < 0 ? argument + length : argument;
-			for ( ; --i >= 0; ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		}),
-
-		"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
-			var i = argument < 0 ? argument + length : argument;
-			for ( ; ++i < length; ) {
-				matchIndexes.push( i );
-			}
-			return matchIndexes;
-		})
-	}
-};
-
-Expr.pseudos["nth"] = Expr.pseudos["eq"];
-
-// Add button/input type pseudos
-for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
-	Expr.pseudos[ i ] = createInputPseudo( i );
-}
-for ( i in { submit: true, reset: true } ) {
-	Expr.pseudos[ i ] = createButtonPseudo( i );
-}
-
-// Easy API for creating new setFilters
-function setFilters() {}
-setFilters.prototype = Expr.filters = Expr.pseudos;
-Expr.setFilters = new setFilters();
-
-tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
-	var matched, match, tokens, type,
-		soFar, groups, preFilters,
-		cached = tokenCache[ selector + " " ];
-
-	if ( cached ) {
-		return parseOnly ? 0 : cached.slice( 0 );
-	}
-
-	soFar = selector;
-	groups = [];
-	preFilters = Expr.preFilter;
-
-	while ( soFar ) {
-
-		// Comma and first run
-		if ( !matched || (match = rcomma.exec( soFar )) ) {
-			if ( match ) {
-				// Don't consume trailing commas as valid
-				soFar = soFar.slice( match[0].length ) || soFar;
-			}
-			groups.push( (tokens = []) );
-		}
-
-		matched = false;
-
-		// Combinators
-		if ( (match = rcombinators.exec( soFar )) ) {
-			matched = match.shift();
-			tokens.push({
-				value: matched,
-				// Cast descendant combinators to space
-				type: match[0].replace( rtrim, " " )
-			});
-			soFar = soFar.slice( matched.length );
-		}
-
-		// Filters
-		for ( type in Expr.filter ) {
-			if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
-				(match = preFilters[ type ]( match ))) ) {
-				matched = match.shift();
-				tokens.push({
-					value: matched,
-					type: type,
-					matches: match
-				});
-				soFar = soFar.slice( matched.length );
-			}
-		}
-
-		if ( !matched ) {
-			break;
-		}
-	}
-
-	// Return the length of the invalid excess
-	// if we're just parsing
-	// Otherwise, throw an error or return tokens
-	return parseOnly ?
-		soFar.length :
-		soFar ?
-			Sizzle.error( selector ) :
-			// Cache the tokens
-			tokenCache( selector, groups ).slice( 0 );
-};
-
-function toSelector( tokens ) {
-	var i = 0,
-		len = tokens.length,
-		selector = "";
-	for ( ; i < len; i++ ) {
-		selector += tokens[i].value;
-	}
-	return selector;
-}
-
-function addCombinator( matcher, combinator, base ) {
-	var dir = combinator.dir,
-		checkNonElements = base && dir === "parentNode",
-		doneName = done++;
-
-	return combinator.first ?
-		// Check against closest ancestor/preceding element
-		function( elem, context, xml ) {
-			while ( (elem = elem[ dir ]) ) {
-				if ( elem.nodeType === 1 || checkNonElements ) {
-					return matcher( elem, context, xml );
-				}
-			}
-		} :
-
-		// Check against all ancestor/preceding elements
-		function( elem, context, xml ) {
-			var oldCache, outerCache,
-				newCache = [ dirruns, doneName ];
-
-			// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
-			if ( xml ) {
-				while ( (elem = elem[ dir ]) ) {
-					if ( elem.nodeType === 1 || checkNonElements ) {
-						if ( matcher( elem, context, xml ) ) {
-							return true;
-						}
-					}
-				}
-			} else {
-				while ( (elem = elem[ dir ]) ) {
-					if ( elem.nodeType === 1 || checkNonElements ) {
-						outerCache = elem[ expando ] || (elem[ expando ] = {});
-						if ( (oldCache = outerCache[ dir ]) &&
-							oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
-
-							// Assign to newCache so results back-propagate to previous elements
-							return (newCache[ 2 ] = oldCache[ 2 ]);
-						} else {
-							// Reuse newcache so results back-propagate to previous elements
-							outerCache[ dir ] = newCache;
-
-							// A match means we're done; a fail means we have to keep checking
-							if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
-								return true;
-							}
-						}
-					}
-				}
-			}
-		};
-}
-
-function elementMatcher( matchers ) {
-	return matchers.length > 1 ?
-		function( elem, context, xml ) {
-			var i = matchers.length;
-			while ( i-- ) {
-				if ( !matchers[i]( elem, context, xml ) ) {
-					return false;
-				}
-			}
-			return true;
-		} :
-		matchers[0];
-}
-
-function multipleContexts( selector, contexts, results ) {
-	var i = 0,
-		len = contexts.length;
-	for ( ; i < len; i++ ) {
-		Sizzle( selector, contexts[i], results );
-	}
-	return results;
-}
-
-function condense( unmatched, map, filter, context, xml ) {
-	var elem,
-		newUnmatched = [],
-		i = 0,
-		len = unmatched.length,
-		mapped = map != null;
-
-	for ( ; i < len; i++ ) {
-		if ( (elem = unmatched[i]) ) {
-			if ( !filter || filter( elem, context, xml ) ) {
-				newUnmatched.push( elem );
-				if ( mapped ) {
-					map.push( i );
-				}
-			}
-		}
-	}
-
-	return newUnmatched;
-}
-
-function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
-	if ( postFilter && !postFilter[ expando ] ) {
-		postFilter = setMatcher( postFilter );
-	}
-	if ( postFinder && !postFinder[ expando ] ) {
-		postFinder = setMatcher( postFinder, postSelector );
-	}
-	return markFunction(function( seed, results, context, xml ) {
-		var temp, i, elem,
-			preMap = [],
-			postMap = [],
-			preexisting = results.length,
-
-			// Get initial elements from seed or context
-			elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
-
-			// Prefilter to get matcher input, preserving a map for seed-results synchronization
-			matcherIn = preFilter && ( seed || !selector ) ?
-				condense( elems, preMap, preFilter, context, xml ) :
-				elems,
-
-			matcherOut = matcher ?
-				// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
-				postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
-
-					// ...intermediate processing is necessary
-					[] :
-
-					// ...otherwise use results directly
-					results :
-				matcherIn;
-
-		// Find primary matches
-		if ( matcher ) {
-			matcher( matcherIn, matcherOut, context, xml );
-		}
-
-		// Apply postFilter
-		if ( postFilter ) {
-			temp = condense( matcherOut, postMap );
-			postFilter( temp, [], context, xml );
-
-			// Un-match failing elements by moving them back to matcherIn
-			i = temp.length;
-			while ( i-- ) {
-				if ( (elem = temp[i]) ) {
-					matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
-				}
-			}
-		}
-
-		if ( seed ) {
-			if ( postFinder || preFilter ) {
-				if ( postFinder ) {
-					// Get the final matcherOut by condensing this intermediate into postFinder contexts
-					temp = [];
-					i = matcherOut.length;
-					while ( i-- ) {
-						if ( (elem = matcherOut[i]) ) {
-							// Restore matcherIn since elem is not yet a final match
-							temp.push( (matcherIn[i] = elem) );
-						}
-					}
-					postFinder( null, (matcherOut = []), temp, xml );
-				}
-
-				// Move matched elements from seed to results to keep them synchronized
-				i = matcherOut.length;
-				while ( i-- ) {
-					if ( (elem = matcherOut[i]) &&
-						(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
-
-						seed[temp] = !(results[temp] = elem);
-					}
-				}
-			}
-
-		// Add elements to results, through postFinder if defined
-		} else {
-			matcherOut = condense(
-				matcherOut === results ?
-					matcherOut.splice( preexisting, matcherOut.length ) :
-					matcherOut
-			);
-			if ( postFinder ) {
-				postFinder( null, results, matcherOut, xml );
-			} else {
-				push.apply( results, matcherOut );
-			}
-		}
-	});
-}
-
-function matcherFromTokens( tokens ) {
-	var checkContext, matcher, j,
-		len = tokens.length,
-		leadingRelative = Expr.relative[ tokens[0].type ],
-		implicitRelative = leadingRelative || Expr.relative[" "],
-		i = leadingRelative ? 1 : 0,
-
-		// The foundational matcher ensures that elements are reachable from top-level context(s)
-		matchContext = addCombinator( function( elem ) {
-			return elem === checkContext;
-		}, implicitRelative, true ),
-		matchAnyContext = addCombinator( function( elem ) {
-			return indexOf.call( checkContext, elem ) > -1;
-		}, implicitRelative, true ),
-		matchers = [ function( elem, context, xml ) {
-			return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
-				(checkContext = context).nodeType ?
-					matchContext( elem, context, xml ) :
-					matchAnyContext( elem, context, xml ) );
-		} ];
-
-	for ( ; i < len; i++ ) {
-		if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
-			matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
-		} else {
-			matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
-
-			// Return special upon seeing a positional matcher
-			if ( matcher[ expando ] ) {
-				// Find the next relative operator (if any) for proper handling
-				j = ++i;
-				for ( ; j < len; j++ ) {
-					if ( Expr.relative[ tokens[j].type ] ) {
-						break;
-					}
-				}
-				return setMatcher(
-					i > 1 && elementMatcher( matchers ),
-					i > 1 && toSelector(
-						// If the preceding token was a descendant combinator, insert an implicit any-element `*`
-						tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
-					).replace( rtrim, "$1" ),
-					matcher,
-					i < j && matcherFromTokens( tokens.slice( i, j ) ),
-					j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
-					j < len && toSelector( tokens )
-				);
-			}
-			matchers.push( matcher );
-		}
-	}
-
-	return elementMatcher( matchers );
-}
-
-function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
-	var bySet = setMatchers.length > 0,
-		byElement = elementMatchers.length > 0,
-		superMatcher = function( seed, context, xml, results, outermost ) {
-			var elem, j, matcher,
-				matchedCount = 0,
-				i = "0",
-				unmatched = seed && [],
-				setMatched = [],
-				contextBackup = outermostContext,
-				// We must always have either seed elements or outermost context
-				elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
-				// Use integer dirruns iff this is the outermost matcher
-				dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
-				len = elems.length;
-
-			if ( outermost ) {
-				outermostContext = context !== document && context;
-			}
-
-			// Add elements passing elementMatchers directly to results
-			// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
-			// Support: IE<9, Safari
-			// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
-			for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
-				if ( byElement && elem ) {
-					j = 0;
-					while ( (matcher = elementMatchers[j++]) ) {
-						if ( matcher( elem, context, xml ) ) {
-							results.push( elem );
-							break;
-						}
-					}
-					if ( outermost ) {
-						dirruns = dirrunsUnique;
-					}
-				}
-
-				// Track unmatched elements for set filters
-				if ( bySet ) {
-					// They will have gone through all possible matchers
-					if ( (elem = !matcher && elem) ) {
-						matchedCount--;
-					}
-
-					// Lengthen the array for every element, matched or not
-					if ( seed ) {
-						unmatched.push( elem );
-					}
-				}
-			}
-
-			// Apply set filters to unmatched elements
-			matchedCount += i;
-			if ( bySet && i !== matchedCount ) {
-				j = 0;
-				while ( (matcher = setMatchers[j++]) ) {
-					matcher( unmatched, setMatched, context, xml );
-				}
-
-				if ( seed ) {
-					// Reintegrate element matches to eliminate the need for sorting
-					if ( matchedCount > 0 ) {
-						while ( i-- ) {
-							if ( !(unmatched[i] || setMatched[i]) ) {
-								setMatched[i] = pop.call( results );
-							}
-						}
-					}
-
-					// Discard index placeholder values to get only actual matches
-					setMatched = condense( setMatched );
-				}
-
-				// Add matches to results
-				push.apply( results, setMatched );
-
-				// Seedless set matches succeeding multiple successful matchers stipulate sorting
-				if ( outermost && !seed && setMatched.length > 0 &&
-					( matchedCount + setMatchers.length ) > 1 ) {
-
-					Sizzle.uniqueSort( results );
-				}
-			}
-
-			// Override manipulation of globals by nested matchers
-			if ( outermost ) {
-				dirruns = dirrunsUnique;
-				outermostContext = contextBackup;
-			}
-
-			return unmatched;
-		};
-
-	return bySet ?
-		markFunction( superMatcher ) :
-		superMatcher;
-}
-
-compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
-	var i,
-		setMatchers = [],
-		elementMatchers = [],
-		cached = compilerCache[ selector + " " ];
-
-	if ( !cached ) {
-		// Generate a function of recursive functions that can be used to check each element
-		if ( !match ) {
-			match = tokenize( selector );
-		}
-		i = match.length;
-		while ( i-- ) {
-			cached = matcherFromTokens( match[i] );
-			if ( cached[ expando ] ) {
-				setMatchers.push( cached );
-			} else {
-				elementMatchers.push( cached );
-			}
-		}
-
-		// Cache the compiled function
-		cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
-
-		// Save selector and tokenization
-		cached.selector = selector;
-	}
-	return cached;
-};
-
-/**
- * A low-level selection function that works with Sizzle's compiled
- *  selector functions
- * @param {String|Function} selector A selector or a pre-compiled
- *  selector function built with Sizzle.compile
- * @param {Element} context
- * @param {Array} [results]
- * @param {Array} [seed] A set of elements to match against
- */
-select = Sizzle.select = function( selector, context, results, seed ) {
-	var i, tokens, token, type, find,
-		compiled = typeof selector === "function" && selector,
-		match = !seed && tokenize( (selector = compiled.selector || selector) );
-
-	results = results || [];
-
-	// Try to minimize operations if there is no seed and only one group
-	if ( match.length === 1 ) {
-
-		// Take a shortcut and set the context if the root selector is an ID
-		tokens = match[0] = match[0].slice( 0 );
-		if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
-				support.getById && context.nodeType === 9 && documentIsHTML &&
-				Expr.relative[ tokens[1].type ] ) {
-
-			context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
-			if ( !context ) {
-				return results;
-
-			// Precompiled matchers will still verify ancestry, so step up a level
-			} else if ( compiled ) {
-				context = context.parentNode;
-			}
-
-			selector = selector.slice( tokens.shift().value.length );
-		}
-
-		// Fetch a seed set for right-to-left matching
-		i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
-		while ( i-- ) {
-			token = tokens[i];
-
-			// Abort if we hit a combinator
-			if ( Expr.relative[ (type = token.type) ] ) {
-				break;
-			}
-			if ( (find = Expr.find[ type ]) ) {
-				// Search, expanding context for leading sibling combinators
-				if ( (seed = find(
-					token.matches[0].replace( runescape, funescape ),
-					rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
-				)) ) {
-
-					// If seed is empty or no tokens remain, we can return early
-					tokens.splice( i, 1 );
-					selector = seed.length && toSelector( tokens );
-					if ( !selector ) {
-						push.apply( results, seed );
-						return results;
-					}
-
-					break;
-				}
-			}
-		}
-	}
-
-	// Compile and execute a filtering function if one is not provided
-	// Provide `match` to avoid retokenization if we modified the selector above
-	( compiled || compile( selector, match ) )(
-		seed,
-		context,
-		!documentIsHTML,
-		results,
-		rsibling.test( selector ) && testContext( context.parentNode ) || context
-	);
-	return results;
-};
-
-// One-time assignments
-
-// Sort stability
-support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
-
-// Support: Chrome<14
-// Always assume duplicates if they aren't passed to the comparison function
-support.detectDuplicates = !!hasDuplicate;
-
-// Initialize against the default document
-setDocument();
-
-// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
-// Detached nodes confoundingly follow *each other*
-support.sortDetached = assert(function( div1 ) {
-	// Should return 1, but returns 4 (following)
-	return div1.compareDocumentPosition( document.createElement("div") ) & 1;
-});
-
-// Support: IE<8
-// Prevent attribute/property "interpolation"
-// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
-if ( !assert(function( div ) {
-	div.innerHTML = "<a href='#'></a>";
-	return div.firstChild.getAttribute("href") === "#" ;
-}) ) {
-	addHandle( "type|href|height|width", function( elem, name, isXML ) {
-		if ( !isXML ) {
-			return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
-		}
-	});
-}
-
-// Support: IE<9
-// Use defaultValue in place of getAttribute("value")
-if ( !support.attributes || !assert(function( div ) {
-	div.innerHTML = "<input/>";
-	div.firstChild.setAttribute( "value", "" );
-	return div.firstChild.getAttribute( "value" ) === "";
-}) ) {
-	addHandle( "value", function( elem, name, isXML ) {
-		if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
-			return elem.defaultValue;
-		}
-	});
-}
-
-// Support: IE<9
-// Use getAttributeNode to fetch booleans when getAttribute lies
-if ( !assert(function( div ) {
-	return div.getAttribute("disabled") == null;
-}) ) {
-	addHandle( booleans, function( elem, name, isXML ) {
-		var val;
-		if ( !isXML ) {
-			return elem[ name ] === true ? name.toLowerCase() :
-					(val = elem.getAttributeNode( name )) && val.specified ?
-					val.value :
-				null;
-		}
-	});
-}
-
-return Sizzle;
-
-})( window );
-
-
-
-jQuery.find = Sizzle;
-jQuery.expr = Sizzle.selectors;
-jQuery.expr[":"] = jQuery.expr.pseudos;
-jQuery.unique = Sizzle.uniqueSort;
-jQuery.text = Sizzle.getText;
-jQuery.isXMLDoc = Sizzle.isXML;
-jQuery.contains = Sizzle.contains;
-
-
-
-var rneedsContext = jQuery.expr.match.needsContext;
-
-var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
-
-
-
-var risSimple = /^.[^:#\[\.,]*$/;
-
-// Implement the identical functionality for filter and not
-function winnow( elements, qualifier, not ) {
-	if ( jQuery.isFunction( qualifier ) ) {
-		return jQuery.grep( elements, function( elem, i ) {
-			/* jshint -W018 */
-			return !!qualifier.call( elem, i, elem ) !== not;
-		});
-
-	}
-
-	if ( qualifier.nodeType ) {
-		return jQuery.grep( elements, function( elem ) {
-			return ( elem === qualifier ) !== not;
-		});
-
-	}
-
-	if ( typeof qualifier === "string" ) {
-		if ( risSimple.test( qualifier ) ) {
-			return jQuery.filter( qualifier, elements, not );
-		}
-
-		qualifier = jQuery.filter( qualifier, elements );
-	}
-
-	return jQuery.grep( elements, function( elem ) {
-		return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
-	});
-}
-
-jQuery.filter = function( expr, elems, not ) {
-	var elem = elems[ 0 ];
-
-	if ( not ) {
-		expr = ":not(" + expr + ")";
-	}
-
-	return elems.length === 1 && elem.nodeType === 1 ?
-		jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
-		jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
-			return elem.nodeType === 1;
-		}));
-};
-
-jQuery.fn.extend({
-	find: function( selector ) {
-		var i,
-			len = this.length,
-			ret = [],
-			self = this;
-
-		if ( typeof selector !== "string" ) {
-			return this.pushStack( jQuery( selector ).filter(function() {
-				for ( i = 0; i < len; i++ ) {
-					if ( jQuery.contains( self[ i ], this ) ) {
-						return true;
-					}
-				}
-			}) );
-		}
-
-		for ( i = 0; i < len; i++ ) {
-			jQuery.find( selector, self[ i ], ret );
-		}
-
-		// Needed because $( selector, context ) becomes $( context ).find( selector )
-		ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
-		ret.selector = this.selector ? this.selector + " " + selector : selector;
-		return ret;
-	},
-	filter: function( selector ) {
-		return this.pushStack( winnow(this, selector || [], false) );
-	},
-	not: function( selector ) {
-		return this.pushStack( winnow(this, selector || [], true) );
-	},
-	is: function( selector ) {
-		return !!winnow(
-			this,
-
-			// If this is a positional/relative selector, check membership in the returned set
-			// so $("p:first").is("p:last") won't return true for a doc with two "p".
-			typeof selector === "string" && rneedsContext.test( selector ) ?
-				jQuery( selector ) :
-				selector || [],
-			false
-		).length;
-	}
-});
-
-
-// Initialize a jQuery object
-
-
-// A central reference to the root jQuery(document)
-var rootjQuery,
-
-	// A simple way to check for HTML strings
-	// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
-	// Strict HTML recognition (#11290: must start with <)
-	rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
-
-	init = jQuery.fn.init = function( selector, context ) {
-		var match, elem;
-
-		// HANDLE: $(""), $(null), $(undefined), $(false)
-		if ( !selector ) {
-			return this;
-		}
-
-		// Handle HTML strings
-		if ( typeof selector === "string" ) {
-			if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
-				// Assume that strings that start and end with <> are HTML and skip the regex check
-				match = [ null, selector, null ];
-
-			} else {
-				match = rquickExpr.exec( selector );
-			}
-
-			// Match html or make sure no context is specified for #id
-			if ( match && (match[1] || !context) ) {
-
-				// HANDLE: $(html) -> $(array)
-				if ( match[1] ) {
-					context = context instanceof jQuery ? context[0] : context;
-
-					// scripts is true for back-compat
-					// Intentionally let the error be thrown if parseHTML is not present
-					jQuery.merge( this, jQuery.parseHTML(
-						match[1],
-						context && context.nodeType ? context.ownerDocument || context : document,
-						true
-					) );
-
-					// HANDLE: $(html, props)
-					if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
-						for ( match in context ) {
-							// Properties of context are called as methods if possible
-							if ( jQuery.isFunction( this[ match ] ) ) {
-								this[ match ]( context[ match ] );
-
-							// ...and otherwise set as attributes
-							} else {
-								this.attr( match, context[ match ] );
-							}
-						}
-					}
-
-					return this;
-
-				// HANDLE: $(#id)
-				} else {
-					elem = document.getElementById( match[2] );
-
-					// Check parentNode to catch when Blackberry 4.6 returns
-					// nodes that are no longer in the document #6963
-					if ( elem && elem.parentNode ) {
-						// Inject the element directly into the jQuery object
-						this.length = 1;
-						this[0] = elem;
-					}
-
-					this.context = document;
-					this.selector = selector;
-					return this;
-				}
-
-			// HANDLE: $(expr, $(...))
-			} else if ( !context || context.jquery ) {
-				return ( context || rootjQuery ).find( selector );
-
-			// HANDLE: $(expr, context)
-			// (which is just equivalent to: $(context).find(expr)
-			} else {
-				return this.constructor( context ).find( selector );
-			}
-
-		// HANDLE: $(DOMElement)
-		} else if ( selector.nodeType ) {
-			this.context = this[0] = selector;
-			this.length = 1;
-			return this;
-
-		// HANDLE: $(function)
-		// Shortcut for document ready
-		} else if ( jQuery.isFunction( selector ) ) {
-			return typeof rootjQuery.ready !== "undefined" ?
-				rootjQuery.ready( selector ) :
-				// Execute immediately if ready is not present
-				selector( jQuery );
-		}
-
-		if ( selector.selector !== undefined ) {
-			this.selector = selector.selector;
-			this.context = selector.context;
-		}
-
-		return jQuery.makeArray( selector, this );
-	};
-
-// Give the init function the jQuery prototype for later instantiation
-init.prototype = jQuery.fn;
-
-// Initialize central reference
-rootjQuery = jQuery( document );
-
-
-var rparentsprev = /^(?:parents|prev(?:Until|All))/,
-	// methods guaranteed to produce a unique set when starting from a unique set
-	guaranteedUnique = {
-		children: true,
-		contents: true,
-		next: true,
-		prev: true
-	};
-
-jQuery.extend({
-	dir: function( elem, dir, until ) {
-		var matched = [],
-			truncate = until !== undefined;
-
-		while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
-			if ( elem.nodeType === 1 ) {
-				if ( truncate && jQuery( elem ).is( until ) ) {
-					break;
-				}
-				matched.push( elem );
-			}
-		}
-		return matched;
-	},
-
-	sibling: function( n, elem ) {
-		var matched = [];
-
-		for ( ; n; n = n.nextSibling ) {
-			if ( n.nodeType === 1 && n !== elem ) {
-				matched.push( n );
-			}
-		}
-
-		return matched;
-	}
-});
-
-jQuery.fn.extend({
-	has: function( target ) {
-		var targets = jQuery( target, this ),
-			l = targets.length;
-
-		return this.filter(function() {
-			var i = 0;
-			for ( ; i < l; i++ ) {
-				if ( jQuery.contains( this, targets[i] ) ) {
-					return true;
-				}
-			}
-		});
-	},
-
-	closest: function( selectors, context ) {
-		var cur,
-			i = 0,
-			l = this.length,
-			matched = [],
-			pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
-				jQuery( selectors, context || this.context ) :
-				0;
-
-		for ( ; i < l; i++ ) {
-			for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
-				// Always skip document fragments
-				if ( cur.nodeType < 11 && (pos ?
-					pos.index(cur) > -1 :
-
-					// Don't pass non-elements to Sizzle
-					cur.nodeType === 1 &&
-						jQuery.find.matchesSelector(cur, selectors)) ) {
-
-					matched.push( cur );
-					break;
-				}
-			}
-		}
-
-		return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
-	},
-
-	// Determine the position of an element within
-	// the matched set of elements
-	index: function( elem ) {
-
-		// No argument, return index in parent
-		if ( !elem ) {
-			return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
-		}
-
-		// index in selector
-		if ( typeof elem === "string" ) {
-			return indexOf.call( jQuery( elem ), this[ 0 ] );
-		}
-
-		// Locate the position of the desired element
-		return indexOf.call( this,
-
-			// If it receives a jQuery object, the first element is used
-			elem.jquery ? elem[ 0 ] : elem
-		);
-	},
-
-	add: function( selector, context ) {
-		return this.pushStack(
-			jQuery.unique(
-				jQuery.merge( this.get(), jQuery( selector, context ) )
-			)
-		);
-	},
-
-	addBack: function( selector ) {
-		return this.add( selector == null ?
-			this.prevObject : this.prevObject.filter(selector)
-		);
-	}
-});
-
-function sibling( cur, dir ) {
-	while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
-	return cur;
-}
-
-jQuery.each({
-	parent: function( elem ) {
-		var parent = elem.parentNode;
-		return parent && parent.nodeType !== 11 ? parent : null;
-	},
-	parents: function( elem ) {
-		return jQuery.dir( elem, "parentNode" );
-	},
-	parentsUntil: function( elem, i, until ) {
-		return jQuery.dir( elem, "parentNode", until );
-	},
-	next: function( elem ) {
-		return sibling( elem, "nextSibling" );
-	},
-	prev: function( elem ) {
-		return sibling( elem, "previousSibling" );
-	},
-	nextAll: function( elem ) {
-		return jQuery.dir( elem, "nextSibling" );
-	},
-	prevAll: function( elem ) {
-		return jQuery.dir( elem, "previousSibling" );
-	},
-	nextUntil: function( elem, i, until ) {
-		return jQuery.dir( elem, "nextSibling", until );
-	},
-	prevUntil: function( elem, i, until ) {
-		return jQuery.dir( elem, "previousSibling", until );
-	},
-	siblings: function( elem ) {
-		return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
-	},
-	children: function( elem ) {
-		return jQuery.sibling( elem.firstChild );
-	},
-	contents: function( elem ) {
-		return elem.contentDocument || jQuery.merge( [], elem.childNodes );
-	}
-}, function( name, fn ) {
-	jQuery.fn[ name ] = function( until, selector ) {
-		var matched = jQuery.map( this, fn, until );
-
-		if ( name.slice( -5 ) !== "Until" ) {
-			selector = until;
-		}
-
-		if ( selector && typeof selector === "string" ) {
-			matched = jQuery.filter( selector, matched );
-		}
-
-		if ( this.length > 1 ) {
-			// Remove duplicates
-			if ( !guaranteedUnique[ name ] ) {
-				jQuery.unique( matched );
-			}
-
-			// Reverse order for parents* and prev-derivatives
-			if ( rparentsprev.test( name ) ) {
-				matched.reverse();
-			}
-		}
-
-		return this.pushStack( matched );
-	};
-});
-var rnotwhite = (/\S+/g);
-
-
-
-// String to Object options format cache
-var optionsCache = {};
-
-// Convert String-formatted options into Object-formatted ones and store in cache
-function createOptions( options ) {
-	var object = optionsCache[ options ] = {};
-	jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
-		object[ flag ] = true;
-	});
-	return object;
-}
-
-/*
- * Create a callback list using the following parameters:
- *
- *	options: an optional list of space-separated options that will change how
- *			the callback list behaves or a more traditional option object
- *
- * By default a callback list will act like an event callback list and can be
- * "fired" multiple times.
- *
- * Possible options:
- *
- *	once:			will ensure the callback list can only be fired once (like a Deferred)
- *
- *	memory:			will keep track of previous values and will call any callback added
- *					after the list has been fired right away with the latest "memorized"
- *					values (like a Deferred)
- *
- *	unique:			will ensure a callback can only be added once (no duplicate in the list)
- *
- *	stopOnFalse:	interrupt callings when a callback returns false
- *
- */
-jQuery.Callbacks = function( options ) {
-
-	// Convert options from String-formatted to Object-formatted if needed
-	// (we check in cache first)
-	options = typeof options === "string" ?
-		( optionsCache[ options ] || createOptions( options ) ) :
-		jQuery.extend( {}, options );
-
-	var // Last fire value (for non-forgettable lists)
-		memory,
-		// Flag to know if list was already fired
-		fired,
-		// Flag to know if list is currently firing
-		firing,
-		// First callback to fire (used internally by add and fireWith)
-		firingStart,
-		// End of the loop when firing
-		firingLength,
-		// Index of currently firing callback (modified by remove if needed)
-		firingIndex,
-		// Actual callback list
-		list = [],
-		// Stack of fire calls for repeatable lists
-		stack = !options.once && [],
-		// Fire callbacks
-		fire = function( data ) {
-			memory = options.memory && data;
-			fired = true;
-			firingIndex = firingStart || 0;
-			firingStart = 0;
-			firingLength = list.length;
-			firing = true;
-			for ( ; list && firingIndex < firingLength; firingIndex++ ) {
-				if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
-					memory = false; // To prevent further calls using add
-					break;
-				}
-			}
-			firing = false;
-			if ( list ) {
-				if ( stack ) {
-					if ( stack.length ) {
-						fire( stack.shift() );
-					}
-				} else if ( memory ) {
-					list = [];
-				} else {
-					self.disable();
-				}
-			}
-		},
-		// Actual Callbacks object
-		self = {
-			// Add a callback or a collection of callbacks to the list
-			add: function() {
-				if ( list ) {
-					// First, we save the current length
-					var start = list.length;
-					(function add( args ) {
-						jQuery.each( args, function( _, arg ) {
-							var type = jQuery.type( arg );
-							if ( type === "function" ) {
-								if ( !options.unique || !self.has( arg ) ) {
-									list.push( arg );
-								}
-							} else if ( arg && arg.length && type !== "string" ) {
-								// Inspect recursively
-								add( arg );
-							}
-						});
-					})( arguments );
-					// Do we need to add the callbacks to the
-					// current firing batch?
-					if ( firing ) {
-						firingLength = list.length;
-					// With memory, if we're not firing then
-					// we should call right away
-					} else if ( memory ) {
-						firingStart = start;
-						fire( memory );
-					}
-				}
-				return this;
-			},
-			// Remove a callback from the list
-			remove: function() {
-				if ( list ) {
-					jQuery.each( arguments, function( _, arg ) {
-						var index;
-						while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
-							list.splice( index, 1 );
-							// Handle firing indexes
-							if ( firing ) {
-								if ( index <= firingLength ) {
-									firingLength--;
-								}
-								if ( index <= firingIndex ) {
-									firingIndex--;
-								}
-							}
-						}
-					});
-				}
-				return this;
-			},
-			// Check if a given callback is in the list.
-			// If no argument is given, return whether or not list has callbacks attached.
-			has: function( fn ) {
-				return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
-			},
-			// Remove all callbacks from the list
-			empty: function() {
-				list = [];
-				firingLength = 0;
-				return this;
-			},
-			// Have the list do nothing anymore
-			disable: function() {
-				list = stack = memory = undefined;
-				return this;
-			},
-			// Is it disabled?
-			disabled: function() {
-				return !list;
-			},
-			// Lock the list in its current state
-			lock: function() {
-				stack = undefined;
-				if ( !memory ) {
-					self.disable();
-				}
-				return this;
-			},
-			// Is it locked?
-			locked: function() {
-				return !stack;
-			},
-			// Call all callbacks with the given context and arguments
-			fireWith: function( context, args ) {
-				if ( list && ( !fired || stack ) ) {
-					args = args || [];
-					args = [ context, args.slice ? args.slice() : args ];
-					if ( firing ) {
-						stack.push( args );
-					} else {
-						fire( args );
-					}
-				}
-				return this;
-			},
-			// Call all the callbacks with the given arguments
-			fire: function() {
-				self.fireWith( this, arguments );
-				return this;
-			},
-			// To know if the callbacks have already been called at least once
-			fired: function() {
-				return !!fired;
-			}
-		};
-
-	return self;
-};
-
-
-jQuery.extend({
-
-	Deferred: function( func ) {
-		var tuples = [
-				// action, add listener, listener list, final state
-				[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
-				[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
-				[ "notify", "progress", jQuery.Callbacks("memory") ]
-			],
-			state = "pending",
-			promise = {
-				state: function() {
-					return state;
-				},
-				always: function() {
-					deferred.done( arguments ).fail( arguments );
-					return this;
-				},
-				then: function( /* fnDone, fnFail, fnProgress */ ) {
-					var fns = arguments;
-					return jQuery.Deferred(function( newDefer ) {
-						jQuery.each( tuples, function( i, tuple ) {
-							var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
-							// deferred[ done | fail | progress ] for forwarding actions to newDefer
-							deferred[ tuple[1] ](function() {
-								var returned = fn && fn.apply( this, arguments );
-								if ( returned && jQuery.isFunction( returned.promise ) ) {
-									returned.promise()
-										.done( newDefer.resolve )
-										.fail( newDefer.reject )
-										.progress( newDefer.notify );
-								} else {
-									newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
-								}
-							});
-						});
-						fns = null;
-					}).promise();
-				},
-				// Get a promise for this deferred
-				// If obj is provided, the promise aspect is added to the object
-				promise: function( obj ) {
-					return obj != null ? jQuery.extend( obj, promise ) : promise;
-				}
-			},
-			deferred = {};
-
-		// Keep pipe for back-compat
-		promise.pipe = promise.then;
-
-		// Add list-specific methods
-		jQuery.each( tuples, function( i, tuple ) {
-			var list = tuple[ 2 ],
-				stateString = tuple[ 3 ];
-
-			// promise[ done | fail | progress ] = list.add
-			promise[ tuple[1] ] = list.add;
-
-			// Handle state
-			if ( stateString ) {
-				list.add(function() {
-					// state = [ resolved | rejected ]
-					state = stateString;
-
-				// [ reject_list | resolve_list ].disable; progress_list.lock
-				}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
-			}
-
-			// deferred[ resolve | reject | notify ]
-			deferred[ tuple[0] ] = function() {
-				deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
-				return this;
-			};
-			deferred[ tuple[0] + "With" ] = list.fireWith;
-		});
-
-		// Make the deferred a promise
-		promise.promise( deferred );
-
-		// Call given func if any
-		if ( func ) {
-			func.call( deferred, deferred );
-		}
-
-		// All done!
-		return deferred;
-	},
-
-	// Deferred helper
-	when: function( subordinate /* , ..., subordinateN */ ) {
-		var i = 0,
-			resolveValues = slice.call( arguments ),
-			length = resolveValues.length,
-
-			// the count of uncompleted subordinates
-			remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
-
-			// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
-			deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
-
-			// Update function for both resolve and progress values
-			updateFunc = function( i, contexts, values ) {
-				return function( value ) {
-					contexts[ i ] = this;
-					values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
-					if ( values === progressValues ) {
-						deferred.notifyWith( contexts, values );
-					} else if ( !( --remaining ) ) {
-						deferred.resolveWith( contexts, values );
-					}
-				};
-			},
-
-			progressValues, progressContexts, resolveContexts;
-
-		// add listeners to Deferred subordinates; treat others as resolved
-		if ( length > 1 ) {
-			progressValues = new Array( length );
-			progressContexts = new Array( length );
-			resolveContexts = new Array( length );
-			for ( ; i < length; i++ ) {
-				if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
-					resolveValues[ i ].promise()
-						.done( updateFunc( i, resolveContexts, resolveValues ) )
-						.fail( deferred.reject )
-						.progress( updateFunc( i, progressContexts, progressValues ) );
-				} else {
-					--remaining;
-				}
-			}
-		}
-
-		// if we're not waiting on anything, resolve the master
-		if ( !remaining ) {
-			deferred.resolveWith( resolveContexts, resolveValues );
-		}
-
-		return deferred.promise();
-	}
-});
-
-
-// The deferred used on DOM ready
-var readyList;
-
-jQuery.fn.ready = function( fn ) {
-	// Add the callback
-	jQuery.ready.promise().done( fn );
-
-	return this;
-};
-
-jQuery.extend({
-	// Is the DOM ready to be used? Set to true once it occurs.
-	isReady: false,
-
-	// A counter to track how many items to wait for before
-	// the ready event fires. See #6781
-	readyWait: 1,
-
-	// Hold (or release) the ready event
-	holdReady: function( hold ) {
-		if ( hold ) {
-			jQuery.readyWait++;
-		} else {
-			jQuery.ready( true );
-		}
-	},
-
-	// Handle when the DOM is ready
-	ready: function( wait ) {
-
-		// Abort if there are pending holds or we're already ready
-		if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
-			return;
-		}
-
-		// Remember that the DOM is ready
-		jQuery.isReady = true;
-
-		// If a normal DOM Ready event fired, decrement, and wait if need be
-		if ( wait !== true && --jQuery.readyWait > 0 ) {
-			return;
-		}
-
-		// If there are functions bound, to execute
-		readyList.resolveWith( document, [ jQuery ] );
-
-		// Trigger any bound ready events
-		if ( jQuery.fn.triggerHandler ) {
-			jQuery( document ).triggerHandler( "ready" );
-			jQuery( document ).off( "ready" );
-		}
-	}
-});
-
-/**
- * The ready event handler and self cleanup method
- */
-function completed() {
-	document.removeEventListener( "DOMContentLoaded", completed, false );
-	window.removeEventListener( "load", completed, false );
-	jQuery.ready();
-}
-
-jQuery.ready.promise = function( obj ) {
-	if ( !readyList ) {
-
-		readyList = jQuery.Deferred();
-
-		// Catch cases where $(document).ready() is called after the browser event has already occurred.
-		// we once tried to use readyState "interactive" here, but it caused issues like the one
-		// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
-		if ( document.readyState === "complete" ) {
-			// Handle it asynchronously to allow scripts the opportunity to delay ready
-			setTimeout( jQuery.ready );
-
-		} else {
-
-			// Use the handy event callback
-			document.addEventListener( "DOMContentLoaded", completed, false );
-
-			// A fallback to window.onload, that will always work
-			window.addEventListener( "load", completed, false );
-		}
-	}
-	return readyList.promise( obj );
-};
-
-// Kick off the DOM ready check even if the user does not
-jQuery.ready.promise();
-
-
-
-
-// Multifunctional method to get and set values of a collection
-// The value/s can optionally be executed if it's a function
-var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
-	var i = 0,
-		len = elems.length,
-		bulk = key == null;
-
-	// Sets many values
-	if ( jQuery.type( key ) === "object" ) {
-		chainable = true;
-		for ( i in key ) {
-			jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
-		}
-
-	// Sets one value
-	} else if ( value !== undefined ) {
-		chainable = true;
-
-		if ( !jQuery.isFunction( value ) ) {
-			raw = true;
-		}
-
-		if ( bulk ) {
-			// Bulk operations run against the entire set
-			if ( raw ) {
-				fn.call( elems, value );
-				fn = null;
-
-			// ...except when executing function values
-			} else {
-				bulk = fn;
-				fn = function( elem, key, value ) {
-					return bulk.call( jQuery( elem ), value );
-				};
-			}
-		}
-
-		if ( fn ) {
-			for ( ; i < len; i++ ) {
-				fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
-			}
-		}
-	}
-
-	return chainable ?
-		elems :
-
-		// Gets
-		bulk ?
-			fn.call( elems ) :
-			len ? fn( elems[0], key ) : emptyGet;
-};
-
-
-/**
- * Determines whether an object can have data
- */
-jQuery.acceptData = function( owner ) {
-	// Accepts only:
-	//  - Node
-	//    - Node.ELEMENT_NODE
-	//    - Node.DOCUMENT_NODE
-	//  - Object
-	//    - Any
-	/* jshint -W018 */
-	return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
-};
-
-
-function Data() {
-	// Support: Android < 4,
-	// Old WebKit does not have Object.preventExtensions/freeze method,
-	// return new empty object instead with no [[set]] accessor
-	Object.defineProperty( this.cache = {}, 0, {
-		get: function() {
-			return {};
-		}
-	});
-
-	this.expando = jQuery.expando + Math.random();
-}
-
-Data.uid = 1;
-Data.accepts = jQuery.acceptData;
-
-Data.prototype = {
-	key: function( owner ) {
-		// We can accept data for non-element nodes in modern browsers,
-		// but we should not, see #8335.
-		// Always return the key for a frozen object.
-		if ( !Data.accepts( owner ) ) {
-			return 0;
-		}
-
-		var descriptor = {},
-			// Check if the owner object already has a cache key
-			unlock = owner[ this.expando ];
-
-		// If not, create one
-		if ( !unlock ) {
-			unlock = Data.uid++;
-
-			// Secure it in a non-enumerable, non-writable property
-			try {
-				descriptor[ this.expando ] = { value: unlock };
-				Object.defineProperties( owner, descriptor );
-
-			// Support: Android < 4
-			// Fallback to a less secure definition
-			} catch ( e ) {
-				descriptor[ this.expando ] = unlock;
-				jQuery.extend( owner, descriptor );
-			}
-		}
-
-		// Ensure the cache object
-		if ( !this.cache[ unlock ] ) {
-			this.cache[ unlock ] = {};
-		}
-
-		return unlock;
-	},
-	set: function( owner, data, value ) {
-		var prop,
-			// There may be an unlock assigned to this node,
-			// if there is no entry for this "owner", create one inline
-			// and set the unlock as though an owner entry had always existed
-			unlock = this.key( owner ),
-			cache = this.cache[ unlock ];
-
-		// Handle: [ owner, key, value ] args
-		if ( typeof data === "string" ) {
-			cache[ data ] = value;
-
-		// Handle: [ owner, { properties } ] args
-		} else {
-			// Fresh assignments by object are shallow copied
-			if ( jQuery.isEmptyObject( cache ) ) {
-				jQuery.extend( this.cache[ unlock ], data );
-			// Otherwise, copy the properties one-by-one to the cache object
-			} else {
-				for ( prop in data ) {
-					cache[ prop ] = data[ prop ];
-				}
-			}
-		}
-		return cache;
-	},
-	get: function( owner, key ) {
-		// Either a valid cache is found, or will be created.
-		// New caches will be created and the unlock returned,
-		// allowing direct access to the newly created
-		// empty data object. A valid owner object must be provided.
-		var cache = this.cache[ this.key( owner ) ];
-
-		return key === undefined ?
-			cache : cache[ key ];
-	},
-	access: function( owner, key, value ) {
-		var stored;
-		// In cases where either:
-		//
-		//   1. No key was specified
-		//   2. A string key was specified, but no value provided
-		//
-		// Take the "read" path and allow the get method to determine
-		// which value to return, respectively either:
-		//
-		//   1. The entire cache object
-		//   2. The data stored at the key
-		//
-		if ( key === undefined ||
-				((key && typeof key === "string") && value === undefined) ) {
-
-			stored = this.get( owner, key );
-
-			return stored !== undefined ?
-				stored : this.get( owner, jQuery.camelCase(key) );
-		}
-
-		// [*]When the key is not a string, or both a key and value
-		// are specified, set or extend (existing objects) with either:
-		//
-		//   1. An object of properties
-		//   2. A key and value
-		//
-		this.set( owner, key, value );
-
-		// Since the "set" path can have two possible entry points
-		// return the expected data based on which path was taken[*]
-		return value !== undefined ? value : key;
-	},
-	remove: function( owner, key ) {
-		var i, name, camel,
-			unlock = this.key( owner ),
-			cache = this.cache[ unlock ];
-
-		if ( key === undefined ) {
-			this.cache[ unlock ] = {};
-
-		} else {
-			// Support array or space separated string of keys
-			if ( jQuery.isArray( key ) ) {
-				// If "name" is an array of keys...
-				// When data is initially created, via ("key", "val") signature,
-				// keys will be converted to camelCase.
-				// Since there is no way to tell _how_ a key was added, remove
-				// both plain key and camelCase key. #12786
-				// This will only penalize the array argument path.
-				name = key.concat( key.map( jQuery.camelCase ) );
-			} else {
-				camel = jQuery.camelCase( key );
-				// Try the string as a key before any manipulation
-				if ( key in cache ) {
-					name = [ key, camel ];
-				} else {
-					// If a key with the spaces exists, use it.
-					// Otherwise, create an array by matching non-whitespace
-					name = camel;
-					name = name in cache ?
-						[ name ] : ( name.match( rnotwhite ) || [] );
-				}
-			}
-
-			i = name.length;
-			while ( i-- ) {
-				delete cache[ name[ i ] ];
-			}
-		}
-	},
-	hasData: function( owner ) {
-		return !jQuery.isEmptyObject(
-			this.cache[ owner[ this.expando ] ] || {}
-		);
-	},
-	discard: function( owner ) {
-		if ( owner[ this.expando ] ) {
-			delete this.cache[ owner[ this.expando ] ];
-		}
-	}
-};
-var data_priv = new Data();
-
-var data_user = new Data();
-
-
-
-/*
-	Implementation Summary
-
-	1. Enforce API surface and semantic compatibility with 1.9.x branch
-	2. Improve the module's maintainability by reducing the storage
-		paths to a single mechanism.
-	3. Use the same single mechanism to support "private" and "user" data.
-	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
-	5. Avoid exposing implementation details on user objects (eg. expando properties)
-	6. Provide a clear path for implementation upgrade to WeakMap in 2014
-*/
-var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
-	rmultiDash = /([A-Z])/g;
-
-function dataAttr( elem, key, data ) {
-	var name;
-
-	// If nothing was found internally, try to fetch any
-	// data from the HTML5 data-* attribute
-	if ( data === undefined && elem.nodeType === 1 ) {
-		name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
-		data = elem.getAttribute( name );
-
-		if ( typeof data === "string" ) {
-			try {
-				data = data === "true" ? true :
-					data === "false" ? false :
-					data === "null" ? null :
-					// Only convert to a number if it doesn't change the string
-					+data + "" === data ? +data :
-					rbrace.test( data ) ? jQuery.parseJSON( data ) :
-					data;
-			} catch( e ) {}
-
-			// Make sure we set the data so it isn't changed later
-			data_user.set( elem, key, data );
-		} else {
-			data = undefined;
-		}
-	}
-	return data;
-}
-
-jQuery.extend({
-	hasData: function( elem ) {
-		return data_user.hasData( elem ) || data_priv.hasData( elem );
-	},
-
-	data: function( elem, name, data ) {
-		return data_user.access( elem, name, data );
-	},
-
-	removeData: function( elem, name ) {
-		data_user.remove( elem, name );
-	},
-
-	// TODO: Now that all calls to _data and _removeData have been replaced
-	// with direct calls to data_priv methods, these can be deprecated.
-	_data: function( elem, name, data ) {
-		return data_priv.access( elem, name, data );
-	},
-
-	_removeData: function( elem, name ) {
-		data_priv.remove( elem, name );
-	}
-});
-
-jQuery.fn.extend({
-	data: function( key, value ) {
-		var i, name, data,
-			elem = this[ 0 ],
-			attrs = elem && elem.attributes;
-
-		// Gets all values
-		if ( key === undefined ) {
-			if ( this.length ) {
-				data = data_user.get( elem );
-
-				if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
-					i = attrs.length;
-					while ( i-- ) {
-
-						// Support: IE11+
-						// The attrs elements can be null (#14894)
-						if ( attrs[ i ] ) {
-							name = attrs[ i ].name;
-							if ( name.indexOf( "data-" ) === 0 ) {
-								name = jQuery.camelCase( name.slice(5) );
-								dataAttr( elem, name, data[ name ] );
-							}
-						}
-					}
-					data_priv.set( elem, "hasDataAttrs", true );
-				}
-			}
-
-			return data;
-		}
-
-		// Sets multiple values
-		if ( typeof key === "object" ) {
-			return this.each(function() {
-				data_user.set( this, key );
-			});
-		}
-
-		return access( this, function( value ) {
-			var data,
-				camelKey = jQuery.camelCase( key );
-
-			// The calling jQuery object (element matches) is not empty
-			// (and therefore has an element appears at this[ 0 ]) and the
-			// `value` parameter was not undefined. An empty jQuery object
-			// will result in `undefined` for elem = this[ 0 ] which will
-			// throw an exception if an attempt to read a data cache is made.
-			if ( elem && value === undefined ) {
-				// Attempt to get data from the cache
-				// with the key as-is
-				data = data_user.get( elem, key );
-				if ( data !== undefined ) {
-					return data;
-				}
-
-				// Attempt to get data from the cache
-				// with the key camelized
-				data = data_user.get( elem, camelKey );
-				if ( data !== undefined ) {
-					return data;
-				}
-
-				// Attempt to "discover" the data in
-				// HTML5 custom data-* attrs
-				data = dataAttr( elem, camelKey, undefined );
-				if ( data !== undefined ) {
-					return data;
-				}
-
-				// We tried really hard, but the data doesn't exist.
-				return;
-			}
-
-			// Set the data...
-			this.each(function() {
-				// First, attempt to store a copy or reference of any
-				// data that might've been store with a camelCased key.
-				var data = data_user.get( this, camelKey );
-
-				// For HTML5 data-* attribute interop, we have to
-				// store property names with dashes in a camelCase form.
-				// This might not apply to all properties...*
-				data_user.set( this, camelKey, value );
-
-				// *... In the case of properties that might _actually_
-				// have dashes, we need to also store a copy of that
-				// unchanged property.
-				if ( key.indexOf("-") !== -1 && data !== undefined ) {
-					data_user.set( this, key, value );
-				}
-			});
-		}, null, value, arguments.length > 1, null, true );
-	},
-
-	removeData: function( key ) {
-		return this.each(function() {
-			data_user.remove( this, key );
-		});
-	}
-});
-
-
-jQuery.extend({
-	queue: function( elem, type, data ) {
-		var queue;
-
-		if ( elem ) {
-			type = ( type || "fx" ) + "queue";
-			queue = data_priv.get( elem, type );
-
-			// Speed up dequeue by getting out quickly if this is just a lookup
-			if ( data ) {
-				if ( !queue || jQuery.isArray( data ) ) {
-					queue = data_priv.access( elem, type, jQuery.makeArray(data) );
-				} else {
-					queue.push( data );
-				}
-			}
-			return queue || [];
-		}
-	},
-
-	dequeue: function( elem, type ) {
-		type = type || "fx";
-
-		var queue = jQuery.queue( elem, type ),
-			startLength = queue.length,
-			fn = queue.shift(),
-			hooks = jQuery._queueHooks( elem, type ),
-			next = function() {
-				jQuery.dequeue( elem, type );
-			};
-
-		// If the fx queue is dequeued, always remove the progress sentinel
-		if ( fn === "inprogress" ) {
-			fn = queue.shift();
-			startLength--;
-		}
-
-		if ( fn ) {
-
-			// Add a progress sentinel to prevent the fx queue from being
-			// automatically dequeued
-			if ( type === "fx" ) {
-				queue.unshift( "inprogress" );
-			}
-
-			// clear up the last queue stop function
-			delete hooks.stop;
-			fn.call( elem, next, hooks );
-		}
-
-		if ( !startLength && hooks ) {
-			hooks.empty.fire();
-		}
-	},
-
-	// not intended for public consumption - generates a queueHooks object, or returns the current one
-	_queueHooks: function( elem, type ) {
-		var key = type + "queueHooks";
-		return data_priv.get( elem, key ) || data_priv.access( elem, key, {
-			empty: jQuery.Callbacks("once memory").add(function() {
-				data_priv.remove( elem, [ type + "queue", key ] );
-			})
-		});
-	}
-});
-
-jQuery.fn.extend({
-	queue: function( type, data ) {
-		var setter = 2;
-
-		if ( typeof type !== "string" ) {
-			data = type;
-			type = "fx";
-			setter--;
-		}
-
-		if ( arguments.length < setter ) {
-			return jQuery.queue( this[0], type );
-		}
-
-		return data === undefined ?
-			this :
-			this.each(function() {
-				var queue = jQuery.queue( this, type, data );
-
-				// ensure a hooks for this queue
-				jQuery._queueHooks( this, type );
-
-				if ( type === "fx" && queue[0] !== "inprogress" ) {
-					jQuery.dequeue( this, type );
-				}
-			});
-	},
-	dequeue: function( type ) {
-		return this.each(function() {
-			jQuery.dequeue( this, type );
-		});
-	},
-	clearQueue: function( type ) {
-		return this.queue( type || "fx", [] );
-	},
-	// Get a promise resolved when queues of a certain type
-	// are emptied (fx is the type by default)
-	promise: function( type, obj ) {
-		var tmp,
-			count = 1,
-			defer = jQuery.Deferred(),
-			elements = this,
-			i = this.length,
-			resolve = function() {
-				if ( !( --count ) ) {
-					defer.resolveWith( elements, [ elements ] );
-				}
-			};
-
-		if ( typeof type !== "string" ) {
-			obj = type;
-			type = undefined;
-		}
-		type = type || "fx";
-
-		while ( i-- ) {
-			tmp = data_priv.get( elements[ i ], type + "queueHooks" );
-			if ( tmp && tmp.empty ) {
-				count++;
-				tmp.empty.add( resolve );
-			}
-		}
-		resolve();
-		return defer.promise( obj );
-	}
-});
-var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
-
-var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
-
-var isHidden = function( elem, el ) {
-		// isHidden might be called from jQuery#filter function;
-		// in that case, element will be second argument
-		elem = el || elem;
-		return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
-	};
-
-var rcheckableType = (/^(?:checkbox|radio)$/i);
-
-
-
-(function() {
-	var fragment = document.createDocumentFragment(),
-		div = fragment.appendChild( document.createElement( "div" ) ),
-		input = document.createElement( "input" );
-
-	// #11217 - WebKit loses check when the name is after the checked attribute
-	// Support: Windows Web Apps (WWA)
-	// `name` and `type` need .setAttribute for WWA
-	input.setAttribute( "type", "radio" );
-	input.setAttribute( "checked", "checked" );
-	input.setAttribute( "name", "t" );
-
-	div.appendChild( input );
-
-	// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
-	// old WebKit doesn't clone checked state correctly in fragments
-	support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
-
-	// Make sure textarea (and checkbox) defaultValue is properly cloned
-	// Support: IE9-IE11+
-	div.innerHTML = "<textarea>x</textarea>";
-	support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
-})();
-var strundefined = typeof undefined;
-
-
-
-support.focusinBubbles = "onfocusin" in window;
-
-
-var
-	rkeyEvent = /^key/,
-	rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
-	rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
-	rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
-
-function returnTrue() {
-	return true;
-}
-
-function returnFalse() {
-	return false;
-}
-
-function safeActiveElement() {
-	try {
-		return document.activeElement;
-	} catch ( err ) { }
-}
-
-/*
- * Helper functions for managing events -- not part of the public interface.
- * Props to Dean Edwards' addEvent library for many of the ideas.
- */
-jQuery.event = {
-
-	global: {},
-
-	add: function( elem, types, handler, data, selector ) {
-
-		var handleObjIn, eventHandle, tmp,
-			events, t, handleObj,
-			special, handlers, type, namespaces, origType,
-			elemData = data_priv.get( elem );
-
-		// Don't attach events to noData or text/comment nodes (but allow plain objects)
-		if ( !elemData ) {
-			return;
-		}
-
-		// Caller can pass in an object of custom data in lieu of the handler
-		if ( handler.handler ) {
-			handleObjIn = handler;
-			handler = handleObjIn.handler;
-			selector = handleObjIn.selector;
-		}
-
-		// Make sure that the handler has a unique ID, used to find/remove it later
-		if ( !handler.guid ) {
-			handler.guid = jQuery.guid++;
-		}
-
-		// Init the element's event structure and main handler, if this is the first
-		if ( !(events = elemData.events) ) {
-			events = elemData.events = {};
-		}
-		if ( !(eventHandle = elemData.handle) ) {
-			eventHandle = elemData.handle = function( e ) {
-				// Discard the second event of a jQuery.event.trigger() and
-				// when an event is called after a page has unloaded
-				return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
-					jQuery.event.dispatch.apply( elem, arguments ) : undefined;
-			};
-		}
-
-		// Handle multiple events separated by a space
-		types = ( types || "" ).match( rnotwhite ) || [ "" ];
-		t = types.length;
-		while ( t-- ) {
-			tmp = rtypenamespace.exec( types[t] ) || [];
-			type = origType = tmp[1];
-			namespaces = ( tmp[2] || "" ).split( "." ).sort();
-
-			// There *must* be a type, no attaching namespace-only handlers
-			if ( !type ) {
-				continue;
-			}
-
-			// If event changes its type, use the special event handlers for the changed type
-			special = jQuery.event.special[ type ] || {};
-
-			// If selector defined, determine special event api type, otherwise given type
-			type = ( selector ? special.delegateType : special.bindType ) || type;
-
-			// Update special based on newly reset type
-			special = jQuery.event.special[ type ] || {};
-
-			// handleObj is passed to all event handlers
-			handleObj = jQuery.extend({
-				type: type,
-				origType: origType,
-				data: data,
-				handler: handler,
-				guid: handler.guid,
-				selector: selector,
-				needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
-				namespace: namespaces.join(".")
-			}, handleObjIn );
-
-			// Init the event handler queue if we're the first
-			if ( !(handlers = events[ type ]) ) {
-				handlers = events[ type ] = [];
-				handlers.delegateCount = 0;
-
-				// Only use addEventListener if the special events handler returns false
-				if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
-					if ( elem.addEventListener ) {
-						elem.addEventListener( type, eventHandle, false );
-					}
-				}
-			}
-
-			if ( special.add ) {
-				special.add.call( elem, handleObj );
-
-				if ( !handleObj.handler.guid ) {
-					handleObj.handler.guid = handler.guid;
-				}
-			}
-
-			// Add to the element's handler list, delegates in front
-			if ( selector ) {
-				handlers.splice( handlers.delegateCount++, 0, handleObj );
-			} else {
-				handlers.push( handleObj );
-			}
-
-			// Keep track of which events have ever been used, for event optimization
-			jQuery.event.global[ type ] = true;
-		}
-
-	},
-
-	// Detach an event or set of events from an element
-	remove: function( elem, types, handler, selector, mappedTypes ) {
-
-		var j, origCount, tmp,
-			events, t, handleObj,
-			special, handlers, type, namespaces, origType,
-			elemData = data_priv.hasData( elem ) && data_priv.get( elem );
-
-		if ( !elemData || !(events = elemData.events) ) {
-			return;
-		}
-
-		// Once for each type.namespace in types; type may be omitted
-		types = ( types || "" ).match( rnotwhite ) || [ "" ];
-		t = types.length;
-		while ( t-- ) {
-			tmp = rtypenamespace.exec( types[t] ) || [];
-			type = origType = tmp[1];
-			namespaces = ( tmp[2] || "" ).split( "." ).sort();
-
-			// Unbind all events (on this namespace, if provided) for the element
-			if ( !type ) {
-				for ( type in events ) {
-					jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
-				}
-				continue;
-			}
-
-			special = jQuery.event.special[ type ] || {};
-			type = ( selector ? special.delegateType : special.bindType ) || type;
-			handlers = events[ type ] || [];
-			tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
-
-			// Remove matching events
-			origCount = j = handlers.length;
-			while ( j-- ) {
-				handleObj = handlers[ j ];
-
-				if ( ( mappedTypes || origType === handleObj.origType ) &&
-					( !handler || handler.guid === handleObj.guid ) &&
-					( !tmp || tmp.test( handleObj.namespace ) ) &&
-					( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
-					handlers.splice( j, 1 );
-
-					if ( handleObj.selector ) {
-						handlers.delegateCount--;
-					}
-					if ( special.remove ) {
-						special.remove.call( elem, handleObj );
-					}
-				}
-			}
-
-			// Remove generic event handler if we removed something and no more handlers exist
-			// (avoids potential for endless recursion during removal of special event handlers)
-			if ( origCount && !handlers.length ) {
-				if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
-					jQuery.removeEvent( elem, type, elemData.handle );
-				}
-
-				delete events[ type ];
-			}
-		}
-
-		// Remove the expando if it's no longer used
-		if ( jQuery.isEmptyObject( events ) ) {
-			delete elemData.handle;
-			data_priv.remove( elem, "events" );
-		}
-	},
-
-	trigger: function( event, data, elem, onlyHandlers ) {
-
-		var i, cur, tmp, bubbleType, ontype, handle, special,
-			eventPath = [ elem || document ],
-			type = hasOwn.call( event, "type" ) ? event.type : event,
-			namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
-
-		cur = tmp = elem = elem || document;
-
-		// Don't do events on text and comment nodes
-		if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
-			return;
-		}
-
-		// focus/blur morphs to focusin/out; ensure we're not firing them right now
-		if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
-			return;
-		}
-
-		if ( type.indexOf(".") >= 0 ) {
-			// Namespaced trigger; create a regexp to match event type in handle()
-			namespaces = type.split(".");
-			type = namespaces.shift();
-			namespaces.sort();
-		}
-		ontype = type.indexOf(":") < 0 && "on" + type;
-
-		// Caller can pass in a jQuery.Event object, Object, or just an event type string
-		event = event[ jQuery.expando ] ?
-			event :
-			new jQuery.Event( type, typeof event === "object" && event );
-
-		// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
-		event.isTrigger = onlyHandlers ? 2 : 3;
-		event.namespace = namespaces.join(".");
-		event.namespace_re = event.namespace ?
-			new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
-			null;
-
-		// Clean up the event in case it is being reused
-		event.result = undefined;
-		if ( !event.target ) {
-			event.target = elem;
-		}
-
-		// Clone any incoming data and prepend the event, creating the handler arg list
-		data = data == null ?
-			[ event ] :
-			jQuery.makeArray( data, [ event ] );
-
-		// Allow special events to draw outside the lines
-		special = jQuery.event.special[ type ] || {};
-		if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
-			return;
-		}
-
-		// Determine event propagation path in advance, per W3C events spec (#9951)
-		// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
-		if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
-
-			bubbleType = special.delegateType || type;
-			if ( !rfocusMorph.test( bubbleType + type ) ) {
-				cur = cur.parentNode;
-			}
-			for ( ; cur; cur = cur.parentNode ) {
-				eventPath.push( cur );
-				tmp = cur;
-			}
-
-			// Only add window if we got to document (e.g., not plain obj or detached DOM)
-			if ( tmp === (elem.ownerDocument || document) ) {
-				eventPath.push( tmp.defaultView || tmp.parentWindow || window );
-			}
-		}
-
-		// Fire handlers on the event path
-		i = 0;
-		while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
-
-			event.type = i > 1 ?
-				bubbleType :
-				special.bindType || type;
-
-			// jQuery handler
-			handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
-			if ( handle ) {
-				handle.apply( cur, data );
-			}
-
-			// Native handler
-			handle = ontype && cur[ ontype ];
-			if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
-				event.result = handle.apply( cur, data );
-				if ( event.result === false ) {
-					event.preventDefault();
-				}
-			}
-		}
-		event.type = type;
-
-		// If nobody prevented the default action, do it now
-		if ( !onlyHandlers && !event.isDefaultPrevented() ) {
-
-			if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
-				jQuery.acceptData( elem ) ) {
-
-				// Call a native DOM method on the target with the same name name as the event.
-				// Don't do default actions on window, that's where global variables be (#6170)
-				if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
-
-					// Don't re-trigger an onFOO event when we call its FOO() method
-					tmp = elem[ ontype ];
-
-					if ( tmp ) {
-						elem[ ontype ] = null;
-					}
-
-					// Prevent re-triggering of the same event, since we already bubbled it above
-					jQuery.event.triggered = type;
-					elem[ type ]();
-					jQuery.event.triggered = undefined;
-
-					if ( tmp ) {
-						elem[ ontype ] = tmp;
-					}
-				}
-			}
-		}
-
-		return event.result;
-	},
-
-	dispatch: function( event ) {
-
-		// Make a writable jQuery.Event from the native event object
-		event = jQuery.event.fix( event );
-
-		var i, j, ret, matched, handleObj,
-			handlerQueue = [],
-			args = slice.call( arguments ),
-			handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
-			special = jQuery.event.special[ event.type ] || {};
-
-		// Use the fix-ed jQuery.Event rather than the (read-only) native event
-		args[0] = event;
-		event.delegateTarget = this;
-
-		// Call the preDispatch hook for the mapped type, and let it bail if desired
-		if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
-			return;
-		}
-
-		// Determine handlers
-		handlerQueue = jQuery.event.handlers.call( this, event, handlers );
-
-		// Run delegates first; they may want to stop propagation beneath us
-		i = 0;
-		while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
-			event.currentTarget = matched.elem;
-
-			j = 0;
-			while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
-
-				// Triggered event must either 1) have no namespace, or
-				// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
-				if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
-
-					event.handleObj = handleObj;
-					event.data = handleObj.data;
-
-					ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
-							.apply( matched.elem, args );
-
-					if ( ret !== undefined ) {
-						if ( (event.result = ret) === false ) {
-							event.preventDefault();
-							event.stopPropagation();
-						}
-					}
-				}
-			}
-		}
-
-		// Call the postDispatch hook for the mapped type
-		if ( special.postDispatch ) {
-			special.postDispatch.call( this, event );
-		}
-
-		return event.result;
-	},
-
-	handlers: function( event, handlers ) {
-		var i, matches, sel, handleObj,
-			handlerQueue = [],
-			delegateCount = handlers.delegateCount,
-			cur = event.target;
-
-		// Find delegate handlers
-		// Black-hole SVG <use> instance trees (#13180)
-		// Avoid non-left-click bubbling in Firefox (#3861)
-		if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
-
-			for ( ; cur !== this; cur = cur.parentNode || this ) {
-
-				// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
-				if ( cur.disabled !== true || event.type !== "click" ) {
-					matches = [];
-					for ( i = 0; i < delegateCount; i++ ) {
-						handleObj = handlers[ i ];
-
-						// Don't conflict with Object.prototype properties (#13203)
-						sel = handleObj.selector + " ";
-
-						if ( matches[ sel ] === undefined ) {
-							matches[ sel ] = handleObj.needsContext ?
-								jQuery( sel, this ).index( cur ) >= 0 :
-								jQuery.find( sel, this, null, [ cur ] ).length;
-						}
-						if ( matches[ sel ] ) {
-							matches.push( handleObj );
-						}
-					}
-					if ( matches.length ) {
-						handlerQueue.push({ elem: cur, handlers: matches });
-					}
-				}
-			}
-		}
-
-		// Add the remaining (directly-bound) handlers
-		if ( delegateCount < handlers.length ) {
-			handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
-		}
-
-		return handlerQueue;
-	},
-
-	// Includes some event props shared by KeyEvent and MouseEvent
-	props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
-
-	fixHooks: {},
-
-	keyHooks: {
-		props: "char charCode key keyCode".split(" "),
-		filter: function( event, original ) {
-
-			// Add which for key events
-			if ( event.which == null ) {
-				event.which = original.charCode != null ? original.charCode : original.keyCode;
-			}
-
-			return event;
-		}
-	},
-
-	mouseHooks: {
-		props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
-		filter: function( event, original ) {
-			var eventDoc, doc, body,
-				button = original.button;
-
-			// Calculate pageX/Y if missing and clientX/Y available
-			if ( event.pageX == null && original.clientX != null ) {
-				eventDoc = event.target.ownerDocument || document;
-				doc = eventDoc.documentElement;
-				body = eventDoc.body;
-
-				event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
-				event.pageY = original.clientY + ( doc && doc.scrollTop  || body && body.scrollTop  || 0 ) - ( doc && doc.clientTop  || body && body.clientTop  || 0 );
-			}
-
-			// Add which for click: 1 === left; 2 === middle; 3 === right
-			// Note: button is not normalized, so don't use it
-			if ( !event.which && button !== undefined ) {
-				event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
-			}
-
-			return event;
-		}
-	},
-
-	fix: function( event ) {
-		if ( event[ jQuery.expando ] ) {
-			return event;
-		}
-
-		// Create a writable copy of the event object and normalize some properties
-		var i, prop, copy,
-			type = event.type,
-			originalEvent = event,
-			fixHook = this.fixHooks[ type ];
-
-		if ( !fixHook ) {
-			this.fixHooks[ type ] = fixHook =
-				rmouseEvent.test( type ) ? this.mouseHooks :
-				rkeyEvent.test( type ) ? this.keyHooks :
-				{};
-		}
-		copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
-
-		event = new jQuery.Event( originalEvent );
-
-		i = copy.length;
-		while ( i-- ) {
-			prop = copy[ i ];
-			event[ prop ] = originalEvent[ prop ];
-		}
-
-		// Support: Cordova 2.5 (WebKit) (#13255)
-		// All events should have a target; Cordova deviceready doesn't
-		if ( !event.target ) {
-			event.target = document;
-		}
-
-		// Support: Safari 6.0+, Chrome < 28
-		// Target should not be a text node (#504, #13143)
-		if ( event.target.nodeType === 3 ) {
-			event.target = event.target.parentNode;
-		}
-
-		return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
-	},
-
-	special: {
-		load: {
-			// Prevent triggered image.load events from bubbling to window.load
-			noBubble: true
-		},
-		focus: {
-			// Fire native event if possible so blur/focus sequence is correct
-			trigger: function() {
-				if ( this !== safeActiveElement() && this.focus ) {
-					this.focus();
-					return false;
-				}
-			},
-			delegateType: "focusin"
-		},
-		blur: {
-			trigger: function() {
-				if ( this === safeActiveElement() && this.blur ) {
-					this.blur();
-					return false;
-				}
-			},
-			delegateType: "focusout"
-		},
-		click: {
-			// For checkbox, fire native event so checked state will be right
-			trigger: function() {
-				if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
-					this.click();
-					return false;
-				}
-			},
-
-			// For cross-browser consistency, don't fire native .click() on links
-			_default: function( event ) {
-				return jQuery.nodeName( event.target, "a" );
-			}
-		},
-
-		beforeunload: {
-			postDispatch: function( event ) {
-
-				// Support: Firefox 20+
-				// Firefox doesn't alert if the returnValue field is not set.
-				if ( event.result !== undefined && event.originalEvent ) {
-					event.originalEvent.returnValue = event.result;
-				}
-			}
-		}
-	},
-
-	simulate: function( type, elem, event, bubble ) {
-		// Piggyback on a donor event to simulate a different one.
-		// Fake originalEvent to avoid donor's stopPropagation, but if the
-		// simulated event prevents default then we do the same on the donor.
-		var e = jQuery.extend(
-			new jQuery.Event(),
-			event,
-			{
-				type: type,
-				isSimulated: true,
-				originalEvent: {}
-			}
-		);
-		if ( bubble ) {
-			jQuery.event.trigger( e, null, elem );
-		} else {
-			jQuery.event.dispatch.call( elem, e );
-		}
-		if ( e.isDefaultPrevented() ) {
-			event.preventDefault();
-		}
-	}
-};
-
-jQuery.removeEvent = function( elem, type, handle ) {
-	if ( elem.removeEventListener ) {
-		elem.removeEventListener( type, handle, false );
-	}
-};
-
-jQuery.Event = function( src, props ) {
-	// Allow instantiation without the 'new' keyword
-	if ( !(this instanceof jQuery.Event) ) {
-		return new jQuery.Event( src, props );
-	}
-
-	// Event object
-	if ( src && src.type ) {
-		this.originalEvent = src;
-		this.type = src.type;
-
-		// Events bubbling up the document may have been marked as prevented
-		// by a handler lower down the tree; reflect the correct value.
-		this.isDefaultPrevented = src.defaultPrevented ||
-				src.defaultPrevented === undefined &&
-				// Support: Android < 4.0
-				src.returnValue === false ?
-			returnTrue :
-			returnFalse;
-
-	// Event type
-	} else {
-		this.type = src;
-	}
-
-	// Put explicitly provided properties onto the event object
-	if ( props ) {
-		jQuery.extend( this, props );
-	}
-
-	// Create a timestamp if incoming event doesn't have one
-	this.timeStamp = src && src.timeStamp || jQuery.now();
-
-	// Mark it as fixed
-	this[ jQuery.expando ] = 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 = {
-	isDefaultPrevented: returnFalse,
-	isPropagationStopped: returnFalse,
-	isImmediatePropagationStopped: returnFalse,
-
-	preventDefault: function() {
-		var e = this.originalEvent;
-
-		this.isDefaultPrevented = returnTrue;
-
-		if ( e && e.preventDefault ) {
-			e.preventDefault();
-		}
-	},
-	stopPropagation: function() {
-		var e = this.originalEvent;
-
-		this.isPropagationStopped = returnTrue;
-
-		if ( e && e.stopPropagation ) {
-			e.stopPropagation();
-		}
-	},
-	stopImmediatePropagation: function() {
-		var e = this.originalEvent;
-
-		this.isImmediatePropagationStopped = returnTrue;
-
-		if ( e && e.stopImmediatePropagation ) {
-			e.stopImmediatePropagation();
-		}
-
-		this.stopPropagation();
-	}
-};
-
-// Create mouseenter/leave events using mouseover/out and event-time checks
-// Support: Chrome 15+
-jQuery.each({
-	mouseenter: "mouseover",
-	mouseleave: "mouseout",
-	pointerenter: "pointerover",
-	pointerleave: "pointerout"
-}, function( orig, fix ) {
-	jQuery.event.special[ orig ] = {
-		delegateType: fix,
-		bindType: fix,
-
-		handle: function( event ) {
-			var ret,
-				target = this,
-				related = event.relatedTarget,
-				handleObj = event.handleObj;
-
-			// For mousenter/leave call the handler if related is outside the target.
-			// NB: No relatedTarget if the mouse left/entered the browser window
-			if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
-				event.type = handleObj.origType;
-				ret = handleObj.handler.apply( this, arguments );
-				event.type = fix;
-			}
-			return ret;
-		}
-	};
-});
-
-// Create "bubbling" focus and blur events
-// Support: Firefox, Chrome, Safari
-if ( !support.focusinBubbles ) {
-	jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
-
-		// Attach a single capturing handler on the document while someone wants focusin/focusout
-		var handler = function( event ) {
-				jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
-			};
-
-		jQuery.event.special[ fix ] = {
-			setup: function() {
-				var doc = this.ownerDocument || this,
-					attaches = data_priv.access( doc, fix );
-
-				if ( !attaches ) {
-					doc.addEventListener( orig, handler, true );
-				}
-				data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
-			},
-			teardown: function() {
-				var doc = this.ownerDocument || this,
-					attaches = data_priv.access( doc, fix ) - 1;
-
-				if ( !attaches ) {
-					doc.removeEventListener( orig, handler, true );
-					data_priv.remove( doc, fix );
-
-				} else {
-					data_priv.access( doc, fix, attaches );
-				}
-			}
-		};
-	});
-}
-
-jQuery.fn.extend({
-
-	on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
-		var origFn, type;
-
-		// Types can be a map of types/handlers
-		if ( typeof types === "object" ) {
-			// ( types-Object, selector, data )
-			if ( typeof selector !== "string" ) {
-				// ( types-Object, data )
-				data = data || selector;
-				selector = undefined;
-			}
-			for ( type in types ) {
-				this.on( type, selector, data, types[ type ], one );
-			}
-			return this;
-		}
-
-		if ( data == null && fn == null ) {
-			// ( types, fn )
-			fn = selector;
-			data = selector = undefined;
-		} else if ( fn == null ) {
-			if ( typeof selector === "string" ) {
-				// ( types, selector, fn )
-				fn = data;
-				data = undefined;
-			} else {
-				// ( types, data, fn )
-				fn = data;
-				data = selector;
-				selector = undefined;
-			}
-		}
-		if ( fn === false ) {
-			fn = returnFalse;
-		} else if ( !fn ) {
-			return this;
-		}
-
-		if ( one === 1 ) {
-			origFn = fn;
-			fn = function( event ) {
-				// Can use an empty set, since event contains the info
-				jQuery().off( event );
-				return origFn.apply( this, arguments );
-			};
-			// Use same guid so caller can remove using origFn
-			fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
-		}
-		return this.each( function() {
-			jQuery.event.add( this, types, fn, data, selector );
-		});
-	},
-	one: function( types, selector, data, fn ) {
-		return this.on( types, selector, data, fn, 1 );
-	},
-	off: function( types, selector, fn ) {
-		var handleObj, type;
-		if ( types && types.preventDefault && types.handleObj ) {
-			// ( event )  dispatched jQuery.Event
-			handleObj = types.handleObj;
-			jQuery( types.delegateTarget ).off(
-				handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
-				handleObj.selector,
-				handleObj.handler
-			);
-			return this;
-		}
-		if ( typeof types === "object" ) {
-			// ( types-object [, selector] )
-			for ( type in types ) {
-				this.off( type, selector, types[ type ] );
-			}
-			return this;
-		}
-		if ( selector === false || typeof selector === "function" ) {
-			// ( types [, fn] )
-			fn = selector;
-			selector = undefined;
-		}
-		if ( fn === false ) {
-			fn = returnFalse;
-		}
-		return this.each(function() {
-			jQuery.event.remove( this, types, fn, selector );
-		});
-	},
-
-	trigger: function( type, data ) {
-		return this.each(function() {
-			jQuery.event.trigger( type, data, this );
-		});
-	},
-	triggerHandler: function( type, data ) {
-		var elem = this[0];
-		if ( elem ) {
-			return jQuery.event.trigger( type, data, elem, true );
-		}
-	}
-});
-
-
-var
-	rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
-	rtagName = /<([\w:]+)/,
-	rhtml = /<|&#?\w+;/,
-	rnoInnerhtml = /<(?:script|style|link)/i,
-	// checked="checked" or checked
-	rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
-	rscriptType = /^$|\/(?:java|ecma)script/i,
-	rscriptTypeMasked = /^true\/(.*)/,
-	rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
-
-	// We have to close these tags to support XHTML (#13200)
-	wrapMap = {
-
-		// Support: IE 9
-		option: [ 1, "<select multiple='multiple'>", "</select>" ],
-
-		thead: [ 1, "<table>", "</table>" ],
-		col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
-		tr: [ 2, "<table><tbody>", "</tbody></table>" ],
-		td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
-
-		_default: [ 0, "", "" ]
-	};
-
-// Support: IE 9
-wrapMap.optgroup = wrapMap.option;
-
-wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
-wrapMap.th = wrapMap.td;
-
-// Support: 1.x compatibility
-// Manipulating tables requires a tbody
-function manipulationTarget( elem, content ) {
-	return jQuery.nodeName( elem, "table" ) &&
-		jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
-
-		elem.getElementsByTagName("tbody")[0] ||
-			elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
-		elem;
-}
-
-// Replace/restore the type attribute of script elements for safe DOM manipulation
-function disableScript( elem ) {
-	elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
-	return elem;
-}
-function restoreScript( elem ) {
-	var match = rscriptTypeMasked.exec( elem.type );
-
-	if ( match ) {
-		elem.type = match[ 1 ];
-	} else {
-		elem.removeAttribute("type");
-	}
-
-	return elem;
-}
-
-// Mark scripts as having already been evaluated
-function setGlobalEval( elems, refElements ) {
-	var i = 0,
-		l = elems.length;
-
-	for ( ; i < l; i++ ) {
-		data_priv.set(
-			elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
-		);
-	}
-}
-
-function cloneCopyEvent( src, dest ) {
-	var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
-
-	if ( dest.nodeType !== 1 ) {
-		return;
-	}
-
-	// 1. Copy private data: events, handlers, etc.
-	if ( data_priv.hasData( src ) ) {
-		pdataOld = data_priv.access( src );
-		pdataCur = data_priv.set( dest, pdataOld );
-		events = pdataOld.events;
-
-		if ( events ) {
-			delete pdataCur.handle;
-			pdataCur.events = {};
-
-			for ( type in events ) {
-				for ( i = 0, l = events[ type ].length; i < l; i++ ) {
-					jQuery.event.add( dest, type, events[ type ][ i ] );
-				}
-			}
-		}
-	}
-
-	// 2. Copy user data
-	if ( data_user.hasData( src ) ) {
-		udataOld = data_user.access( src );
-		udataCur = jQuery.extend( {}, udataOld );
-
-		data_user.set( dest, udataCur );
-	}
-}
-
-function getAll( context, tag ) {
-	var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
-			context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
-			[];
-
-	return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
-		jQuery.merge( [ context ], ret ) :
-		ret;
-}
-
-// Support: IE >= 9
-function fixInput( src, dest ) {
-	var nodeName = dest.nodeName.toLowerCase();
-
-	// Fails to persist the checked state of a cloned checkbox or radio button.
-	if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
-		dest.checked = src.checked;
-
-	// Fails to return the selected option to the default selected state when cloning options
-	} else if ( nodeName === "input" || nodeName === "textarea" ) {
-		dest.defaultValue = src.defaultValue;
-	}
-}
-
-jQuery.extend({
-	clone: function( elem, dataAndEvents, deepDataAndEvents ) {
-		var i, l, srcElements, destElements,
-			clone = elem.cloneNode( true ),
-			inPage = jQuery.contains( elem.ownerDocument, elem );
-
-		// Support: IE >= 9
-		// Fix Cloning issues
-		if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
-				!jQuery.isXMLDoc( elem ) ) {
-
-			// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
-			destElements = getAll( clone );
-			srcElements = getAll( elem );
-
-			for ( i = 0, l = srcElements.length; i < l; i++ ) {
-				fixInput( srcElements[ i ], destElements[ i ] );
-			}
-		}
-
-		// Copy the events from the original to the clone
-		if ( dataAndEvents ) {
-			if ( deepDataAndEvents ) {
-				srcElements = srcElements || getAll( elem );
-				destElements = destElements || getAll( clone );
-
-				for ( i = 0, l = srcElements.length; i < l; i++ ) {
-					cloneCopyEvent( srcElements[ i ], destElements[ i ] );
-				}
-			} else {
-				cloneCopyEvent( elem, clone );
-			}
-		}
-
-		// Preserve script evaluation history
-		destElements = getAll( clone, "script" );
-		if ( destElements.length > 0 ) {
-			setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
-		}
-
-		// Return the cloned set
-		return clone;
-	},
-
-	buildFragment: function( elems, context, scripts, selection ) {
-		var elem, tmp, tag, wrap, contains, j,
-			fragment = context.createDocumentFragment(),
-			nodes = [],
-			i = 0,
-			l = elems.length;
-
-		for ( ; i < l; i++ ) {
-			elem = elems[ i ];
-
-			if ( elem || elem === 0 ) {
-
-				// Add nodes directly
-				if ( jQuery.type( elem ) === "object" ) {
-					// Support: QtWebKit
-					// jQuery.merge because push.apply(_, arraylike) throws
-					jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
-
-				// Convert non-html into a text node
-				} else if ( !rhtml.test( elem ) ) {
-					nodes.push( context.createTextNode( elem ) );
-
-				// Convert html into DOM nodes
-				} else {
-					tmp = tmp || fragment.appendChild( context.createElement("div") );
-
-					// Deserialize a standard representation
-					tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
-					wrap = wrapMap[ tag ] || wrapMap._default;
-					tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
-
-					// Descend through wrappers to the right content
-					j = wrap[ 0 ];
-					while ( j-- ) {
-						tmp = tmp.lastChild;
-					}
-
-					// Support: QtWebKit
-					// jQuery.merge because push.apply(_, arraylike) throws
-					jQuery.merge( nodes, tmp.childNodes );
-
-					// Remember the top-level container
-					tmp = fragment.firstChild;
-
-					// Fixes #12346
-					// Support: Webkit, IE
-					tmp.textContent = "";
-				}
-			}
-		}
-
-		// Remove wrapper from fragment
-		fragment.textContent = "";
-
-		i = 0;
-		while ( (elem = nodes[ i++ ]) ) {
-
-			// #4087 - If origin and destination elements are the same, and this is
-			// that element, do not do anything
-			if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
-				continue;
-			}
-
-			contains = jQuery.contains( elem.ownerDocument, elem );
-
-			// Append to fragment
-			tmp = getAll( fragment.appendChild( elem ), "script" );
-
-			// Preserve script evaluation history
-			if ( contains ) {
-				setGlobalEval( tmp );
-			}
-
-			// Capture executables
-			if ( scripts ) {
-				j = 0;
-				while ( (elem = tmp[ j++ ]) ) {
-					if ( rscriptType.test( elem.type || "" ) ) {
-						scripts.push( elem );
-					}
-				}
-			}
-		}
-
-		return fragment;
-	},
-
-	cleanData: function( elems ) {
-		var data, elem, type, key,
-			special = jQuery.event.special,
-			i = 0;
-
-		for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
-			if ( jQuery.acceptData( elem ) ) {
-				key = elem[ data_priv.expando ];
-
-				if ( key && (data = data_priv.cache[ key ]) ) {
-					if ( data.events ) {
-						for ( type in data.events ) {
-							if ( special[ type ] ) {
-								jQuery.event.remove( elem, type );
-
-							// This is a shortcut to avoid jQuery.event.remove's overhead
-							} else {
-								jQuery.removeEvent( elem, type, data.handle );
-							}
-						}
-					}
-					if ( data_priv.cache[ key ] ) {
-						// Discard any remaining `private` data
-						delete data_priv.cache[ key ];
-					}
-				}
-			}
-			// Discard any remaining `user` data
-			delete data_user.cache[ elem[ data_user.expando ] ];
-		}
-	}
-});
-
-jQuery.fn.extend({
-	text: function( value ) {
-		return access( this, function( value ) {
-			return value === undefined ?
-				jQuery.text( this ) :
-				this.empty().each(function() {
-					if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
-						this.textContent = value;
-					}
-				});
-		}, null, value, arguments.length );
-	},
-
-	append: function() {
-		return this.domManip( arguments, function( elem ) {
-			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
-				var target = manipulationTarget( this, elem );
-				target.appendChild( elem );
-			}
-		});
-	},
-
-	prepend: function() {
-		return this.domManip( arguments, function( elem ) {
-			if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
-				var target = manipulationTarget( this, elem );
-				target.insertBefore( elem, target.firstChild );
-			}
-		});
-	},
-
-	before: function() {
-		return this.domManip( arguments, function( elem ) {
-			if ( this.parentNode ) {
-				this.parentNode.insertBefore( elem, this );
-			}
-		});
-	},
-
-	after: function() {
-		return this.domManip( arguments, function( elem ) {
-			if ( this.parentNode ) {
-				this.parentNode.insertBefore( elem, this.nextSibling );
-			}
-		});
-	},
-
-	remove: function( selector, keepData /* Internal Use Only */ ) {
-		var elem,
-			elems = selector ? jQuery.filter( selector, this ) : this,
-			i = 0;
-
-		for ( ; (elem = elems[i]) != null; i++ ) {
-			if ( !keepData && elem.nodeType === 1 ) {
-				jQuery.cleanData( getAll( elem ) );
-			}
-
-			if ( elem.parentNode ) {
-				if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
-					setGlobalEval( getAll( elem, "script" ) );
-				}
-				elem.parentNode.removeChild( elem );
-			}
-		}
-
-		return this;
-	},
-
-	empty: function() {
-		var elem,
-			i = 0;
-
-		for ( ; (elem = this[i]) != null; i++ ) {
-			if ( elem.nodeType === 1 ) {
-
-				// Prevent memory leaks
-				jQuery.cleanData( getAll( elem, false ) );
-
-				// Remove any remaining nodes
-				elem.textContent = "";
-			}
-		}
-
-		return this;
-	},
-
-	clone: function( dataAndEvents, deepDataAndEvents ) {
-		dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
-		deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
-
-		return this.map(function() {
-			return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
-		});
-	},
-
-	html: function( value ) {
-		return access( this, function( value ) {
-			var elem = this[ 0 ] || {},
-				i = 0,
-				l = this.length;
-
-			if ( value === undefined && elem.nodeType === 1 ) {
-				return elem.innerHTML;
-			}
-
-			// See if we can take a shortcut and just use innerHTML
-			if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
-				!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
-
-				value = value.replace( rxhtmlTag, "<$1></$2>" );
-
-				try {
-					for ( ; i < l; i++ ) {
-						elem = this[ i ] || {};
-
-						// Remove element nodes and prevent memory leaks
-						if ( elem.nodeType === 1 ) {
-							jQuery.cleanData( getAll( elem, false ) );
-							elem.innerHTML = value;
-						}
-					}
-
-					elem = 0;
-
-				// If using innerHTML throws an exception, use the fallback method
-				} catch( e ) {}
-			}
-
-			if ( elem ) {
-				this.empty().append( value );
-			}
-		}, null, value, arguments.length );
-	},
-
-	replaceWith: function() {
-		var arg = arguments[ 0 ];
-
-		// Make the changes, replacing each context element with the new content
-		this.domManip( arguments, function( elem ) {
-			arg = this.parentNode;
-
-			jQuery.cleanData( getAll( this ) );
-
-			if ( arg ) {
-				arg.replaceChild( elem, this );
-			}
-		});
-
-		// Force removal if there was no new content (e.g., from empty arguments)
-		return arg && (arg.length || arg.nodeType) ? this : this.remove();
-	},
-
-	detach: function( selector ) {
-		return this.remove( selector, true );
-	},
-
-	domManip: function( args, callback ) {
-
-		// Flatten any nested arrays
-		args = concat.apply( [], args );
-
-		var fragment, first, scripts, hasScripts, node, doc,
-			i = 0,
-			l = this.length,
-			set = this,
-			iNoClone = l - 1,
-			value = args[ 0 ],
-			isFunction = jQuery.isFunction( value );
-
-		// We can't cloneNode fragments that contain checked, in WebKit
-		if ( isFunction ||
-				( l > 1 && typeof value === "string" &&
-					!support.checkClone && rchecked.test( value ) ) ) {
-			return this.each(function( index ) {
-				var self = set.eq( index );
-				if ( isFunction ) {
-					args[ 0 ] = value.call( this, index, self.html() );
-				}
-				self.domManip( args, callback );
-			});
-		}
-
-		if ( l ) {
-			fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
-			first = fragment.firstChild;
-
-			if ( fragment.childNodes.length === 1 ) {
-				fragment = first;
-			}
-
-			if ( first ) {
-				scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
-				hasScripts = scripts.length;
-
-				// Use the original fragment for the last item instead of the first because it can end up
-				// being emptied incorrectly in certain situations (#8070).
-				for ( ; i < l; i++ ) {
-					node = fragment;
-
-					if ( i !== iNoClone ) {
-						node = jQuery.clone( node, true, true );
-
-						// Keep references to cloned scripts for later restoration
-						if ( hasScripts ) {
-							// Support: QtWebKit
-							// jQuery.merge because push.apply(_, arraylike) throws
-							jQuery.merge( scripts, getAll( node, "script" ) );
-						}
-					}
-
-					callback.call( this[ i ], node, i );
-				}
-
-				if ( hasScripts ) {
-					doc = scripts[ scripts.length - 1 ].ownerDocument;
-
-					// Reenable scripts
-					jQuery.map( scripts, restoreScript );
-
-					// Evaluate executable scripts on first document insertion
-					for ( i = 0; i < hasScripts; i++ ) {
-						node = scripts[ i ];
-						if ( rscriptType.test( node.type || "" ) &&
-							!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
-
-							if ( node.src ) {
-								// Optional AJAX dependency, but won't run scripts if not present
-								if ( jQuery._evalUrl ) {
-									jQuery._evalUrl( node.src );
-								}
-							} else {
-								jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
-							}
-						}
-					}
-				}
-			}
-		}
-
-		return this;
-	}
-});
-
-jQuery.each({
-	appendTo: "append",
-	prependTo: "prepend",
-	insertBefore: "before",
-	insertAfter: "after",
-	replaceAll: "replaceWith"
-}, function( name, original ) {
-	jQuery.fn[ name ] = function( selector ) {
-		var elems,
-			ret = [],
-			insert = jQuery( selector ),
-			last = insert.length - 1,
-			i = 0;
-
-		for ( ; i <= last; i++ ) {
-			elems = i === last ? this : this.clone( true );
-			jQuery( insert[ i ] )[ original ]( elems );
-
-			// Support: QtWebKit
-			// .get() because push.apply(_, arraylike) throws
-			push.apply( ret, elems.get() );
-		}
-
-		return this.pushStack( ret );
-	};
-});
-
-
-var iframe,
-	elemdisplay = {};
-
-/**
- * Retrieve the actual display of a element
- * @param {String} name nodeName of the element
- * @param {Object} doc Document object
- */
-// Called only from within defaultDisplay
-function actualDisplay( name, doc ) {
-	var style,
-		elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
-
-		// getDefaultComputedStyle might be reliably used only on attached element
-		display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
-
-			// Use of this method is a temporary fix (more like optmization) until something better comes along,
-			// since it was removed from specification and supported only in FF
-			style.display : jQuery.css( elem[ 0 ], "display" );
-
-	// We don't have any data stored on the element,
-	// so use "detach" method as fast way to get rid of the element
-	elem.detach();
-
-	return display;
-}
-
-/**
- * Try to determine the default display value of an element
- * @param {String} nodeName
- */
-function defaultDisplay( nodeName ) {
-	var doc = document,
-		display = elemdisplay[ nodeName ];
-
-	if ( !display ) {
-		display = actualDisplay( nodeName, doc );
-
-		// If the simple way fails, read from inside an iframe
-		if ( display === "none" || !display ) {
-
-			// Use the already-created iframe if possible
-			iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
-
-			// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
-			doc = iframe[ 0 ].contentDocument;
-
-			// Support: IE
-			doc.write();
-			doc.close();
-
-			display = actualDisplay( nodeName, doc );
-			iframe.detach();
-		}
-
-		// Store the correct default display
-		elemdisplay[ nodeName ] = display;
-	}
-
-	return display;
-}
-var rmargin = (/^margin/);
-
-var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
-
-var getStyles = function( elem ) {
-		return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
-	};
-
-
-
-function curCSS( elem, name, computed ) {
-	var width, minWidth, maxWidth, ret,
-		style = elem.style;
-
-	computed = computed || getStyles( elem );
-
-	// Support: IE9
-	// getPropertyValue is only needed for .css('filter') in IE9, see #12537
-	if ( computed ) {
-		ret = computed.getPropertyValue( name ) || computed[ name ];
-	}
-
-	if ( computed ) {
-
-		if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
-			ret = jQuery.style( elem, name );
-		}
-
-		// Support: iOS < 6
-		// A tribute to the "awesome hack by Dean Edwards"
-		// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
-		// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
-		if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
-
-			// Remember the original values
-			width = style.width;
-			minWidth = style.minWidth;
-			maxWidth = style.maxWidth;
-
-			// Put in the new values to get a computed value out
-			style.minWidth = style.maxWidth = style.width = ret;
-			ret = computed.width;
-
-			// Revert the changed values
-			style.width = width;
-			style.minWidth = minWidth;
-			style.maxWidth = maxWidth;
-		}
-	}
-
-	return ret !== undefined ?
-		// Support: IE
-		// IE returns zIndex value as an integer.
-		ret + "" :
-		ret;
-}
-
-
-function addGetHookIf( conditionFn, hookFn ) {
-	// Define the hook, we'll check on the first run if it's really needed.
-	return {
-		get: function() {
-			if ( conditionFn() ) {
-				// Hook not needed (or it's not possible to use it due to missing dependency),
-				// remove it.
-				// Since there are no other hooks for marginRight, remove the whole object.
-				delete this.get;
-				return;
-			}
-
-			// Hook needed; redefine it so that the support test is not executed again.
-
-			return (this.get = hookFn).apply( this, arguments );
-		}
-	};
-}
-
-
-(function() {
-	var pixelPositionVal, boxSizingReliableVal,
-		docElem = document.documentElement,
-		container = document.createElement( "div" ),
-		div = document.createElement( "div" );
-
-	if ( !div.style ) {
-		return;
-	}
-
-	div.style.backgroundClip = "content-box";
-	div.cloneNode( true ).style.backgroundClip = "";
-	support.clearCloneStyle = div.style.backgroundClip === "content-box";
-
-	container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
-		"position:absolute";
-	container.appendChild( div );
-
-	// Executing both pixelPosition & boxSizingReliable tests require only one layout
-	// so they're executed at the same time to save the second computation.
-	function computePixelPositionAndBoxSizingReliable() {
-		div.style.cssText =
-			// Support: Firefox<29, Android 2.3
-			// Vendor-prefix box-sizing
-			"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
-			"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
-			"border:1px;padding:1px;width:4px;position:absolute";
-		div.innerHTML = "";
-		docElem.appendChild( container );
-
-		var divStyle = window.getComputedStyle( div, null );
-		pixelPositionVal = divStyle.top !== "1%";
-		boxSizingReliableVal = divStyle.width === "4px";
-
-		docElem.removeChild( container );
-	}
-
-	// Support: node.js jsdom
-	// Don't assume that getComputedStyle is a property of the global object
-	if ( window.getComputedStyle ) {
-		jQuery.extend( support, {
-			pixelPosition: function() {
-				// This test is executed only once but we still do memoizing
-				// since we can use the boxSizingReliable pre-computing.
-				// No need to check if the test was already performed, though.
-				computePixelPositionAndBoxSizingReliable();
-				return pixelPositionVal;
-			},
-			boxSizingReliable: function() {
-				if ( boxSizingReliableVal == null ) {
-					computePixelPositionAndBoxSizingReliable();
-				}
-				return boxSizingReliableVal;
-			},
-			reliableMarginRight: function() {
-				// Support: Android 2.3
-				// Check if div with explicit width and no margin-right incorrectly
-				// gets computed margin-right based on width of container. (#3333)
-				// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
-				// This support function is only executed once so no memoizing is needed.
-				var ret,
-					marginDiv = div.appendChild( document.createElement( "div" ) );
-
-				// Reset CSS: box-sizing; display; margin; border; padding
-				marginDiv.style.cssText = div.style.cssText =
-					// Support: Firefox<29, Android 2.3
-					// Vendor-prefix box-sizing
-					"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
-					"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
-				marginDiv.style.marginRight = marginDiv.style.width = "0";
-				div.style.width = "1px";
-				docElem.appendChild( container );
-
-				ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
-
-				docElem.removeChild( container );
-
-				return ret;
-			}
-		});
-	}
-})();
-
-
-// A method for quickly swapping in/out CSS properties to get correct calculations.
-jQuery.swap = function( elem, options, callback, args ) {
-	var ret, name,
-		old = {};
-
-	// Remember the old values, and insert the new ones
-	for ( name in options ) {
-		old[ name ] = elem.style[ name ];
-		elem.style[ name ] = options[ name ];
-	}
-
-	ret = callback.apply( elem, args || [] );
-
-	// Revert the old values
-	for ( name in options ) {
-		elem.style[ name ] = old[ name ];
-	}
-
-	return ret;
-};
-
-
-var
-	// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
-	// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
-	rdisplayswap = /^(none|table(?!-c[ea]).+)/,
-	rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
-	rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
-
-	cssShow = { position: "absolute", visibility: "hidden", display: "block" },
-	cssNormalTransform = {
-		letterSpacing: "0",
-		fontWeight: "400"
-	},
-
-	cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
-
-// return a css property mapped to a potentially vendor prefixed property
-function vendorPropName( style, name ) {
-
-	// shortcut for names that are not vendor prefixed
-	if ( name in style ) {
-		return name;
-	}
-
-	// check for vendor prefixed names
-	var capName = name[0].toUpperCase() + name.slice(1),
-		origName = name,
-		i = cssPrefixes.length;
-
-	while ( i-- ) {
-		name = cssPrefixes[ i ] + capName;
-		if ( name in style ) {
-			return name;
-		}
-	}
-
-	return origName;
-}
-
-function setPositiveNumber( elem, value, subtract ) {
-	var matches = rnumsplit.exec( value );
-	return matches ?
-		// Guard against undefined "subtract", e.g., when used as in cssHooks
-		Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
-		value;
-}
-
-function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
-	var i = extra === ( isBorderBox ? "border" : "content" ) ?
-		// If we already have the right measurement, avoid augmentation
-		4 :
-		// Otherwise initialize for horizontal or vertical properties
-		name === "width" ? 1 : 0,
-
-		val = 0;
-
-	for ( ; i < 4; i += 2 ) {
-		// both box models exclude margin, so add it if we want it
-		if ( extra === "margin" ) {
-			val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
-		}
-
-		if ( isBorderBox ) {
-			// border-box includes padding, so remove it if we want content
-			if ( extra === "content" ) {
-				val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
-			}
-
-			// at this point, extra isn't border nor margin, so remove border
-			if ( extra !== "margin" ) {
-				val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
-			}
-		} else {
-			// at this point, extra isn't content, so add padding
-			val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
-
-			// at this point, extra isn't content nor padding, so add border
-			if ( extra !== "padding" ) {
-				val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
-			}
-		}
-	}
-
-	return val;
-}
-
-function getWidthOrHeight( elem, name, extra ) {
-
-	// Start with offset property, which is equivalent to the border-box value
-	var valueIsBorderBox = true,
-		val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
-		styles = getStyles( elem ),
-		isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
-
-	// some non-html elements return undefined for offsetWidth, so check for null/undefined
-	// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
-	// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
-	if ( val <= 0 || val == null ) {
-		// Fall back to computed then uncomputed css if necessary
-		val = curCSS( elem, name, styles );
-		if ( val < 0 || val == null ) {
-			val = elem.style[ name ];
-		}
-
-		// Computed unit is not pixels. Stop here and return.
-		if ( rnumnonpx.test(val) ) {
-			return val;
-		}
-
-		// we need the check for style in case a browser which returns unreliable values
-		// for getComputedStyle silently falls back to the reliable elem.style
-		valueIsBorderBox = isBorderBox &&
-			( support.boxSizingReliable() || val === elem.style[ name ] );
-
-		// Normalize "", auto, and prepare for extra
-		val = parseFloat( val ) || 0;
-	}
-
-	// use the active box-sizing model to add/subtract irrelevant styles
-	return ( val +
-		augmentWidthOrHeight(
-			elem,
-			name,
-			extra || ( isBorderBox ? "border" : "content" ),
-			valueIsBorderBox,
-			styles
-		)
-	) + "px";
-}
-
-function showHide( elements, show ) {
-	var display, elem, hidden,
-		values = [],
-		index = 0,
-		length = elements.length;
-
-	for ( ; index < length; index++ ) {
-		elem = elements[ index ];
-		if ( !elem.style ) {
-			continue;
-		}
-
-		values[ index ] = data_priv.get( elem, "olddisplay" );
-		display = elem.style.display;
-		if ( show ) {
-			// Reset the inline display of this element to learn if it is
-			// being hidden by cascaded rules or not
-			if ( !values[ index ] && display === "none" ) {
-				elem.style.display = "";
-			}
-
-			// Set elements which have been overridden with display: none
-			// in a stylesheet to whatever the default browser style is
-			// for such an element
-			if ( elem.style.display === "" && isHidden( elem ) ) {
-				values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
-			}
-		} else {
-			hidden = isHidden( elem );
-
-			if ( display !== "none" || !hidden ) {
-				data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
-			}
-		}
-	}
-
-	// Set the display of most of the elements in a second loop
-	// to avoid the constant reflow
-	for ( index = 0; index < length; index++ ) {
-		elem = elements[ index ];
-		if ( !elem.style ) {
-			continue;
-		}
-		if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
-			elem.style.display = show ? values[ index ] || "" : "none";
-		}
-	}
-
-	return elements;
-}
-
-jQuery.extend({
-	// Add in style property hooks for overriding the default
-	// behavior of getting and setting a style property
-	cssHooks: {
-		opacity: {
-			get: function( elem, computed ) {
-				if ( computed ) {
-					// We should always get a number back from opacity
-					var ret = curCSS( elem, "opacity" );
-					return ret === "" ? "1" : ret;
-				}
-			}
-		}
-	},
-
-	// Don't automatically add "px" to these possibly-unitless properties
-	cssNumber: {
-		"columnCount": true,
-		"fillOpacity": true,
-		"flexGrow": true,
-		"flexShrink": true,
-		"fontWeight": true,
-		"lineHeight": true,
-		"opacity": true,
-		"order": true,
-		"orphans": true,
-		"widows": true,
-		"zIndex": true,
-		"zoom": true
-	},
-
-	// Add in properties whose names you wish to fix before
-	// setting or getting the value
-	cssProps: {
-		// normalize float css property
-		"float": "cssFloat"
-	},
-
-	// Get and set the style property on a DOM Node
-	style: function( elem, name, value, extra ) {
-		// Don't set styles on text and comment nodes
-		if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
-			return;
-		}
-
-		// Make sure that we're working with the right name
-		var ret, type, hooks,
-			origName = jQuery.camelCase( name ),
-			style = elem.style;
-
-		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
-
-		// gets hook for the prefixed version
-		// followed by the unprefixed version
-		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
-
-		// Check if we're setting a value
-		if ( value !== undefined ) {
-			type = typeof value;
-
-			// convert relative number strings (+= or -=) to relative numbers. #7345
-			if ( type === "string" && (ret = rrelNum.exec( value )) ) {
-				value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
-				// Fixes bug #9237
-				type = "number";
-			}
-
-			// Make sure that null and NaN values aren't set. See: #7116
-			if ( value == null || value !== value ) {
-				return;
-			}
-
-			// If a number was passed in, add 'px' to the (except for certain CSS properties)
-			if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
-				value += "px";
-			}
-
-			// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
-			// but it would mean to define eight (for every problematic property) identical functions
-			if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
-				style[ name ] = "inherit";
-			}
-
-			// If a hook was provided, use that value, otherwise just set the specified value
-			if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
-				style[ name ] = value;
-			}
-
-		} else {
-			// If a hook was provided get the non-computed value from there
-			if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
-				return ret;
-			}
-
-			// Otherwise just get the value from the style object
-			return style[ name ];
-		}
-	},
-
-	css: function( elem, name, extra, styles ) {
-		var val, num, hooks,
-			origName = jQuery.camelCase( name );
-
-		// Make sure that we're working with the right name
-		name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
-
-		// gets hook for the prefixed version
-		// followed by the unprefixed version
-		hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
-
-		// If a hook was provided get the computed value from there
-		if ( hooks && "get" in hooks ) {
-			val = hooks.get( elem, true, extra );
-		}
-
-		// Otherwise, if a way to get the computed value exists, use that
-		if ( val === undefined ) {
-			val = curCSS( elem, name, styles );
-		}
-
-		//convert "normal" to computed value
-		if ( val === "normal" && name in cssNormalTransform ) {
-			val = cssNormalTransform[ name ];
-		}
-
-		// Return, converting to number if forced or a qualifier was provided and val looks numeric
-		if ( extra === "" || extra ) {
-			num = parseFloat( val );
-			return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
-		}
-		return val;
-	}
-});
-
-jQuery.each([ "height", "width" ], function( i, name ) {
-	jQuery.cssHooks[ name ] = {
-		get: function( elem, computed, extra ) {
-			if ( computed ) {
-				// certain elements can have dimension info if we invisibly show them
-				// however, it must have a current display style that would benefit from this
-				return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
-					jQuery.swap( elem, cssShow, function() {
-						return getWidthOrHeight( elem, name, extra );
-					}) :
-					getWidthOrHeight( elem, name, extra );
-			}
-		},
-
-		set: function( elem, value, extra ) {
-			var styles = extra && getStyles( elem );
-			return setPositiveNumber( elem, value, extra ?
-				augmentWidthOrHeight(
-					elem,
-					name,
-					extra,
-					jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
-					styles
-				) : 0
-			);
-		}
-	};
-});
-
-// Support: Android 2.3
-jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
-	function( elem, computed ) {
-		if ( computed ) {
-			// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
-			// Work around by temporarily setting element display to inline-block
-			return jQuery.swap( elem, { "display": "inline-block" },
-				curCSS, [ elem, "marginRight" ] );
-		}
-	}
-);
-
-// These hooks are used by animate to expand properties
-jQuery.each({
-	margin: "",
-	padding: "",
-	border: "Width"
-}, function( prefix, suffix ) {
-	jQuery.cssHooks[ prefix + suffix ] = {
-		expand: function( value ) {
-			var i = 0,
-				expanded = {},
-
-				// assumes a single number if not a string
-				parts = typeof value === "string" ? value.split(" ") : [ value ];
-
-			for ( ; i < 4; i++ ) {
-				expanded[ prefix + cssExpand[ i ] + suffix ] =
-					parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
-			}
-
-			return expanded;
-		}
-	};
-
-	if ( !rmargin.test( prefix ) ) {
-		jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
-	}
-});
-
-jQuery.fn.extend({
-	css: function( name, value ) {
-		return access( this, function( elem, name, value ) {
-			var styles, len,
-				map = {},
-				i = 0;
-
-			if ( jQuery.isArray( name ) ) {
-				styles = getStyles( elem );
-				len = name.length;
-
-				for ( ; i < len; i++ ) {
-					map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
-				}
-
-				return map;
-			}
-
-			return value !== undefined ?
-				jQuery.style( elem, name, value ) :
-				jQuery.css( elem, name );
-		}, name, value, arguments.length > 1 );
-	},
-	show: function() {
-		return showHide( this, true );
-	},
-	hide: function() {
-		return showHide( this );
-	},
-	toggle: function( state ) {
-		if ( typeof state === "boolean" ) {
-			return state ? this.show() : this.hide();
-		}
-
-		return this.each(function() {
-			if ( isHidden( this ) ) {
-				jQuery( this ).show();
-			} else {
-				jQuery( this ).hide();
-			}
-		});
-	}
-});
-
-
-function Tween( elem, options, prop, end, easing ) {
-	return new Tween.prototype.init( elem, options, prop, end, easing );
-}
-jQuery.Tween = Tween;
-
-Tween.prototype = {
-	constructor: Tween,
-	init: function( elem, options, prop, end, easing, unit ) {
-		this.elem = elem;
-		this.prop = prop;
-		this.easing = easing || "swing";
-		this.options = options;
-		this.start = this.now = this.cur();
-		this.end = end;
-		this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
-	},
-	cur: function() {
-		var hooks = Tween.propHooks[ this.prop ];
-
-		return hooks && hooks.get ?
-			hooks.get( this ) :
-			Tween.propHooks._default.get( this );
-	},
-	run: function( percent ) {
-		var eased,
-			hooks = Tween.propHooks[ this.prop ];
-
-		if ( this.options.duration ) {
-			this.pos = eased = jQuery.easing[ this.easing ](
-				percent, this.options.duration * percent, 0, 1, this.options.duration
-			);
-		} else {
-			this.pos = eased = percent;
-		}
-		this.now = ( this.end - this.start ) * eased + this.start;
-
-		if ( this.options.step ) {
-			this.options.step.call( this.elem, this.now, this );
-		}
-
-		if ( hooks && hooks.set ) {
-			hooks.set( this );
-		} else {
-			Tween.propHooks._default.set( this );
-		}
-		return this;
-	}
-};
-
-Tween.prototype.init.prototype = Tween.prototype;
-
-Tween.propHooks = {
-	_default: {
-		get: function( tween ) {
-			var result;
-
-			if ( tween.elem[ tween.prop ] != null &&
-				(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
-				return tween.elem[ tween.prop ];
-			}
-
-			// passing an empty string as a 3rd parameter to .css will automatically
-			// attempt a parseFloat and fallback to a string if the parse fails
-			// so, simple values such as "10px" are parsed to Float.
-			// complex values such as "rotate(1rad)" are returned as is.
-			result = jQuery.css( tween.elem, tween.prop, "" );
-			// Empty strings, null, undefined and "auto" are converted to 0.
-			return !result || result === "auto" ? 0 : result;
-		},
-		set: function( tween ) {
-			// use step hook for back compat - use cssHook if its there - use .style if its
-			// available and use plain properties where available
-			if ( jQuery.fx.step[ tween.prop ] ) {
-				jQuery.fx.step[ tween.prop ]( tween );
-			} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
-				jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
-			} else {
-				tween.elem[ tween.prop ] = tween.now;
-			}
-		}
-	}
-};
-
-// Support: IE9
-// Panic based approach to setting things on disconnected nodes
-
-Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
-	set: function( tween ) {
-		if ( tween.elem.nodeType && tween.elem.parentNode ) {
-			tween.elem[ tween.prop ] = tween.now;
-		}
-	}
-};
-
-jQuery.easing = {
-	linear: function( p ) {
-		return p;
-	},
-	swing: function( p ) {
-		return 0.5 - Math.cos( p * Math.PI ) / 2;
-	}
-};
-
-jQuery.fx = Tween.prototype.init;
-
-// Back Compat <1.8 extension point
-jQuery.fx.step = {};
-
-
-
-
-var
-	fxNow, timerId,
-	rfxtypes = /^(?:toggle|show|hide)$/,
-	rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
-	rrun = /queueHooks$/,
-	animationPrefilters = [ defaultPrefilter ],
-	tweeners = {
-		"*": [ function( prop, value ) {
-			var tween = this.createTween( prop, value ),
-				target = tween.cur(),
-				parts = rfxnum.exec( value ),
-				unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
-
-				// Starting value computation is required for potential unit mismatches
-				start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
-					rfxnum.exec( jQuery.css( tween.elem, prop ) ),
-				scale = 1,
-				maxIterations = 20;
-
-			if ( start && start[ 3 ] !== unit ) {
-				// Trust units reported by jQuery.css
-				unit = unit || start[ 3 ];
-
-				// Make sure we update the tween properties later on
-				parts = parts || [];
-
-				// Iteratively approximate from a nonzero starting point
-				start = +target || 1;
-
-				do {
-					// If previous iteration zeroed out, double until we get *something*
-					// Use a string for doubling factor so we don't accidentally see scale as unchanged below
-					scale = scale || ".5";
-
-					// Adjust and apply
-					start = start / scale;
-					jQuery.style( tween.elem, prop, start + unit );
-
-				// Update scale, tolerating zero or NaN from tween.cur()
-				// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
-				} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
-			}
-
-			// Update tween properties
-			if ( parts ) {
-				start = tween.start = +start || +target || 0;
-				tween.unit = unit;
-				// If a +=/-= token was provided, we're doing a relative animation
-				tween.end = parts[ 1 ] ?
-					start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
-					+parts[ 2 ];
-			}
-
-			return tween;
-		} ]
-	};
-
-// Animations created synchronously will run synchronously
-function createFxNow() {
-	setTimeout(function() {
-		fxNow = undefined;
-	});
-	return ( fxNow = jQuery.now() );
-}
-
-// Generate parameters to create a standard animation
-function genFx( type, includeWidth ) {
-	var which,
-		i = 0,
-		attrs = { height: type };
-
-	// if we include width, step value is 1 to do all cssExpand values,
-	// if we don't include width, step value is 2 to skip over Left and Right
-	includeWidth = includeWidth ? 1 : 0;
-	for ( ; i < 4 ; i += 2 - includeWidth ) {
-		which = cssExpand[ i ];
-		attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
-	}
-
-	if ( includeWidth ) {
-		attrs.opacity = attrs.width = type;
-	}
-
-	return attrs;
-}
-
-function createTween( value, prop, animation ) {
-	var tween,
-		collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
-		index = 0,
-		length = collection.length;
-	for ( ; index < length; index++ ) {
-		if ( (tween = collection[ index ].call( animation, prop, value )) ) {
-
-			// we're done with this property
-			return tween;
-		}
-	}
-}
-
-function defaultPrefilter( elem, props, opts ) {
-	/* jshint validthis: true */
-	var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
-		anim = this,
-		orig = {},
-		style = elem.style,
-		hidden = elem.nodeType && isHidden( elem ),
-		dataShow = data_priv.get( elem, "fxshow" );
-
-	// handle queue: false promises
-	if ( !opts.queue ) {
-		hooks = jQuery._queueHooks( elem, "fx" );
-		if ( hooks.unqueued == null ) {
-			hooks.unqueued = 0;
-			oldfire = hooks.empty.fire;
-			hooks.empty.fire = function() {
-				if ( !hooks.unqueued ) {
-					oldfire();
-				}
-			};
-		}
-		hooks.unqueued++;
-
-		anim.always(function() {
-			// doing this makes sure that the complete handler will be called
-			// before this completes
-			anim.always(function() {
-				hooks.unqueued--;
-				if ( !jQuery.queue( elem, "fx" ).length ) {
-					hooks.empty.fire();
-				}
-			});
-		});
-	}
-
-	// height/width overflow pass
-	if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
-		// Make sure that nothing sneaks out
-		// Record all 3 overflow attributes because IE9-10 do not
-		// change the overflow attribute when overflowX and
-		// overflowY are set to the same value
-		opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
-
-		// Set display property to inline-block for height/width
-		// animations on inline elements that are having width/height animated
-		display = jQuery.css( elem, "display" );
-
-		// Test default display if display is currently "none"
-		checkDisplay = display === "none" ?
-			data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
-
-		if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
-			style.display = "inline-block";
-		}
-	}
-
-	if ( opts.overflow ) {
-		style.overflow = "hidden";
-		anim.always(function() {
-			style.overflow = opts.overflow[ 0 ];
-			style.overflowX = opts.overflow[ 1 ];
-			style.overflowY = opts.overflow[ 2 ];
-		});
-	}
-
-	// show/hide pass
-	for ( prop in props ) {
-		value = props[ prop ];
-		if ( rfxtypes.exec( value ) ) {
-			delete props[ prop ];
-			toggle = toggle || value === "toggle";
-			if ( value === ( hidden ? "hide" : "show" ) ) {
-
-				// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
-				if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
-					hidden = true;
-				} else {
-					continue;
-				}
-			}
-			orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
-
-		// Any non-fx value stops us from restoring the original display value
-		} else {
-			display = undefined;
-		}
-	}
-
-	if ( !jQuery.isEmptyObject( orig ) ) {
-		if ( dataShow ) {
-			if ( "hidden" in dataShow ) {
-				hidden = dataShow.hidden;
-			}
-		} else {
-			dataShow = data_priv.access( elem, "fxshow", {} );
-		}
-
-		// store state if its toggle - enables .stop().toggle() to "reverse"
-		if ( toggle ) {
-			dataShow.hidden = !hidden;
-		}
-		if ( hidden ) {
-			jQuery( elem ).show();
-		} else {
-			anim.done(function() {
-				jQuery( elem ).hide();
-			});
-		}
-		anim.done(function() {
-			var prop;
-
-			data_priv.remove( elem, "fxshow" );
-			for ( prop in orig ) {
-				jQuery.style( elem, prop, orig[ prop ] );
-			}
-		});
-		for ( prop in orig ) {
-			tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
-
-			if ( !( prop in dataShow ) ) {
-				dataShow[ prop ] = tween.start;
-				if ( hidden ) {
-					tween.end = tween.start;
-					tween.start = prop === "width" || prop === "height" ? 1 : 0;
-				}
-			}
-		}
-
-	// If this is a noop like .hide().hide(), restore an overwritten display value
-	} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
-		style.display = display;
-	}
-}
-
-function propFilter( props, specialEasing ) {
-	var index, name, easing, value, hooks;
-
-	// camelCase, specialEasing and expand cssHook pass
-	for ( index in props ) {
-		name = jQuery.camelCase( index );
-		easing = specialEasing[ name ];
-		value = props[ index ];
-		if ( jQuery.isArray( value ) ) {
-			easing = value[ 1 ];
-			value = props[ index ] = value[ 0 ];
-		}
-
-		if ( index !== name ) {
-			props[ name ] = value;
-			delete props[ index ];
-		}
-
-		hooks = jQuery.cssHooks[ name ];
-		if ( hooks && "expand" in hooks ) {
-			value = hooks.expand( value );
-			delete props[ name ];
-
-			// not quite $.extend, this wont overwrite keys already present.
-			// also - reusing 'index' from above because we have the correct "name"
-			for ( index in value ) {
-				if ( !( index in props ) ) {
-					props[ index ] = value[ index ];
-					specialEasing[ index ] = easing;
-				}
-			}
-		} else {
-			specialEasing[ name ] = easing;
-		}
-	}
-}
-
-function Animation( elem, properties, options ) {
-	var result,
-		stopped,
-		index = 0,
-		length = animationPrefilters.length,
-		deferred = jQuery.Deferred().always( function() {
-			// don't match elem in the :animated selector
-			delete tick.elem;
-		}),
-		tick = function() {
-			if ( stopped ) {
-				return false;
-			}
-			var currentTime = fxNow || createFxNow(),
-				remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
-				// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
-				temp = remaining / animation.duration || 0,
-				percent = 1 - temp,
-				index = 0,
-				length = animation.tweens.length;
-
-			for ( ; index < length ; index++ ) {
-				animation.tweens[ index ].run( percent );
-			}
-
-			deferred.notifyWith( elem, [ animation, percent, remaining ]);
-
-			if ( percent < 1 && length ) {
-				return remaining;
-			} else {
-				deferred.resolveWith( elem, [ animation ] );
-				return false;
-			}
-		},
-		animation = deferred.promise({
-			elem: elem,
-			props: jQuery.extend( {}, properties ),
-			opts: jQuery.extend( true, { specialEasing: {} }, options ),
-			originalProperties: properties,
-			originalOptions: options,
-			startTime: fxNow || createFxNow(),
-			duration: options.duration,
-			tweens: [],
-			createTween: function( prop, end ) {
-				var tween = jQuery.Tween( elem, animation.opts, prop, end,
-						animation.opts.specialEasing[ prop ] || animation.opts.easing );
-				animation.tweens.push( tween );
-				return tween;
-			},
-			stop: function( gotoEnd ) {
-				var index = 0,
-					// if we are going to the end, we want to run all the tweens
-					// otherwise we skip this part
-					length = gotoEnd ? animation.tweens.length : 0;
-				if ( stopped ) {
-					return this;
-				}
-				stopped = true;
-				for ( ; index < length ; index++ ) {
-					animation.tweens[ index ].run( 1 );
-				}
-
-				// resolve when we played the last frame
-				// otherwise, reject
-				if ( gotoEnd ) {
-					deferred.resolveWith( elem, [ animation, gotoEnd ] );
-				} else {
-					deferred.rejectWith( elem, [ animation, gotoEnd ] );
-				}
-				return this;
-			}
-		}),
-		props = animation.props;
-
-	propFilter( props, animation.opts.specialEasing );
-
-	for ( ; index < length ; index++ ) {
-		result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
-		if ( result ) {
-			return result;
-		}
-	}
-
-	jQuery.map( props, createTween, animation );
-
-	if ( jQuery.isFunction( animation.opts.start ) ) {
-		animation.opts.start.call( elem, animation );
-	}
-
-	jQuery.fx.timer(
-		jQuery.extend( tick, {
-			elem: elem,
-			anim: animation,
-			queue: animation.opts.queue
-		})
-	);
-
-	// attach callbacks from options
-	return animation.progress( animation.opts.progress )
-		.done( animation.opts.done, animation.opts.complete )
-		.fail( animation.opts.fail )
-		.always( animation.opts.always );
-}
-
-jQuery.Animation = jQuery.extend( Animation, {
-
-	tweener: function( props, callback ) {
-		if ( jQuery.isFunction( props ) ) {
-			callback = props;
-			props = [ "*" ];
-		} else {
-			props = props.split(" ");
-		}
-
-		var prop,
-			index = 0,
-			length = props.length;
-
-		for ( ; index < length ; index++ ) {
-			prop = props[ index ];
-			tweeners[ prop ] = tweeners[ prop ] || [];
-			tweeners[ prop ].unshift( callback );
-		}
-	},
-
-	prefilter: function( callback, prepend ) {
-		if ( prepend ) {
-			animationPrefilters.unshift( callback );
-		} else {
-			animationPrefilters.push( callback );
-		}
-	}
-});
-
-jQuery.speed = function( speed, easing, fn ) {
-	var opt = speed && typeof speed === "object" ? jQuery.extend( {}, 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 :
-		opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
-
-	// normalize opt.queue - true/undefined/null -> "fx"
-	if ( opt.queue == null || opt.queue === true ) {
-		opt.queue = "fx";
-	}
-
-	// Queueing
-	opt.old = opt.complete;
-
-	opt.complete = function() {
-		if ( jQuery.isFunction( opt.old ) ) {
-			opt.old.call( this );
-		}
-
-		if ( opt.queue ) {
-			jQuery.dequeue( this, opt.queue );
-		}
-	};
-
-	return opt;
-};
-
-jQuery.fn.extend({
-	fadeTo: function( speed, to, easing, callback ) {
-
-		// show any hidden elements after setting opacity to 0
-		return this.filter( isHidden ).css( "opacity", 0 ).show()
-
-			// animate to the value specified
-			.end().animate({ opacity: to }, speed, easing, callback );
-	},
-	animate: function( prop, speed, easing, callback ) {
-		var empty = jQuery.isEmptyObject( prop ),
-			optall = jQuery.speed( speed, easing, callback ),
-			doAnimation = function() {
-				// Operate on a copy of prop so per-property easing won't be lost
-				var anim = Animation( this, jQuery.extend( {}, prop ), optall );
-
-				// Empty animations, or finishing resolves immediately
-				if ( empty || data_priv.get( this, "finish" ) ) {
-					anim.stop( true );
-				}
-			};
-			doAnimation.finish = doAnimation;
-
-		return empty || optall.queue === false ?
-			this.each( doAnimation ) :
-			this.queue( optall.queue, doAnimation );
-	},
-	stop: function( type, clearQueue, gotoEnd ) {
-		var stopQueue = function( hooks ) {
-			var stop = hooks.stop;
-			delete hooks.stop;
-			stop( gotoEnd );
-		};
-
-		if ( typeof type !== "string" ) {
-			gotoEnd = clearQueue;
-			clearQueue = type;
-			type = undefined;
-		}
-		if ( clearQueue && type !== false ) {
-			this.queue( type || "fx", [] );
-		}
-
-		return this.each(function() {
-			var dequeue = true,
-				index = type != null && type + "queueHooks",
-				timers = jQuery.timers,
-				data = data_priv.get( this );
-
-			if ( index ) {
-				if ( data[ index ] && data[ index ].stop ) {
-					stopQueue( data[ index ] );
-				}
-			} else {
-				for ( index in data ) {
-					if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
-						stopQueue( data[ index ] );
-					}
-				}
-			}
-
-			for ( index = timers.length; index--; ) {
-				if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
-					timers[ index ].anim.stop( gotoEnd );
-					dequeue = false;
-					timers.splice( index, 1 );
-				}
-			}
-
-			// start the next in the queue if the last step wasn't forced
-			// timers currently will call their complete callbacks, which will dequeue
-			// but only if they were gotoEnd
-			if ( dequeue || !gotoEnd ) {
-				jQuery.dequeue( this, type );
-			}
-		});
-	},
-	finish: function( type ) {
-		if ( type !== false ) {
-			type = type || "fx";
-		}
-		return this.each(function() {
-			var index,
-				data = data_priv.get( this ),
-				queue = data[ type + "queue" ],
-				hooks = data[ type + "queueHooks" ],
-				timers = jQuery.timers,
-				length = queue ? queue.length : 0;
-
-			// enable finishing flag on private data
-			data.finish = true;
-
-			// empty the queue first
-			jQuery.queue( this, type, [] );
-
-			if ( hooks && hooks.stop ) {
-				hooks.stop.call( this, true );
-			}
-
-			// look for any active animations, and finish them
-			for ( index = timers.length; index--; ) {
-				if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
-					timers[ index ].anim.stop( true );
-					timers.splice( index, 1 );
-				}
-			}
-
-			// look for any animations in the old queue and finish them
-			for ( index = 0; index < length; index++ ) {
-				if ( queue[ index ] && queue[ index ].finish ) {
-					queue[ index ].finish.call( this );
-				}
-			}
-
-			// turn off finishing flag
-			delete data.finish;
-		});
-	}
-});
-
-jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
-	var cssFn = jQuery.fn[ name ];
-	jQuery.fn[ name ] = function( speed, easing, callback ) {
-		return speed == null || typeof speed === "boolean" ?
-			cssFn.apply( this, arguments ) :
-			this.animate( genFx( name, true ), speed, easing, callback );
-	};
-});
-
-// Generate shortcuts for custom animations
-jQuery.each({
-	slideDown: genFx("show"),
-	slideUp: genFx("hide"),
-	slideToggle: genFx("toggle"),
-	fadeIn: { opacity: "show" },
-	fadeOut: { opacity: "hide" },
-	fadeToggle: { opacity: "toggle" }
-}, function( name, props ) {
-	jQuery.fn[ name ] = function( speed, easing, callback ) {
-		return this.animate( props, speed, easing, callback );
-	};
-});
-
-jQuery.timers = [];
-jQuery.fx.tick = function() {
-	var timer,
-		i = 0,
-		timers = jQuery.timers;
-
-	fxNow = jQuery.now();
-
-	for ( ; i < timers.length; i++ ) {
-		timer = timers[ i ];
-		// Checks the timer has not already been removed
-		if ( !timer() && timers[ i ] === timer ) {
-			timers.splice( i--, 1 );
-		}
-	}
-
-	if ( !timers.length ) {
-		jQuery.fx.stop();
-	}
-	fxNow = undefined;
-};
-
-jQuery.fx.timer = function( timer ) {
-	jQuery.timers.push( timer );
-	if ( timer() ) {
-		jQuery.fx.start();
-	} else {
-		jQuery.timers.pop();
-	}
-};
-
-jQuery.fx.interval = 13;
-
-jQuery.fx.start = function() {
-	if ( !timerId ) {
-		timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
-	}
-};
-
-jQuery.fx.stop = function() {
-	clearInterval( timerId );
-	timerId = null;
-};
-
-jQuery.fx.speeds = {
-	slow: 600,
-	fast: 200,
-	// Default speed
-	_default: 400
-};
-
-
-// Based off of the plugin by Clint Helfers, with permission.
-// http://blindsignals.com/index.php/2009/07/jquery-delay/
-jQuery.fn.delay = function( time, type ) {
-	time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
-	type = type || "fx";
-
-	return this.queue( type, function( next, hooks ) {
-		var timeout = setTimeout( next, time );
-		hooks.stop = function() {
-			clearTimeout( timeout );
-		};
-	});
-};
-
-
-(function() {
-	var input = document.createElement( "input" ),
-		select = document.createElement( "select" ),
-		opt = select.appendChild( document.createElement( "option" ) );
-
-	input.type = "checkbox";
-
-	// Support: iOS 5.1, Android 4.x, Android 2.3
-	// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
-	support.checkOn = input.value !== "";
-
-	// Must access the parent to make an option select properly
-	// Support: IE9, IE10
-	support.optSelected = opt.selected;
-
-	// Make sure that the options inside disabled selects aren't marked as disabled
-	// (WebKit marks them as disabled)
-	select.disabled = true;
-	support.optDisabled = !opt.disabled;
-
-	// Check if an input maintains its value after becoming a radio
-	// Support: IE9, IE10
-	input = document.createElement( "input" );
-	input.value = "t";
-	input.type = "radio";
-	support.radioValue = input.value === "t";
-})();
-
-
-var nodeHook, boolHook,
-	attrHandle = jQuery.expr.attrHandle;
-
-jQuery.fn.extend({
-	attr: function( name, value ) {
-		return access( this, jQuery.attr, name, value, arguments.length > 1 );
-	},
-
-	removeAttr: function( name ) {
-		return this.each(function() {
-			jQuery.removeAttr( this, name );
-		});
-	}
-});
-
-jQuery.extend({
-	attr: function( elem, name, value ) {
-		var hooks, ret,
-			nType = elem.nodeType;
-
-		// don't get/set attributes on text, comment and attribute nodes
-		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
-			return;
-		}
-
-		// Fallback to prop when attributes are not supported
-		if ( typeof elem.getAttribute === strundefined ) {
-			return jQuery.prop( elem, name, value );
-		}
-
-		// All attributes are lowercase
-		// Grab necessary hook if one is defined
-		if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
-			name = name.toLowerCase();
-			hooks = jQuery.attrHooks[ name ] ||
-				( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
-		}
-
-		if ( value !== undefined ) {
-
-			if ( value === null ) {
-				jQuery.removeAttr( elem, name );
-
-			} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
-				return ret;
-
-			} else {
-				elem.setAttribute( name, value + "" );
-				return value;
-			}
-
-		} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
-			return ret;
-
-		} else {
-			ret = jQuery.find.attr( elem, name );
-
-			// Non-existent attributes return null, we normalize to undefined
-			return ret == null ?
-				undefined :
-				ret;
-		}
-	},
-
-	removeAttr: function( elem, value ) {
-		var name, propName,
-			i = 0,
-			attrNames = value && value.match( rnotwhite );
-
-		if ( attrNames && elem.nodeType === 1 ) {
-			while ( (name = attrNames[i++]) ) {
-				propName = jQuery.propFix[ name ] || name;
-
-				// Boolean attributes get special treatment (#10870)
-				if ( jQuery.expr.match.bool.test( name ) ) {
-					// Set corresponding property to false
-					elem[ propName ] = false;
-				}
-
-				elem.removeAttribute( name );
-			}
-		}
-	},
-
-	attrHooks: {
-		type: {
-			set: function( elem, value ) {
-				if ( !support.radioValue && value === "radio" &&
-					jQuery.nodeName( elem, "input" ) ) {
-					// Setting the type on a radio button after the value resets the value in IE6-9
-					// Reset value to default in case type is set after value during creation
-					var val = elem.value;
-					elem.setAttribute( "type", value );
-					if ( val ) {
-						elem.value = val;
-					}
-					return value;
-				}
-			}
-		}
-	}
-});
-
-// Hooks for boolean attributes
-boolHook = {
-	set: function( elem, value, name ) {
-		if ( value === false ) {
-			// Remove boolean attributes when set to false
-			jQuery.removeAttr( elem, name );
-		} else {
-			elem.setAttribute( name, name );
-		}
-		return name;
-	}
-};
-jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
-	var getter = attrHandle[ name ] || jQuery.find.attr;
-
-	attrHandle[ name ] = function( elem, name, isXML ) {
-		var ret, handle;
-		if ( !isXML ) {
-			// Avoid an infinite loop by temporarily removing this function from the getter
-			handle = attrHandle[ name ];
-			attrHandle[ name ] = ret;
-			ret = getter( elem, name, isXML ) != null ?
-				name.toLowerCase() :
-				null;
-			attrHandle[ name ] = handle;
-		}
-		return ret;
-	};
-});
-
-
-
-
-var rfocusable = /^(?:input|select|textarea|button)$/i;
-
-jQuery.fn.extend({
-	prop: function( name, value ) {
-		return access( this, jQuery.prop, name, value, arguments.length > 1 );
-	},
-
-	removeProp: function( name ) {
-		return this.each(function() {
-			delete this[ jQuery.propFix[ name ] || name ];
-		});
-	}
-});
-
-jQuery.extend({
-	propFix: {
-		"for": "htmlFor",
-		"class": "className"
-	},
-
-	prop: function( elem, name, value ) {
-		var ret, hooks, notxml,
-			nType = elem.nodeType;
-
-		// don't get/set properties on text, comment and attribute nodes
-		if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
-			return;
-		}
-
-		notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
-
-		if ( notxml ) {
-			// Fix name and attach hooks
-			name = jQuery.propFix[ name ] || name;
-			hooks = jQuery.propHooks[ name ];
-		}
-
-		if ( value !== undefined ) {
-			return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
-				ret :
-				( elem[ name ] = value );
-
-		} else {
-			return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
-				ret :
-				elem[ name ];
-		}
-	},
-
-	propHooks: {
-		tabIndex: {
-			get: function( elem ) {
-				return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
-					elem.tabIndex :
-					-1;
-			}
-		}
-	}
-});
-
-// Support: IE9+
-// Selectedness for an option in an optgroup can be inaccurate
-if ( !support.optSelected ) {
-	jQuery.propHooks.selected = {
-		get: function( elem ) {
-			var parent = elem.parentNode;
-			if ( parent && parent.parentNode ) {
-				parent.parentNode.selectedIndex;
-			}
-			return null;
-		}
-	};
-}
-
-jQuery.each([
-	"tabIndex",
-	"readOnly",
-	"maxLength",
-	"cellSpacing",
-	"cellPadding",
-	"rowSpan",
-	"colSpan",
-	"useMap",
-	"frameBorder",
-	"contentEditable"
-], function() {
-	jQuery.propFix[ this.toLowerCase() ] = this;
-});
-
-
-
-
-var rclass = /[\t\r\n\f]/g;
-
-jQuery.fn.extend({
-	addClass: function( value ) {
-		var classes, elem, cur, clazz, j, finalValue,
-			proceed = typeof value === "string" && value,
-			i = 0,
-			len = this.length;
-
-		if ( jQuery.isFunction( value ) ) {
-			return this.each(function( j ) {
-				jQuery( this ).addClass( value.call( this, j, this.className ) );
-			});
-		}
-
-		if ( proceed ) {
-			// The disjunction here is for better compressibility (see removeClass)
-			classes = ( value || "" ).match( rnotwhite ) || [];
-
-			for ( ; i < len; i++ ) {
-				elem = this[ i ];
-				cur = elem.nodeType === 1 && ( elem.className ?
-					( " " + elem.className + " " ).replace( rclass, " " ) :
-					" "
-				);
-
-				if ( cur ) {
-					j = 0;
-					while ( (clazz = classes[j++]) ) {
-						if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
-							cur += clazz + " ";
-						}
-					}
-
-					// only assign if different to avoid unneeded rendering.
-					finalValue = jQuery.trim( cur );
-					if ( elem.className !== finalValue ) {
-						elem.className = finalValue;
-					}
-				}
-			}
-		}
-
-		return this;
-	},
-
-	removeClass: function( value ) {
-		var classes, elem, cur, clazz, j, finalValue,
-			proceed = arguments.length === 0 || typeof value === "string" && value,
-			i = 0,
-			len = this.length;
-
-		if ( jQuery.isFunction( value ) ) {
-			return this.each(function( j ) {
-				jQuery( this ).removeClass( value.call( this, j, this.className ) );
-			});
-		}
-		if ( proceed ) {
-			classes = ( value || "" ).match( rnotwhite ) || [];
-
-			for ( ; i < len; i++ ) {
-				elem = this[ i ];
-				// This expression is here for better compressibility (see addClass)
-				cur = elem.nodeType === 1 && ( elem.className ?
-					( " " + elem.className + " " ).replace( rclass, " " ) :
-					""
-				);
-
-				if ( cur ) {
-					j = 0;
-					while ( (clazz = classes[j++]) ) {
-						// Remove *all* instances
-						while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
-							cur = cur.replace( " " + clazz + " ", " " );
-						}
-					}
-
-					// only assign if different to avoid unneeded rendering.
-					finalValue = value ? jQuery.trim( cur ) : "";
-					if ( elem.className !== finalValue ) {
-						elem.className = finalValue;
-					}
-				}
-			}
-		}
-
-		return this;
-	},
-
-	toggleClass: function( value, stateVal ) {
-		var type = typeof value;
-
-		if ( typeof stateVal === "boolean" && type === "string" ) {
-			return stateVal ? this.addClass( value ) : this.removeClass( value );
-		}
-
-		if ( jQuery.isFunction( value ) ) {
-			return this.each(function( i ) {
-				jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
-			});
-		}
-
-		return this.each(function() {
-			if ( type === "string" ) {
-				// toggle individual class names
-				var className,
-					i = 0,
-					self = jQuery( this ),
-					classNames = value.match( rnotwhite ) || [];
-
-				while ( (className = classNames[ i++ ]) ) {
-					// check each className given, space separated list
-					if ( self.hasClass( className ) ) {
-						self.removeClass( className );
-					} else {
-						self.addClass( className );
-					}
-				}
-
-			// Toggle whole class name
-			} else if ( type === strundefined || type === "boolean" ) {
-				if ( this.className ) {
-					// store className if set
-					data_priv.set( this, "__className__", this.className );
-				}
-
-				// If the element has a class name or if we're passed "false",
-				// then remove the whole classname (if there was one, the above saved it).
-				// Otherwise bring back whatever was previously saved (if anything),
-				// falling back to the empty string if nothing was stored.
-				this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
-			}
-		});
-	},
-
-	hasClass: function( selector ) {
-		var className = " " + selector + " ",
-			i = 0,
-			l = this.length;
-		for ( ; i < l; i++ ) {
-			if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
-				return true;
-			}
-		}
-
-		return false;
-	}
-});
-
-
-
-
-var rreturn = /\r/g;
-
-jQuery.fn.extend({
-	val: function( value ) {
-		var hooks, ret, isFunction,
-			elem = this[0];
-
-		if ( !arguments.length ) {
-			if ( elem ) {
-				hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
-
-				if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
-					return ret;
-				}
-
-				ret = elem.value;
-
-				return typeof ret === "string" ?
-					// handle most common string cases
-					ret.replace(rreturn, "") :
-					// handle cases where value is null/undef or number
-					ret == null ? "" : ret;
-			}
-
-			return;
-		}
-
-		isFunction = jQuery.isFunction( value );
-
-		return this.each(function( i ) {
-			var val;
-
-			if ( this.nodeType !== 1 ) {
-				return;
-			}
-
-			if ( isFunction ) {
-				val = value.call( this, i, jQuery( this ).val() );
-			} else {
-				val = value;
-			}
-
-			// Treat null/undefined as ""; convert numbers to string
-			if ( val == null ) {
-				val = "";
-
-			} else if ( typeof val === "number" ) {
-				val += "";
-
-			} else if ( jQuery.isArray( val ) ) {
-				val = jQuery.map( val, function( value ) {
-					return value == null ? "" : value + "";
-				});
-			}
-
-			hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
-
-			// If set returns undefined, fall back to normal setting
-			if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
-				this.value = val;
-			}
-		});
-	}
-});
-
-jQuery.extend({
-	valHooks: {
-		option: {
-			get: function( elem ) {
-				var val = jQuery.find.attr( elem, "value" );
-				return val != null ?
-					val :
-					// Support: IE10-11+
-					// option.text throws exceptions (#14686, #14858)
-					jQuery.trim( jQuery.text( elem ) );
-			}
-		},
-		select: {
-			get: function( elem ) {
-				var value, option,
-					options = elem.options,
-					index = elem.selectedIndex,
-					one = elem.type === "select-one" || index < 0,
-					values = one ? null : [],
-					max = one ? index + 1 : options.length,
-					i = index < 0 ?
-						max :
-						one ? index : 0;
-
-				// Loop through all the selected options
-				for ( ; i < max; i++ ) {
-					option = options[ i ];
-
-					// IE6-9 doesn't update selected after form reset (#2551)
-					if ( ( option.selected || i === index ) &&
-							// Don't return options that are disabled or in a disabled optgroup
-							( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
-							( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
-
-						// Get the specific 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;
-			},
-
-			set: function( elem, value ) {
-				var optionSet, option,
-					options = elem.options,
-					values = jQuery.makeArray( value ),
-					i = options.length;
-
-				while ( i-- ) {
-					option = options[ i ];
-					if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
-						optionSet = true;
-					}
-				}
-
-				// force browsers to behave consistently when non-matching value is set
-				if ( !optionSet ) {
-					elem.selectedIndex = -1;
-				}
-				return values;
-			}
-		}
-	}
-});
-
-// Radios and checkboxes getter/setter
-jQuery.each([ "radio", "checkbox" ], function() {
-	jQuery.valHooks[ this ] = {
-		set: function( elem, value ) {
-			if ( jQuery.isArray( value ) ) {
-				return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
-			}
-		}
-	};
-	if ( !support.checkOn ) {
-		jQuery.valHooks[ this ].get = function( elem ) {
-			// Support: Webkit
-			// "" is returned instead of "on" if a value isn't specified
-			return elem.getAttribute("value") === null ? "on" : elem.value;
-		};
-	}
-});
-
-
-
-
-// Return jQuery for attributes-only inclusion
-
-
-jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
-	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
-	"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
-
-	// Handle event binding
-	jQuery.fn[ name ] = function( data, fn ) {
-		return arguments.length > 0 ?
-			this.on( name, null, data, fn ) :
-			this.trigger( name );
-	};
-});
-
-jQuery.fn.extend({
-	hover: function( fnOver, fnOut ) {
-		return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
-	},
-
-	bind: function( types, data, fn ) {
-		return this.on( types, null, data, fn );
-	},
-	unbind: function( types, fn ) {
-		return this.off( types, null, fn );
-	},
-
-	delegate: function( selector, types, data, fn ) {
-		return this.on( types, selector, data, fn );
-	},
-	undelegate: function( selector, types, fn ) {
-		// ( namespace ) or ( selector, types [, fn] )
-		return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
-	}
-});
-
-
-var nonce = jQuery.now();
-
-var rquery = (/\?/);
-
-
-
-// Support: Android 2.3
-// Workaround failure to string-cast null input
-jQuery.parseJSON = function( data ) {
-	return JSON.parse( data + "" );
-};
-
-
-// Cross-browser xml parsing
-jQuery.parseXML = function( data ) {
-	var xml, tmp;
-	if ( !data || typeof data !== "string" ) {
-		return null;
-	}
-
-	// Support: IE9
-	try {
-		tmp = new DOMParser();
-		xml = tmp.parseFromString( data, "text/xml" );
-	} catch ( e ) {
-		xml = undefined;
-	}
-
-	if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
-		jQuery.error( "Invalid XML: " + data );
-	}
-	return xml;
-};
-
-
-var
-	// Document location
-	ajaxLocParts,
-	ajaxLocation,
-
-	rhash = /#.*$/,
-	rts = /([?&])_=[^&]*/,
-	rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
-	// #7653, #8125, #8152: local protocol detection
-	rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
-	rnoContent = /^(?:GET|HEAD)$/,
-	rprotocol = /^\/\//,
-	rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
-
-	/* Prefilters
-	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
-	 * 2) These are called:
-	 *    - BEFORE asking for a transport
-	 *    - AFTER param serialization (s.data is a string if s.processData is true)
-	 * 3) key is the dataType
-	 * 4) the catchall symbol "*" can be used
-	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
-	 */
-	prefilters = {},
-
-	/* Transports bindings
-	 * 1) key is the dataType
-	 * 2) the catchall symbol "*" can be used
-	 * 3) selection will start with transport dataType and THEN go to "*" if needed
-	 */
-	transports = {},
-
-	// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
-	allTypes = "*/".concat("*");
-
-// #8138, IE may throw an exception when accessing
-// a field from window.location if document.domain has been set
-try {
-	ajaxLocation = location.href;
-} catch( e ) {
-	// Use the href attribute of an A element
-	// since IE will modify it given document.location
-	ajaxLocation = document.createElement( "a" );
-	ajaxLocation.href = "";
-	ajaxLocation = ajaxLocation.href;
-}
-
-// Segment location into parts
-ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
-
-// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
-function addToPrefiltersOrTransports( structure ) {
-
-	// dataTypeExpression is optional and defaults to "*"
-	return function( dataTypeExpression, func ) {
-
-		if ( typeof dataTypeExpression !== "string" ) {
-			func = dataTypeExpression;
-			dataTypeExpression = "*";
-		}
-
-		var dataType,
-			i = 0,
-			dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
-
-		if ( jQuery.isFunction( func ) ) {
-			// For each dataType in the dataTypeExpression
-			while ( (dataType = dataTypes[i++]) ) {
-				// Prepend if requested
-				if ( dataType[0] === "+" ) {
-					dataType = dataType.slice( 1 ) || "*";
-					(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
-
-				// Otherwise append
-				} else {
-					(structure[ dataType ] = structure[ dataType ] || []).push( func );
-				}
-			}
-		}
-	};
-}
-
-// Base inspection function for prefilters and transports
-function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
-
-	var inspected = {},
-		seekingTransport = ( structure === transports );
-
-	function inspect( dataType ) {
-		var selected;
-		inspected[ dataType ] = true;
-		jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
-			var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
-			if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
-				options.dataTypes.unshift( dataTypeOrTransport );
-				inspect( dataTypeOrTransport );
-				return false;
-			} else if ( seekingTransport ) {
-				return !( selected = dataTypeOrTransport );
-			}
-		});
-		return selected;
-	}
-
-	return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
-}
-
-// A special extend for ajax options
-// that takes "flat" options (not to be deep extended)
-// Fixes #9887
-function ajaxExtend( target, src ) {
-	var key, deep,
-		flatOptions = jQuery.ajaxSettings.flatOptions || {};
-
-	for ( key in src ) {
-		if ( src[ key ] !== undefined ) {
-			( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
-		}
-	}
-	if ( deep ) {
-		jQuery.extend( true, target, deep );
-	}
-
-	return target;
-}
-
-/* Handles responses to an ajax request:
- * - finds the right dataType (mediates between content-type and expected dataType)
- * - returns the corresponding response
- */
-function ajaxHandleResponses( s, jqXHR, responses ) {
-
-	var ct, type, finalDataType, firstDataType,
-		contents = s.contents,
-		dataTypes = s.dataTypes;
-
-	// Remove auto dataType and get content-type in the process
-	while ( dataTypes[ 0 ] === "*" ) {
-		dataTypes.shift();
-		if ( ct === undefined ) {
-			ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
-		}
-	}
-
-	// Check if we're dealing with a known content-type
-	if ( ct ) {
-		for ( type in contents ) {
-			if ( contents[ type ] && contents[ type ].test( ct ) ) {
-				dataTypes.unshift( type );
-				break;
-			}
-		}
-	}
-
-	// Check to see if we have a response for the expected dataType
-	if ( dataTypes[ 0 ] in responses ) {
-		finalDataType = dataTypes[ 0 ];
-	} else {
-		// Try convertible dataTypes
-		for ( type in responses ) {
-			if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
-				finalDataType = type;
-				break;
-			}
-			if ( !firstDataType ) {
-				firstDataType = type;
-			}
-		}
-		// Or just use first one
-		finalDataType = finalDataType || firstDataType;
-	}
-
-	// If we found a dataType
-	// We add the dataType to the list if needed
-	// and return the corresponding response
-	if ( finalDataType ) {
-		if ( finalDataType !== dataTypes[ 0 ] ) {
-			dataTypes.unshift( finalDataType );
-		}
-		return responses[ finalDataType ];
-	}
-}
-
-/* Chain conversions given the request and the original response
- * Also sets the responseXXX fields on the jqXHR instance
- */
-function ajaxConvert( s, response, jqXHR, isSuccess ) {
-	var conv2, current, conv, tmp, prev,
-		converters = {},
-		// Work with a copy of dataTypes in case we need to modify it for conversion
-		dataTypes = s.dataTypes.slice();
-
-	// Create converters map with lowercased keys
-	if ( dataTypes[ 1 ] ) {
-		for ( conv in s.converters ) {
-			converters[ conv.toLowerCase() ] = s.converters[ conv ];
-		}
-	}
-
-	current = dataTypes.shift();
-
-	// Convert to each sequential dataType
-	while ( current ) {
-
-		if ( s.responseFields[ current ] ) {
-			jqXHR[ s.responseFields[ current ] ] = response;
-		}
-
-		// Apply the dataFilter if provided
-		if ( !prev && isSuccess && s.dataFilter ) {
-			response = s.dataFilter( response, s.dataType );
-		}
-
-		prev = current;
-		current = dataTypes.shift();
-
-		if ( current ) {
-
-		// There's only work to do if current dataType is non-auto
-			if ( current === "*" ) {
-
-				current = prev;
-
-			// Convert response if prev dataType is non-auto and differs from current
-			} else if ( prev !== "*" && prev !== current ) {
-
-				// Seek a direct converter
-				conv = converters[ prev + " " + current ] || converters[ "* " + current ];
-
-				// If none found, seek a pair
-				if ( !conv ) {
-					for ( conv2 in converters ) {
-
-						// If conv2 outputs current
-						tmp = conv2.split( " " );
-						if ( tmp[ 1 ] === current ) {
-
-							// If prev can be converted to accepted input
-							conv = converters[ prev + " " + tmp[ 0 ] ] ||
-								converters[ "* " + tmp[ 0 ] ];
-							if ( conv ) {
-								// Condense equivalence converters
-								if ( conv === true ) {
-									conv = converters[ conv2 ];
-
-								// Otherwise, insert the intermediate dataType
-								} else if ( converters[ conv2 ] !== true ) {
-									current = tmp[ 0 ];
-									dataTypes.unshift( tmp[ 1 ] );
-								}
-								break;
-							}
-						}
-					}
-				}
-
-				// Apply converter (if not an equivalence)
-				if ( conv !== true ) {
-
-					// Unless errors are allowed to bubble, catch and return them
-					if ( conv && s[ "throws" ] ) {
-						response = conv( response );
-					} else {
-						try {
-							response = conv( response );
-						} catch ( e ) {
-							return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
-						}
-					}
-				}
-			}
-		}
-	}
-
-	return { state: "success", data: response };
-}
-
-jQuery.extend({
-
-	// Counter for holding the number of active queries
-	active: 0,
-
-	// Last-Modified header cache for next request
-	lastModified: {},
-	etag: {},
-
-	ajaxSettings: {
-		url: ajaxLocation,
-		type: "GET",
-		isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
-		global: true,
-		processData: true,
-		async: true,
-		contentType: "application/x-www-form-urlencoded; charset=UTF-8",
-		/*
-		timeout: 0,
-		data: null,
-		dataType: null,
-		username: null,
-		password: null,
-		cache: null,
-		throws: false,
-		traditional: false,
-		headers: {},
-		*/
-
-		accepts: {
-			"*": allTypes,
-			text: "text/plain",
-			html: "text/html",
-			xml: "application/xml, text/xml",
-			json: "application/json, text/javascript"
-		},
-
-		contents: {
-			xml: /xml/,
-			html: /html/,
-			json: /json/
-		},
-
-		responseFields: {
-			xml: "responseXML",
-			text: "responseText",
-			json: "responseJSON"
-		},
-
-		// Data converters
-		// Keys separate source (or catchall "*") and destination types with a single space
-		converters: {
-
-			// Convert anything to text
-			"* text": String,
-
-			// Text to html (true = no transformation)
-			"text html": true,
-
-			// Evaluate text as a json expression
-			"text json": jQuery.parseJSON,
-
-			// Parse text as xml
-			"text xml": jQuery.parseXML
-		},
-
-		// For options that shouldn't be deep extended:
-		// you can add your own custom options here if
-		// and when you create one that shouldn't be
-		// deep extended (see ajaxExtend)
-		flatOptions: {
-			url: true,
-			context: true
-		}
-	},
-
-	// Creates a full fledged settings object into target
-	// with both ajaxSettings and settings fields.
-	// If target is omitted, writes into ajaxSettings.
-	ajaxSetup: function( target, settings ) {
-		return settings ?
-
-			// Building a settings object
-			ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
-
-			// Extending ajaxSettings
-			ajaxExtend( jQuery.ajaxSettings, target );
-	},
-
-	ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
-	ajaxTransport: addToPrefiltersOrTransports( transports ),
-
-	// Main method
-	ajax: function( url, options ) {
-
-		// If url is an object, simulate pre-1.5 signature
-		if ( typeof url === "object" ) {
-			options = url;
-			url = undefined;
-		}
-
-		// Force options to be an object
-		options = options || {};
-
-		var transport,
-			// URL without anti-cache param
-			cacheURL,
-			// Response headers
-			responseHeadersString,
-			responseHeaders,
-			// timeout handle
-			timeoutTimer,
-			// Cross-domain detection vars
-			parts,
-			// To know if global events are to be dispatched
-			fireGlobals,
-			// Loop variable
-			i,
-			// Create the final options object
-			s = jQuery.ajaxSetup( {}, options ),
-			// Callbacks context
-			callbackContext = s.context || s,
-			// Context for global events is callbackContext if it is a DOM node or jQuery collection
-			globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
-				jQuery( callbackContext ) :
-				jQuery.event,
-			// Deferreds
-			deferred = jQuery.Deferred(),
-			completeDeferred = jQuery.Callbacks("once memory"),
-			// Status-dependent callbacks
-			statusCode = s.statusCode || {},
-			// Headers (they are sent all at once)
-			requestHeaders = {},
-			requestHeadersNames = {},
-			// The jqXHR state
-			state = 0,
-			// Default abort message
-			strAbort = "canceled",
-			// Fake xhr
-			jqXHR = {
-				readyState: 0,
-
-				// Builds headers hashtable if needed
-				getResponseHeader: function( key ) {
-					var match;
-					if ( state === 2 ) {
-						if ( !responseHeaders ) {
-							responseHeaders = {};
-							while ( (match = rheaders.exec( responseHeadersString )) ) {
-								responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
-							}
-						}
-						match = responseHeaders[ key.toLowerCase() ];
-					}
-					return match == null ? null : match;
-				},
-
-				// Raw string
-				getAllResponseHeaders: function() {
-					return state === 2 ? responseHeadersString : null;
-				},
-
-				// Caches the header
-				setRequestHeader: function( name, value ) {
-					var lname = name.toLowerCase();
-					if ( !state ) {
-						name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
-						requestHeaders[ name ] = value;
-					}
-					return this;
-				},
-
-				// Overrides response content-type header
-				overrideMimeType: function( type ) {
-					if ( !state ) {
-						s.mimeType = type;
-					}
-					return this;
-				},
-
-				// Status-dependent callbacks
-				statusCode: function( map ) {
-					var code;
-					if ( map ) {
-						if ( state < 2 ) {
-							for ( code in map ) {
-								// Lazy-add the new callback in a way that preserves old ones
-								statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
-							}
-						} else {
-							// Execute the appropriate callbacks
-							jqXHR.always( map[ jqXHR.status ] );
-						}
-					}
-					return this;
-				},
-
-				// Cancel the request
-				abort: function( statusText ) {
-					var finalText = statusText || strAbort;
-					if ( transport ) {
-						transport.abort( finalText );
-					}
-					done( 0, finalText );
-					return this;
-				}
-			};
-
-		// Attach deferreds
-		deferred.promise( jqXHR ).complete = completeDeferred.add;
-		jqXHR.success = jqXHR.done;
-		jqXHR.error = jqXHR.fail;
-
-		// Remove hash character (#7531: and string promotion)
-		// Add protocol if not provided (prefilters might expect it)
-		// Handle falsy url in the settings object (#10093: consistency with old signature)
-		// We also use the url parameter if available
-		s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
-			.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
-
-		// Alias method option to type as per ticket #12004
-		s.type = options.method || options.type || s.method || s.type;
-
-		// Extract dataTypes list
-		s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
-
-		// A cross-domain request is in order when we have a protocol:host:port mismatch
-		if ( s.crossDomain == null ) {
-			parts = rurl.exec( s.url.toLowerCase() );
-			s.crossDomain = !!( parts &&
-				( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
-					( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
-						( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
-			);
-		}
-
-		// Convert data if not already a string
-		if ( s.data && s.processData && typeof s.data !== "string" ) {
-			s.data = jQuery.param( s.data, s.traditional );
-		}
-
-		// Apply prefilters
-		inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
-
-		// If request was aborted inside a prefilter, stop there
-		if ( state === 2 ) {
-			return jqXHR;
-		}
-
-		// We can fire global events as of now if asked to
-		fireGlobals = s.global;
-
-		// Watch for a new set of requests
-		if ( fireGlobals && jQuery.active++ === 0 ) {
-			jQuery.event.trigger("ajaxStart");
-		}
-
-		// Uppercase the type
-		s.type = s.type.toUpperCase();
-
-		// Determine if request has content
-		s.hasContent = !rnoContent.test( s.type );
-
-		// Save the URL in case we're toying with the If-Modified-Since
-		// and/or If-None-Match header later on
-		cacheURL = s.url;
-
-		// More options handling for requests with no content
-		if ( !s.hasContent ) {
-
-			// If data is available, append data to url
-			if ( s.data ) {
-				cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
-				// #9682: remove data so that it's not used in an eventual retry
-				delete s.data;
-			}
-
-			// Add anti-cache in url if needed
-			if ( s.cache === false ) {
-				s.url = rts.test( cacheURL ) ?
-
-					// If there is already a '_' parameter, set its value
-					cacheURL.replace( rts, "$1_=" + nonce++ ) :
-
-					// Otherwise add one to the end
-					cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
-			}
-		}
-
-		// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
-		if ( s.ifModified ) {
-			if ( jQuery.lastModified[ cacheURL ] ) {
-				jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
-			}
-			if ( jQuery.etag[ cacheURL ] ) {
-				jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
-			}
-		}
-
-		// Set the correct header, if data is being sent
-		if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
-			jqXHR.setRequestHeader( "Content-Type", s.contentType );
-		}
-
-		// Set the Accepts header for the server, depending on the dataType
-		jqXHR.setRequestHeader(
-			"Accept",
-			s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
-				s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
-				s.accepts[ "*" ]
-		);
-
-		// Check for headers option
-		for ( i in s.headers ) {
-			jqXHR.setRequestHeader( i, s.headers[ i ] );
-		}
-
-		// Allow custom headers/mimetypes and early abort
-		if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
-			// Abort if not done already and return
-			return jqXHR.abort();
-		}
-
-		// aborting is no longer a cancellation
-		strAbort = "abort";
-
-		// Install callbacks on deferreds
-		for ( i in { success: 1, error: 1, complete: 1 } ) {
-			jqXHR[ i ]( s[ i ] );
-		}
-
-		// Get transport
-		transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
-
-		// If no transport, we auto-abort
-		if ( !transport ) {
-			done( -1, "No Transport" );
-		} else {
-			jqXHR.readyState = 1;
-
-			// Send global event
-			if ( fireGlobals ) {
-				globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
-			}
-			// Timeout
-			if ( s.async && s.timeout > 0 ) {
-				timeoutTimer = setTimeout(function() {
-					jqXHR.abort("timeout");
-				}, s.timeout );
-			}
-
-			try {
-				state = 1;
-				transport.send( requestHeaders, done );
-			} catch ( e ) {
-				// Propagate exception as error if not done
-				if ( state < 2 ) {
-					done( -1, e );
-				// Simply rethrow otherwise
-				} else {
-					throw e;
-				}
-			}
-		}
-
-		// Callback for when everything is done
-		function done( status, nativeStatusText, responses, headers ) {
-			var isSuccess, success, error, response, modified,
-				statusText = nativeStatusText;
-
-			// Called once
-			if ( state === 2 ) {
-				return;
-			}
-
-			// State is "done" now
-			state = 2;
-
-			// Clear timeout if it exists
-			if ( timeoutTimer ) {
-				clearTimeout( timeoutTimer );
-			}
-
-			// Dereference transport for early garbage collection
-			// (no matter how long the jqXHR object will be used)
-			transport = undefined;
-
-			// Cache response headers
-			responseHeadersString = headers || "";
-
-			// Set readyState
-			jqXHR.readyState = status > 0 ? 4 : 0;
-
-			// Determine if successful
-			isSuccess = status >= 200 && status < 300 || status === 304;
-
-			// Get response data
-			if ( responses ) {
-				response = ajaxHandleResponses( s, jqXHR, responses );
-			}
-
-			// Convert no matter what (that way responseXXX fields are always set)
-			response = ajaxConvert( s, response, jqXHR, isSuccess );
-
-			// If successful, handle type chaining
-			if ( isSuccess ) {
-
-				// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
-				if ( s.ifModified ) {
-					modified = jqXHR.getResponseHeader("Last-Modified");
-					if ( modified ) {
-						jQuery.lastModified[ cacheURL ] = modified;
-					}
-					modified = jqXHR.getResponseHeader("etag");
-					if ( modified ) {
-						jQuery.etag[ cacheURL ] = modified;
-					}
-				}
-
-				// if no content
-				if ( status === 204 || s.type === "HEAD" ) {
-					statusText = "nocontent";
-
-				// if not modified
-				} else if ( status === 304 ) {
-					statusText = "notmodified";
-
-				// If we have data, let's convert it
-				} else {
-					statusText = response.state;
-					success = response.data;
-					error = response.error;
-					isSuccess = !error;
-				}
-			} else {
-				// We extract error from statusText
-				// then normalize statusText and status for non-aborts
-				error = statusText;
-				if ( status || !statusText ) {
-					statusText = "error";
-					if ( status < 0 ) {
-						status = 0;
-					}
-				}
-			}
-
-			// Set data for the fake xhr object
-			jqXHR.status = status;
-			jqXHR.statusText = ( nativeStatusText || statusText ) + "";
-
-			// Success/Error
-			if ( isSuccess ) {
-				deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
-			} else {
-				deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
-			}
-
-			// Status-dependent callbacks
-			jqXHR.statusCode( statusCode );
-			statusCode = undefined;
-
-			if ( fireGlobals ) {
-				globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
-					[ jqXHR, s, isSuccess ? success : error ] );
-			}
-
-			// Complete
-			completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
-
-			if ( fireGlobals ) {
-				globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
-				// Handle the global AJAX counter
-				if ( !( --jQuery.active ) ) {
-					jQuery.event.trigger("ajaxStop");
-				}
-			}
-		}
-
-		return jqXHR;
-	},
-
-	getJSON: function( url, data, callback ) {
-		return jQuery.get( url, data, callback, "json" );
-	},
-
-	getScript: function( url, callback ) {
-		return jQuery.get( url, undefined, callback, "script" );
-	}
-});
-
-jQuery.each( [ "get", "post" ], function( i, method ) {
-	jQuery[ method ] = function( url, data, callback, type ) {
-		// shift arguments if data argument was omitted
-		if ( jQuery.isFunction( data ) ) {
-			type = type || callback;
-			callback = data;
-			data = undefined;
-		}
-
-		return jQuery.ajax({
-			url: url,
-			type: method,
-			dataType: type,
-			data: data,
-			success: callback
-		});
-	};
-});
-
-// Attach a bunch of functions for handling common AJAX events
-jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
-	jQuery.fn[ type ] = function( fn ) {
-		return this.on( type, fn );
-	};
-});
-
-
-jQuery._evalUrl = function( url ) {
-	return jQuery.ajax({
-		url: url,
-		type: "GET",
-		dataType: "script",
-		async: false,
-		global: false,
-		"throws": true
-	});
-};
-
-
-jQuery.fn.extend({
-	wrapAll: function( html ) {
-		var wrap;
-
-		if ( jQuery.isFunction( html ) ) {
-			return this.each(function( i ) {
-				jQuery( this ).wrapAll( html.call(this, i) );
-			});
-		}
-
-		if ( this[ 0 ] ) {
-
-			// The elements to wrap the target around
-			wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
-
-			if ( this[ 0 ].parentNode ) {
-				wrap.insertBefore( this[ 0 ] );
-			}
-
-			wrap.map(function() {
-				var elem = this;
-
-				while ( elem.firstElementChild ) {
-					elem = elem.firstElementChild;
-				}
-
-				return elem;
-			}).append( this );
-		}
-
-		return this;
-	},
-
-	wrapInner: function( html ) {
-		if ( jQuery.isFunction( html ) ) {
-			return this.each(function( i ) {
-				jQuery( this ).wrapInner( html.call(this, i) );
-			});
-		}
-
-		return this.each(function() {
-			var self = jQuery( this ),
-				contents = self.contents();
-
-			if ( contents.length ) {
-				contents.wrapAll( html );
-
-			} else {
-				self.append( html );
-			}
-		});
-	},
-
-	wrap: function( html ) {
-		var isFunction = jQuery.isFunction( html );
-
-		return this.each(function( i ) {
-			jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
-		});
-	},
-
-	unwrap: function() {
-		return this.parent().each(function() {
-			if ( !jQuery.nodeName( this, "body" ) ) {
-				jQuery( this ).replaceWith( this.childNodes );
-			}
-		}).end();
-	}
-});
-
-
-jQuery.expr.filters.hidden = function( elem ) {
-	// Support: Opera <= 12.12
-	// Opera reports offsetWidths and offsetHeights less than zero on some elements
-	return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
-};
-jQuery.expr.filters.visible = function( elem ) {
-	return !jQuery.expr.filters.hidden( elem );
-};
-
-
-
-
-var r20 = /%20/g,
-	rbracket = /\[\]$/,
-	rCRLF = /\r?\n/g,
-	rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
-	rsubmittable = /^(?:input|select|textarea|keygen)/i;
-
-function buildParams( prefix, obj, traditional, add ) {
-	var name;
-
-	if ( jQuery.isArray( obj ) ) {
-		// Serialize array item.
-		jQuery.each( obj, function( i, v ) {
-			if ( traditional || rbracket.test( prefix ) ) {
-				// Treat each array item as a scalar.
-				add( prefix, v );
-
-			} else {
-				// Item is non-scalar (array or object), encode its numeric index.
-				buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
-			}
-		});
-
-	} else if ( !traditional && jQuery.type( obj ) === "object" ) {
-		// Serialize object item.
-		for ( name in obj ) {
-			buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
-		}
-
-	} else {
-		// Serialize scalar item.
-		add( prefix, obj );
-	}
-}
-
-// Serialize an array of form elements or a set of
-// key/values into a query string
-jQuery.param = function( a, traditional ) {
-	var prefix,
-		s = [],
-		add = function( key, value ) {
-			// If value is a function, invoke it and return its value
-			value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
-			s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
-		};
-
-	// Set traditional to true for jQuery <= 1.3.2 behavior.
-	if ( traditional === undefined ) {
-		traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
-	}
-
-	// If an array was passed in, assume that it is an array of form elements.
-	if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
-		// Serialize the form elements
-		jQuery.each( a, function() {
-			add( this.name, this.value );
-		});
-
-	} else {
-		// If traditional, encode the "old" way (the way 1.3.2 or older
-		// did it), otherwise encode params recursively.
-		for ( prefix in a ) {
-			buildParams( prefix, a[ prefix ], traditional, add );
-		}
-	}
-
-	// Return the resulting serialization
-	return s.join( "&" ).replace( r20, "+" );
-};
-
-jQuery.fn.extend({
-	serialize: function() {
-		return jQuery.param( this.serializeArray() );
-	},
-	serializeArray: function() {
-		return this.map(function() {
-			// Can add propHook for "elements" to filter or add form elements
-			var elements = jQuery.prop( this, "elements" );
-			return elements ? jQuery.makeArray( elements ) : this;
-		})
-		.filter(function() {
-			var type = this.type;
-
-			// Use .is( ":disabled" ) so that fieldset[disabled] works
-			return this.name && !jQuery( this ).is( ":disabled" ) &&
-				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
-				( this.checked || !rcheckableType.test( type ) );
-		})
-		.map(function( i, elem ) {
-			var val = jQuery( this ).val();
-
-			return val == null ?
-				null :
-				jQuery.isArray( val ) ?
-					jQuery.map( val, function( val ) {
-						return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
-					}) :
-					{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
-		}).get();
-	}
-});
-
-
-jQuery.ajaxSettings.xhr = function() {
-	try {
-		return new XMLHttpRequest();
-	} catch( e ) {}
-};
-
-var xhrId = 0,
-	xhrCallbacks = {},
-	xhrSuccessStatus = {
-		// file protocol always yields status code 0, assume 200
-		0: 200,
-		// Support: IE9
-		// #1450: sometimes IE returns 1223 when it should be 204
-		1223: 204
-	},
-	xhrSupported = jQuery.ajaxSettings.xhr();
-
-// Support: IE9
-// Open requests must be manually aborted on unload (#5280)
-if ( window.ActiveXObject ) {
-	jQuery( window ).on( "unload", function() {
-		for ( var key in xhrCallbacks ) {
-			xhrCallbacks[ key ]();
-		}
-	});
-}
-
-support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
-support.ajax = xhrSupported = !!xhrSupported;
-
-jQuery.ajaxTransport(function( options ) {
-	var callback;
-
-	// Cross domain only allowed if supported through XMLHttpRequest
-	if ( support.cors || xhrSupported && !options.crossDomain ) {
-		return {
-			send: function( headers, complete ) {
-				var i,
-					xhr = options.xhr(),
-					id = ++xhrId;
-
-				xhr.open( options.type, options.url, options.async, options.username, options.password );
-
-				// Apply custom fields if provided
-				if ( options.xhrFields ) {
-					for ( i in options.xhrFields ) {
-						xhr[ i ] = options.xhrFields[ i ];
-					}
-				}
-
-				// Override mime type if needed
-				if ( options.mimeType && xhr.overrideMimeType ) {
-					xhr.overrideMimeType( options.mimeType );
-				}
-
-				// X-Requested-With header
-				// For cross-domain requests, seeing as conditions for a preflight are
-				// akin to a jigsaw puzzle, we simply never set it to be sure.
-				// (it can always be set on a per-request basis or even using ajaxSetup)
-				// For same-domain requests, won't change header if already provided.
-				if ( !options.crossDomain && !headers["X-Requested-With"] ) {
-					headers["X-Requested-With"] = "XMLHttpRequest";
-				}
-
-				// Set headers
-				for ( i in headers ) {
-					xhr.setRequestHeader( i, headers[ i ] );
-				}
-
-				// Callback
-				callback = function( type ) {
-					return function() {
-						if ( callback ) {
-							delete xhrCallbacks[ id ];
-							callback = xhr.onload = xhr.onerror = null;
-
-							if ( type === "abort" ) {
-								xhr.abort();
-							} else if ( type === "error" ) {
-								complete(
-									// file: protocol always yields status 0; see #8605, #14207
-									xhr.status,
-									xhr.statusText
-								);
-							} else {
-								complete(
-									xhrSuccessStatus[ xhr.status ] || xhr.status,
-									xhr.statusText,
-									// Support: IE9
-									// Accessing binary-data responseText throws an exception
-									// (#11426)
-									typeof xhr.responseText === "string" ? {
-										text: xhr.responseText
-									} : undefined,
-									xhr.getAllResponseHeaders()
-								);
-							}
-						}
-					};
-				};
-
-				// Listen to events
-				xhr.onload = callback();
-				xhr.onerror = callback("error");
-
-				// Create the abort callback
-				callback = xhrCallbacks[ id ] = callback("abort");
-
-				try {
-					// Do send the request (this may raise an exception)
-					xhr.send( options.hasContent && options.data || null );
-				} catch ( e ) {
-					// #14683: Only rethrow if this hasn't been notified as an error yet
-					if ( callback ) {
-						throw e;
-					}
-				}
-			},
-
-			abort: function() {
-				if ( callback ) {
-					callback();
-				}
-			}
-		};
-	}
-});
-
-
-
-
-// Install script dataType
-jQuery.ajaxSetup({
-	accepts: {
-		script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
-	},
-	contents: {
-		script: /(?:java|ecma)script/
-	},
-	converters: {
-		"text script": function( text ) {
-			jQuery.globalEval( text );
-			return text;
-		}
-	}
-});
-
-// Handle cache's special case and crossDomain
-jQuery.ajaxPrefilter( "script", function( s ) {
-	if ( s.cache === undefined ) {
-		s.cache = false;
-	}
-	if ( s.crossDomain ) {
-		s.type = "GET";
-	}
-});
-
-// Bind script tag hack transport
-jQuery.ajaxTransport( "script", function( s ) {
-	// This transport only deals with cross domain requests
-	if ( s.crossDomain ) {
-		var script, callback;
-		return {
-			send: function( _, complete ) {
-				script = jQuery("<script>").prop({
-					async: true,
-					charset: s.scriptCharset,
-					src: s.url
-				}).on(
-					"load error",
-					callback = function( evt ) {
-						script.remove();
-						callback = null;
-						if ( evt ) {
-							complete( evt.type === "error" ? 404 : 200, evt.type );
-						}
-					}
-				);
-				document.head.appendChild( script[ 0 ] );
-			},
-			abort: function() {
-				if ( callback ) {
-					callback();
-				}
-			}
-		};
-	}
-});
-
-
-
-
-var oldCallbacks = [],
-	rjsonp = /(=)\?(?=&|$)|\?\?/;
-
-// Default jsonp settings
-jQuery.ajaxSetup({
-	jsonp: "callback",
-	jsonpCallback: function() {
-		var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
-		this[ callback ] = true;
-		return callback;
-	}
-});
-
-// Detect, normalize options and install callbacks for jsonp requests
-jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
-
-	var callbackName, overwritten, responseContainer,
-		jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
-			"url" :
-			typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
-		);
-
-	// Handle iff the expected data type is "jsonp" or we have a parameter to set
-	if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
-
-		// Get callback name, remembering preexisting value associated with it
-		callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
-			s.jsonpCallback() :
-			s.jsonpCallback;
-
-		// Insert callback into url or form data
-		if ( jsonProp ) {
-			s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
-		} else if ( s.jsonp !== false ) {
-			s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
-		}
-
-		// Use data converter to retrieve json after script execution
-		s.converters["script json"] = function() {
-			if ( !responseContainer ) {
-				jQuery.error( callbackName + " was not called" );
-			}
-			return responseContainer[ 0 ];
-		};
-
-		// force json dataType
-		s.dataTypes[ 0 ] = "json";
-
-		// Install callback
-		overwritten = window[ callbackName ];
-		window[ callbackName ] = function() {
-			responseContainer = arguments;
-		};
-
-		// Clean-up function (fires after converters)
-		jqXHR.always(function() {
-			// Restore preexisting value
-			window[ callbackName ] = overwritten;
-
-			// Save back as free
-			if ( s[ callbackName ] ) {
-				// make sure that re-using the options doesn't screw things around
-				s.jsonpCallback = originalSettings.jsonpCallback;
-
-				// save the callback name for future use
-				oldCallbacks.push( callbackName );
-			}
-
-			// Call if it was a function and we have a response
-			if ( responseContainer && jQuery.isFunction( overwritten ) ) {
-				overwritten( responseContainer[ 0 ] );
-			}
-
-			responseContainer = overwritten = undefined;
-		});
-
-		// Delegate to script
-		return "script";
-	}
-});
-
-
-
-
-// data: string of html
-// context (optional): If specified, the fragment will be created in this context, defaults to document
-// keepScripts (optional): If true, will include scripts passed in the html string
-jQuery.parseHTML = function( data, context, keepScripts ) {
-	if ( !data || typeof data !== "string" ) {
-		return null;
-	}
-	if ( typeof context === "boolean" ) {
-		keepScripts = context;
-		context = false;
-	}
-	context = context || document;
-
-	var parsed = rsingleTag.exec( data ),
-		scripts = !keepScripts && [];
-
-	// Single tag
-	if ( parsed ) {
-		return [ context.createElement( parsed[1] ) ];
-	}
-
-	parsed = jQuery.buildFragment( [ data ], context, scripts );
-
-	if ( scripts && scripts.length ) {
-		jQuery( scripts ).remove();
-	}
-
-	return jQuery.merge( [], parsed.childNodes );
-};
-
-
-// Keep a copy of the old load method
-var _load = jQuery.fn.load;
-
-/**
- * Load a url into a page
- */
-jQuery.fn.load = function( url, params, callback ) {
-	if ( typeof url !== "string" && _load ) {
-		return _load.apply( this, arguments );
-	}
-
-	var selector, type, response,
-		self = this,
-		off = url.indexOf(" ");
-
-	if ( off >= 0 ) {
-		selector = jQuery.trim( url.slice( off ) );
-		url = url.slice( 0, off );
-	}
-
-	// If it's a function
-	if ( jQuery.isFunction( params ) ) {
-
-		// We assume that it's the callback
-		callback = params;
-		params = undefined;
-
-	// Otherwise, build a param string
-	} else if ( params && typeof params === "object" ) {
-		type = "POST";
-	}
-
-	// If we have elements to modify, make the request
-	if ( self.length > 0 ) {
-		jQuery.ajax({
-			url: url,
-
-			// if "type" variable is undefined, then "GET" method will be used
-			type: type,
-			dataType: "html",
-			data: params
-		}).done(function( responseText ) {
-
-			// Save response for use in complete callback
-			response = arguments;
-
-			self.html( selector ?
-
-				// If a selector was specified, locate the right elements in a dummy div
-				// Exclude scripts to avoid IE 'Permission Denied' errors
-				jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
-
-				// Otherwise use the full result
-				responseText );
-
-		}).complete( callback && function( jqXHR, status ) {
-			self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
-		});
-	}
-
-	return this;
-};
-
-
-
-
-jQuery.expr.filters.animated = function( elem ) {
-	return jQuery.grep(jQuery.timers, function( fn ) {
-		return elem === fn.elem;
-	}).length;
-};
-
-
-
-
-var docElem = window.document.documentElement;
-
-/**
- * Gets a window from an element
- */
-function getWindow( elem ) {
-	return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
-}
-
-jQuery.offset = {
-	setOffset: function( elem, options, i ) {
-		var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
-			position = jQuery.css( elem, "position" ),
-			curElem = jQuery( elem ),
-			props = {};
-
-		// Set position first, in-case top/left are set even on static elem
-		if ( position === "static" ) {
-			elem.style.position = "relative";
-		}
-
-		curOffset = curElem.offset();
-		curCSSTop = jQuery.css( elem, "top" );
-		curCSSLeft = jQuery.css( elem, "left" );
-		calculatePosition = ( position === "absolute" || position === "fixed" ) &&
-			( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
-
-		// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
-		if ( calculatePosition ) {
-			curPosition = curElem.position();
-			curTop = curPosition.top;
-			curLeft = curPosition.left;
-
-		} else {
-			curTop = parseFloat( curCSSTop ) || 0;
-			curLeft = parseFloat( curCSSLeft ) || 0;
-		}
-
-		if ( jQuery.isFunction( options ) ) {
-			options = options.call( elem, i, curOffset );
-		}
-
-		if ( options.top != null ) {
-			props.top = ( options.top - curOffset.top ) + curTop;
-		}
-		if ( options.left != null ) {
-			props.left = ( options.left - curOffset.left ) + curLeft;
-		}
-
-		if ( "using" in options ) {
-			options.using.call( elem, props );
-
-		} else {
-			curElem.css( props );
-		}
-	}
-};
-
-jQuery.fn.extend({
-	offset: function( options ) {
-		if ( arguments.length ) {
-			return options === undefined ?
-				this :
-				this.each(function( i ) {
-					jQuery.offset.setOffset( this, options, i );
-				});
-		}
-
-		var docElem, win,
-			elem = this[ 0 ],
-			box = { top: 0, left: 0 },
-			doc = elem && elem.ownerDocument;
-
-		if ( !doc ) {
-			return;
-		}
-
-		docElem = doc.documentElement;
-
-		// Make sure it's not a disconnected DOM node
-		if ( !jQuery.contains( docElem, elem ) ) {
-			return box;
-		}
-
-		// If we don't have gBCR, just use 0,0 rather than error
-		// BlackBerry 5, iOS 3 (original iPhone)
-		if ( typeof elem.getBoundingClientRect !== strundefined ) {
-			box = elem.getBoundingClientRect();
-		}
-		win = getWindow( doc );
-		return {
-			top: box.top + win.pageYOffset - docElem.clientTop,
-			left: box.left + win.pageXOffset - docElem.clientLeft
-		};
-	},
-
-	position: function() {
-		if ( !this[ 0 ] ) {
-			return;
-		}
-
-		var offsetParent, offset,
-			elem = this[ 0 ],
-			parentOffset = { top: 0, left: 0 };
-
-		// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
-		if ( jQuery.css( elem, "position" ) === "fixed" ) {
-			// We assume that getBoundingClientRect is available when computed position is fixed
-			offset = elem.getBoundingClientRect();
-
-		} else {
-			// Get *real* offsetParent
-			offsetParent = this.offsetParent();
-
-			// Get correct offsets
-			offset = this.offset();
-			if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
-				parentOffset = offsetParent.offset();
-			}
-
-			// Add offsetParent borders
-			parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
-			parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
-		}
-
-		// Subtract parent offsets and element margins
-		return {
-			top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
-			left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
-		};
-	},
-
-	offsetParent: function() {
-		return this.map(function() {
-			var offsetParent = this.offsetParent || docElem;
-
-			while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
-				offsetParent = offsetParent.offsetParent;
-			}
-
-			return offsetParent || docElem;
-		});
-	}
-});
-
-// Create scrollLeft and scrollTop methods
-jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
-	var top = "pageYOffset" === prop;
-
-	jQuery.fn[ method ] = function( val ) {
-		return access( this, function( elem, method, val ) {
-			var win = getWindow( elem );
-
-			if ( val === undefined ) {
-				return win ? win[ prop ] : elem[ method ];
-			}
-
-			if ( win ) {
-				win.scrollTo(
-					!top ? val : window.pageXOffset,
-					top ? val : window.pageYOffset
-				);
-
-			} else {
-				elem[ method ] = val;
-			}
-		}, method, val, arguments.length, null );
-	};
-});
-
-// Add the top/left cssHooks using jQuery.fn.position
-// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
-// getComputedStyle returns percent when specified for top/left/bottom/right
-// rather than make the css module depend on the offset module, we just check for it here
-jQuery.each( [ "top", "left" ], function( i, prop ) {
-	jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
-		function( elem, computed ) {
-			if ( computed ) {
-				computed = curCSS( elem, prop );
-				// if curCSS returns percentage, fallback to offset
-				return rnumnonpx.test( computed ) ?
-					jQuery( elem ).position()[ prop ] + "px" :
-					computed;
-			}
-		}
-	);
-});
-
-
-// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
-jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
-	jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
-		// margin is only for outerHeight, outerWidth
-		jQuery.fn[ funcName ] = function( margin, value ) {
-			var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
-				extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
-
-			return access( this, function( elem, type, value ) {
-				var doc;
-
-				if ( jQuery.isWindow( elem ) ) {
-					// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
-					// isn't a whole lot we can do. See pull request at this URL for discussion:
-					// https://github.com/jquery/jquery/pull/764
-					return elem.document.documentElement[ "client" + name ];
-				}
-
-				// Get document width or height
-				if ( elem.nodeType === 9 ) {
-					doc = elem.documentElement;
-
-					// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
-					// whichever is greatest
-					return Math.max(
-						elem.body[ "scroll" + name ], doc[ "scroll" + name ],
-						elem.body[ "offset" + name ], doc[ "offset" + name ],
-						doc[ "client" + name ]
-					);
-				}
-
-				return value === undefined ?
-					// Get width or height on the element, requesting but not forcing parseFloat
-					jQuery.css( elem, type, extra ) :
-
-					// Set width or height on the element
-					jQuery.style( elem, type, value, extra );
-			}, type, chainable ? margin : undefined, chainable, null );
-		};
-	});
-});
-
-
-// The number of elements contained in the matched element set
-jQuery.fn.size = function() {
-	return this.length;
-};
-
-jQuery.fn.andSelf = jQuery.fn.addBack;
-
-
-
-
-// Register as a named AMD module, since jQuery can be concatenated with other
-// files that may use define, but not via a proper concatenation script that
-// understands anonymous AMD modules. A named AMD is safest and most robust
-// way to register. Lowercase jquery is used because AMD module names are
-// derived from file names, and jQuery is normally delivered in a lowercase
-// file name. Do this after creating the global so that if an AMD module wants
-// to call noConflict to hide this version of jQuery, it will work.
-
-// Note that for maximum portability, libraries that are not jQuery should
-// declare themselves as anonymous modules, and avoid setting a global if an
-// AMD loader is present. jQuery is a special case. For more information, see
-// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
-
-if ( typeof define === "function" && define.amd ) {
-	define( "jquery", [], function() {
-		return jQuery;
-	});
-}
-
-
-
-
-var
-	// Map over jQuery in case of overwrite
-	_jQuery = window.jQuery,
-
-	// Map over the $ in case of overwrite
-	_$ = window.$;
-
-jQuery.noConflict = function( deep ) {
-	if ( window.$ === jQuery ) {
-		window.$ = _$;
-	}
-
-	if ( deep && window.jQuery === jQuery ) {
-		window.jQuery = _jQuery;
-	}
-
-	return jQuery;
-};
-
-// Expose jQuery and $ identifiers, even in
-// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
-// and CommonJS for browser emulators (#13566)
-if ( typeof noGlobal === strundefined ) {
-	window.jQuery = window.$ = jQuery;
-}
-
-
-
-
-return jQuery;
-
-}));
diff --git a/static/js/jquery.min.js b/static/js/jquery.min.js
deleted file mode 100644
--- a/static/js/jquery.min.js
+++ /dev/null
@@ -1,4 +0,0 @@
-/*! jQuery v2.1.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
-!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l=a.document,m="2.1.1",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return!n.isArray(a)&&a-parseFloat(a)>=0},isPlainObject:function(a){return"object"!==n.type(a)||a.nodeType||n.isWindow(a)?!1:a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf")?!1:!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=l.createElement("script"),b.text=a,l.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:k}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="<select msallowclip=''><option selected=''></option></select>",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=lb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=mb(b);function pb(){}pb.prototype=d.filters=d.pseudos,d.setFilters=new pb,g=fb.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=S.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=T.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(R," ")}),h=h.slice(c.length));for(g in d.filter)!(e=X[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fb.error(a):z(a,i).slice(0)};function qb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+Math.random()}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)
-},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=L.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var Q=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,R=["Top","Right","Bottom","Left"],S=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},T=/^(?:checkbox|radio)$/i;!function(){var a=l.createDocumentFragment(),b=a.appendChild(l.createElement("div")),c=l.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button;return null==a.pageX&&null!=b.clientX&&(c=a.target.ownerDocument||l,d=c.documentElement,e=c.body,a.pageX=b.clientX+(d&&d.scrollLeft||e&&e.scrollLeft||0)-(d&&d.clientLeft||e&&e.clientLeft||0),a.pageY=b.clientY+(d&&d.scrollTop||e&&e.scrollTop||0)-(d&&d.clientTop||e&&e.clientTop||0)),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=W.test(e)?this.mouseHooks:V.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=l),3===a.target.nodeType&&(a.target=a.target.parentNode),g.filter?g.filter(a,f):a},special:{load:{noBubble:!0},focus:{trigger:function(){return this!==_()&&this.focus?(this.focus(),!1):void 0},delegateType:"focusin"},blur:{trigger:function(){return this===_()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return"checkbox"===this.type&&this.click&&n.nodeName(this,"input")?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?Z:$):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=Z,a&&a.preventDefault&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=Z,a&&a.stopPropagation&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=Z,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),k.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=L.access(d,b);e||d.addEventListener(a,c,!0),L.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=L.access(d,b)-1;e?L.access(d,b,e):(d.removeEventListener(a,c,!0),L.remove(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(g in a)this.on(g,b,c,a[g],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=$;else if(!d)return this;return 1===e&&(f=d,d=function(a){return n().off(a),f.apply(this,arguments)},d.guid=f.guid||(f.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=$),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ab=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,ib={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1></$2>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=qb[0].contentDocument,b.write(),b.close(),c=sb(a,b),qb.detach()),rb[a]=c),c}var ub=/^margin/,vb=new RegExp("^("+Q+")(?!px)[a-z%]+$","i"),wb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)};function xb(a,b,c){var d,e,f,g,h=a.style;return c=c||wb(a),c&&(g=c.getPropertyValue(b)||c[b]),c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),vb.test(g)&&ub.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function yb(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d=l.documentElement,e=l.createElement("div"),f=l.createElement("div");if(f.style){f.style.backgroundClip="content-box",f.cloneNode(!0).style.backgroundClip="",k.clearCloneStyle="content-box"===f.style.backgroundClip,e.style.cssText="border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;position:absolute",e.appendChild(f);function g(){f.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",f.innerHTML="",d.appendChild(e);var g=a.getComputedStyle(f,null);b="1%"!==g.top,c="4px"===g.width,d.removeChild(e)}a.getComputedStyle&&n.extend(k,{pixelPosition:function(){return g(),b},boxSizingReliable:function(){return null==c&&g(),c},reliableMarginRight:function(){var b,c=f.appendChild(l.createElement("div"));return c.style.cssText=f.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",c.style.marginRight=c.style.width="0",f.style.width="1px",d.appendChild(e),b=!parseFloat(a.getComputedStyle(c,null).marginRight),d.removeChild(e),b}})}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var zb=/^(none|table(?!-c[ea]).+)/,Ab=new RegExp("^("+Q+")(.*)$","i"),Bb=new RegExp("^([+-])=("+Q+")","i"),Cb={position:"absolute",visibility:"hidden",display:"block"},Db={letterSpacing:"0",fontWeight:"400"},Eb=["Webkit","O","Moz","ms"];function Fb(a,b){if(b in a)return b;var c=b[0].toUpperCase()+b.slice(1),d=b,e=Eb.length;while(e--)if(b=Eb[e]+c,b in a)return b;return d}function Gb(a,b,c){var d=Ab.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Hb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+R[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+R[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+R[f]+"Width",!0,e))):(g+=n.css(a,"padding"+R[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+R[f]+"Width",!0,e)));return g}function Ib(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=wb(a),g="border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=xb(a,b,f),(0>e||null==e)&&(e=a.style[b]),vb.test(e))return e;d=g&&(k.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Hb(a,b,c||(g?"border":"content"),d,f)+"px"}function Jb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=L.get(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&S(d)&&(f[g]=L.access(d,"olddisplay",tb(d.nodeName)))):(e=S(d),"none"===c&&e||L.set(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=xb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;return b=n.cssProps[h]||(n.cssProps[h]=Fb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=Bb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),k.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Fb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=xb(a,b,d)),"normal"===e&&b in Db&&(e=Db[b]),""===c||c?(f=parseFloat(e),c===!0||n.isNumeric(f)?f||0:e):e}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?zb.test(n.css(a,"display"))&&0===a.offsetWidth?n.swap(a,Cb,function(){return Ib(a,b,d)}):Ib(a,b,d):void 0},set:function(a,c,d){var e=d&&wb(a);return Gb(a,c,d?Hb(a,b,d,"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),n.cssHooks.marginRight=yb(k.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},xb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+R[d]+b]=f[d]||f[d-2]||f[0];return e}},ub.test(a)||(n.cssHooks[a+b].set=Gb)}),n.fn.extend({css:function(a,b){return J(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=wb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return Jb(this,!0)},hide:function(){return Jb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){S(this)?n(this).show():n(this).hide()})}});function Kb(a,b,c,d,e){return new Kb.prototype.init(a,b,c,d,e)}n.Tween=Kb,Kb.prototype={constructor:Kb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=Kb.propHooks[this.prop];return a&&a.get?a.get(this):Kb.propHooks._default.get(this)},run:function(a){var b,c=Kb.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Kb.propHooks._default.set(this),this}},Kb.prototype.init.prototype=Kb.prototype,Kb.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},Kb.propHooks.scrollTop=Kb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=Kb.prototype.init,n.fx.step={};var Lb,Mb,Nb=/^(?:toggle|show|hide)$/,Ob=new RegExp("^(?:([+-])=|)("+Q+")([a-z%]*)$","i"),Pb=/queueHooks$/,Qb=[Vb],Rb={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=Ob.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&Ob.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function Sb(){return setTimeout(function(){Lb=void 0}),Lb=n.now()}function Tb(a,b){var c,d=0,e={height:a};for(b=b?1:0;4>d;d+=2-b)c=R[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function Ub(a,b,c){for(var d,e=(Rb[b]||[]).concat(Rb["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function Vb(a,b,c){var d,e,f,g,h,i,j,k,l=this,m={},o=a.style,p=a.nodeType&&S(a),q=L.get(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,l.always(function(){l.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=n.css(a,"display"),k="none"===j?L.get(a,"olddisplay")||tb(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(o.display="inline-block")),c.overflow&&(o.overflow="hidden",l.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],Nb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}m[d]=q&&q[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(m))"inline"===("none"===j?tb(a.nodeName):j)&&(o.display=j);else{q?"hidden"in q&&(p=q.hidden):q=L.access(a,"fxshow",{}),f&&(q.hidden=!p),p?n(a).show():l.done(function(){n(a).hide()}),l.done(function(){var b;L.remove(a,"fxshow");for(b in m)n.style(a,b,m[b])});for(d in m)g=Ub(p?q[d]:0,d,l),d in q||(q[d]=g.start,p&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function Wb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function Xb(a,b,c){var d,e,f=0,g=Qb.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Lb||Sb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:Lb||Sb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(Wb(k,j.opts.specialEasing);g>f;f++)if(d=Qb[f].call(j,a,k,j.opts))return d;return n.map(k,Ub,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(Xb,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],Rb[c]=Rb[c]||[],Rb[c].unshift(b)},prefilter:function(a,b){b?Qb.unshift(a):Qb.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(S).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=Xb(this,n.extend({},a),f);(e||L.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=L.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&Pb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=L.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(Tb(b,!0),a,d,e)}}),n.each({slideDown:Tb("show"),slideUp:Tb("hide"),slideToggle:Tb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=0,c=n.timers;for(Lb=n.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||n.fx.stop(),Lb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){Mb||(Mb=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(Mb),Mb=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a=l.createElement("input"),b=l.createElement("select"),c=b.appendChild(l.createElement("option"));a.type="checkbox",k.checkOn=""!==a.value,k.optSelected=c.selected,b.disabled=!0,k.optDisabled=!c.disabled,a=l.createElement("input"),a.value="t",a.type="radio",k.radioValue="t"===a.value}();var Yb,Zb,$b=n.expr.attrHandle;n.fn.extend({attr:function(a,b){return J(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===U?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?Zb:Yb)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))
-},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(E);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)&&(a[d]=!1),a.removeAttribute(c)},attrHooks:{type:{set:function(a,b){if(!k.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),Zb={set:function(a,b,c){return b===!1?n.removeAttr(a,c):a.setAttribute(c,c),c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=$b[b]||n.find.attr;$b[b]=function(a,b,d){var e,f;return d||(f=$b[b],$b[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,$b[b]=f),e}});var _b=/^(?:input|select|textarea|button)$/i;n.fn.extend({prop:function(a,b){return J(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[n.propFix[a]||a]})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){return a.hasAttribute("tabindex")||_b.test(a.nodeName)||a.href?a.tabIndex:-1}}}}),k.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var ac=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h="string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0===arguments.length||"string"==typeof a&&a,i=0,j=this.length;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(h)for(b=(a||"").match(E)||[];j>i;i++)if(c=this[i],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(ac," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(E)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===U||"boolean"===c)&&(this.className&&L.set(this,"__className__",this.className),this.className=this.className||a===!1?"":L.get(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(ac," ").indexOf(b)>=0)return!0;return!1}});var bc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(bc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a))}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(k.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(d.value,f)>=0)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},k.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var cc=n.now(),dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){var b,c;if(!a||"string"!=typeof a)return null;try{c=new DOMParser,b=c.parseFromString(a,"text/xml")}catch(d){b=void 0}return(!b||b.getElementsByTagName("parsererror").length)&&n.error("Invalid XML: "+a),b};var ec,fc,gc=/#.*$/,hc=/([?&])_=[^&]*/,ic=/^(.*?):[ \t]*([^\r\n]*)$/gm,jc=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,kc=/^(?:GET|HEAD)$/,lc=/^\/\//,mc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,nc={},oc={},pc="*/".concat("*");try{fc=location.href}catch(qc){fc=l.createElement("a"),fc.href="",fc=fc.href}ec=mc.exec(fc.toLowerCase())||[];function rc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(E)||[];if(n.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function sc(a,b,c,d){var e={},f=a===oc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function tc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&n.extend(!0,a,d),a}function uc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function vc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:fc,type:"GET",isLocal:jc.test(ec[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":pc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?tc(tc(a,n.ajaxSettings),b):tc(n.ajaxSettings,a)},ajaxPrefilter:rc(nc),ajaxTransport:rc(oc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!f){f={};while(b=ic.exec(e))f[b[1].toLowerCase()]=b[2]}b=f[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?e:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return c&&c.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||fc)+"").replace(gc,"").replace(lc,ec[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(E)||[""],null==k.crossDomain&&(h=mc.exec(k.url.toLowerCase()),k.crossDomain=!(!h||h[1]===ec[1]&&h[2]===ec[2]&&(h[3]||("http:"===h[1]?"80":"443"))===(ec[3]||("http:"===ec[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),sc(nc,k,b,v),2===t)return v;i=k.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!kc.test(k.type),d=k.url,k.hasContent||(k.data&&(d=k.url+=(dc.test(d)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=hc.test(d)?d.replace(hc,"$1_="+cc++):d+(dc.test(d)?"&":"?")+"_="+cc++)),k.ifModified&&(n.lastModified[d]&&v.setRequestHeader("If-Modified-Since",n.lastModified[d]),n.etag[d]&&v.setRequestHeader("If-None-Match",n.etag[d])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+pc+"; q=0.01":""):k.accepts["*"]);for(j in k.headers)v.setRequestHeader(j,k.headers[j]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(j in{success:1,error:1,complete:1})v[j](k[j]);if(c=sc(oc,k,b,v)){v.readyState=1,i&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,c.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,f,h){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),c=void 0,e=h||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,f&&(u=uc(k,v,f)),u=vc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[d]=w),w=v.getResponseHeader("etag"),w&&(n.etag[d]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,i&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),i&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){var b;return n.isFunction(a)?this.each(function(b){n(this).wrapAll(a.call(this,b))}):(this[0]&&(b=n(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this)},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var wc=/%20/g,xc=/\[\]$/,yc=/\r?\n/g,zc=/^(?:submit|button|image|reset|file)$/i,Ac=/^(?:input|select|textarea|keygen)/i;function Bc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||xc.test(a)?d(a,e):Bc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Bc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Bc(c,a[c],b,e);return d.join("&").replace(wc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Ac.test(this.nodeName)&&!zc.test(a)&&(this.checked||!T.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(yc,"\r\n")}}):{name:b.name,value:c.replace(yc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(a){}};var Cc=0,Dc={},Ec={0:200,1223:204},Fc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Dc)Dc[a]()}),k.cors=!!Fc&&"withCredentials"in Fc,k.ajax=Fc=!!Fc,n.ajaxTransport(function(a){var b;return k.cors||Fc&&!a.crossDomain?{send:function(c,d){var e,f=a.xhr(),g=++Cc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)f.setRequestHeader(e,c[e]);b=function(a){return function(){b&&(delete Dc[g],b=f.onload=f.onerror=null,"abort"===a?f.abort():"error"===a?d(f.status,f.statusText):d(Ec[f.status]||f.status,f.statusText,"string"==typeof f.responseText?{text:f.responseText}:void 0,f.getAllResponseHeaders()))}},f.onload=b(),f.onerror=b("error"),b=Dc[g]=b("abort");try{f.send(a.hasContent&&a.data||null)}catch(h){if(b)throw h}},abort:function(){b&&b()}}:void 0}),n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(d,e){b=n("<script>").prop({async:!0,charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&e("error"===a.type?404:200,a.type)}),l.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Gc=[],Hc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Gc.pop()||n.expando+"_"+cc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Hc.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Hc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Hc,"$1"+e):b.jsonp!==!1&&(b.url+=(dc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Gc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||l;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var Ic=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&Ic)return Ic.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=n.trim(a.slice(h)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e,dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,f||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var Jc=a.document.documentElement;function Kc(a){return n.isWindow(a)?a:9===a.nodeType&&a.defaultView}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d=this[0],e={top:0,left:0},f=d&&d.ownerDocument;if(f)return b=f.documentElement,n.contains(b,d)?(typeof d.getBoundingClientRect!==U&&(e=d.getBoundingClientRect()),c=Kc(f),{top:e.top+c.pageYOffset-b.clientTop,left:e.left+c.pageXOffset-b.clientLeft}):e},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===n.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(d=a.offset()),d.top+=n.css(a[0],"borderTopWidth",!0),d.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-d.top-n.css(c,"marginTop",!0),left:b.left-d.left-n.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||Jc;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Jc})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b,c){var d="pageYOffset"===c;n.fn[b]=function(e){return J(this,function(b,e,f){var g=Kc(b);return void 0===f?g?g[c]:b[e]:void(g?g.scrollTo(d?a.pageXOffset:f,d?f:a.pageYOffset):b[e]=f)},b,e,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=yb(k.pixelPosition,function(a,c){return c?(c=xb(a,b),vb.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return J(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var Lc=a.jQuery,Mc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=Mc),b&&a.jQuery===n&&(a.jQuery=Lc),n},typeof b===U&&(a.jQuery=a.$=n),n});
diff --git a/static/js/jquery.url.js b/static/js/jquery.url.js
deleted file mode 100644
--- a/static/js/jquery.url.js
+++ /dev/null
@@ -1,181 +0,0 @@
-// JQuery URL Parser
-// Written by Mark Perkins, mark@allmarkedup.com
-// License: http://unlicense.org/ (i.e. do what you want with it!)
-
-jQuery.url = function()
-{
-	var segments = {};
-	
-	var parsed = {};
-	
-	/**
-    * Options object. Only the URI and strictMode values can be changed via the setters below.
-    */
-  	var options = {
-	
-		url : window.location, // default URI is the page in which the script is running
-		
-		strictMode: false, // 'loose' parsing by default
-	
-		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query 
-		
-		q: {
-			name: "queryKey",
-			parser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
-		},
-		
-		parser: {
-			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
-			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
-		}
-		
-	};
-	
-    /**
-     * Deals with the parsing of the URI according to the regex above.
- 	 * Written by Steven Levithan - see credits at top.
-     */		
-	var parseUri = function()
-	{
-		str = decodeURI( options.url );
-		
-		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
-		var uri = {};
-		var i = 14;
-
-		while ( i-- ) {
-			uri[ options.key[i] ] = m[i] || "";
-		}
-
-		uri[ options.q.name ] = {};
-		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
-			if ($1) {
-				uri[options.q.name][$1] = $2;
-			}
-		});
-
-		return uri;
-	};
-
-    /**
-     * Returns the value of the passed in key from the parsed URI.
-  	 * 
-	 * @param string key The key whose value is required
-     */		
-	var key = function( key )
-	{
-		if ( jQuery.isEmptyObject(parsed) )
-		{
-			setUp(); // if the URI has not been parsed yet then do this first...	
-		} 
-		if ( key == "base" )
-		{
-			if ( parsed.port !== null && parsed.port !== "" )
-			{
-				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";	
-			}
-			else
-			{
-				return parsed.protocol+"://"+parsed.host+"/";
-			}
-		}
-	
-		return ( parsed[key] === "" ) ? null : parsed[key];
-	};
-	
-	/**
-     * Returns the value of the required query string parameter.
-  	 * 
-	 * @param string item The parameter whose value is required
-     */		
-	var param = function( item )
-	{
-		if ( jQuery.isEmptyObject(parsed) )
-		{
-			setUp(); // if the URI has not been parsed yet then do this first...	
-		}
-		if ( item === undefined )
-		{
-            return parsed.queryKey;
-        }
-        else
-        {
-            return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
-        }
-	};
-
-    /**
-     * 'Constructor' (not really!) function.
-     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments. 
-     */	
-	var setUp = function()
-	{
-		parsed = parseUri();
-		
-		getSegments();	
-	};
-	
-    /**
-     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
-     */
-	var getSegments = function()
-	{
-		var p = parsed.path;
-		segments = []; // clear out segments array
-		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
-	};
-	
-	return {
-		
-	    /**
-	     * Sets the parsing mode - either strict or loose. Set to loose by default.
-	     *
-	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
-	     */
-		setMode : function( mode )
-		{
-			options.strictMode = mode == "strict" ? true : false;
-			return this;
-		},
-		
-		/**
-	     * Sets URI to parse if you don't want to to parse the current page's URI.
-		 * Calling the function with no value for newUri resets it to the current page's URI.
-	     *
-	     * @param string newUri The URI to parse.
-	     */		
-		setUrl : function( newUri )
-		{
-			options.url = newUri === undefined ? window.location : newUri;
-			setUp();
-			return this;
-		},		
-		
-		/**
-	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
-		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
-		 *
-		 * If no integer is passed into the function it returns the number of segments in the URI.
-	     *
-	     * @param int pos The position of the segment to return. Can be empty.
-	     */	
-		segment : function( pos )
-		{
-			if ( jQuery.isEmptyObject(parsed) )
-			{
-				setUp(); // if the URI has not been parsed yet then do this first...	
-			} 
-			if ( pos === undefined )
-			{
-				return segments.length;
-			}
-			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
-		},
-		
-		attr : key, // provides public access to private 'key' function - see above
-		
-		param : param // provides public access to private 'param' function - see above
-		
-	};
-	
-}();
diff --git a/static/js/typeahead.bundle.js b/static/js/typeahead.bundle.js
deleted file mode 100644
--- a/static/js/typeahead.bundle.js
+++ /dev/null
@@ -1,1782 +0,0 @@
-/*!
- * typeahead.js 0.10.4
- * https://github.com/twitter/typeahead.js
- * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
- */
-
-(function($) {
-    var _ = function() {
-        "use strict";
-        return {
-            isMsie: function() {
-                return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
-            },
-            isBlankString: function(str) {
-                return !str || /^\s*$/.test(str);
-            },
-            escapeRegExChars: function(str) {
-                return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
-            },
-            isString: function(obj) {
-                return typeof obj === "string";
-            },
-            isNumber: function(obj) {
-                return typeof obj === "number";
-            },
-            isArray: $.isArray,
-            isFunction: $.isFunction,
-            isObject: $.isPlainObject,
-            isUndefined: function(obj) {
-                return typeof obj === "undefined";
-            },
-            toStr: function toStr(s) {
-                return _.isUndefined(s) || s === null ? "" : s + "";
-            },
-            bind: $.proxy,
-            each: function(collection, cb) {
-                $.each(collection, reverseArgs);
-                function reverseArgs(index, value) {
-                    return cb(value, index);
-                }
-            },
-            map: $.map,
-            filter: $.grep,
-            every: function(obj, test) {
-                var result = true;
-                if (!obj) {
-                    return result;
-                }
-                $.each(obj, function(key, val) {
-                    if (!(result = test.call(null, val, key, obj))) {
-                        return false;
-                    }
-                });
-                return !!result;
-            },
-            some: function(obj, test) {
-                var result = false;
-                if (!obj) {
-                    return result;
-                }
-                $.each(obj, function(key, val) {
-                    if (result = test.call(null, val, key, obj)) {
-                        return false;
-                    }
-                });
-                return !!result;
-            },
-            mixin: $.extend,
-            getUniqueId: function() {
-                var counter = 0;
-                return function() {
-                    return counter++;
-                };
-            }(),
-            templatify: function templatify(obj) {
-                return $.isFunction(obj) ? obj : template;
-                function template() {
-                    return String(obj);
-                }
-            },
-            defer: function(fn) {
-                setTimeout(fn, 0);
-            },
-            debounce: function(func, wait, immediate) {
-                var timeout, result;
-                return function() {
-                    var context = this, args = arguments, later, callNow;
-                    later = function() {
-                        timeout = null;
-                        if (!immediate) {
-                            result = func.apply(context, args);
-                        }
-                    };
-                    callNow = immediate && !timeout;
-                    clearTimeout(timeout);
-                    timeout = setTimeout(later, wait);
-                    if (callNow) {
-                        result = func.apply(context, args);
-                    }
-                    return result;
-                };
-            },
-            throttle: function(func, wait) {
-                var context, args, timeout, result, previous, later;
-                previous = 0;
-                later = function() {
-                    previous = new Date();
-                    timeout = null;
-                    result = func.apply(context, args);
-                };
-                return function() {
-                    var now = new Date(), remaining = wait - (now - previous);
-                    context = this;
-                    args = arguments;
-                    if (remaining <= 0) {
-                        clearTimeout(timeout);
-                        timeout = null;
-                        previous = now;
-                        result = func.apply(context, args);
-                    } else if (!timeout) {
-                        timeout = setTimeout(later, remaining);
-                    }
-                    return result;
-                };
-            },
-            noop: function() {}
-        };
-    }();
-    var VERSION = "0.10.4";
-    var tokenizers = function() {
-        "use strict";
-        return {
-            nonword: nonword,
-            whitespace: whitespace,
-            obj: {
-                nonword: getObjTokenizer(nonword),
-                whitespace: getObjTokenizer(whitespace)
-            }
-        };
-        function whitespace(str) {
-            str = _.toStr(str);
-            return str ? str.split(/\s+/) : [];
-        }
-        function nonword(str) {
-            str = _.toStr(str);
-            return str ? str.split(/\W+/) : [];
-        }
-        function getObjTokenizer(tokenizer) {
-            return function setKey() {
-                var args = [].slice.call(arguments, 0);
-                return function tokenize(o) {
-                    var tokens = [];
-                    _.each(args, function(k) {
-                        tokens = tokens.concat(tokenizer(_.toStr(o[k])));
-                    });
-                    return tokens;
-                };
-            };
-        }
-    }();
-    var LruCache = function() {
-        "use strict";
-        function LruCache(maxSize) {
-            this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
-            this.reset();
-            if (this.maxSize <= 0) {
-                this.set = this.get = $.noop;
-            }
-        }
-        _.mixin(LruCache.prototype, {
-            set: function set(key, val) {
-                var tailItem = this.list.tail, node;
-                if (this.size >= this.maxSize) {
-                    this.list.remove(tailItem);
-                    delete this.hash[tailItem.key];
-                }
-                if (node = this.hash[key]) {
-                    node.val = val;
-                    this.list.moveToFront(node);
-                } else {
-                    node = new Node(key, val);
-                    this.list.add(node);
-                    this.hash[key] = node;
-                    this.size++;
-                }
-            },
-            get: function get(key) {
-                var node = this.hash[key];
-                if (node) {
-                    this.list.moveToFront(node);
-                    return node.val;
-                }
-            },
-            reset: function reset() {
-                this.size = 0;
-                this.hash = {};
-                this.list = new List();
-            }
-        });
-        function List() {
-            this.head = this.tail = null;
-        }
-        _.mixin(List.prototype, {
-            add: function add(node) {
-                if (this.head) {
-                    node.next = this.head;
-                    this.head.prev = node;
-                }
-                this.head = node;
-                this.tail = this.tail || node;
-            },
-            remove: function remove(node) {
-                node.prev ? node.prev.next = node.next : this.head = node.next;
-                node.next ? node.next.prev = node.prev : this.tail = node.prev;
-            },
-            moveToFront: function(node) {
-                this.remove(node);
-                this.add(node);
-            }
-        });
-        function Node(key, val) {
-            this.key = key;
-            this.val = val;
-            this.prev = this.next = null;
-        }
-        return LruCache;
-    }();
-    var PersistentStorage = function() {
-        "use strict";
-        var ls, methods;
-        try {
-            ls = window.localStorage;
-            ls.setItem("~~~", "!");
-            ls.removeItem("~~~");
-        } catch (err) {
-            ls = null;
-        }
-        function PersistentStorage(namespace) {
-            this.prefix = [ "__", namespace, "__" ].join("");
-            this.ttlKey = "__ttl__";
-            this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
-        }
-        if (ls && window.JSON) {
-            methods = {
-                _prefix: function(key) {
-                    return this.prefix + key;
-                },
-                _ttlKey: function(key) {
-                    return this._prefix(key) + this.ttlKey;
-                },
-                get: function(key) {
-                    if (this.isExpired(key)) {
-                        this.remove(key);
-                    }
-                    return decode(ls.getItem(this._prefix(key)));
-                },
-                set: function(key, val, ttl) {
-                    if (_.isNumber(ttl)) {
-                        ls.setItem(this._ttlKey(key), encode(now() + ttl));
-                    } else {
-                        ls.removeItem(this._ttlKey(key));
-                    }
-                    return ls.setItem(this._prefix(key), encode(val));
-                },
-                remove: function(key) {
-                    ls.removeItem(this._ttlKey(key));
-                    ls.removeItem(this._prefix(key));
-                    return this;
-                },
-                clear: function() {
-                    var i, key, keys = [], len = ls.length;
-                    for (i = 0; i < len; i++) {
-                        if ((key = ls.key(i)).match(this.keyMatcher)) {
-                            keys.push(key.replace(this.keyMatcher, ""));
-                        }
-                    }
-                    for (i = keys.length; i--; ) {
-                        this.remove(keys[i]);
-                    }
-                    return this;
-                },
-                isExpired: function(key) {
-                    var ttl = decode(ls.getItem(this._ttlKey(key)));
-                    return _.isNumber(ttl) && now() > ttl ? true : false;
-                }
-            };
-        } else {
-            methods = {
-                get: _.noop,
-                set: _.noop,
-                remove: _.noop,
-                clear: _.noop,
-                isExpired: _.noop
-            };
-        }
-        _.mixin(PersistentStorage.prototype, methods);
-        return PersistentStorage;
-        function now() {
-            return new Date().getTime();
-        }
-        function encode(val) {
-            return JSON.stringify(_.isUndefined(val) ? null : val);
-        }
-        function decode(val) {
-            return JSON.parse(val);
-        }
-    }();
-    var Transport = function() {
-        "use strict";
-        var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
-        function Transport(o) {
-            o = o || {};
-            this.cancelled = false;
-            this.lastUrl = null;
-            this._send = o.transport ? callbackToDeferred(o.transport) : $.ajax;
-            this._get = o.rateLimiter ? o.rateLimiter(this._get) : this._get;
-            this._cache = o.cache === false ? new LruCache(0) : sharedCache;
-        }
-        Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
-            maxPendingRequests = num;
-        };
-        Transport.resetCache = function resetCache() {
-            sharedCache.reset();
-        };
-        _.mixin(Transport.prototype, {
-            _get: function(url, o, cb) {
-                var that = this, jqXhr;
-                if (this.cancelled || url !== this.lastUrl) {
-                    return;
-                }
-                if (jqXhr = pendingRequests[url]) {
-                    jqXhr.done(done).fail(fail);
-                } else if (pendingRequestsCount < maxPendingRequests) {
-                    pendingRequestsCount++;
-                    pendingRequests[url] = this._send(url, o).done(done).fail(fail).always(always);
-                } else {
-                    this.onDeckRequestArgs = [].slice.call(arguments, 0);
-                }
-                function done(resp) {
-                    cb && cb(null, resp);
-                    that._cache.set(url, resp);
-                }
-                function fail() {
-                    cb && cb(true);
-                }
-                function always() {
-                    pendingRequestsCount--;
-                    delete pendingRequests[url];
-                    if (that.onDeckRequestArgs) {
-                        that._get.apply(that, that.onDeckRequestArgs);
-                        that.onDeckRequestArgs = null;
-                    }
-                }
-            },
-            get: function(url, o, cb) {
-                var resp;
-                if (_.isFunction(o)) {
-                    cb = o;
-                    o = {};
-                }
-                this.cancelled = false;
-                this.lastUrl = url;
-                if (resp = this._cache.get(url)) {
-                    _.defer(function() {
-                        cb && cb(null, resp);
-                    });
-                } else {
-                    this._get(url, o, cb);
-                }
-                return !!resp;
-            },
-            cancel: function() {
-                this.cancelled = true;
-            }
-        });
-        return Transport;
-        function callbackToDeferred(fn) {
-            return function customSendWrapper(url, o) {
-                var deferred = $.Deferred();
-                fn(url, o, onSuccess, onError);
-                return deferred;
-                function onSuccess(resp) {
-                    _.defer(function() {
-                        deferred.resolve(resp);
-                    });
-                }
-                function onError(err) {
-                    _.defer(function() {
-                        deferred.reject(err);
-                    });
-                }
-            };
-        }
-    }();
-    var SearchIndex = function() {
-        "use strict";
-        function SearchIndex(o) {
-            o = o || {};
-            if (!o.datumTokenizer || !o.queryTokenizer) {
-                $.error("datumTokenizer and queryTokenizer are both required");
-            }
-            this.datumTokenizer = o.datumTokenizer;
-            this.queryTokenizer = o.queryTokenizer;
-            this.reset();
-        }
-        _.mixin(SearchIndex.prototype, {
-            bootstrap: function bootstrap(o) {
-                this.datums = o.datums;
-                this.trie = o.trie;
-            },
-            add: function(data) {
-                var that = this;
-                data = _.isArray(data) ? data : [ data ];
-                _.each(data, function(datum) {
-                    var id, tokens;
-                    id = that.datums.push(datum) - 1;
-                    tokens = normalizeTokens(that.datumTokenizer(datum));
-                    _.each(tokens, function(token) {
-                        var node, chars, ch;
-                        node = that.trie;
-                        chars = token.split("");
-                        while (ch = chars.shift()) {
-                            node = node.children[ch] || (node.children[ch] = newNode());
-                            node.ids.push(id);
-                        }
-                    });
-                });
-            },
-            get: function get(query) {
-                var that = this, tokens, matches;
-                tokens = normalizeTokens(this.queryTokenizer(query));
-                _.each(tokens, function(token) {
-                    var node, chars, ch, ids;
-                    if (matches && matches.length === 0) {
-                        return false;
-                    }
-                    node = that.trie;
-                    chars = token.split("");
-                    while (node && (ch = chars.shift())) {
-                        node = node.children[ch];
-                    }
-                    if (node && chars.length === 0) {
-                        ids = node.ids.slice(0);
-                        matches = matches ? getIntersection(matches, ids) : ids;
-                    } else {
-                        matches = [];
-                        return false;
-                    }
-                });
-                return matches ? _.map(unique(matches), function(id) {
-                    return that.datums[id];
-                }) : [];
-            },
-            reset: function reset() {
-                this.datums = [];
-                this.trie = newNode();
-            },
-            serialize: function serialize() {
-                return {
-                    datums: this.datums,
-                    trie: this.trie
-                };
-            }
-        });
-        return SearchIndex;
-        function normalizeTokens(tokens) {
-            tokens = _.filter(tokens, function(token) {
-                return !!token;
-            });
-            tokens = _.map(tokens, function(token) {
-                return token.toLowerCase();
-            });
-            return tokens;
-        }
-        function newNode() {
-            return {
-                ids: [],
-                children: {}
-            };
-        }
-        function unique(array) {
-            var seen = {}, uniques = [];
-            for (var i = 0, len = array.length; i < len; i++) {
-                if (!seen[array[i]]) {
-                    seen[array[i]] = true;
-                    uniques.push(array[i]);
-                }
-            }
-            return uniques;
-        }
-        function getIntersection(arrayA, arrayB) {
-            var ai = 0, bi = 0, intersection = [];
-            arrayA = arrayA.sort(compare);
-            arrayB = arrayB.sort(compare);
-            var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
-            while (ai < lenArrayA && bi < lenArrayB) {
-                if (arrayA[ai] < arrayB[bi]) {
-                    ai++;
-                } else if (arrayA[ai] > arrayB[bi]) {
-                    bi++;
-                } else {
-                    intersection.push(arrayA[ai]);
-                    ai++;
-                    bi++;
-                }
-            }
-            return intersection;
-            function compare(a, b) {
-                return a - b;
-            }
-        }
-    }();
-    var oParser = function() {
-        "use strict";
-        return {
-            local: getLocal,
-            prefetch: getPrefetch,
-            remote: getRemote
-        };
-        function getLocal(o) {
-            return o.local || null;
-        }
-        function getPrefetch(o) {
-            var prefetch, defaults;
-            defaults = {
-                url: null,
-                thumbprint: "",
-                ttl: 24 * 60 * 60 * 1e3,
-                filter: null,
-                ajax: {}
-            };
-            if (prefetch = o.prefetch || null) {
-                prefetch = _.isString(prefetch) ? {
-                    url: prefetch
-                } : prefetch;
-                prefetch = _.mixin(defaults, prefetch);
-                prefetch.thumbprint = VERSION + prefetch.thumbprint;
-                prefetch.ajax.type = prefetch.ajax.type || "GET";
-                prefetch.ajax.dataType = prefetch.ajax.dataType || "json";
-                !prefetch.url && $.error("prefetch requires url to be set");
-            }
-            return prefetch;
-        }
-        function getRemote(o) {
-            var remote, defaults;
-            defaults = {
-                url: null,
-                cache: true,
-                wildcard: "%QUERY",
-                replace: null,
-                rateLimitBy: "debounce",
-                rateLimitWait: 300,
-                send: null,
-                filter: null,
-                ajax: {}
-            };
-            if (remote = o.remote || null) {
-                remote = _.isString(remote) ? {
-                    url: remote
-                } : remote;
-                remote = _.mixin(defaults, remote);
-                remote.rateLimiter = /^throttle$/i.test(remote.rateLimitBy) ? byThrottle(remote.rateLimitWait) : byDebounce(remote.rateLimitWait);
-                remote.ajax.type = remote.ajax.type || "GET";
-                remote.ajax.dataType = remote.ajax.dataType || "json";
-                delete remote.rateLimitBy;
-                delete remote.rateLimitWait;
-                !remote.url && $.error("remote requires url to be set");
-            }
-            return remote;
-            function byDebounce(wait) {
-                return function(fn) {
-                    return _.debounce(fn, wait);
-                };
-            }
-            function byThrottle(wait) {
-                return function(fn) {
-                    return _.throttle(fn, wait);
-                };
-            }
-        }
-    }();
-    (function(root) {
-        "use strict";
-        var old, keys;
-        old = root.Bloodhound;
-        keys = {
-            data: "data",
-            protocol: "protocol",
-            thumbprint: "thumbprint"
-        };
-        root.Bloodhound = Bloodhound;
-        function Bloodhound(o) {
-            if (!o || !o.local && !o.prefetch && !o.remote) {
-                $.error("one of local, prefetch, or remote is required");
-            }
-            this.limit = o.limit || 5;
-            this.sorter = getSorter(o.sorter);
-            this.dupDetector = o.dupDetector || ignoreDuplicates;
-            this.local = oParser.local(o);
-            this.prefetch = oParser.prefetch(o);
-            this.remote = oParser.remote(o);
-            this.cacheKey = this.prefetch ? this.prefetch.cacheKey || this.prefetch.url : null;
-            this.index = new SearchIndex({
-                datumTokenizer: o.datumTokenizer,
-                queryTokenizer: o.queryTokenizer
-            });
-            this.storage = this.cacheKey ? new PersistentStorage(this.cacheKey) : null;
-        }
-        Bloodhound.noConflict = function noConflict() {
-            root.Bloodhound = old;
-            return Bloodhound;
-        };
-        Bloodhound.tokenizers = tokenizers;
-        _.mixin(Bloodhound.prototype, {
-            _loadPrefetch: function loadPrefetch(o) {
-                var that = this, serialized, deferred;
-                if (serialized = this._readFromStorage(o.thumbprint)) {
-                    this.index.bootstrap(serialized);
-                    deferred = $.Deferred().resolve();
-                } else {
-                    deferred = $.ajax(o.url, o.ajax).done(handlePrefetchResponse);
-                }
-                return deferred;
-                function handlePrefetchResponse(resp) {
-                    that.clear();
-                    that.add(o.filter ? o.filter(resp) : resp);
-                    that._saveToStorage(that.index.serialize(), o.thumbprint, o.ttl);
-                }
-            },
-            _getFromRemote: function getFromRemote(query, cb) {
-                var that = this, url, uriEncodedQuery;
-                if (!this.transport) {
-                    return;
-                }
-                query = query || "";
-                uriEncodedQuery = encodeURIComponent(query);
-                url = this.remote.replace ? this.remote.replace(this.remote.url, query) : this.remote.url.replace(this.remote.wildcard, uriEncodedQuery);
-                return this.transport.get(url, this.remote.ajax, handleRemoteResponse);
-                function handleRemoteResponse(err, resp) {
-                    err ? cb([]) : cb(that.remote.filter ? that.remote.filter(resp) : resp);
-                }
-            },
-            _cancelLastRemoteRequest: function cancelLastRemoteRequest() {
-                this.transport && this.transport.cancel();
-            },
-            _saveToStorage: function saveToStorage(data, thumbprint, ttl) {
-                if (this.storage) {
-                    this.storage.set(keys.data, data, ttl);
-                    this.storage.set(keys.protocol, location.protocol, ttl);
-                    this.storage.set(keys.thumbprint, thumbprint, ttl);
-                }
-            },
-            _readFromStorage: function readFromStorage(thumbprint) {
-                var stored = {}, isExpired;
-                if (this.storage) {
-                    stored.data = this.storage.get(keys.data);
-                    stored.protocol = this.storage.get(keys.protocol);
-                    stored.thumbprint = this.storage.get(keys.thumbprint);
-                }
-                isExpired = stored.thumbprint !== thumbprint || stored.protocol !== location.protocol;
-                return stored.data && !isExpired ? stored.data : null;
-            },
-            _initialize: function initialize() {
-                var that = this, local = this.local, deferred;
-                deferred = this.prefetch ? this._loadPrefetch(this.prefetch) : $.Deferred().resolve();
-                local && deferred.done(addLocalToIndex);
-                this.transport = this.remote ? new Transport(this.remote) : null;
-                return this.initPromise = deferred.promise();
-                function addLocalToIndex() {
-                    that.add(_.isFunction(local) ? local() : local);
-                }
-            },
-            initialize: function initialize(force) {
-                return !this.initPromise || force ? this._initialize() : this.initPromise;
-            },
-            add: function add(data) {
-                this.index.add(data);
-            },
-            get: function get(query, cb) {
-                var that = this, matches = [], cacheHit = false;
-                matches = this.index.get(query);
-                matches = this.sorter(matches).slice(0, this.limit);
-                matches.length < this.limit ? cacheHit = this._getFromRemote(query, returnRemoteMatches) : this._cancelLastRemoteRequest();
-                if (!cacheHit) {
-                    (matches.length > 0 || !this.transport) && cb && cb(matches);
-                }
-                function returnRemoteMatches(remoteMatches) {
-                    var matchesWithBackfill = matches.slice(0);
-                    _.each(remoteMatches, function(remoteMatch) {
-                        var isDuplicate;
-                        isDuplicate = _.some(matchesWithBackfill, function(match) {
-                            return that.dupDetector(remoteMatch, match);
-                        });
-                        !isDuplicate && matchesWithBackfill.push(remoteMatch);
-                        return matchesWithBackfill.length < that.limit;
-                    });
-                    cb && cb(that.sorter(matchesWithBackfill));
-                }
-            },
-            clear: function clear() {
-                this.index.reset();
-            },
-            clearPrefetchCache: function clearPrefetchCache() {
-                this.storage && this.storage.clear();
-            },
-            clearRemoteCache: function clearRemoteCache() {
-                this.transport && Transport.resetCache();
-            },
-            ttAdapter: function ttAdapter() {
-                return _.bind(this.get, this);
-            }
-        });
-        return Bloodhound;
-        function getSorter(sortFn) {
-            return _.isFunction(sortFn) ? sort : noSort;
-            function sort(array) {
-                return array.sort(sortFn);
-            }
-            function noSort(array) {
-                return array;
-            }
-        }
-        function ignoreDuplicates() {
-            return false;
-        }
-    })(this);
-    var html = function() {
-        return {
-            wrapper: '<span class="twitter-typeahead"></span>',
-            dropdown: '<span class="tt-dropdown-menu"></span>',
-            dataset: '<div class="tt-dataset-%CLASS%"></div>',
-            suggestions: '<span class="tt-suggestions"></span>',
-            suggestion: '<div class="tt-suggestion"></div>'
-        };
-    }();
-    var css = function() {
-        "use strict";
-        var css = {
-            wrapper: {
-                position: "relative",
-                display: "inline-block"
-            },
-            hint: {
-                position: "absolute",
-                top: "0",
-                left: "0",
-                borderColor: "transparent",
-                boxShadow: "none",
-                opacity: "1"
-            },
-            input: {
-                position: "relative",
-                verticalAlign: "top",
-                backgroundColor: "transparent"
-            },
-            inputWithNoHint: {
-                position: "relative",
-                verticalAlign: "top"
-            },
-            dropdown: {
-                position: "absolute",
-                top: "100%",
-                left: "0",
-                zIndex: "100",
-                display: "none"
-            },
-            suggestions: {
-                display: "block"
-            },
-            suggestion: {
-                whiteSpace: "nowrap",
-                cursor: "pointer"
-            },
-            suggestionChild: {
-                whiteSpace: "normal"
-            },
-            ltr: {
-                left: "0",
-                right: "auto"
-            },
-            rtl: {
-                left: "auto",
-                right: " 0"
-            }
-        };
-        if (_.isMsie()) {
-            _.mixin(css.input, {
-                backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
-            });
-        }
-        if (_.isMsie() && _.isMsie() <= 7) {
-            _.mixin(css.input, {
-                marginTop: "-1px"
-            });
-        }
-        return css;
-    }();
-    var EventBus = function() {
-        "use strict";
-        var namespace = "typeahead:";
-        function EventBus(o) {
-            if (!o || !o.el) {
-                $.error("EventBus initialized without el");
-            }
-            this.$el = $(o.el);
-        }
-        _.mixin(EventBus.prototype, {
-            trigger: function(type) {
-                var args = [].slice.call(arguments, 1);
-                this.$el.trigger(namespace + type, args);
-            }
-        });
-        return EventBus;
-    }();
-    var EventEmitter = function() {
-        "use strict";
-        var splitter = /\s+/, nextTick = getNextTick();
-        return {
-            onSync: onSync,
-            onAsync: onAsync,
-            off: off,
-            trigger: trigger
-        };
-        function on(method, types, cb, context) {
-            var type;
-            if (!cb) {
-                return this;
-            }
-            types = types.split(splitter);
-            cb = context ? bindContext(cb, context) : cb;
-            this._callbacks = this._callbacks || {};
-            while (type = types.shift()) {
-                this._callbacks[type] = this._callbacks[type] || {
-                    sync: [],
-                    async: []
-                };
-                this._callbacks[type][method].push(cb);
-            }
-            return this;
-        }
-        function onAsync(types, cb, context) {
-            return on.call(this, "async", types, cb, context);
-        }
-        function onSync(types, cb, context) {
-            return on.call(this, "sync", types, cb, context);
-        }
-        function off(types) {
-            var type;
-            if (!this._callbacks) {
-                return this;
-            }
-            types = types.split(splitter);
-            while (type = types.shift()) {
-                delete this._callbacks[type];
-            }
-            return this;
-        }
-        function trigger(types) {
-            var type, callbacks, args, syncFlush, asyncFlush;
-            if (!this._callbacks) {
-                return this;
-            }
-            types = types.split(splitter);
-            args = [].slice.call(arguments, 1);
-            while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
-                syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
-                asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
-                syncFlush() && nextTick(asyncFlush);
-            }
-            return this;
-        }
-        function getFlush(callbacks, context, args) {
-            return flush;
-            function flush() {
-                var cancelled;
-                for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
-                    cancelled = callbacks[i].apply(context, args) === false;
-                }
-                return !cancelled;
-            }
-        }
-        function getNextTick() {
-            var nextTickFn;
-            if (window.setImmediate) {
-                nextTickFn = function nextTickSetImmediate(fn) {
-                    setImmediate(function() {
-                        fn();
-                    });
-                };
-            } else {
-                nextTickFn = function nextTickSetTimeout(fn) {
-                    setTimeout(function() {
-                        fn();
-                    }, 0);
-                };
-            }
-            return nextTickFn;
-        }
-        function bindContext(fn, context) {
-            return fn.bind ? fn.bind(context) : function() {
-                fn.apply(context, [].slice.call(arguments, 0));
-            };
-        }
-    }();
-    var highlight = function(doc) {
-        "use strict";
-        var defaults = {
-            node: null,
-            pattern: null,
-            tagName: "strong",
-            className: null,
-            wordsOnly: false,
-            caseSensitive: false
-        };
-        return function hightlight(o) {
-            var regex;
-            o = _.mixin({}, defaults, o);
-            if (!o.node || !o.pattern) {
-                return;
-            }
-            o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
-            regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
-            traverse(o.node, hightlightTextNode);
-            function hightlightTextNode(textNode) {
-                var match, patternNode, wrapperNode;
-                if (match = regex.exec(textNode.data)) {
-                    wrapperNode = doc.createElement(o.tagName);
-                    o.className && (wrapperNode.className = o.className);
-                    patternNode = textNode.splitText(match.index);
-                    patternNode.splitText(match[0].length);
-                    wrapperNode.appendChild(patternNode.cloneNode(true));
-                    textNode.parentNode.replaceChild(wrapperNode, patternNode);
-                }
-                return !!match;
-            }
-            function traverse(el, hightlightTextNode) {
-                var childNode, TEXT_NODE_TYPE = 3;
-                for (var i = 0; i < el.childNodes.length; i++) {
-                    childNode = el.childNodes[i];
-                    if (childNode.nodeType === TEXT_NODE_TYPE) {
-                        i += hightlightTextNode(childNode) ? 1 : 0;
-                    } else {
-                        traverse(childNode, hightlightTextNode);
-                    }
-                }
-            }
-        };
-        function getRegex(patterns, caseSensitive, wordsOnly) {
-            var escapedPatterns = [], regexStr;
-            for (var i = 0, len = patterns.length; i < len; i++) {
-                escapedPatterns.push(_.escapeRegExChars(patterns[i]));
-            }
-            regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
-            return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
-        }
-    }(window.document);
-    var Input = function() {
-        "use strict";
-        var specialKeyCodeMap;
-        specialKeyCodeMap = {
-            9: "tab",
-            27: "esc",
-            37: "left",
-            39: "right",
-            13: "enter",
-            38: "up",
-            40: "down"
-        };
-        function Input(o) {
-            var that = this, onBlur, onFocus, onKeydown, onInput;
-            o = o || {};
-            if (!o.input) {
-                $.error("input is missing");
-            }
-            onBlur = _.bind(this._onBlur, this);
-            onFocus = _.bind(this._onFocus, this);
-            onKeydown = _.bind(this._onKeydown, this);
-            onInput = _.bind(this._onInput, this);
-            this.$hint = $(o.hint);
-            this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
-            if (this.$hint.length === 0) {
-                this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
-            }
-            if (!_.isMsie()) {
-                this.$input.on("input.tt", onInput);
-            } else {
-                this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
-                    if (specialKeyCodeMap[$e.which || $e.keyCode]) {
-                        return;
-                    }
-                    _.defer(_.bind(that._onInput, that, $e));
-                });
-            }
-            this.query = this.$input.val();
-            this.$overflowHelper = buildOverflowHelper(this.$input);
-        }
-        Input.normalizeQuery = function(str) {
-            return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
-        };
-        _.mixin(Input.prototype, EventEmitter, {
-            _onBlur: function onBlur() {
-                this.resetInputValue();
-                this.trigger("blurred");
-            },
-            _onFocus: function onFocus() {
-                this.trigger("focused");
-            },
-            _onKeydown: function onKeydown($e) {
-                var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
-                this._managePreventDefault(keyName, $e);
-                if (keyName && this._shouldTrigger(keyName, $e)) {
-                    this.trigger(keyName + "Keyed", $e);
-                }
-            },
-            _onInput: function onInput() {
-                this._checkInputValue();
-            },
-            _managePreventDefault: function managePreventDefault(keyName, $e) {
-                var preventDefault, hintValue, inputValue;
-                switch (keyName) {
-                  case "tab":
-                    hintValue = this.getHint();
-                    inputValue = this.getInputValue();
-                    preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
-                    break;
-
-                  case "up":
-                  case "down":
-                    preventDefault = !withModifier($e);
-                    break;
-
-                  default:
-                    preventDefault = false;
-                }
-                preventDefault && $e.preventDefault();
-            },
-            _shouldTrigger: function shouldTrigger(keyName, $e) {
-                var trigger;
-                switch (keyName) {
-                  case "tab":
-                    trigger = !withModifier($e);
-                    break;
-
-                  default:
-                    trigger = true;
-                }
-                return trigger;
-            },
-            _checkInputValue: function checkInputValue() {
-                var inputValue, areEquivalent, hasDifferentWhitespace;
-                inputValue = this.getInputValue();
-                areEquivalent = areQueriesEquivalent(inputValue, this.query);
-                hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
-                this.query = inputValue;
-                if (!areEquivalent) {
-                    this.trigger("queryChanged", this.query);
-                } else if (hasDifferentWhitespace) {
-                    this.trigger("whitespaceChanged", this.query);
-                }
-            },
-            focus: function focus() {
-                this.$input.focus();
-            },
-            blur: function blur() {
-                this.$input.blur();
-            },
-            getQuery: function getQuery() {
-                return this.query;
-            },
-            setQuery: function setQuery(query) {
-                this.query = query;
-            },
-            getInputValue: function getInputValue() {
-                return this.$input.val();
-            },
-            setInputValue: function setInputValue(value, silent) {
-                this.$input.val(value);
-                silent ? this.clearHint() : this._checkInputValue();
-            },
-            resetInputValue: function resetInputValue() {
-                this.setInputValue(this.query, true);
-            },
-            getHint: function getHint() {
-                return this.$hint.val();
-            },
-            setHint: function setHint(value) {
-                this.$hint.val(value);
-            },
-            clearHint: function clearHint() {
-                this.setHint("");
-            },
-            clearHintIfInvalid: function clearHintIfInvalid() {
-                var val, hint, valIsPrefixOfHint, isValid;
-                val = this.getInputValue();
-                hint = this.getHint();
-                valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
-                isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
-                !isValid && this.clearHint();
-            },
-            getLanguageDirection: function getLanguageDirection() {
-                return (this.$input.css("direction") || "ltr").toLowerCase();
-            },
-            hasOverflow: function hasOverflow() {
-                var constraint = this.$input.width() - 2;
-                this.$overflowHelper.text(this.getInputValue());
-                return this.$overflowHelper.width() >= constraint;
-            },
-            isCursorAtEnd: function() {
-                var valueLength, selectionStart, range;
-                valueLength = this.$input.val().length;
-                selectionStart = this.$input[0].selectionStart;
-                if (_.isNumber(selectionStart)) {
-                    return selectionStart === valueLength;
-                } else if (document.selection) {
-                    range = document.selection.createRange();
-                    range.moveStart("character", -valueLength);
-                    return valueLength === range.text.length;
-                }
-                return true;
-            },
-            destroy: function destroy() {
-                this.$hint.off(".tt");
-                this.$input.off(".tt");
-                this.$hint = this.$input = this.$overflowHelper = null;
-            }
-        });
-        return Input;
-        function buildOverflowHelper($input) {
-            return $('<pre aria-hidden="true"></pre>').css({
-                position: "absolute",
-                visibility: "hidden",
-                whiteSpace: "pre",
-                fontFamily: $input.css("font-family"),
-                fontSize: $input.css("font-size"),
-                fontStyle: $input.css("font-style"),
-                fontVariant: $input.css("font-variant"),
-                fontWeight: $input.css("font-weight"),
-                wordSpacing: $input.css("word-spacing"),
-                letterSpacing: $input.css("letter-spacing"),
-                textIndent: $input.css("text-indent"),
-                textRendering: $input.css("text-rendering"),
-                textTransform: $input.css("text-transform")
-            }).insertAfter($input);
-        }
-        function areQueriesEquivalent(a, b) {
-            return Input.normalizeQuery(a) === Input.normalizeQuery(b);
-        }
-        function withModifier($e) {
-            return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
-        }
-    }();
-    var Dataset = function() {
-        "use strict";
-        var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
-        function Dataset(o) {
-            o = o || {};
-            o.templates = o.templates || {};
-            if (!o.source) {
-                $.error("missing source");
-            }
-            if (o.name && !isValidName(o.name)) {
-                $.error("invalid dataset name: " + o.name);
-            }
-            this.query = null;
-            this.highlight = !!o.highlight;
-            this.name = o.name || _.getUniqueId();
-            this.source = o.source;
-            this.displayFn = getDisplayFn(o.display || o.displayKey);
-            this.templates = getTemplates(o.templates, this.displayFn);
-            this.$el = $(html.dataset.replace("%CLASS%", this.name));
-        }
-        Dataset.extractDatasetName = function extractDatasetName(el) {
-            return $(el).data(datasetKey);
-        };
-        Dataset.extractValue = function extractDatum(el) {
-            return $(el).data(valueKey);
-        };
-        Dataset.extractDatum = function extractDatum(el) {
-            return $(el).data(datumKey);
-        };
-        _.mixin(Dataset.prototype, EventEmitter, {
-            _render: function render(query, suggestions) {
-                if (!this.$el) {
-                    return;
-                }
-                var that = this, hasSuggestions;
-                this.$el.empty();
-                hasSuggestions = suggestions && suggestions.length;
-                if (!hasSuggestions && this.templates.empty) {
-                    this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
-                } else if (hasSuggestions) {
-                    this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
-                }
-                this.trigger("rendered");
-                function getEmptyHtml() {
-                    return that.templates.empty({
-                        query: query,
-                        isEmpty: true
-                    });
-                }
-                function getSuggestionsHtml() {
-                    var $suggestions, nodes;
-                    $suggestions = $(html.suggestions).css(css.suggestions);
-                    nodes = _.map(suggestions, getSuggestionNode);
-                    $suggestions.append.apply($suggestions, nodes);
-                    that.highlight && highlight({
-                        className: "tt-highlight",
-                        node: $suggestions[0],
-                        pattern: query
-                    });
-                    return $suggestions;
-                    function getSuggestionNode(suggestion) {
-                        var $el;
-                        $el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
-                        $el.children().each(function() {
-                            $(this).css(css.suggestionChild);
-                        });
-                        return $el;
-                    }
-                }
-                function getHeaderHtml() {
-                    return that.templates.header({
-                        query: query,
-                        isEmpty: !hasSuggestions
-                    });
-                }
-                function getFooterHtml() {
-                    return that.templates.footer({
-                        query: query,
-                        isEmpty: !hasSuggestions
-                    });
-                }
-            },
-            getRoot: function getRoot() {
-                return this.$el;
-            },
-            update: function update(query) {
-                var that = this;
-                this.query = query;
-                this.canceled = false;
-                this.source(query, render);
-                function render(suggestions) {
-                    if (!that.canceled && query === that.query) {
-                        that._render(query, suggestions);
-                    }
-                }
-            },
-            cancel: function cancel() {
-                this.canceled = true;
-            },
-            clear: function clear() {
-                this.cancel();
-                this.$el.empty();
-                this.trigger("rendered");
-            },
-            isEmpty: function isEmpty() {
-                return this.$el.is(":empty");
-            },
-            destroy: function destroy() {
-                this.$el = null;
-            }
-        });
-        return Dataset;
-        function getDisplayFn(display) {
-            display = display || "value";
-            return _.isFunction(display) ? display : displayFn;
-            function displayFn(obj) {
-                return obj[display];
-            }
-        }
-        function getTemplates(templates, displayFn) {
-            return {
-                empty: templates.empty && _.templatify(templates.empty),
-                header: templates.header && _.templatify(templates.header),
-                footer: templates.footer && _.templatify(templates.footer),
-                suggestion: templates.suggestion || suggestionTemplate
-            };
-            function suggestionTemplate(context) {
-                return "<p>" + displayFn(context) + "</p>";
-            }
-        }
-        function isValidName(str) {
-            return /^[_a-zA-Z0-9-]+$/.test(str);
-        }
-    }();
-    var Dropdown = function() {
-        "use strict";
-        function Dropdown(o) {
-            var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
-            o = o || {};
-            if (!o.menu) {
-                $.error("menu is required");
-            }
-            this.isOpen = false;
-            this.isEmpty = true;
-            this.datasets = _.map(o.datasets, initializeDataset);
-            onSuggestionClick = _.bind(this._onSuggestionClick, this);
-            onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
-            onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
-            this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
-            _.each(this.datasets, function(dataset) {
-                that.$menu.append(dataset.getRoot());
-                dataset.onSync("rendered", that._onRendered, that);
-            });
-        }
-        _.mixin(Dropdown.prototype, EventEmitter, {
-            _onSuggestionClick: function onSuggestionClick($e) {
-                this.trigger("suggestionClicked", $($e.currentTarget));
-            },
-            _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
-                this._removeCursor();
-                this._setCursor($($e.currentTarget), true);
-            },
-            _onSuggestionMouseLeave: function onSuggestionMouseLeave() {
-                this._removeCursor();
-            },
-            _onRendered: function onRendered() {
-                this.isEmpty = _.every(this.datasets, isDatasetEmpty);
-                this.isEmpty ? this._hide() : this.isOpen && this._show();
-                this.trigger("datasetRendered");
-                function isDatasetEmpty(dataset) {
-                    return dataset.isEmpty();
-                }
-            },
-            _hide: function() {
-                this.$menu.hide();
-            },
-            _show: function() {
-                this.$menu.css("display", "block");
-            },
-            _getSuggestions: function getSuggestions() {
-                return this.$menu.find(".tt-suggestion");
-            },
-            _getCursor: function getCursor() {
-                return this.$menu.find(".tt-cursor").first();
-            },
-            _setCursor: function setCursor($el, silent) {
-                $el.first().addClass("tt-cursor");
-                !silent && this.trigger("cursorMoved");
-            },
-            _removeCursor: function removeCursor() {
-                this._getCursor().removeClass("tt-cursor");
-            },
-            _moveCursor: function moveCursor(increment) {
-                var $suggestions, $oldCursor, newCursorIndex, $newCursor;
-                if (!this.isOpen) {
-                    return;
-                }
-                $oldCursor = this._getCursor();
-                $suggestions = this._getSuggestions();
-                this._removeCursor();
-                newCursorIndex = $suggestions.index($oldCursor) + increment;
-                newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
-                if (newCursorIndex === -1) {
-                    this.trigger("cursorRemoved");
-                    return;
-                } else if (newCursorIndex < -1) {
-                    newCursorIndex = $suggestions.length - 1;
-                }
-                this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
-                this._ensureVisible($newCursor);
-            },
-            _ensureVisible: function ensureVisible($el) {
-                var elTop, elBottom, menuScrollTop, menuHeight;
-                elTop = $el.position().top;
-                elBottom = elTop + $el.outerHeight(true);
-                menuScrollTop = this.$menu.scrollTop();
-                menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
-                if (elTop < 0) {
-                    this.$menu.scrollTop(menuScrollTop + elTop);
-                } else if (menuHeight < elBottom) {
-                    this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
-                }
-            },
-            close: function close() {
-                if (this.isOpen) {
-                    this.isOpen = false;
-                    this._removeCursor();
-                    this._hide();
-                    this.trigger("closed");
-                }
-            },
-            open: function open() {
-                if (!this.isOpen) {
-                    this.isOpen = true;
-                    !this.isEmpty && this._show();
-                    this.trigger("opened");
-                }
-            },
-            setLanguageDirection: function setLanguageDirection(dir) {
-                this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
-            },
-            moveCursorUp: function moveCursorUp() {
-                this._moveCursor(-1);
-            },
-            moveCursorDown: function moveCursorDown() {
-                this._moveCursor(+1);
-            },
-            getDatumForSuggestion: function getDatumForSuggestion($el) {
-                var datum = null;
-                if ($el.length) {
-                    datum = {
-                        raw: Dataset.extractDatum($el),
-                        value: Dataset.extractValue($el),
-                        datasetName: Dataset.extractDatasetName($el)
-                    };
-                }
-                return datum;
-            },
-            getDatumForCursor: function getDatumForCursor() {
-                return this.getDatumForSuggestion(this._getCursor().first());
-            },
-            getDatumForTopSuggestion: function getDatumForTopSuggestion() {
-                return this.getDatumForSuggestion(this._getSuggestions().first());
-            },
-            update: function update(query) {
-                _.each(this.datasets, updateDataset);
-                function updateDataset(dataset) {
-                    dataset.update(query);
-                }
-            },
-            empty: function empty() {
-                _.each(this.datasets, clearDataset);
-                this.isEmpty = true;
-                function clearDataset(dataset) {
-                    dataset.clear();
-                }
-            },
-            isVisible: function isVisible() {
-                return this.isOpen && !this.isEmpty;
-            },
-            destroy: function destroy() {
-                this.$menu.off(".tt");
-                this.$menu = null;
-                _.each(this.datasets, destroyDataset);
-                function destroyDataset(dataset) {
-                    dataset.destroy();
-                }
-            }
-        });
-        return Dropdown;
-        function initializeDataset(oDataset) {
-            return new Dataset(oDataset);
-        }
-    }();
-    var Typeahead = function() {
-        "use strict";
-        var attrsKey = "ttAttrs";
-        function Typeahead(o) {
-            var $menu, $input, $hint;
-            o = o || {};
-            if (!o.input) {
-                $.error("missing input");
-            }
-            this.isActivated = false;
-            this.autoselect = !!o.autoselect;
-            this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
-            this.$node = buildDom(o.input, o.withHint);
-            $menu = this.$node.find(".tt-dropdown-menu");
-            $input = this.$node.find(".tt-input");
-            $hint = this.$node.find(".tt-hint");
-            $input.on("blur.tt", function($e) {
-                var active, isActive, hasActive;
-                active = document.activeElement;
-                isActive = $menu.is(active);
-                hasActive = $menu.has(active).length > 0;
-                if (_.isMsie() && (isActive || hasActive)) {
-                    $e.preventDefault();
-                    $e.stopImmediatePropagation();
-                    _.defer(function() {
-                        $input.focus();
-                    });
-                }
-            });
-            $menu.on("mousedown.tt", function($e) {
-                $e.preventDefault();
-            });
-            this.eventBus = o.eventBus || new EventBus({
-                el: $input
-            });
-            this.dropdown = new Dropdown({
-                menu: $menu,
-                datasets: o.datasets
-            }).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
-            this.input = new Input({
-                input: $input,
-                hint: $hint
-            }).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
-            this._setLanguageDirection();
-        }
-        _.mixin(Typeahead.prototype, {
-            _onSuggestionClicked: function onSuggestionClicked(type, $el) {
-                var datum;
-                if (datum = this.dropdown.getDatumForSuggestion($el)) {
-                    this._select(datum);
-                }
-            },
-            _onCursorMoved: function onCursorMoved() {
-                var datum = this.dropdown.getDatumForCursor();
-                this.input.setInputValue(datum.value, true);
-                this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
-            },
-            _onCursorRemoved: function onCursorRemoved() {
-                this.input.resetInputValue();
-                this._updateHint();
-            },
-            _onDatasetRendered: function onDatasetRendered() {
-                this._updateHint();
-            },
-            _onOpened: function onOpened() {
-                this._updateHint();
-                this.eventBus.trigger("opened");
-            },
-            _onClosed: function onClosed() {
-                this.input.clearHint();
-                this.eventBus.trigger("closed");
-            },
-            _onFocused: function onFocused() {
-                this.isActivated = true;
-                this.dropdown.open();
-            },
-            _onBlurred: function onBlurred() {
-                this.isActivated = false;
-                this.dropdown.empty();
-                this.dropdown.close();
-            },
-            _onEnterKeyed: function onEnterKeyed(type, $e) {
-                var cursorDatum, topSuggestionDatum;
-                cursorDatum = this.dropdown.getDatumForCursor();
-                topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
-                if (cursorDatum) {
-                    this._select(cursorDatum);
-                    $e.preventDefault();
-                } else if (this.autoselect && topSuggestionDatum) {
-                    this._select(topSuggestionDatum);
-                    $e.preventDefault();
-                }
-            },
-            _onTabKeyed: function onTabKeyed(type, $e) {
-                var datum;
-                if (datum = this.dropdown.getDatumForCursor()) {
-                    this._select(datum);
-                    $e.preventDefault();
-                } else {
-                    this._autocomplete(true);
-                }
-            },
-            _onEscKeyed: function onEscKeyed() {
-                this.dropdown.close();
-                this.input.resetInputValue();
-            },
-            _onUpKeyed: function onUpKeyed() {
-                var query = this.input.getQuery();
-                this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
-                this.dropdown.open();
-            },
-            _onDownKeyed: function onDownKeyed() {
-                var query = this.input.getQuery();
-                this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
-                this.dropdown.open();
-            },
-            _onLeftKeyed: function onLeftKeyed() {
-                this.dir === "rtl" && this._autocomplete();
-            },
-            _onRightKeyed: function onRightKeyed() {
-                this.dir === "ltr" && this._autocomplete();
-            },
-            _onQueryChanged: function onQueryChanged(e, query) {
-                this.input.clearHintIfInvalid();
-                query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
-                this.dropdown.open();
-                this._setLanguageDirection();
-            },
-            _onWhitespaceChanged: function onWhitespaceChanged() {
-                this._updateHint();
-                this.dropdown.open();
-            },
-            _setLanguageDirection: function setLanguageDirection() {
-                var dir;
-                if (this.dir !== (dir = this.input.getLanguageDirection())) {
-                    this.dir = dir;
-                    this.$node.css("direction", dir);
-                    this.dropdown.setLanguageDirection(dir);
-                }
-            },
-            _updateHint: function updateHint() {
-                var datum, val, query, escapedQuery, frontMatchRegEx, match;
-                datum = this.dropdown.getDatumForTopSuggestion();
-                if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
-                    val = this.input.getInputValue();
-                    query = Input.normalizeQuery(val);
-                    escapedQuery = _.escapeRegExChars(query);
-                    frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
-                    match = frontMatchRegEx.exec(datum.value);
-                    match ? this.input.setHint(val + match[1]) : this.input.clearHint();
-                } else {
-                    this.input.clearHint();
-                }
-            },
-            _autocomplete: function autocomplete(laxCursor) {
-                var hint, query, isCursorAtEnd, datum;
-                hint = this.input.getHint();
-                query = this.input.getQuery();
-                isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
-                if (hint && query !== hint && isCursorAtEnd) {
-                    datum = this.dropdown.getDatumForTopSuggestion();
-                    datum && this.input.setInputValue(datum.value);
-                    this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
-                }
-            },
-            _select: function select(datum) {
-                this.input.setQuery(datum.value);
-                this.input.setInputValue(datum.value, true);
-                this._setLanguageDirection();
-                this.eventBus.trigger("selected", datum.raw, datum.datasetName);
-                this.dropdown.close();
-                _.defer(_.bind(this.dropdown.empty, this.dropdown));
-            },
-            open: function open() {
-                this.dropdown.open();
-            },
-            close: function close() {
-                this.dropdown.close();
-            },
-            setVal: function setVal(val) {
-                val = _.toStr(val);
-                if (this.isActivated) {
-                    this.input.setInputValue(val);
-                } else {
-                    this.input.setQuery(val);
-                    this.input.setInputValue(val, true);
-                }
-                this._setLanguageDirection();
-            },
-            getVal: function getVal() {
-                return this.input.getQuery();
-            },
-            destroy: function destroy() {
-                this.input.destroy();
-                this.dropdown.destroy();
-                destroyDomStructure(this.$node);
-                this.$node = null;
-            }
-        });
-        return Typeahead;
-        function buildDom(input, withHint) {
-            var $input, $wrapper, $dropdown, $hint;
-            $input = $(input);
-            $wrapper = $(html.wrapper).css(css.wrapper);
-            $dropdown = $(html.dropdown).css(css.dropdown);
-            $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
-            $hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
-                autocomplete: "off",
-                spellcheck: "false",
-                tabindex: -1
-            });
-            $input.data(attrsKey, {
-                dir: $input.attr("dir"),
-                autocomplete: $input.attr("autocomplete"),
-                spellcheck: $input.attr("spellcheck"),
-                style: $input.attr("style")
-            });
-            $input.addClass("tt-input").attr({
-                autocomplete: "off",
-                spellcheck: false
-            }).css(withHint ? css.input : css.inputWithNoHint);
-            try {
-                !$input.attr("dir") && $input.attr("dir", "auto");
-            } catch (e) {}
-            return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
-        }
-        function getBackgroundStyles($el) {
-            return {
-                backgroundAttachment: $el.css("background-attachment"),
-                backgroundClip: $el.css("background-clip"),
-                backgroundColor: $el.css("background-color"),
-                backgroundImage: $el.css("background-image"),
-                backgroundOrigin: $el.css("background-origin"),
-                backgroundPosition: $el.css("background-position"),
-                backgroundRepeat: $el.css("background-repeat"),
-                backgroundSize: $el.css("background-size")
-            };
-        }
-        function destroyDomStructure($node) {
-            var $input = $node.find(".tt-input");
-            _.each($input.data(attrsKey), function(val, key) {
-                _.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
-            });
-            $input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
-            $node.remove();
-        }
-    }();
-    (function() {
-        "use strict";
-        var old, typeaheadKey, methods;
-        old = $.fn.typeahead;
-        typeaheadKey = "ttTypeahead";
-        methods = {
-            initialize: function initialize(o, datasets) {
-                datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
-                o = o || {};
-                return this.each(attach);
-                function attach() {
-                    var $input = $(this), eventBus, typeahead;
-                    _.each(datasets, function(d) {
-                        d.highlight = !!o.highlight;
-                    });
-                    typeahead = new Typeahead({
-                        input: $input,
-                        eventBus: eventBus = new EventBus({
-                            el: $input
-                        }),
-                        withHint: _.isUndefined(o.hint) ? true : !!o.hint,
-                        minLength: o.minLength,
-                        autoselect: o.autoselect,
-                        datasets: datasets
-                    });
-                    $input.data(typeaheadKey, typeahead);
-                }
-            },
-            open: function open() {
-                return this.each(openTypeahead);
-                function openTypeahead() {
-                    var $input = $(this), typeahead;
-                    if (typeahead = $input.data(typeaheadKey)) {
-                        typeahead.open();
-                    }
-                }
-            },
-            close: function close() {
-                return this.each(closeTypeahead);
-                function closeTypeahead() {
-                    var $input = $(this), typeahead;
-                    if (typeahead = $input.data(typeaheadKey)) {
-                        typeahead.close();
-                    }
-                }
-            },
-            val: function val(newVal) {
-                return !arguments.length ? getVal(this.first()) : this.each(setVal);
-                function setVal() {
-                    var $input = $(this), typeahead;
-                    if (typeahead = $input.data(typeaheadKey)) {
-                        typeahead.setVal(newVal);
-                    }
-                }
-                function getVal($input) {
-                    var typeahead, query;
-                    if (typeahead = $input.data(typeaheadKey)) {
-                        query = typeahead.getVal();
-                    }
-                    return query;
-                }
-            },
-            destroy: function destroy() {
-                return this.each(unattach);
-                function unattach() {
-                    var $input = $(this), typeahead;
-                    if (typeahead = $input.data(typeaheadKey)) {
-                        typeahead.destroy();
-                        $input.removeData(typeaheadKey);
-                    }
-                }
-            }
-        };
-        $.fn.typeahead = function(method) {
-            var tts;
-            if (methods[method] && method !== "initialize") {
-                tts = this.filter(function() {
-                    return !!$(this).data(typeaheadKey);
-                });
-                return methods[method].apply(tts, [].slice.call(arguments, 1));
-            } else {
-                return methods.initialize.apply(this, arguments);
-            }
-        };
-        $.fn.typeahead.noConflict = function noConflict() {
-            $.fn.typeahead = old;
-            return this;
-        };
-    })();
-})(window.jQuery);
diff --git a/static/js/typeahead.bundle.min.js b/static/js/typeahead.bundle.min.js
deleted file mode 100644
--- a/static/js/typeahead.bundle.min.js
+++ /dev/null
@@ -1,7 +0,0 @@
-/*!
- * typeahead.js 0.10.4
- * https://github.com/twitter/typeahead.js
- * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
- */
-
-!function(a){var b=function(){"use strict";return{isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},toStr:function(a){return b.isUndefined(a)||null===a?"":a+""},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,getUniqueId:function(){var a=0;return function(){return a++}}(),templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},noop:function(){}}}(),c="0.10.4",d=function(){"use strict";function a(a){return a=b.toStr(a),a?a.split(/\s+/):[]}function c(a){return a=b.toStr(a),a?a.split(/\W+/):[]}function d(a){return function(){var c=[].slice.call(arguments,0);return function(d){var e=[];return b.each(c,function(c){e=e.concat(a(b.toStr(d[c])))}),e}}}return{nonword:c,whitespace:a,obj:{nonword:d(c),whitespace:d(a)}}}(),e=function(){"use strict";function c(c){this.maxSize=b.isNumber(c)?c:100,this.reset(),this.maxSize<=0&&(this.set=this.get=a.noop)}function d(){this.head=this.tail=null}function e(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(c.prototype,{set:function(a,b){var c,d=this.list.tail;this.size>=this.maxSize&&(this.list.remove(d),delete this.hash[d.key]),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new e(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0},reset:function(){this.size=0,this.hash={},this.list=new d}}),b.mixin(d.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),c}(),f=function(){"use strict";function a(a){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+b.escapeRegExChars(this.prefix))}function c(){return(new Date).getTime()}function d(a){return JSON.stringify(b.isUndefined(a)?null:a)}function e(a){return JSON.parse(a)}var f,g;try{f=window.localStorage,f.setItem("~~~","!"),f.removeItem("~~~")}catch(h){f=null}return g=f&&window.JSON?{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},get:function(a){return this.isExpired(a)&&this.remove(a),e(f.getItem(this._prefix(a)))},set:function(a,e,g){return b.isNumber(g)?f.setItem(this._ttlKey(a),d(c()+g)):f.removeItem(this._ttlKey(a)),f.setItem(this._prefix(a),d(e))},remove:function(a){return f.removeItem(this._ttlKey(a)),f.removeItem(this._prefix(a)),this},clear:function(){var a,b,c=[],d=f.length;for(a=0;d>a;a++)(b=f.key(a)).match(this.keyMatcher)&&c.push(b.replace(this.keyMatcher,""));for(a=c.length;a--;)this.remove(c[a]);return this},isExpired:function(a){var d=e(f.getItem(this._ttlKey(a)));return b.isNumber(d)&&c()>d?!0:!1}}:{get:b.noop,set:b.noop,remove:b.noop,clear:b.noop,isExpired:b.noop},b.mixin(a.prototype,g),a}(),g=function(){"use strict";function c(b){b=b||{},this.cancelled=!1,this.lastUrl=null,this._send=b.transport?d(b.transport):a.ajax,this._get=b.rateLimiter?b.rateLimiter(this._get):this._get,this._cache=b.cache===!1?new e(0):i}function d(c){return function(d,e){function f(a){b.defer(function(){h.resolve(a)})}function g(a){b.defer(function(){h.reject(a)})}var h=a.Deferred();return c(d,e,f,g),h}}var f=0,g={},h=6,i=new e(10);return c.setMaxPendingRequests=function(a){h=a},c.resetCache=function(){i.reset()},b.mixin(c.prototype,{_get:function(a,b,c){function d(b){c&&c(null,b),k._cache.set(a,b)}function e(){c&&c(!0)}function i(){f--,delete g[a],k.onDeckRequestArgs&&(k._get.apply(k,k.onDeckRequestArgs),k.onDeckRequestArgs=null)}var j,k=this;this.cancelled||a!==this.lastUrl||((j=g[a])?j.done(d).fail(e):h>f?(f++,g[a]=this._send(a,b).done(d).fail(e).always(i)):this.onDeckRequestArgs=[].slice.call(arguments,0))},get:function(a,c,d){var e;return b.isFunction(c)&&(d=c,c={}),this.cancelled=!1,this.lastUrl=a,(e=this._cache.get(a))?b.defer(function(){d&&d(null,e)}):this._get(a,c,d),!!e},cancel:function(){this.cancelled=!0}}),c}(),h=function(){"use strict";function c(b){b=b||{},b.datumTokenizer&&b.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.datumTokenizer=b.datumTokenizer,this.queryTokenizer=b.queryTokenizer,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){return{ids:[],children:{}}}function f(a){for(var b={},c=[],d=0,e=a.length;e>d;d++)b[a[d]]||(b[a[d]]=!0,c.push(a[d]));return c}function g(a,b){function c(a,b){return a-b}var d=0,e=0,f=[];a=a.sort(c),b=b.sort(c);for(var g=a.length,h=b.length;g>d&&h>e;)a[d]<b[e]?d++:a[d]>b[e]?e++:(f.push(a[d]),d++,e++);return f}return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;f=c.datums.push(a)-1,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b.children[g]||(b.children[g]=e()),b.ids.push(f)})})},get:function(a){var c,e,h=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length)return!1;for(b=h.trie,c=a.split("");b&&(d=c.shift());)b=b.children[d];return b&&0===c.length?(f=b.ids.slice(0),void(e=e?g(e,f):f)):(e=[],!1)}),e?b.map(f(e),function(a){return h.datums[a]}):[]},reset:function(){this.datums=[],this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){"use strict";function d(a){return a.local||null}function e(d){var e,f;return f={url:null,thumbprint:"",ttl:864e5,filter:null,ajax:{}},(e=d.prefetch||null)&&(e=b.isString(e)?{url:e}:e,e=b.mixin(f,e),e.thumbprint=c+e.thumbprint,e.ajax.type=e.ajax.type||"GET",e.ajax.dataType=e.ajax.dataType||"json",!e.url&&a.error("prefetch requires url to be set")),e}function f(c){function d(a){return function(c){return b.debounce(c,a)}}function e(a){return function(c){return b.throttle(c,a)}}var f,g;return g={url:null,cache:!0,wildcard:"%QUERY",replace:null,rateLimitBy:"debounce",rateLimitWait:300,send:null,filter:null,ajax:{}},(f=c.remote||null)&&(f=b.isString(f)?{url:f}:f,f=b.mixin(g,f),f.rateLimiter=/^throttle$/i.test(f.rateLimitBy)?e(f.rateLimitWait):d(f.rateLimitWait),f.ajax.type=f.ajax.type||"GET",f.ajax.dataType=f.ajax.dataType||"json",delete f.rateLimitBy,delete f.rateLimitWait,!f.url&&a.error("remote requires url to be set")),f}return{local:d,prefetch:e,remote:f}}();!function(c){"use strict";function e(b){b&&(b.local||b.prefetch||b.remote)||a.error("one of local, prefetch, or remote is required"),this.limit=b.limit||5,this.sorter=j(b.sorter),this.dupDetector=b.dupDetector||k,this.local=i.local(b),this.prefetch=i.prefetch(b),this.remote=i.remote(b),this.cacheKey=this.prefetch?this.prefetch.cacheKey||this.prefetch.url:null,this.index=new h({datumTokenizer:b.datumTokenizer,queryTokenizer:b.queryTokenizer}),this.storage=this.cacheKey?new f(this.cacheKey):null}function j(a){function c(b){return b.sort(a)}function d(a){return a}return b.isFunction(a)?c:d}function k(){return!1}var l,m;return l=c.Bloodhound,m={data:"data",protocol:"protocol",thumbprint:"thumbprint"},c.Bloodhound=e,e.noConflict=function(){return c.Bloodhound=l,e},e.tokenizers=d,b.mixin(e.prototype,{_loadPrefetch:function(b){function c(a){f.clear(),f.add(b.filter?b.filter(a):a),f._saveToStorage(f.index.serialize(),b.thumbprint,b.ttl)}var d,e,f=this;return(d=this._readFromStorage(b.thumbprint))?(this.index.bootstrap(d),e=a.Deferred().resolve()):e=a.ajax(b.url,b.ajax).done(c),e},_getFromRemote:function(a,b){function c(a,c){b(a?[]:f.remote.filter?f.remote.filter(c):c)}var d,e,f=this;if(this.transport)return a=a||"",e=encodeURIComponent(a),d=this.remote.replace?this.remote.replace(this.remote.url,a):this.remote.url.replace(this.remote.wildcard,e),this.transport.get(d,this.remote.ajax,c)},_cancelLastRemoteRequest:function(){this.transport&&this.transport.cancel()},_saveToStorage:function(a,b,c){this.storage&&(this.storage.set(m.data,a,c),this.storage.set(m.protocol,location.protocol,c),this.storage.set(m.thumbprint,b,c))},_readFromStorage:function(a){var b,c={};return this.storage&&(c.data=this.storage.get(m.data),c.protocol=this.storage.get(m.protocol),c.thumbprint=this.storage.get(m.thumbprint)),b=c.thumbprint!==a||c.protocol!==location.protocol,c.data&&!b?c.data:null},_initialize:function(){function c(){e.add(b.isFunction(f)?f():f)}var d,e=this,f=this.local;return d=this.prefetch?this._loadPrefetch(this.prefetch):a.Deferred().resolve(),f&&d.done(c),this.transport=this.remote?new g(this.remote):null,this.initPromise=d.promise()},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){this.index.add(a)},get:function(a,c){function d(a){var d=f.slice(0);b.each(a,function(a){var c;return c=b.some(d,function(b){return e.dupDetector(a,b)}),!c&&d.push(a),d.length<e.limit}),c&&c(e.sorter(d))}var e=this,f=[],g=!1;f=this.index.get(a),f=this.sorter(f).slice(0,this.limit),f.length<this.limit?g=this._getFromRemote(a,d):this._cancelLastRemoteRequest(),g||(f.length>0||!this.transport)&&c&&c(f)},clear:function(){this.index.reset()},clearPrefetchCache:function(){this.storage&&this.storage.clear()},clearRemoteCache:function(){this.transport&&g.resetCache()},ttAdapter:function(){return b.bind(this.get,this)}}),e}(this);var j=function(){return{wrapper:'<span class="twitter-typeahead"></span>',dropdown:'<span class="tt-dropdown-menu"></span>',dataset:'<div class="tt-dataset-%CLASS%"></div>',suggestions:'<span class="tt-suggestions"></span>',suggestion:'<div class="tt-suggestion"></div>'}}(),k=function(){"use strict";var a={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none",opacity:"1"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};return b.isMsie()&&b.mixin(a.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),b.isMsie()&&b.isMsie()<=7&&b.mixin(a.input,{marginTop:"-1px"}),a}(),l=function(){"use strict";function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d="typeahead:";return b.mixin(c.prototype,{trigger:function(a){var b=[].slice.call(arguments,1);this.$el.trigger(d+a,b)}}),c}(),m=function(){"use strict";function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0,f=a.length;!d&&f>e;e+=1)d=a[e].apply(b,c)===!1;return!d}return d}function g(){var a;return a=window.setImmediate?function(a){setImmediate(function(){a()})}:function(a){setTimeout(function(){a()},0)}}function h(a,b){return a.bind?a.bind(b):function(){a.apply(b,[].slice.call(arguments,0))}}var i=/\s+/,j=g();return{onSync:c,onAsync:b,off:d,trigger:e}}(),n=function(a){"use strict";function c(a,c,d){for(var e,f=[],g=0,h=a.length;h>g;g++)f.push(b.escapeRegExChars(a[g]));return e=d?"\\b("+f.join("|")+")\\b":"("+f.join("|")+")",c?new RegExp(e):new RegExp(e,"i")}var d={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:!1,caseSensitive:!1};return function(e){function f(b){var c,d,f;return(c=h.exec(b.data))&&(f=a.createElement(e.tagName),e.className&&(f.className=e.className),d=b.splitText(c.index),d.splitText(c[0].length),f.appendChild(d.cloneNode(!0)),b.parentNode.replaceChild(f,d)),!!c}function g(a,b){for(var c,d=3,e=0;e<a.childNodes.length;e++)c=a.childNodes[e],c.nodeType===d?e+=b(c)?1:0:g(c,b)}var h;e=b.mixin({},d,e),e.node&&e.pattern&&(e.pattern=b.isArray(e.pattern)?e.pattern:[e.pattern],h=c(e.pattern,e.caseSensitive,e.wordsOnly),g(e.node,f))}}(window.document),o=function(){"use strict";function c(c){var e,f,h,i,j=this;c=c||{},c.input||a.error("input is missing"),e=b.bind(this._onBlur,this),f=b.bind(this._onFocus,this),h=b.bind(this._onKeydown,this),i=b.bind(this._onInput,this),this.$hint=a(c.hint),this.$input=a(c.input).on("blur.tt",e).on("focus.tt",f).on("keydown.tt",h),0===this.$hint.length&&(this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=b.noop),b.isMsie()?this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function(a){g[a.which||a.keyCode]||b.defer(b.bind(j._onInput,j,a))}):this.$input.on("input.tt",i),this.query=this.$input.val(),this.$overflowHelper=d(this.$input)}function d(b){return a('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function e(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function f(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var g;return g={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return(a||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,m,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.trigger("focused")},_onKeydown:function(a){var b=g[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._checkInputValue()},_managePreventDefault:function(a,b){var c,d,e;switch(a){case"tab":d=this.getHint(),e=this.getInputValue(),c=d&&d!==e&&!f(b);break;case"up":case"down":c=!f(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!f(b);break;default:c=!0}return c},_checkInputValue:function(){var a,b,c;a=this.getInputValue(),b=e(a,this.query),c=b?this.query.length!==a.length:!1,this.query=a,b?c&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query)},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getQuery:function(){return this.query},setQuery:function(a){this.query=a},getInputValue:function(){return this.$input.val()},setInputValue:function(a,b){this.$input.val(a),b?this.clearHint():this._checkInputValue()},resetInputValue:function(){this.setInputValue(this.query,!0)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},getLanguageDirection:function(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$hint=this.$input=this.$overflowHelper=null}}),c}(),p=function(){"use strict";function c(c){c=c||{},c.templates=c.templates||{},c.source||a.error("missing source"),c.name&&!f(c.name)&&a.error("invalid dataset name: "+c.name),this.query=null,this.highlight=!!c.highlight,this.name=c.name||b.getUniqueId(),this.source=c.source,this.displayFn=d(c.display||c.displayKey),this.templates=e(c.templates,this.displayFn),this.$el=a(j.dataset.replace("%CLASS%",this.name))}function d(a){function c(b){return b[a]}return a=a||"value",b.isFunction(a)?a:c}function e(a,c){function d(a){return"<p>"+c(a)+"</p>"}return{empty:a.empty&&b.templatify(a.empty),header:a.header&&b.templatify(a.header),footer:a.footer&&b.templatify(a.footer),suggestion:a.suggestion||d}}function f(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var g="ttDataset",h="ttValue",i="ttDatum";return c.extractDatasetName=function(b){return a(b).data(g)},c.extractValue=function(b){return a(b).data(h)},c.extractDatum=function(b){return a(b).data(i)},b.mixin(c.prototype,m,{_render:function(c,d){function e(){return p.templates.empty({query:c,isEmpty:!0})}function f(){function e(b){var c;return c=a(j.suggestion).append(p.templates.suggestion(b)).data(g,p.name).data(h,p.displayFn(b)).data(i,b),c.children().each(function(){a(this).css(k.suggestionChild)}),c}var f,l;return f=a(j.suggestions).css(k.suggestions),l=b.map(d,e),f.append.apply(f,l),p.highlight&&n({className:"tt-highlight",node:f[0],pattern:c}),f}function l(){return p.templates.header({query:c,isEmpty:!o})}function m(){return p.templates.footer({query:c,isEmpty:!o})}if(this.$el){var o,p=this;this.$el.empty(),o=d&&d.length,!o&&this.templates.empty?this.$el.html(e()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null):o&&this.$el.html(f()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null),this.trigger("rendered")}},getRoot:function(){return this.$el},update:function(a){function b(b){c.canceled||a!==c.query||c._render(a,b)}var c=this;this.query=a,this.canceled=!1,this.source(a,b)},cancel:function(){this.canceled=!0},clear:function(){this.cancel(),this.$el.empty(),this.trigger("rendered")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=null}}),c}(),q=function(){"use strict";function c(c){var e,f,g,h=this;c=c||{},c.menu||a.error("menu is required"),this.isOpen=!1,this.isEmpty=!0,this.datasets=b.map(c.datasets,d),e=b.bind(this._onSuggestionClick,this),f=b.bind(this._onSuggestionMouseEnter,this),g=b.bind(this._onSuggestionMouseLeave,this),this.$menu=a(c.menu).on("click.tt",".tt-suggestion",e).on("mouseenter.tt",".tt-suggestion",f).on("mouseleave.tt",".tt-suggestion",g),b.each(this.datasets,function(a){h.$menu.append(a.getRoot()),a.onSync("rendered",h._onRendered,h)})}function d(a){return new p(a)}return b.mixin(c.prototype,m,{_onSuggestionClick:function(b){this.trigger("suggestionClicked",a(b.currentTarget))},_onSuggestionMouseEnter:function(b){this._removeCursor(),this._setCursor(a(b.currentTarget),!0)},_onSuggestionMouseLeave:function(){this._removeCursor()},_onRendered:function(){function a(a){return a.isEmpty()}this.isEmpty=b.every(this.datasets,a),this.isEmpty?this._hide():this.isOpen&&this._show(),this.trigger("datasetRendered")},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function(){return this.$menu.find(".tt-suggestion")},_getCursor:function(){return this.$menu.find(".tt-cursor").first()},_setCursor:function(a,b){a.first().addClass("tt-cursor"),!b&&this.trigger("cursorMoved")},_removeCursor:function(){this._getCursor().removeClass("tt-cursor")},_moveCursor:function(a){var b,c,d,e;if(this.isOpen){if(c=this._getCursor(),b=this._getSuggestions(),this._removeCursor(),d=b.index(c)+a,d=(d+1)%(b.length+1)-1,-1===d)return void this.trigger("cursorRemoved");-1>d&&(d=b.length-1),this._setCursor(e=b.eq(d)),this._ensureVisible(e)}},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$menu.scrollTop(),e=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10),0>b?this.$menu.scrollTop(d+b):c>e&&this.$menu.scrollTop(d+(c-e))},close:function(){this.isOpen&&(this.isOpen=!1,this._removeCursor(),this._hide(),this.trigger("closed"))},open:function(){this.isOpen||(this.isOpen=!0,!this.isEmpty&&this._show(),this.trigger("opened"))},setLanguageDirection:function(a){this.$menu.css("ltr"===a?k.ltr:k.rtl)},moveCursorUp:function(){this._moveCursor(-1)},moveCursorDown:function(){this._moveCursor(1)},getDatumForSuggestion:function(a){var b=null;return a.length&&(b={raw:p.extractDatum(a),value:p.extractValue(a),datasetName:p.extractDatasetName(a)}),b},getDatumForCursor:function(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function(a){function c(b){b.update(a)}b.each(this.datasets,c)},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.isEmpty=!0},isVisible:function(){return this.isOpen&&!this.isEmpty},destroy:function(){function a(a){a.destroy()}this.$menu.off(".tt"),this.$menu=null,b.each(this.datasets,a)}}),c}(),r=function(){"use strict";function c(c){var e,f,g;c=c||{},c.input||a.error("missing input"),this.isActivated=!1,this.autoselect=!!c.autoselect,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.$node=d(c.input,c.withHint),e=this.$node.find(".tt-dropdown-menu"),f=this.$node.find(".tt-input"),g=this.$node.find(".tt-hint"),f.on("blur.tt",function(a){var c,d,g;c=document.activeElement,d=e.is(c),g=e.has(c).length>0,b.isMsie()&&(d||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){f.focus()}))}),e.on("mousedown.tt",function(a){a.preventDefault()}),this.eventBus=c.eventBus||new l({el:f}),this.dropdown=new q({menu:e,datasets:c.datasets}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this),this.input=new o({input:f,hint:g}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this),this._setLanguageDirection()}function d(b,c){var d,f,h,i;d=a(b),f=a(j.wrapper).css(k.wrapper),h=a(j.dropdown).css(k.dropdown),i=d.clone().css(k.hint).css(e(d)),i.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly",!0).attr({autocomplete:"off",spellcheck:"false",tabindex:-1}),d.data(g,{dir:d.attr("dir"),autocomplete:d.attr("autocomplete"),spellcheck:d.attr("spellcheck"),style:d.attr("style")}),d.addClass("tt-input").attr({autocomplete:"off",spellcheck:!1}).css(c?k.input:k.inputWithNoHint);try{!d.attr("dir")&&d.attr("dir","auto")}catch(l){}return d.wrap(f).parent().prepend(c?i:null).append(h)}function e(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function f(a){var c=a.find(".tt-input");b.each(c.data(g),function(a,d){b.isUndefined(a)?c.removeAttr(d):c.attr(d,a)}),c.detach().removeData(g).removeClass("tt-input").insertAfter(a),a.remove()}var g="ttAttrs";return b.mixin(c.prototype,{_onSuggestionClicked:function(a,b){var c;(c=this.dropdown.getDatumForSuggestion(b))&&this._select(c)},_onCursorMoved:function(){var a=this.dropdown.getDatumForCursor();this.input.setInputValue(a.value,!0),this.eventBus.trigger("cursorchanged",a.raw,a.datasetName)},_onCursorRemoved:function(){this.input.resetInputValue(),this._updateHint()},_onDatasetRendered:function(){this._updateHint()},_onOpened:function(){this._updateHint(),this.eventBus.trigger("opened")},_onClosed:function(){this.input.clearHint(),this.eventBus.trigger("closed")},_onFocused:function(){this.isActivated=!0,this.dropdown.open()},_onBlurred:function(){this.isActivated=!1,this.dropdown.empty(),this.dropdown.close()},_onEnterKeyed:function(a,b){var c,d;c=this.dropdown.getDatumForCursor(),d=this.dropdown.getDatumForTopSuggestion(),c?(this._select(c),b.preventDefault()):this.autoselect&&d&&(this._select(d),b.preventDefault())},_onTabKeyed:function(a,b){var c;(c=this.dropdown.getDatumForCursor())?(this._select(c),b.preventDefault()):this._autocomplete(!0)},_onEscKeyed:function(){this.dropdown.close(),this.input.resetInputValue()},_onUpKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorUp(),this.dropdown.open()},_onDownKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorDown(),this.dropdown.open()},_onLeftKeyed:function(){"rtl"===this.dir&&this._autocomplete()},_onRightKeyed:function(){"ltr"===this.dir&&this._autocomplete()},_onQueryChanged:function(a,b){this.input.clearHintIfInvalid(),b.length>=this.minLength?this.dropdown.update(b):this.dropdown.empty(),this.dropdown.open(),this._setLanguageDirection()},_onWhitespaceChanged:function(){this._updateHint(),this.dropdown.open()},_setLanguageDirection:function(){var a;this.dir!==(a=this.input.getLanguageDirection())&&(this.dir=a,this.$node.css("direction",a),this.dropdown.setLanguageDirection(a))},_updateHint:function(){var a,c,d,e,f,g;a=this.dropdown.getDatumForTopSuggestion(),a&&this.dropdown.isVisible()&&!this.input.hasOverflow()?(c=this.input.getInputValue(),d=o.normalizeQuery(c),e=b.escapeRegExChars(d),f=new RegExp("^(?:"+e+")(.+$)","i"),g=f.exec(a.value),g?this.input.setHint(c+g[1]):this.input.clearHint()):this.input.clearHint()},_autocomplete:function(a){var b,c,d,e;b=this.input.getHint(),c=this.input.getQuery(),d=a||this.input.isCursorAtEnd(),b&&c!==b&&d&&(e=this.dropdown.getDatumForTopSuggestion(),e&&this.input.setInputValue(e.value),this.eventBus.trigger("autocompleted",e.raw,e.datasetName))},_select:function(a){this.input.setQuery(a.value),this.input.setInputValue(a.value,!0),this._setLanguageDirection(),this.eventBus.trigger("selected",a.raw,a.datasetName),this.dropdown.close(),b.defer(b.bind(this.dropdown.empty,this.dropdown))},open:function(){this.dropdown.open()},close:function(){this.dropdown.close()},setVal:function(a){a=b.toStr(a),this.isActivated?this.input.setInputValue(a):(this.input.setQuery(a),this.input.setInputValue(a,!0)),this._setLanguageDirection()},getVal:function(){return this.input.getQuery()},destroy:function(){this.input.destroy(),this.dropdown.destroy(),f(this.$node),this.$node=null}}),c}();!function(){"use strict";var c,d,e;c=a.fn.typeahead,d="ttTypeahead",e={initialize:function(c,e){function f(){var f,g,h=a(this);b.each(e,function(a){a.highlight=!!c.highlight}),g=new r({input:h,eventBus:f=new l({el:h}),withHint:b.isUndefined(c.hint)?!0:!!c.hint,minLength:c.minLength,autoselect:c.autoselect,datasets:e}),h.data(d,g)}return e=b.isArray(e)?e:[].slice.call(arguments,1),c=c||{},this.each(f)},open:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.open()}return this.each(b)},close:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.close()}return this.each(b)},val:function(b){function c(){var c,e=a(this);(c=e.data(d))&&c.setVal(b)}function e(a){var b,c;return(b=a.data(d))&&(c=b.getVal()),c}return arguments.length?this.each(c):e(this.first())},destroy:function(){function b(){var b,c=a(this);(b=c.data(d))&&(b.destroy(),c.removeData(d))}return this.each(b)}},a.fn.typeahead=function(b){var c;return e[b]&&"initialize"!==b?(c=this.filter(function(){return!!a(this).data(d)}),e[b].apply(c,[].slice.call(arguments,1))):e.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=c,this}}()}(window.jQuery);
diff --git a/templates/add-form.hamlet b/templates/add-form.hamlet
--- a/templates/add-form.hamlet
+++ b/templates/add-form.hamlet
@@ -1,54 +1,14 @@
-<script>
-
-  jQuery(document).ready(function() {
-
-    // Set up global completers which can be attached to appropriate inputs when needed
-
-    globalThis.descriptionsCompleter = new Bloodhound({
-      local:#{toBloodhoundJson (toList descriptions)},
-      limit:100,
-      datumTokenizer: function(d) { return [d.value]; },
-      queryTokenizer: function(q) { return [q]; }
-    });
-    globalThis.descriptionsCompleter.initialize();
-
-    globalThis.accountsCompleter = new Bloodhound({
-      local:#{toBloodhoundJson (journalAccountNamesDeclaredOrImplied j)},
-      limit:100,
-      datumTokenizer: function(d) { return [d.value]; },
-      queryTokenizer: function(q) { return [q]; }
-    });
-    globalThis.accountsCompleter.initialize();
-
-    // use template to ensure proper escaping
-    globalThis.suggestionTemplate = function(d) {
-      var p = document.createElement('p');
-      p.textContent = d.value;
-      return p;
-    };
-
-    // Attach the completers to the initial form inputs.
-    jQuery('input[name=description]').typeahead({ highlight: true }, { source: globalThis.descriptionsCompleter.ttAdapter(), templates: { suggestion: globalThis.suggestionTemplate } });
-    jQuery('input[name=account]'    ).typeahead({ highlight: true }, { source: globalThis.accountsCompleter.ttAdapter(), templates: { suggestion: globalThis.suggestionTemplate } });
-  });
-
-  const utf8textdecoder = new TextDecoder();
-  function decodeBase64EncodedText(b64) {
-      const unb64 = window.atob(b64);
-      const arr = new Uint8Array(unb64.length);
-      for (let i = 0; i < arr.length; i++) {
-          arr[i] = unb64.charCodeAt(i);
-      }
-      return utf8textdecoder.decode(arr);
-  }
-
 ^{extra}
 
 <div .row>
   <div .col-md-3.col-sm-5.col-xs-6 :isJust (fvErrors dateView):.has-error>
+    $# The date field stays a text input so that hledger's smart dates
+    $# ("today", "2/15") still work. The button opens the browser's own date
+    $# picker, via the hidden date input next to it.
     <div #dateWrap .form-group.input-group.date>
       ^{fvInput dateView}
-      <div .input-group-addon>
+      <input #datepicked type=date tabindex=-1 aria-hidden=true>
+      <div #datebutton .input-group-addon title=_{HMsg "Pick a date"}>
         <span .glyphicon .glyphicon-th>
     $maybe err <- fvErrors dateView
       <span .help-block .error-block>#{err}
@@ -58,28 +18,39 @@
     $maybe err <- fvErrors descView
       <span .help-block .error-block>#{err}
 
-<div .account-postings>
+$# The placeholder templates are also read by hledger.js when it adds rows.
+<div .account-postings data-account-placeholder=#{accountPlaceholder} data-amount-placeholder=#{amountPlaceholder}>
   $forall (n, (acc, amt, accE, amtE)) <- displayRows
-    <div .form-group .row .account-group style="padding-left:1em;">
+    <div .form-group .row .account-group>
       <div .col-sm-9.col-xs-9 :isJust accE:.has-error>
-        <input .account-input.form-control.input-lg.typeahead type=text
-          name=account placeholder="Account #{n}" value="#{acc}">
+        <input .account-input.form-control.input-lg type=text list=accountnames
+          name=account placeholder=#{numbered accountPlaceholder n} value="#{acc}">
         $maybe err <- accE
           <span .help-block .error-block>_{err}
       <div .col-sm-3.col-xs-3 :isJust amtE:.has-error>
         <input .amount-input.form-control.input-lg type=text
-          name=amount placeholder="Amount #{n}" value="#{amt}">
+          name=amount placeholder=#{numbered amountPlaceholder n} value="#{amt}">
         $maybe err <- amtE
           <span .help-block .error-block>_{err}
 
 <div .row>
   <div .col-sm-9.col-xs-9>
     $if length files > 1
-      Add to:
+      _{HMsg "Add to:"}
       &nbsp;
-      <div style="display:inline-block; width:auto;" .form-group :isJust (fvErrors fileView):.has-error>
+      <div .form-group .file-select :isJust (fvErrors fileView):.has-error>
         ^{fvInput fileView}
         $maybe err <- fvErrors fileView
           <span .help-block .error-block>#{err}
-  <div .col-sm-3.col-xs-3 style="text-align:right;">
-    <button type=submit .btn .btn-default .btn-lg name=submit style="font-weight:bold;">Save
+  <div .col-sm-3.col-xs-3.text-right>
+    <button type=submit .btn .btn-default .btn-lg name=submit>_{HMsg "Save"}
+
+$# Completion data for the account and description fields. The browser filters
+$# these itself, so there is no javascript and no library involved, and hamlet's
+$# escaping keeps journal text inert.
+<datalist #accountnames>
+  $forall acct <- journalAccountNamesDeclaredOrImplied j
+    <option value=#{acct}>
+<datalist #descriptionnames>
+  $forall desc <- toList descriptions
+    <option value=#{desc}>
diff --git a/templates/balance-report.hamlet b/templates/balance-report.hamlet
--- a/templates/balance-report.hamlet
+++ b/templates/balance-report.hamlet
@@ -1,25 +1,55 @@
-<tr :here == journalR:.inacct>
-  <td .top .acct>
-    <a href=@{journalR} :here == journalR:.inacct
-       title="Show general journal entries, most recent first">
-      Journal
-  <td .top>
+$# A page's label spans both columns: it may be longer than an account name,
+$# and nothing goes beside it.
+$forall (route, label, title) <- reports
+  <tr :here == route:.inacct>
+    <td .top .acct colspan=2>
+      <a href=@?{(route, reportParams)} :here == route:.inacct title=#{tr trs title}>
+        #{tr trs label}
+$# The - and + buttons that fold or open a level of the accounts
+$# (default-layout.hamlet's script) at the left, over the account names,
+$# and the balances' date at the right, over the amounts, when given.
+$# The date is a button that hides or shows the balances (hledger.js,
+$# remembered in the showbalances cookie); while they are hidden it
+$# reads just "Balances". When the balances were not served (the default),
+$# showing them reloads the page (data-reload).
+$if isJust mcaption || stepper
+  <tr .depth-row>
+    <td colspan=2>
+      $if stepper
+        <span .depth-stepper>
+          <button .depth-step type=button data-step=-1 title=#{tr trs "Fold the accounts one level more"}>&#x2212;
+          <button .depth-step type=button data-step=1 title=#{tr trs "Open the accounts one level more"}>+
+      $maybe (caption, captiontitle) <- mcaption
+        <button .balances-toggle type=button :not withBalances:data-reload=1 title=#{tr trs "Show or hide the balances"}>
+          <span .balances-date title=#{captiontitle}>#{caption}
+          <span .balances-word>#{tr trs "Balances"}
 $forall (acct, adisplay, aindent, abal) <- items
-  <tr
+  <tr data-indent=#{aindent} data-acct=#{acct}
      :matchesAcctSelector acct:.inacct
      :hideEmpty && not (isInterestingAccount acct):.hide>
     <td .acct :not (isInterestingAccount acct):.empty>
       <div .ff-wrapper>
         \#{indent aindent}
-        <a.acct-name href="@?{(registerR, [("q", replaceInacct qparam $ accountQuery acct)])}"
-           title="Show transactions affecting this account and subaccounts">
+        <a.acct-name href="@?{acctlink acct}"
+           title=#{tr trs "Show transactions affecting this account and subaccounts"}>
           #{adisplay}
         $if hasSubAccounts acct
-          <a href="@?{(registerR, [("q", replaceInacct qparam $ accountOnlyQuery acct)])}" .only.hidden-sm.hidden-xs
-             title="Show transactions affecting this account but not subaccounts">only
+          <a href="@?{acctonlylink acct}" .only.hidden-sm.hidden-xs
+             title=#{tr trs "Show transactions affecting this account but not subaccounts"}>#{tr trs "only"}
+    $if withBalances
+      <td .amount>
+        $if mixedAmountLooksZero abal
+          ^{mixedAmountAsHtmlElided trs abal}
+        $else
+          <a href="@?{amountlink acct}"
+             title=#{tr trs "Show the transactions behind this balance"}>
+            ^{mixedAmountAsHtmlElided trs abal}
+$if withBalances
+  <tr .total>
+    <td .total-label title=#{tottitle}>#{totlabel}
     <td .amount>
-      ^{mixedAmountAsHtml abal}
-<tr .total>
-  <td>
-  <td .amount>
-    ^{mixedAmountAsHtml total}
+      $if mixedAmountLooksZero total
+        ^{mixedAmountAsHtmlElided trs total}
+      $else
+        <a href="@?{totallink}" title=#{tr trs "Show the transactions behind this total"}>
+          ^{mixedAmountAsHtmlElided trs total}
diff --git a/templates/chart.hamlet b/templates/chart.hamlet
--- a/templates/chart.hamlet
+++ b/templates/chart.hamlet
@@ -1,162 +1,25 @@
-$# If $ is the first character in a line, it must be \-escaped to hide it from hamlet.
-<label #register-chart-label style=""><br>
-<div #register-chart style="height:150px; margin-bottom:1em; display:block;">
-<script type=text/javascript>
-  \$(document).ready(function() {
-    var $chartdiv = $('#register-chart');
-    if ($chartdiv.is(':visible')) {
-      \$('#register-chart-label').text('#{charttitle}');
-      var seriesData = [
-      $forall (c,items) <- percommoditytxnreports
-        // we render each commodity using two series:
-        // one with extra data points added to show a stepped balance line
-        {
-        data: [
-          $forall i <- reverse items
-            [
-            #{dayToUtcNoonTimestamp $ triDate i},
-            #{simpleMixedAmountQuantity $ triCommodityBalance c i}
-            ],
-        ],
-        label: '#{shownull $ T.unpack c}',
-        color: #{colorForCommodity c},
-        lines: {
-          show: true,
-          steps: true,
-        },
-        points: {
-          show: false,
-        },
-        clickable: false,
-        hoverable: false,
-        },
-        // and one with the original data, showing one clickable, hoverable point per transaction
-        {
-        data: [
-          $forall i <- reverse items
-            [
-            #{dayToUtcNoonTimestamp $ triDate i},
-            #{simpleMixedAmountQuantity $ triCommodityBalance c i},
-            '#{showZeroCommodity $ triCommodityAmount c i}',
-            '#{showZeroCommodity $ triCommodityBalance c i}',
-            '#{concat $ intersperse "\\n" $ lines $ T.unpack $ showTransaction $ triOrigTransaction i}',
-            #{tindex $ triOrigTransaction i}
-            ],
-        ],
-        label: '',
-        color: #{colorForCommodity c},
-        lines: {
-          show: false,
-        },
-        points: {
-          show: true,
-        },
-        },
-      ];
-      var plot = registerChart($chartdiv, seriesData);
-      plot.setSelection({ xaxis: { from: 500, to: 700 } });  // ?
-      \$chartdiv.bind("plotclick",    registerChartClick);
-      \$chartdiv.bind("plotselected", registerChartSelect);
-    };
-  });
-
-  //eslint-disable-next-line no-unused-vars
-  function registerChart($container, series) {
-    // https://github.com/flot/flot/blob/master/API.md
-    return $container.plot(
-      series,
-      {
-        xaxis: {
-          mode: "time",
-          timeformat: "%Y/%m/%d",
-        },
-        selection: {
-          mode: "x"
-        },
-        legend: {
-          position: 'sw'
-        },
-        grid: {
-          markings: function () {
-            var now = Date.now();
-            return [
-              {
-                xaxis: { to: now }, // past
-                yaxis: { to: 0 },   // <0
-                color: '#ffdddd',
-              },
-              {
-                xaxis: { from: now }, // future
-                yaxis: { from: 0 },   // >0
-                color: '#e0e0e0',
-              },
-              {
-                xaxis: { from: now }, // future
-                yaxis: { to: 0 },     // <0
-                color: '#e8c8c8',
-              },
-              {
-                yaxis: { from: 0, to: 0 }, // =0
-                color: '#bb0000',
-                lineWidth:1
-              },
-            ];
-          },
-          hoverable: true,
-          autoHighlight: true,
-          clickable: true,
-        },
-        // https://github.com/krzysu/flot.tooltip
-        tooltip: true,
-        tooltipOpts: {
-          xDateFormat: "%Y/%m/%d",
-          content:
-            function(label, x, y, flotitem) {
-              var data = flotitem.series.data[flotitem.dataIndex];
-              return data[3]+" balance on %x after "+data[2]+" posted by transaction:<pre>"+data[4]+"</pre>";
-            },
-          onHover: function(flotitem, $tooltipel) {
-            \$tooltipel.css('border-color',flotitem.series.color);
-          },
-        },
-      }
-    ).data("plot");
-  }
-
-  // Handle a click event on the chart.
-  function registerChartClick(ev, pos, item) {
-    if (!item) { return; }
-    var targetselector = '#' + item.series.data[item.dataIndex][5];
-    var $target = $(targetselector);
-    if ($target.length) {
-      window.location.hash = targetselector;
-      \$('html, body').animate({
-        scrollTop: $target.offset().top
-      }, 1000);
-    }
-  }
-
-  // Handle a selection (zoom) event on the chart.
-  function registerChartSelect(ev, ranges) {
-    console.log("selected", ranges.xaxis.from, ranges.xaxis.to);
-
-    // Reconstruct from/to dates carefully based on the selected x-values.
-    // Those x values are unix timestamps (milliseconds since epoch) enclosing the data points' timestamps.
-    // Those are generated by dayToJsTimestamp, and are UTC times representing the transaction dates.
-    var from = new Date(ranges.xaxis.from);
-    var fromy = from.getUTCFullYear();
-    var fromm = from.getUTCMonth() + 1;
-    var fromd = from.getUTCDate();
-    var to = new Date(ranges.xaxis.to + 1 * 24 * 60 * 60 * 1000);
-    var toy = to.getUTCFullYear();
-    var tom = to.getUTCMonth() + 1;
-    var tod = to.getUTCDate();
-
-    var range = fromy + "/" + fromm + "/" + fromd + "-" + toy + "/" + tom + "/" + tod;
-    var baselink = "@?{nodatelink}";
-    if (baselink.endsWith("?q")) {
-      document.location = baselink + "=date:" + range;
-    } else {
-      document.location = baselink + "%20date:" + range;
-    }
-  }
+$# The chart is SVG, drawn by the server as wide as the page's main column
+$# (with the sidebar shown and hidden; see Widget.Chart.chartAtWidths),
+$# and styled by /chart.css. With several commodities, a legend chooses the
+$# one charted: its entries are the labels of radio buttons, each followed
+$# by its commodity's chart, which the css shows while it is chosen, with no
+$# javascript. hledger.js lets you drag across a plot to see the
+$# transactions on those dates, for which it reads each plot's date scale,
+$# and data-baselink, the register's url without its date terms. Keeping
+$# data and code out of the page is what lets script-src be strict (#2703).
+$# The Chart and Data buttons showing or hiding it and the table are
+$# Widget.Chart's chartToggle and dataToggle.
+$if not (null charts)
+  #{chartToggle trs}
+  $if length charts == 1
+    <div .register-chart .report-chart data-baselink=@?{nodatelink}>
+      $forall (k, c) <- indexed
+        #{svg k c}
+      $if leftout > 0
+        <p .chart-note>#{moreCommodities trs leftout}
+  $else
+    <div .register-chart .report-chart .with-legend data-baselink=@?{nodatelink}>
+      #{chartLegend "register-chart" balancelabel legend}
+      $if leftout > 0
+        <p .chart-note>#{moreCommodities trs leftout}
+  #{dataToggle trs}
diff --git a/templates/default-layout-wrapper.hamlet b/templates/default-layout-wrapper.hamlet
--- a/templates/default-layout-wrapper.hamlet
+++ b/templates/default-layout-wrapper.hamlet
@@ -1,10 +1,6 @@
 $newline never
 \<!doctype html>
-\<!--[if lt IE 7]> <html class="no-js ie6 oldie" lang="en"> <![endif]-->
-\<!--[if IE 7]>    <html class="no-js ie7 oldie" lang="en"> <![endif]-->
-\<!--[if IE 8]>    <html class="no-js ie8 oldie" lang="en"> <![endif]-->
-\<!--[if gt IE 8]><!-->
-<html class="no-js" lang="en"> <!--<![endif]-->
+<html class="no-js" lang=#{lang}>
     <head>
         <meta charset="UTF-8">
 
@@ -16,34 +12,19 @@
 
         ^{pageHead pc}
 
-        \<!--[if lt IE 9]>
-        \<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
-        \<![endif]-->
-
-        <script>
+        <script nonce=#{nonce}>
           document.documentElement.className = document.documentElement.className.replace(/\bno-js\b/,'js');
-          document.hledgerWebBaseurl = '#{base_url_ opts}'; // save for binding keys later
+          document.hledgerWebBaseurl = '#{base_url_ opts}'; /* save for binding keys later */
+          document.hledgerWebCookieSuffix = '#{uiCookieSuffix opts}'; /* see App.uiCookie */
 
-    <body>
+    <body :browsemode:data-browse-mode>
+        $# Full window mode (the f key, hledger.js) is remembered in this
+        $# tab's session storage, which is separate for each hledger-web
+        $# (scheme, host and port), and restored here, before anything paints.
+        <script nonce=#{nonce}>
+          try { if (sessionStorage.getItem('fullwindow') === '1') { document.body.classList.add('fullwindow'); } } catch (e) {}
         <div .container-fluid>
             <div .row .row-offcanvas .row-offcanvas-left>
               ^{pageBody pc}
             <footer>
               #{extraCopyright $ appExtra $ settings master}
-
-        $maybe analytics <- extraAnalytics $ appExtra $ settings master
-            <script>
-              if(!window.location.href.match(/localhost/)){
-                window._gaq = [['_setAccount','#{analytics}'],['_trackPageview'],['_trackPageLoadTime']];
-                (function() {
-                \  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
-                \  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
-                \  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
-                })();
-              }
-        \<!-- Prompt IE 6 users to install Chrome Frame. Remove this if you want to support IE 6.  chromium.org/developers/how-tos/chrome-frame-getting-started -->
-        \<!--[if lt IE 7 ]>
-            <script src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js">
-            <script>
-                window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})
-        \<![endif]-->
diff --git a/templates/default-layout.hamlet b/templates/default-layout.hamlet
--- a/templates/default-layout.hamlet
+++ b/templates/default-layout.hamlet
@@ -1,86 +1,380 @@
 
-<div#spacer .col-xs-2.#{topShowsm}.#{topShowmd}>
+$# The sidebar's button, like the s key, shows or hides the sidebar
+$# (hledger.js), or on a narrow screen slides it in or out. It stays at the
+$# top left either way: with the sidebar hidden, the spacer shrinks to fit it.
+<div#spacer .col-xs-2.#{topShow}>
   <h1>
-    <button .visible-xs.btn.btn-default type="button" data-toggle="offcanvas">
-      <span .glyphicon.glyphicon-align-left.tgl-icon>
+    $if elem ViewPermission perms
+      <button #sidebar-toggle .btn.btn-default.hidden-print type=button aria-controls=sidebar-menu aria-expanded=#{sidebarExpanded} aria-keyshortcuts=s title=_{HMsg "Show or hide the sidebar (s)"}>
+        <svg .sidebar-icon viewBox="0 0 16 16" width=18 height=18 aria-hidden=true>
+          <rect .sidebar-icon-pane x=2 y=3 width=4 height=10>
+          <rect x=1.5 y=2.5 width=13 height=11 rx=1.5 fill=none stroke=currentColor>
+          <line x1=6.5 y1=2.5 x2=6.5 y2=13.5 stroke=currentColor>
 
 <div#topbar .col-md-8 .col-sm-8 .col-xs-10>
   <h1>#{takeFileName (journalFilePath j)}
 
 $if elem ViewPermission perms
-  <div#sidebar-menu .sidebar-offcanvas.#{sideShowmd}.#{sideShowsm}>
+  <div#sidebar-menu .sidebar-offcanvas.#{sideShowmd}.#{sideShowsm} :balancesHidden:.balances-hidden>
     <table .main-menu .table>
       ^{accounts}
+  $# Fold the sidebar's account tree as soon as its markup is parsed, ie
+  $# right here, inline (hledger.js loads at the end of the body), for the
+  $# same reason as the scroll restore below: folding at DOMContentLoaded
+  $# paints the tree in full first and then collapses it, a visible jump.
+  $# Folding first also gives the scroll restore the folded height.
+  $# The rows, which carry their indent and account name, get fold carets.
+  $# The tree is folded to a depth of its own, independent of the page's:
+  $# 1 at first, stepped by the - and + buttons above it, which open the
+  $# accounts above that depth (counting account name levels) and fold
+  $# the rest. The groups opened or closed by hand are remembered over
+  $# that ({folded, opened} account names), until a step resets them. The
+  $# depth and the choices are remembered in this browser, so the sidebar
+  $# stays as you left it from page to page. A caret clicked back to the
+  $# depth's fold is forgotten. At the shallowest or deepest depth, - or +
+  $# still folds or opens to that depth any groups opened or closed by hand.
+  <script nonce=#{nonce}>
+    (function () {
+      var menu = document.getElementById('sidebar-menu');
+      var rows = [];
+      menu.querySelectorAll('tr[data-indent]').forEach(function (tr) {
+        rows.push({tr: tr, indent: +tr.getAttribute('data-indent'),
+                   acct: tr.getAttribute('data-acct'), expanded: true, parent: false});
+      });
+      if (!rows.length) { return; }
+      function level(r) { return r.acct.split(':').length; }
+      var deepest = Math.max.apply(null, rows.map(level));
+      var depth = 1, choice = {};
+      try {
+        depth = parseInt(localStorage.getItem('sidebarDepth'), 10) || 1;
+        var saved = JSON.parse(localStorage.getItem('sidebarFolds') || '{}');
+        (saved.folded || []).forEach(function (a) { choice[a] = false; });
+        (saved.opened || []).forEach(function (a) { choice[a] = true; });
+      } catch (e) {}
+      depth = Math.max(1, Math.min(depth, deepest));
+      function baseline(r) { return level(r) < depth; }
+      function apply() {
+        var stack = [];
+        rows.forEach(function (r) {
+          while (stack.length > r.indent) { stack.pop(); }
+          r.tr.classList.toggle('tree-fold-hide', !stack.every(function (open) { return open; }));
+          r.caret.textContent = r.parent ? (r.expanded ? '▾' : '▸') : '';
+          stack.push(r.expanded);
+        });
+      }
+      function saveChoices() {
+        try {
+          var folded = [], opened = [];
+          Object.keys(choice).forEach(function (a) { (choice[a] ? opened : folded).push(a); });
+          localStorage.setItem('sidebarFolds', JSON.stringify({folded: folded, opened: opened}));
+        } catch (e) {}
+      }
+      function save(r) {
+        if (r.expanded === baseline(r)) { delete choice[r.acct]; }
+        else { choice[r.acct] = r.expanded; }
+        saveChoices();
+      }
+      rows.forEach(function (r, i) {
+        r.parent = i + 1 < rows.length && rows[i + 1].indent > r.indent;
+        r.expanded = (r.parent && choice[r.acct] !== undefined) ? choice[r.acct] : baseline(r);
+        r.caret = document.createElement('span');
+        r.caret.className = 'tree-caret';
+        var name = r.tr.querySelector('.ff-wrapper a.acct-name');
+        if (name) { name.parentNode.insertBefore(r.caret, name); }
+        if (r.parent) {
+          r.caret.addEventListener('click', function () { r.expanded = !r.expanded; apply(); save(r); stepsUpdate(); });
+        }
+      });
+      // A step folds or opens the whole tree to the new depth, forgetting
+      // the carets' choices. At either end, it applies the depth it is at,
+      // while some group here was opened or closed by hand; otherwise there
+      // it does nothing. With only one level here, there is nothing to step.
+      var steps = menu.querySelectorAll('.depth-step');
+      function stepTo(b) {
+        return Math.max(1, Math.min(deepest, depth + parseInt(b.getAttribute('data-step'), 10)));
+      }
+      function changedByHand() {
+        return rows.some(function (r) { return r.parent && r.expanded !== baseline(r); });
+      }
+      function stepsUpdate() {
+        var changed = changedByHand();
+        steps.forEach(function (b) { b.disabled = stepTo(b) === depth && !changed; });
+      }
+      // Set the tree to a depth (within 1 and the deepest), as - and + do;
+      // also the shift-digit keys' action (hledger.js), so kept on the sidebar.
+      function depthTo(n) {
+        n = Math.max(1, Math.min(deepest, n));
+        if (n === depth && !changedByHand()) { return; }
+        depth = n;
+        choice = {};
+        rows.forEach(function (r) { r.expanded = baseline(r); });
+        apply();
+        saveChoices();
+        try { localStorage.setItem('sidebarDepth', depth); } catch (e) {}
+        stepsUpdate();
+      }
+      menu.hledgerDepthTo = depthTo;
+      steps.forEach(function (b) {
+        b.addEventListener('click', function () { depthTo(stepTo(b)); });
+      });
+      var stepper = menu.querySelector('.depth-stepper');
+      if (stepper && deepest < 2) { stepper.hidden = true; }
+      stepsUpdate();
+      apply();
+    })();
+  $# Restore the sidebar's scroll position (saved per-tab in sessionStorage)
+  $# as soon as its markup is parsed, ie right here, inline. Waiting for eg
+  $# DOMContentLoaded would be too late: on pages with a long journal/register
+  $# the browser paints the sidebar (at scroll position 0) well before the
+  $# rest of the document is parsed, and restoring then makes the sidebar
+  $# visibly jump. sessionStorage can throw (not just be absent) when storage
+  $# is blocked, eg in a sandboxed iframe, with cookies disabled, or in some
+  $# private-browsing modes; the try makes this convenience a no-op there.
+  <script nonce=#{nonce}>
+    (function () {
+      var sidebar = document.getElementById('sidebar-menu');
+      var key = 'hledgerSidebarScrollTop';
+      var ignoreNextScrollSave = false;
+      try {
+        var saved = parseInt(sessionStorage.getItem(key), 10);
+        if (!isNaN(saved)) {
+          sidebar.scrollTop = saved;
+          // Restoring fires a scroll event, but only if the position actually
+          // changed; on a page whose account list is shorter the value clamps,
+          // so skip saving that one event to avoid shrinking the remembered
+          // offset for later pages.
+          ignoreNextScrollSave = sidebar.scrollTop !== 0;
+        }
+      } catch (e) {}
+      sidebar.addEventListener('scroll', function () {
+        if (ignoreNextScrollSave) { ignoreNextScrollSave = false; return; }
+        try { sessionStorage.setItem(key, sidebar.scrollTop); } catch (e) {}
+      });
+    })();
 
-<div#main-content .col-xs-12.#{mainShowmd}.#{mainShowsm}>
+$# Focusable (but not by tab), so that hledger.js can focus it and the
+$# keyboard scrolls it (see focusPage). The c and d keys hide a report's
+$# chart and its table, remembered in the showchart and showtable cookies
+$# (hledger.js), so each page is born the way the last one was left;
+$# likewise the N key shows the charts' total or net lines (shownet).
+<div#main-content .col-xs-12.#{mainShowmd}.#{mainShowsm} :chartHidden:.chart-hidden :tableHidden:.table-hidden :netShown:.net-shown tabindex=-1>
+  $# Shown by hledger.js while the page can't reach the server.
+  $if browsemode
+    <div #server-stopped .alert.alert-warning role=alert hidden>
+      _{HMsg "hledger-web is no longer running. It exits after fifteen minutes with no browser window showing it, or when stopped. To continue, start it again and reload this page."}
   $maybe m <- msg
     <div #message .alert.alert-info>#{m}
+  $# Shown only in full window mode (the f key), for leaving it without the keyboard.
+  <button #fullwindow-exit .btn.btn-default.btn-sm.hidden-print type=button title=_{HMsg "Leave full window"}>
+    <span .glyphicon .glyphicon-resize-small>
   $if elem ViewPermission perms
+    ^{reportsRow}
     <form#searchform.input-group method=GET>
-      <input .form-control name=q value=#{qparam} placeholder="Search"
-        title="Enter hledger search patterns to filter the data below">
+      <input .form-control name=q value=#{qparam} placeholder=_{HMsgc "search box" "Search"}
+        title=_{HMsg "Enter hledger search patterns to filter the data below"}>
+      $forall (name, value) <- keptParams
+        <input type=hidden name=#{name} value=#{value}>
       <div .input-group-btn>
         $if not (T.null qparam)
-          <a href=@{here} .btn .btn-default title="Clear search terms">
+          <a #search-clear href=@?{(here, keptParams)} .btn .btn-default title=_{HMsg "Clear search terms"}>
             <span .glyphicon .glyphicon-remove-circle>
-        <button .btn .btn-default type=submit title="Apply search terms">
+        <button .btn .btn-default type=submit title=_{HMsg "Apply search terms"}>
           <span .glyphicon .glyphicon-search>
         $if elem EditPermission perms
-          <a href="@{ManageR}" .btn.btn-default title="Manage journal files">
+          <a href="@{ManageR}" .btn.btn-default title=_{HMsg "Manage journal files"}>
             <span .glyphicon .glyphicon-wrench>
         <button .btn .btn-default type=button data-toggle="modal" data-target="#helpmodal"
-           title="Show search and general help">
+           title=_{HMsg "Show search and general help"}>
           <span .glyphicon .glyphicon-question-sign>
   ^{widget}
+  $# Reshaping a report keeps the reader's place: clicking a control link
+  $# saves the page's scroll position (hledger.js, controlsInit), restored
+  $# here, inline right after the page content's markup, so it lands
+  $# before paint. The controls and commodity disclosures need no script:
+  $# their state travels in cookies the server reads, so they are born
+  $# already open.
+  <script nonce=#{nonce}>
+    (function () {
+      try {
+        var st = sessionStorage.getItem('pageScrollTop');
+        if (st !== null) {
+          sessionStorage.removeItem('pageScrollTop');
+          document.documentElement.scrollTop = parseInt(st, 10) || 0;
+        }
+      } catch (e) {}
+    })();
 
-<div .modal.fade #helpmodal tabindex="-1" role="dialog" aria-labelledby="helpLabel" aria-hidden="true">
-  <div .modal-dialog .modal-lg>
-    <div .modal-content>
-      <div .modal-header>
-        <button type="button" .close data-dismiss="modal" aria-hidden="true">&times;
-        <span style="float:right; margin-right:4em;">#{progname} #{packageversion}
-        <h3 .modal-title #helpLabel>Help
-      <div .modal-body>
-        <div .row>
-          <div .col-xs-6>
-            <p>
-              <b>Keyboard shortcuts
-              <ul>
-                <li> <code>h</code> or maybe <code>?</code> - view this help (escape or click to exit)
-                <li> <code>j</code> - go to the Journal view (home)
-                <li> <code>a</code> - add a transaction (escape to cancel)
-                <li> <code>s</code> - toggle sidebar
-                <li> <code>f</code> - focus search form ("find")
-                <li> <code>e</code> - hide empty accounts in sidebar
-            <p>
-              <b>General
-              <ul>
-                <li> The Journal view shows general journal entries, representing zero-sum movements of money (or other commodity) between hierarchical accounts
-                <li> The sidebar shows the resulting accounts and their final balances
-                <li> Parent account balances include subaccount balances
-                <li> Multiple currencies in balances are displayed one above the other
-                <li> Click account name links to see transactions affecting that account, with running balance
-                <li> Click date links to see journal entries on that date
-          <div .col-xs-6>
-            <p>
-              <b>Search
-              <ul>
-                <li> Search patterns with spaces should be enclosed in quotes.
-                <li> <code>REGEX</code> - match account names
-                <li> <code>type:TYPE</code> - match account types
-                <li> <code>date:PERIODEXP</code> - match dates
-                <li> <code>status:*</code>, <code>status:!</code>, <code>status:</code> - match status
-                <li> <code>code:REGEX</code> - match transaction codes
-                <li> <code>desc:REGEX</code> - match transaction descriptions
-                <li> <code>payee:REGEX</code> - match payee part of descriptions
-                <li> <code>note:REGEX</code> - match note part of descriptions
-                <li> <code>amt:N</code>, <code>amt:&lt;N</code>, <code>amt:&gt;N</code> - match unsigned magnitudes, or with signed N, signed amounts. For single-commodity amounts only.
-                <li> <code>cur:REGEX</code> - match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write <code>\$</code>
-                <li> <code>tag:NAME</code>, <code>tag:NAME=REGEX</code> - match tags, or tag and value
-                <li> <code>real:BOOL</code> - match postings' realness/virtualness
-                <li> <code>not:QTERM</code> - prepend not: to negate a search term
-                <li> <code>expr:'QEXPR'</code> - match with a boolean query (and, or, not, (..))
-                <li>  <code>any:'QEXPR'</code> - match transactions where any posting matches
-                <li>  <code>all:'QEXPR'</code> - match transactions where all postings match
-                <li style="margin-top:1em;"> <code>depth:N</code> - clip account names at this depth
-                $# <li> Description, account, status query terms are OR'ed, others are AND'ed.
+$# The g key's menu of pages, each with the key that goes to it (hledger.js),
+$# then the next and previous pages.
+$# The keys are not translated, like the other keys.
+$if elem ViewPermission perms
+  <div #gomenu hidden aria-labelledby="gomenuLabel">
+    <p #gomenuLabel>_{HMsg "Go to"}
+    <ul>
+      $forall (key, link, label, title) <- goItems
+        <li>
+          <a href=@?{link} data-gokey=#{key} title=#{title}><code>#{key}</code> #{label}
+  $# The next and previous pages, for the n and p keys.
+  <div #pagesteps hidden>
+    $forall (key, link) <- pageSteps
+      <a href=@?{link} data-stepkey=#{key}>
+
+<dialog #helpmodal tabindex=-1 aria-labelledby="helpLabel">
+  <div .modal-header>
+    <button type="button" .close data-dismiss="modal" aria-label=_{HMsg "Close"}>&times;
+    <span .version>#{progname} #{packageversion}
+    <h3 .modal-title #helpLabel>_{HMsg "Help"}
+  $# The general keys, then the options' keys, which follow the options
+  $# panel row by row, under its own labels, so that a key can be found by
+  $# the control it acts on. Beside them the search syntax, then the
+  $# manual. The keys and query syntax stay outside the translatable text.
+  <div .modal-body>
+    <div .row>
+      <div .col-sm-6>
+        <h4>_{HMsg "Keyboard shortcuts"}
+        <table .help-keys>
+          <tr>
+            <th><kbd>h</kbd> _{HMsg "or"} <kbd>?</kbd>
+            <td>_{HMsg "view this help"}
+          <tr>
+            <th><kbd>g</kbd>
+            <td>_{HMsg "go to any screen"}
+          <tr>
+            <th><kbd>n</kbd> <kbd>p</kbd>
+            <td>_{HMsg "go to the next or previous screen"}
+          $if elem AddPermission perms
+            <tr>
+              <th><kbd>a</kbd>
+              <td>_{HMsg "add a transaction"}
+          <tr>
+            <th><kbd>s</kbd>
+            <td>_{HMsg "toggle sidebar"}
+          <tr>
+            <th><kbd>Shift</kbd>+<kbd>1</kbd>–<kbd>9</kbd>
+            $# TRANSLATORS: in the help, what shift with a digit key does: fold or open the sidebar's account tree to that many levels.
+            <td>_{HMsg "set the sidebar's account depth"}
+
+          <tr>
+            <th><kbd>b</kbd>
+            <td>_{HMsg "show or hide the sidebar's balances"}
+          <tr>
+            <th><kbd>o</kbd>
+            <td>_{HMsg "toggle report options"}
+          <tr>
+            <th><kbd>c</kbd>
+            <td>_{HMsg "toggle the report's chart"}
+          <tr>
+            <th><kbd>[</kbd> <kbd>]</kbd>
+            <td>_{HMsg "select the chart's commodity"}
+          <tr>
+            <th><kbd>N</kbd>
+            $# TRANSLATORS: in the help, what the N key does: show or hide the chart's net total line, the total of its bars; N is for net.
+            <td>_{HMsg "toggle the chart's net total line"}
+
+          <tr>
+            <th><kbd>d</kbd>
+            <td>_{HMsg "toggle the report's data"}
+          <tr>
+            <th><kbd>f</kbd>
+            <td>_{HMsg "toggle full window"}
+          <tr>
+            <th><kbd>/</kbd>
+            <td>_{HMsg "focus search form"}
+          <tr>
+            $# TRANSLATORS: in the help, what the Del key does: clear the search box, showing everything again.
+            <th><kbd>Del</kbd>
+            <td>_{HMsg "clear the search"}
+
+          <tr>
+            <th><kbd>Esc</kbd>
+            <td>_{HMsg "cancel"}
+        $# TRANSLATORS: in the help, the heading of the options' keys, listed under the options panel's own labels.
+        <h5>_{HMsg "Report options"}
+
+        <table .help-keys .help-options>
+          <tr>
+            <th>_{HMsg "Show:"}
+            <td>
+              <span><kbd>H</kbd> _{HMsg "historical end balances / balance changes"}
+          <tr>
+            <th>_{HMsg "Interval:"}
+            <td>
+              <span><kbd>Y</kbd> _{HMsg "yearly"}
+              <span><kbd>Q</kbd> _{HMsg "quarterly"}
+              <span><kbd>M</kbd> _{HMsg "monthly"}
+              <span><kbd>W</kbd> _{HMsg "weekly"}
+              <span><kbd>D</kbd> _{HMsg "daily"}
+          <tr>
+            <th>_{HMsg "Status:"}
+            <td>
+              <span><kbd>U</kbd> _{HMsg "unmarked"}
+              <span><kbd>P</kbd> _{HMsg "pending"}
+              <span><kbd>C</kbd> _{HMsg "cleared"}
+          <tr>
+            <th>_{HMsg "Postings:"}
+            <td>
+              <span><kbd>R</kbd> _{HMsg "real only / all"}
+          <tr>
+            <th>_{HMsg "Depth limit:"}
+            <td>
+              $# TRANSLATORS: in the help's Depth row: what the digit keys, and the - and + keys, do to the depth limit.
+              <span><kbd>0</kbd>–<kbd>9</kbd> _{HMsg "set it"}
+              <span><kbd>-</kbd> <kbd>+</kbd> _{HMsg "decrease or increase it"}
+
+          <tr>
+            <th>_{HMsg "Accounts:"}
+            <td>
+              <span><kbd>t</kbd> _{HMsgc "accounts" "tree / list"}
+          <tr>
+            <th>_{HMsg "Amounts:"}
+            <td>
+              <span><kbd>B</kbd> _{HMsg "at cost"}
+              <span><kbd>V</kbd> _{HMsg "at market value"}
+          <tr>
+            <th>_{HMsg "Zero balances:"}
+            <td>
+              <span><kbd>z</kbd> _{HMsg "show / hide zero balances"}
+          <tr>
+            <th>_{HMsg "Lots:"}
+            <td>
+              <span><kbd>L</kbd> _{HMsg "show / hide lot details"}
+          <tr>
+            <th>_{HMsg "Extra columns:"}
+            <td>
+              <span><kbd>T</kbd> _{HMsgc "column" "total"}
+              <span><kbd>A</kbd> _{HMsgc "column" "average"}
+          <tr>
+            <th>_{HMsg "Sort:"}
+            <td>
+              <span><kbd>S</kbd> _{HMsg "by amount / by account display order"}
+        $# TRANSLATORS: in the help, below the options' keys.
+        <p .help-note>_{HMsg "Pressed again, an option's key turns it back off."}
+
+      <div .col-sm-6>
+        <h4>_{HMsgc "help heading" "Search queries"}
+        <ul .help-list>
+          <li> _{HMsg "Search patterns with spaces should be enclosed in quotes."}
+          <li> <code>REGEX</code> - _{HMsg "match account names"}
+          <li> <code>type:TYPE</code> - _{HMsg "match account types (A, L, E, R, X, ...)"}
+          <li> <code>date:PERIODEXP</code> - _{HMsg "match dates"}
+          <li> <code>status:*</code>, <code>status:!</code>, <code>status:</code> - _{HMsg "match status"}
+          <li> <code>code:REGEX</code> - _{HMsg "match transaction codes"}
+          <li> <code>desc:REGEX</code> - _{HMsg "match transaction descriptions"}
+          <li> <code>payee:REGEX</code> - _{HMsg "match payee part of descriptions"}
+          <li> <code>note:REGEX</code> - _{HMsg "match note part of descriptions"}
+          <li> <code>amt:N</code>, <code>amt:&lt;N</code>, <code>amt:&gt;N</code> - _{HMsg "match unsigned magnitudes, or with signed N, signed amounts. N may have a commodity symbol."}
+          <li> <code>change:N</code>, <code>change:&lt;N</code>, <code>balance:N</code>, <code>balance:&gt;N</code> - _{HMsg "match report rows (accounts, periods, transactions) by their change or balance, like amt:. N may have a commodity symbol."}
+          <li> <code>cur:REGEX</code> - _{HMsg "match currencies/commodities. Must match the whole symbol/name. To match dollar sign, write"} <code>\$</code>
+          <li> <code>tag:NAME</code>, <code>tag:NAME=REGEX</code> - _{HMsg "match tags, or tag and value"}
+          <li> <code>real:BOOL</code> - _{HMsg "match postings' realness/virtualness"}
+          <li> <code>find:REGEX</code> _{HMsg "or"} <code>::REGEX</code> - _{HMsg "match any field (account, amount, comment, tag, description, code), or a date if REGEX is also a period expression"}
+          <li> <code>not:QTERM</code> - _{HMsg "prepend not: to negate a search term"}
+          <li> <code>expr:'QEXPR'</code> - _{HMsg "match with a boolean query (and, or, not, ())"}
+          <li>  <code>any:'QEXPR'</code> - _{HMsg "match transactions where any posting matches"}
+          <li>  <code>all:'QEXPR'</code> - _{HMsg "match transactions where all postings match"}
+          <li .gap-above> <code>depth:N</code> - _{HMsg "another way to set depth limit (can be per account)"}
+          $# <li> Description, account, status query terms are OR'ed, others are AND'ed.
+        <h4>_{HMsg "More help:"}
+        <ul .help-list>
+          <li>
+            <a href=#{webmanualurl} target=hledgerhelp>_{HMsg "hledger-web user manual"}
diff --git a/templates/edit-form.hamlet b/templates/edit-form.hamlet
--- a/templates/edit-form.hamlet
+++ b/templates/edit-form.hamlet
@@ -1,17 +1,17 @@
 #{extra}
 <h2>
-  Edit file #
+  _{HMsg "Edit file"} #
   <i>#{f}
 <div.alert.alert-danger>
-  Are you sure? This will overwrite your journal!
-<table.table.table-condensed>
+  _{HMsg "Are you sure? This will overwrite your journal!"}
+<table.table.table-condensed.edit-form>
   <tr>
-    <td colspan=2 style="border:0">
+    <td colspan=2>
       ^{fvInput tView}
   <tr>
-    <td style="border:0">
+    <td>
       <span.help>
-        ^{helplink "data-formats" "File format help"}
-    <td .text-right style="border:0">
-      <a.btn.btn-default href="@{ManageR}">Go back
-      <input.btn.btn-default type=submit value="Save">
+        ^{helplink "data-formats" (tr trs "File format help")}
+    <td .text-right>
+      <a.btn.btn-default href="@{ManageR}">_{HMsg "Go back"}
+      <input.btn.btn-default type=submit value=_{HMsg "Save"}>
diff --git a/templates/journal.hamlet b/templates/journal.hamlet
--- a/templates/journal.hamlet
+++ b/templates/journal.hamlet
@@ -1,26 +1,32 @@
+^{controlsRows}
+
 <h2>
   #{title'}
 
 $if elem AddPermission perms
-  <a #addformlink href="#" role="button" style="cursor:pointer; margin-top:1em;"
-     data-toggle="modal" data-target="#addmodal" title="Add a new transaction to the journal">
-    Add a transaction
+  <a #addformlink href="#" role="button"
+     data-toggle="modal" data-target="#addmodal" title=_{HMsg "Add a new transaction to the journal"}>
+    _{HMsg "Add a transaction"}
 
+^{pagingLinks trs JournalR qparam carried page}
+
 <div .table-responsive>
   <table .transactionsreport .table .table-condensed>
     <thead>
-      <th .date style="text-align:left;">Date
-      <th .description style="text-align:left;">Description
-      <th .account style="text-align:left;">Account
-      <th .amount style="text-align:right;">Amount
+      <th .date>_{HMsgc "column heading" "Date"}
+      <th .description>_{HMsgc "column heading" "Description"}
+      <th .account>_{HMsgc "column heading" "Account"}
+      <th .amount>_{HMsgc "column heading" "Amount"}
 
     $forall torig <- items
-      <tr .title ##{transactionFrag torig} title="#{showTransaction torig}">
+      <tr .title ##{transactionFrag torig} data-entry="#{showTransaction torig}">
         <td .date nowrap>
-          #{show (tdate torig)}
+          <a href="@?{(JournalR, dayParams torig)}##{transactionFrag torig}"
+             title=_{HMsg "Show the journal entries on this date"}>
+            #{show (tdate torig)}
         <td colspan=2>
           #{textElideRight 60 (tdescription torig)}
-        <td .amount style="text-align:right;">
+        <td .amount>
 
       $forall Posting { paccount = acc, pamount = amt } <- tpostings torig
         <tr .posting>
@@ -28,10 +34,12 @@
           <td>
           <td>
             &nbsp;
-            <a href="@?{acctlink acc}##{tindex torig}" title="#{acc}">
+            <a href="@?{acctlink acc torig}##{transactionFrag torig}" title="#{acc}">
               #{elideAccountName 40 acc}
-          <td .amount style="text-align:right;">
+          <td .amount>
             ^{mixedAmountAsHtml amt}
+
+^{pagingLinks trs JournalR qparam carried page}
 
 $if elem AddPermission perms
   ^{addModal AddR j today}
diff --git a/templates/manage.hamlet b/templates/manage.hamlet
--- a/templates/manage.hamlet
+++ b/templates/manage.hamlet
@@ -1,22 +1,22 @@
 <h2>
-  Your journal's files
+  _{HMsg "Your journal's files"}
 
 <div.row>
   <div .col-md-6.col-sm-8.col-xs-12>
-    <table .table.table-condensed>
+    <table .table.table-condensed.files>
       <thead>
         <th>
-          File
+          _{HMsgc "column heading" "File"}
         <th>
       <tbody>
-        $forall (path, _) <- jfiles j
+        $forall path <- journalFilePaths j
           <tr>
-            <td style="vertical-align:middle">
+            <td .filename>
               #{path}
-            <td style="text-align:right">
+            <td .text-right>
               <a.btn.btn-default href=@{EditR path}>
-                Edit
+                _{HMsg "Edit"}
               <a.btn.btn-default href=@{UploadR path}>
-                Upload
+                _{HMsg "Upload"}
               <a.btn.btn-default href=@{DownloadR path}>
-                Download
+                _{HMsg "Download"}
diff --git a/templates/paging.hamlet b/templates/paging.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/paging.hamlet
@@ -0,0 +1,17 @@
+$if pgCount > 1
+  <p .report-links .paging>
+    <span>#{showing}
+  <p .report-links .paging-nav>
+    $maybe n <- mnewer
+      <a .newer href=@?{link n} title=#{tr trs "Show the newer transactions"}>‹ #{tr trs "Newer"}
+    $nothing
+      <span .newer .placeholder aria-hidden="true">‹ #{tr trs "Newer"}
+    $forall n <- numbers
+      $if n == pgNumber
+        <span .current aria-current="page">#{n}
+      $else
+        <a href=@?{link n} title=#{pageTitle n} aria-label=#{pageLabel n}>#{n}
+    $maybe n <- molder
+      <a .older href=@?{link n} title=#{tr trs "Show the older transactions"}>#{tr trs "Older"} ›
+    $nothing
+      <span .older .placeholder aria-hidden="true">#{tr trs "Older"} ›
diff --git a/templates/register.hamlet b/templates/register.hamlet
--- a/templates/register.hamlet
+++ b/templates/register.hamlet
@@ -1,39 +1,60 @@
+^{controlsRows}
+
 <h2>
   #{header}
 
-<div>
-  ^{registerChartHtml qparam balancelabel $ accountTransactionsReportByCommodity items}
+^{pagingLinks trs RegisterR qparam modeParams page}
 
-<div.table-responsive>
-  <table .table.table-striped.table-condensed>
+^{registerChartHtml trs (cliopts_ opts) j today chartwidths qparam modeParams chartLink chartacct balancelabel allitems}
+
+<div.table-responsive.report-table>
+  <table .table.table-condensed>
     <thead>
       <tr>
-        <th style="text-align:left;">
-          Date
+        <th>
+          _{HMsgc "column heading" "Date"}
           <span .glyphicon.glyphicon-chevron-up>
-        <th style="text-align:left;">Description
-        <th style="text-align:left;">To/From Account(s)
-        <th style="text-align:right; white-space:normal;">Amount Out/In
-        <th style="text-align:right; white-space:normal;">
-          #{balancelabel}
+        <th>_{HMsgc "column heading" "Description"}
+        <th>_{HMsgc "column heading" "To/From Account(s)"}
+        <th .amount>_{HMsgc "column heading" "Amount Out/In"}
+        <th .amount>
+          <a href=@?{accumToggle} title="#{accumToggleTitle}">#{balancelabel}
 
     <tbody>
       $forall (torig, tacct, split, _acct, amt, bal) <- items
-        <tr ##{tindex torig} title="#{showTransaction torig}" style="vertical-align:top;">
+        <tr ##{transactionFrag torig} data-entry="#{showTransaction torig}">
           <td .date nowrap>
-            <a href="@?{(JournalR, [("q", T.unwords $ removeInacct qparam)])}##{transactionFrag torig}">
+            <a href="@?{(JournalR, dayParams torig)}##{transactionFrag torig}"
+               title=_{HMsg "Show this entry and the other journal entries on its date"}>
               #{show (tdate tacct)}
-          <td>
+          <td .description>
             #{textElideRight 30 (tdescription tacct)}
           <td .account>
             $forall (Posting { paccount = acc }, (summName,comma)) <- otherTransAccounts torig
-              <a href="@?{acctlink acc}##{tindex torig}" title="#{acc}">
-                #{summName}</a>#{comma}
-          <td .amount style="text-align:right; white-space:nowrap;">
+              <a href="@?{acctlink acc torig}##{transactionFrag torig}" title="#{acc}">
+                #{breakAtColons summName}</a>#{comma}
+          <td .amount>
             $if not split || not (mixedAmountLooksZero amt)
-              ^{mixedAmountAsHtml amt}
-          <td style="text-align:right;">
-            ^{mixedAmountAsHtml bal}
+              ^{mixedAmountAsHtmlWith amtfmt amt}
+          <td .amount>
+            ^{runningBalanceAsHtml trs amt bal}
+      $if historical && lastpage
+        $maybe start <- mstart
+          <tr .broughtforward>
+            <td .date nowrap>
+              #{show (snd start)}
+            <td .description>
+              _{HMsg "Balance brought forward"}
+            <td .account>
+            <td .amount>
+            <td .amount>
+              $if mixedAmountLooksZero startbal
+                ^{mixedAmountAsHtmlElided trs startbal}
+              $else
+                <a href=@?{broughtForwardLink start} title=_{HMsg "Show the transactions before this period"}>
+                  ^{mixedAmountAsHtmlElided trs startbal}
+
+^{pagingLinks trs RegisterR qparam modeParams page}
 
 $if elem AddPermission perms
   ^{addModal AddR j today}
diff --git a/templates/upload-form.hamlet b/templates/upload-form.hamlet
--- a/templates/upload-form.hamlet
+++ b/templates/upload-form.hamlet
@@ -1,14 +1,13 @@
 <h2>
-  Upload to file #
+  _{HMsg "Upload to file"} #
   <i>#{f}
 <div.alert.alert-danger>
-  Are you sure? This will overwrite your journal!
+  _{HMsg "Are you sure? This will overwrite your journal!"}
 <div.form-group>
   <label .btn.btn-primary for="file">
-    <input type=file id=file name=file style="display:none"
-      onchange="\$('#file-info').html(this.files[0].name)" />
-    Select file
+    <input type=file id=file name=file>
+    _{HMsg "Select file"}
   <span .label.label-info id="file-info">
 <div.form-group>
-  <input .btn.btn-default type=submit value="Upload">
+  <input .btn.btn-default type=submit value=_{HMsg "Upload"}>
 #{extra}
diff --git a/templates/years.hamlet b/templates/years.hamlet
new file mode 100644
--- /dev/null
+++ b/templates/years.hamlet
@@ -0,0 +1,14 @@
+$newline never
+$if manyYears
+  <p .report-links .years>
+    <span .row-label>#{trc trs "years row" "Years:"}
+    <a href=@?{alllink} :allCurrent:.current :allCurrent:aria-current="page" title=#{tr trs "Show all years"}>#{trc trs "years row" "All"}
+    $if null byDecade
+      $forall y <- years
+        <a href=@?{yearlink y} :isCurrent y:.current :isCurrent y:aria-current="page" title=#{showOnly y}>#{y}
+  $forall (decade, decadeYears) <- byDecade
+    <p .report-links .years>
+      <span .row-label>#{decade}:
+      $forall y <- decadeYears
+        <a href=@?{yearlink y} :isCurrent y:.current :isCurrent y:aria-current="page" title=#{showOnly y}>#{y}
+  <p .controls-hint>#{rangeHint}
