From 7865b8278c27d25e347130feb196ba31cba2522a Mon Sep 17 00:00:00 2001 From: Ne9roni Date: Sun, 19 Apr 2026 23:52:26 +0800 Subject: [PATCH 1/4] feat: add serve command with bundled Piskel web editor Add piskel-cli serve to serve vendor/piskel-prod over HTTP and open a browser, with optional project load via a session URL and ?load= bridge injected into index.html. Include sync-piskel-vendor and assert-vendor scripts so maintainers can refresh upstream builds and npm publish fails if the static bundle is missing. Document usage in README and ship vendor/piskel-prod in-repo for clone and npm pack consumers. Handle missing xdg-open on Linux/WSL by trying wslview, gio, and sensible-browser before printing a manual-open hint. Made-with: Cursor --- README.md | 34 +- package-lock.json | 36 +- package.json | 5 +- scripts/assert-vendor.mjs | 33 + scripts/sync-piskel-vendor.mjs | 102 + src/cli/run.ts | 31 + src/cli/serve-editor.ts | 338 + tests/cli.test.ts | 1 + tests/serve-editor.test.ts | 21 + vendor/README.md | 17 + vendor/piskel-prod/css/fonts/icomoon.eot | Bin 0 -> 4416 bytes vendor/piskel-prod/css/fonts/icomoon.svg | 28 + vendor/piskel-prod/css/fonts/icomoon.ttf | Bin 0 -> 4252 bytes vendor/piskel-prod/css/fonts/icomoon.woff | Bin 0 -> 4328 bytes vendor/piskel-prod/css/fonts/piskel.eot | Bin 0 -> 2588 bytes vendor/piskel-prod/css/fonts/piskel.svg | 13 + vendor/piskel-prod/css/fonts/piskel.ttf | Bin 0 -> 2424 bytes vendor/piskel-prod/css/fonts/piskel.woff | Bin 0 -> 1848 bytes ...piskel-style-packaged-2026-04-19-11-22.css | 4653 ++ vendor/piskel-prod/img/cursors/circle.png | Bin 0 -> 766 bytes .../piskel-prod/img/cursors/color-palette.png | Bin 0 -> 209 bytes vendor/piskel-prod/img/cursors/dither.png | Bin 0 -> 702 bytes vendor/piskel-prod/img/cursors/dropper.png | Bin 0 -> 543 bytes vendor/piskel-prod/img/cursors/eraser.png | Bin 0 -> 656 bytes vendor/piskel-prod/img/cursors/hand.png | Bin 0 -> 672 bytes vendor/piskel-prod/img/cursors/lighten.png | Bin 0 -> 606 bytes vendor/piskel-prod/img/cursors/mirror-pen.png | Bin 0 -> 557 bytes .../piskel-prod/img/cursors/paint-bucket.png | Bin 0 -> 707 bytes vendor/piskel-prod/img/cursors/pen.png | Bin 0 -> 450 bytes vendor/piskel-prod/img/cursors/rectangle.png | Bin 0 -> 660 bytes vendor/piskel-prod/img/cursors/select.png | Bin 0 -> 1145 bytes vendor/piskel-prod/img/cursors/stroke.png | Bin 0 -> 617 bytes .../img/cursors/vertical-mirror-pen.png | Bin 0 -> 603 bytes vendor/piskel-prod/img/cursors/wand.png | Bin 0 -> 570 bytes vendor/piskel-prod/img/icons.png | Bin 0 -> 14264 bytes .../img/icons/common/common-backup-white.png | Bin 0 -> 1957 bytes .../icons/common/common-backup-white@2x.png | Bin 0 -> 4196 bytes .../img/icons/common/common-keyboard-gold.png | Bin 0 -> 340 bytes .../icons/common/common-keyboard-gold@2x.png | Bin 0 -> 570 bytes .../common/common-swapcolors-arrow-grey.png | Bin 0 -> 565 bytes .../common-swapcolors-arrow-grey@2x.png | Bin 0 -> 960 bytes .../img/icons/common/common-warning-red.png | Bin 0 -> 446 bytes .../icons/common/common-warning-red@2x.png | Bin 0 -> 851 bytes .../img/icons/frame/frame-dragndrop-white.png | Bin 0 -> 324 bytes .../icons/frame/frame-dragndrop-white@2x.png | Bin 0 -> 537 bytes .../img/icons/frame/frame-duplicate-white.png | Bin 0 -> 387 bytes .../icons/frame/frame-duplicate-white@2x.png | Bin 0 -> 664 bytes .../img/icons/frame/frame-plus-white.png | Bin 0 -> 210 bytes .../img/icons/frame/frame-plus-white@2x.png | Bin 0 -> 262 bytes .../icons/frame/frame-recyclebin-white.png | Bin 0 -> 319 bytes .../icons/frame/frame-recyclebin-white@2x.png | Bin 0 -> 539 bytes .../img/icons/minimap/minimap-grid-gold.png | Bin 0 -> 135 bytes .../icons/minimap/minimap-grid-gold@2x.png | Bin 0 -> 192 bytes .../img/icons/minimap/minimap-grid-white.png | Bin 0 -> 135 bytes .../icons/minimap/minimap-grid-white@2x.png | Bin 0 -> 186 bytes .../minimap-popup-preview-arrow-gold.png | Bin 0 -> 301 bytes .../minimap-popup-preview-arrow-gold@2x.png | Bin 0 -> 367 bytes .../minimap-popup-preview-arrow-white.png | Bin 0 -> 246 bytes .../minimap-popup-preview-arrow-white@2x.png | Bin 0 -> 357 bytes .../icons/settings/settings-export-white.png | Bin 0 -> 589 bytes .../settings/settings-export-white@2x.png | Bin 0 -> 1016 bytes .../icons/settings/settings-gear-white.png | Bin 0 -> 668 bytes .../icons/settings/settings-gear-white@2x.png | Bin 0 -> 1322 bytes .../settings/settings-open-folder-white.png | Bin 0 -> 587 bytes .../settings-open-folder-white@2x.png | Bin 0 -> 1008 bytes .../icons/settings/settings-resize-white.png | Bin 0 -> 392 bytes .../settings/settings-resize-white@2x.png | Bin 0 -> 656 bytes .../icons/settings/settings-save-white.png | Bin 0 -> 381 bytes .../icons/settings/settings-save-white@2x.png | Bin 0 -> 652 bytes .../img/icons/tools/tool-circle.png | Bin 0 -> 495 bytes .../img/icons/tools/tool-circle@2x.png | Bin 0 -> 1079 bytes .../img/icons/tools/tool-colorpicker.png | Bin 0 -> 563 bytes .../img/icons/tools/tool-colorpicker@2x.png | Bin 0 -> 1154 bytes .../img/icons/tools/tool-colorswap.png | Bin 0 -> 1329 bytes .../img/icons/tools/tool-colorswap@2x.png | Bin 0 -> 2844 bytes .../img/icons/tools/tool-dithering.png | Bin 0 -> 245 bytes .../img/icons/tools/tool-dithering@2x.png | Bin 0 -> 393 bytes .../img/icons/tools/tool-eraser.png | Bin 0 -> 524 bytes .../img/icons/tools/tool-eraser@2x.png | Bin 0 -> 963 bytes .../img/icons/tools/tool-lasso-select.png | Bin 0 -> 827 bytes .../img/icons/tools/tool-lasso-select@2x.png | Bin 0 -> 1718 bytes .../img/icons/tools/tool-lighten.png | Bin 0 -> 690 bytes .../img/icons/tools/tool-lighten@2x.png | Bin 0 -> 1480 bytes .../piskel-prod/img/icons/tools/tool-move.png | Bin 0 -> 547 bytes .../img/icons/tools/tool-move@2x.png | Bin 0 -> 1015 bytes .../img/icons/tools/tool-paint-bucket.png | Bin 0 -> 741 bytes .../img/icons/tools/tool-paint-bucket@2x.png | Bin 0 -> 1582 bytes .../piskel-prod/img/icons/tools/tool-pen.png | Bin 0 -> 670 bytes .../img/icons/tools/tool-pen@2x.png | Bin 0 -> 1488 bytes .../img/icons/tools/tool-rectangle-select.png | Bin 0 -> 276 bytes .../icons/tools/tool-rectangle-select@2x.png | Bin 0 -> 425 bytes .../img/icons/tools/tool-rectangle.png | Bin 0 -> 245 bytes .../img/icons/tools/tool-rectangle@2x.png | Bin 0 -> 395 bytes .../img/icons/tools/tool-shape-select.png | Bin 0 -> 580 bytes .../img/icons/tools/tool-shape-select@2x.png | Bin 0 -> 1288 bytes .../img/icons/tools/tool-stroke.png | Bin 0 -> 802 bytes .../img/icons/tools/tool-stroke@2x.png | Bin 0 -> 1687 bytes .../icons/tools/tool-vertical-mirror-pen.png | Bin 0 -> 744 bytes .../tools/tool-vertical-mirror-pen@2x.png | Bin 0 -> 1570 bytes .../img/icons/transform/tool-center.png | Bin 0 -> 297 bytes .../img/icons/transform/tool-center@2x.png | Bin 0 -> 457 bytes .../img/icons/transform/tool-clone.png | Bin 0 -> 621 bytes .../img/icons/transform/tool-clone@2x.png | Bin 0 -> 1206 bytes .../img/icons/transform/tool-crop.png | Bin 0 -> 393 bytes .../img/icons/transform/tool-crop@2x.png | Bin 0 -> 693 bytes .../img/icons/transform/tool-flip.png | Bin 0 -> 708 bytes .../img/icons/transform/tool-flip@2x.png | Bin 0 -> 1237 bytes .../img/icons/transform/tool-rotate.png | Bin 0 -> 815 bytes .../img/icons/transform/tool-rotate@2x.png | Bin 0 -> 1707 bytes vendor/piskel-prod/img/icons@2x.png | Bin 0 -> 30453 bytes vendor/piskel-prod/index.html | 1662 + .../piskel-prod/js/lib/gif/gif.ie.worker.js | 1 + .../js/piskel-packaged-2026-04-19-11-22.js | 38008 ++++++++++++++++ .../piskel-packaged-2026-04-19-11-22.js.map | 1 + .../piskel-packaged-min-2026-04-19-11-22.js | 56 + ...iskel-packaged-min-2026-04-19-11-22.js.map | 1 + vendor/piskel-prod/logo.png | Bin 0 -> 414 bytes .../piskelapp-partials/main-partial.html | 1537 + .../piskel-web-partial-kids.html | 1541 + .../piskel-web-partial.html | 1540 + 120 files changed, 49624 insertions(+), 35 deletions(-) create mode 100644 scripts/assert-vendor.mjs create mode 100644 scripts/sync-piskel-vendor.mjs create mode 100644 src/cli/serve-editor.ts create mode 100644 tests/serve-editor.test.ts create mode 100644 vendor/README.md create mode 100644 vendor/piskel-prod/css/fonts/icomoon.eot create mode 100644 vendor/piskel-prod/css/fonts/icomoon.svg create mode 100644 vendor/piskel-prod/css/fonts/icomoon.ttf create mode 100644 vendor/piskel-prod/css/fonts/icomoon.woff create mode 100644 vendor/piskel-prod/css/fonts/piskel.eot create mode 100644 vendor/piskel-prod/css/fonts/piskel.svg create mode 100644 vendor/piskel-prod/css/fonts/piskel.ttf create mode 100644 vendor/piskel-prod/css/fonts/piskel.woff create mode 100644 vendor/piskel-prod/css/piskel-style-packaged-2026-04-19-11-22.css create mode 100644 vendor/piskel-prod/img/cursors/circle.png create mode 100644 vendor/piskel-prod/img/cursors/color-palette.png create mode 100644 vendor/piskel-prod/img/cursors/dither.png create mode 100644 vendor/piskel-prod/img/cursors/dropper.png create mode 100644 vendor/piskel-prod/img/cursors/eraser.png create mode 100644 vendor/piskel-prod/img/cursors/hand.png create mode 100644 vendor/piskel-prod/img/cursors/lighten.png create mode 100644 vendor/piskel-prod/img/cursors/mirror-pen.png create mode 100644 vendor/piskel-prod/img/cursors/paint-bucket.png create mode 100644 vendor/piskel-prod/img/cursors/pen.png create mode 100644 vendor/piskel-prod/img/cursors/rectangle.png create mode 100644 vendor/piskel-prod/img/cursors/select.png create mode 100644 vendor/piskel-prod/img/cursors/stroke.png create mode 100644 vendor/piskel-prod/img/cursors/vertical-mirror-pen.png create mode 100644 vendor/piskel-prod/img/cursors/wand.png create mode 100644 vendor/piskel-prod/img/icons.png create mode 100644 vendor/piskel-prod/img/icons/common/common-backup-white.png create mode 100644 vendor/piskel-prod/img/icons/common/common-backup-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/common/common-keyboard-gold.png create mode 100644 vendor/piskel-prod/img/icons/common/common-keyboard-gold@2x.png create mode 100644 vendor/piskel-prod/img/icons/common/common-swapcolors-arrow-grey.png create mode 100644 vendor/piskel-prod/img/icons/common/common-swapcolors-arrow-grey@2x.png create mode 100644 vendor/piskel-prod/img/icons/common/common-warning-red.png create mode 100644 vendor/piskel-prod/img/icons/common/common-warning-red@2x.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-dragndrop-white.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-dragndrop-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-duplicate-white.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-duplicate-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-plus-white.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-plus-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-recyclebin-white.png create mode 100644 vendor/piskel-prod/img/icons/frame/frame-recyclebin-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-grid-gold.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-grid-gold@2x.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-grid-white.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-grid-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-popup-preview-arrow-gold.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-popup-preview-arrow-gold@2x.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-popup-preview-arrow-white.png create mode 100644 vendor/piskel-prod/img/icons/minimap/minimap-popup-preview-arrow-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-export-white.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-export-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-gear-white.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-gear-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-open-folder-white.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-open-folder-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-resize-white.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-resize-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-save-white.png create mode 100644 vendor/piskel-prod/img/icons/settings/settings-save-white@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-circle.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-circle@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-colorpicker.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-colorpicker@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-colorswap.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-colorswap@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-dithering.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-dithering@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-eraser.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-eraser@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-lasso-select.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-lasso-select@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-lighten.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-lighten@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-move.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-move@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-paint-bucket.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-paint-bucket@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-pen.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-pen@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-rectangle-select.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-rectangle-select@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-rectangle.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-rectangle@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-shape-select.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-shape-select@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-stroke.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-stroke@2x.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-vertical-mirror-pen.png create mode 100644 vendor/piskel-prod/img/icons/tools/tool-vertical-mirror-pen@2x.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-center.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-center@2x.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-clone.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-clone@2x.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-crop.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-crop@2x.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-flip.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-flip@2x.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-rotate.png create mode 100644 vendor/piskel-prod/img/icons/transform/tool-rotate@2x.png create mode 100644 vendor/piskel-prod/img/icons@2x.png create mode 100644 vendor/piskel-prod/index.html create mode 100644 vendor/piskel-prod/js/lib/gif/gif.ie.worker.js create mode 100644 vendor/piskel-prod/js/piskel-packaged-2026-04-19-11-22.js create mode 100644 vendor/piskel-prod/js/piskel-packaged-2026-04-19-11-22.js.map create mode 100644 vendor/piskel-prod/js/piskel-packaged-min-2026-04-19-11-22.js create mode 100644 vendor/piskel-prod/js/piskel-packaged-min-2026-04-19-11-22.js.map create mode 100644 vendor/piskel-prod/logo.png create mode 100644 vendor/piskel-prod/piskelapp-partials/main-partial.html create mode 100644 vendor/piskel-prod/piskelapp-partials/piskel-web-partial-kids.html create mode 100644 vendor/piskel-prod/piskelapp-partials/piskel-web-partial.html diff --git a/README.md b/README.md index 3c3b585..1080dd6 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # piskel-cli > **Headless pixel art engine for scripts, pipelines, and AI agents.** -> Create, edit, and export `.piskel` files entirely from the terminal — no browser, no GUI, no clicks. +> Create, edit, and export `.piskel` files from the terminal; use `serve` when you want the bundled **Piskel** web editor in a browser. [![npm version](https://img.shields.io/npm/v/@ne9roni/piskel-cli)](https://www.npmjs.com/package/@ne9roni/piskel-cli) [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE) @@ -118,6 +118,8 @@ npm install -g @ne9roni/piskel-cli piskel-cli --help ``` +The published npm package includes a **production build of Piskel** under `vendor/piskel-prod`, so `npm install -g @ne9roni/piskel-cli` is enough for **`piskel-cli serve`** — no separate clone or download of the editor. + Or use locally from source: ```bash @@ -127,6 +129,21 @@ npm install && npm run build node dist/src/cli.js --help ``` +If you clone without `vendor/piskel-prod`, run `npm run sync-piskel-vendor` once (needs a built [piskel](https://github.com/piskelapp/piskel) tree; see [`vendor/README.md`](vendor/README.md)). + +--- + +## Browser editor (`serve`) + +Optional: open the same pixel editor as [piskelapp.com](https://www.piskelapp.com/) on your machine: + +```bash +piskel-cli serve +piskel-cli serve path/to/project.piskel +``` + +Use `--no-open` to only print the URL, and `--port` / `--host` to control the local server. Press Ctrl+C to stop. + --- ## Quick Start @@ -182,6 +199,7 @@ piskel-cli run my-plan.json --json | **Read** | `read pixel`, `read frame`, `read project`, `read palette`, `read bounds` | | **Export** | `export png`, `export gif`, `export spritesheet`, `export frames` | | **Run** | `run ` — execute multi-step plan files | +| **Serve** | `serve []` — local HTTP + bundled Piskel web UI | Full reference: [`docs/commands.md`](docs/commands.md) @@ -221,6 +239,7 @@ piskel-cli is implemented as a pure **Node.js / TypeScript** library with zero r - **`src/probe/`** — headless read/write engine for `.piskel` files - **`src/cli/`** — command parser and JSON protocol layer +- **`vendor/piskel-prod/`** — shipped copy of upstream Piskel `dest/prod` (used by `serve`; refreshed via `npm run sync-piskel-vendor`) - **`tests/`** — Vitest test suite covering `.piskel` I/O, CLI behavior, export correctness, and plan execution --- @@ -234,6 +253,19 @@ npm test # Run full test suite (Vitest) npm run test:watch # Watch mode ``` +### Bundled Piskel editor (for `serve`) + +From a local clone of [piskelapp/piskel](https://github.com/piskelapp/piskel) with `npm install && npm run build` already run: + +```bash +npm run sync-piskel-vendor +# or: PISKEL_ROOT=/path/to/piskel npm run sync-piskel-vendor +``` + +Details: [`vendor/README.md`](vendor/README.md). + +**Publishing:** `npm publish` runs `prepublishOnly`, which ends with **`npm run assert-vendor`**. If `vendor/piskel-prod/index.html` is missing, publish fails so the registry package never ships a broken `serve`. Run `sync-piskel-vendor` before releasing. + Tests live in [`tests/`](tests/) and cover `.piskel` read/write, CLI behavior, default output paths, and plan execution end-to-end. --- diff --git a/package-lock.json b/package-lock.json index 02857cf..979a7d1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,13 @@ { - "name": "piskel-cli", + "name": "@ne9roni/piskel-cli", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "piskel-cli", + "name": "@ne9roni/piskel-cli", "version": "1.0.0", - "license": "ISC", + "license": "Apache-2.0", "dependencies": { "gifenc": "^1.0.3", "pngjs": "^7.0.0" @@ -629,9 +629,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -649,9 +646,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -669,9 +663,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -689,9 +680,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -709,9 +697,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -729,9 +714,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1292,9 +1274,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1316,9 +1295,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1340,9 +1316,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -1364,9 +1337,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ diff --git a/package.json b/package.json index b46a9e6..c1ddc84 100644 --- a/package.json +++ b/package.json @@ -8,9 +8,11 @@ "piskel-cli": "./dist/src/cli.js" }, "scripts": { + "sync-piskel-vendor": "node scripts/sync-piskel-vendor.mjs", "build": "tsc -p tsconfig.json", "build:reference-exe": "node scripts/build-reference-exe.mjs", - "prepublishOnly": "npm run build && npm test", + "assert-vendor": "node scripts/assert-vendor.mjs", + "prepublishOnly": "npm run build && npm test && npm run assert-vendor", "test": "vitest run", "test:watch": "vitest" }, @@ -27,6 +29,7 @@ "license": "Apache-2.0", "files": [ "dist/src", + "vendor/piskel-prod", "skills", "README.md", "LICENSE", diff --git a/scripts/assert-vendor.mjs b/scripts/assert-vendor.mjs new file mode 100644 index 0000000..0f30803 --- /dev/null +++ b/scripts/assert-vendor.mjs @@ -0,0 +1,33 @@ +#!/usr/bin/env node +/** + * Ensures vendor/piskel-prod exists so `npm pack` / `npm publish` ships the + * bundled Piskel web app (required for `piskel-cli serve`). + * + * Run: node scripts/assert-vendor.mjs + */ + +import { existsSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const indexHtml = path.join(root, "vendor", "piskel-prod", "index.html"); + +if (!existsSync(indexHtml)) { + console.error( + [ + "Missing bundled Piskel editor: vendor/piskel-prod/index.html", + "", + "Publish would ship a package where `piskel-cli serve` cannot run.", + "From a built piskel clone (npm install && npm run build), run:", + "", + " npm run sync-piskel-vendor", + "", + "Or: PISKEL_ROOT=/path/to/piskel npm run sync-piskel-vendor", + "", + ].join("\n"), + ); + process.exit(1); +} + +console.log("OK: vendor/piskel-prod is present."); diff --git a/scripts/sync-piskel-vendor.mjs b/scripts/sync-piskel-vendor.mjs new file mode 100644 index 0000000..ce1f2c1 --- /dev/null +++ b/scripts/sync-piskel-vendor.mjs @@ -0,0 +1,102 @@ +#!/usr/bin/env node +/** + * Copies piskelapp/piskel `dest/prod` into vendor/piskel-prod and injects a small + * script so `index.html?load=/path-on-server` can fetch and open a .piskel JSON. + * + * Usage: + * node scripts/sync-piskel-vendor.mjs + * PISKEL_ROOT=/path/to/piskel node scripts/sync-piskel-vendor.mjs + * + * Requires: upstream `npm install && npm run build` so dest/prod exists. + */ + +import { cp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const REPO_ROOT = path.resolve(__dirname, ".."); +const DEST_VENDOR = path.join(REPO_ROOT, "vendor", "piskel-prod"); + +const PISKEL_ROOT = process.env.PISKEL_ROOT + ? path.resolve(process.env.PISKEL_ROOT) + : path.resolve(REPO_ROOT, "..", "piskel"); + +const SRC_PROD = path.join(PISKEL_ROOT, "dest", "prod"); + +const BRIDGE_MARKER = ""; + +const BRIDGE_SCRIPT = ` ${BRIDGE_MARKER} + +`; + +function injectBridge(html) { + if (html.includes(BRIDGE_MARKER)) { + return html; + } + const normalized = html.replace(/\r\n/g, "\n"); + const anchor = ' + + + +
+
+
+
+
    +
    +
    +
    +
    + +
    + +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    + 1x +
    +
    +
    + Full +
    +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    + + +
    +
    +
    + +
    +

    + Layers +
    +

    +
    + + + + + + + + + + + +
    + +
      + + + + +
      + +
      +

      + Transform + +

      +
        +
        + +
        +

        Palettes

        +
        + + + +
        +
        + + + +
        + +
        +
        +
        + +
        +
        +
        +
        + +
        + +
        + +
        + +
        +
        + +
        +
        +
        +
        +
        +
        + + +
        +
        +
        +
        + +
        + + + + + + + + + + +
        + +
        + +
        + +
        + +
        + + +   + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/piskel-prod/js/lib/gif/gif.ie.worker.js b/vendor/piskel-prod/js/lib/gif/gif.ie.worker.js new file mode 100644 index 0000000..b6150c9 --- /dev/null +++ b/vendor/piskel-prod/js/lib/gif/gif.ie.worker.js @@ -0,0 +1 @@ +(function(b){function a(b,d){if({}.hasOwnProperty.call(a.cache,b))return a.cache[b];var e=a.resolve(b);if(!e)throw new Error('Failed to resolve module '+b);var c={id:b,require:a,filename:b,exports:{},loaded:!1,parent:d,children:[]};d&&d.children.push(c);var f=b.slice(0,b.lastIndexOf('/')+1);return a.cache[b]=c.exports,e.call(c.exports,c,c.exports,f,b),c.loaded=!0,a.cache[b]=c.exports}a.modules={},a.cache={},a.resolve=function(b){return{}.hasOwnProperty.call(a.modules,b)?a.modules[b]:void 0},a.define=function(b,c){a.modules[b]=c},a.define('/gif.worker.coffee',function(d,e,f,g){var b,c;b=a('/GIFEncoder.js',d),c=function(a){var c,e,d,f;return c=new b(a.width,a.height),a.index===0?c.writeHeader():c.firstFrame=!1,c.setTransparent(a.transparent),c.setRepeat(a.repeat),c.setDelay(a.delay),c.setQuality(a.quality),c.setPreserveColors(a.preserveColors),c.addFrame(a.data),a.last&&c.finish(),d=c.stream(),a.data=d.pages,a.cursor=d.cursor,a.pageSize=d.constructor.pageSize,a.canTransfer?(f=function(c){for(var b=0,d=a.data.length;b=c.pageSize&&this.newPage(),this.pages[this.page][this.cursor++]=a},c.prototype.writeUTFBytes=function(b){for(var c=b.length,a=0;a=0&&(this.dispose=a)},b.prototype.setRepeat=function(a){this.repeat=a},b.prototype.setTransparent=function(a){this.transparent=a},b.prototype.setPreserveColors=function(a){this.preserveColors=a},b.prototype.addFrame=function(a){this.image=a,this.getImagePixels(),this.analyzePixels(),this.firstFrame&&(this.writeLSD(),this.writePalette(),this.repeat>=0&&this.writeNetscapeExt()),this.writeGraphicCtrlExt(),this.writeImageDesc(),this.firstFrame||this.writePalette(),this.writePixels(),this.firstFrame=!1},b.prototype.finish=function(){this.out.writeByte(59)},b.prototype.setQuality=function(a){a<1&&(a=1),this.sample=a},b.prototype.writeHeader=function(){this.out.writeUTFBytes('GIF89a')},b.prototype.analyzePixels=function(){var h=this.pixels.length,d=h/3;this.indexedPixels=new Uint8Array(d);var a;if(this.preserveColors){var i=this.toRGBComponents(this.transparent);a=new g(this.pixels,this.sample,i)}else a=new f(this.pixels,this.sample);a.buildColormap(),this.colorTab=a.getColormap();var b=0;for(var c=0;c>16,g:(a&65280)>>8,b:a&255}),b},b.prototype.findClosest=function(e){if(this.colorTab===null)return-1;var k=(e&16711680)>>16,l=(e&65280)>>8,m=e&255,c=0,d=16777216,j=this.colorTab.length;for(var a=0;a=0&&(a=dispose&7),a<<=2,this.out.writeByte(0|a|0|b),this.writeShort(this.delay),this.out.writeByte(this.transIndex),this.out.writeByte(0)},b.prototype.writeImageDesc=function(){this.out.writeByte(44),this.writeShort(0),this.writeShort(0),this.writeShort(this.width),this.writeShort(this.height),this.firstFrame?this.out.writeByte(0):this.out.writeByte(128|this.palSize)},b.prototype.writeLSD=function(){this.writeShort(this.width),this.writeShort(this.height),this.out.writeByte(240|this.palSize),this.out.writeByte(0),this.out.writeByte(0)},b.prototype.writeNetscapeExt=function(){this.out.writeByte(33),this.out.writeByte(255),this.out.writeByte(11),this.out.writeUTFBytes('NETSCAPE2.0'),this.out.writeByte(3),this.out.writeByte(1),this.writeShort(this.repeat),this.out.writeByte(0)},b.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);var b=768-this.colorTab.length;for(var a=0;a>8&255)},b.prototype.writePixels=function(){var a=new h(this.width,this.height,this.indexedPixels,this.colorDepth);a.encode(this.out)},b.prototype.stream=function(){return this.out},e.exports=b}),a.define('/LZWEncoder.js',function(e,g,h,i){function f(y,D,C,B){function w(a,b){r[f++]=a,f>=254&&t(b)}function x(b){u(a),k=i+2,j=!0,l(i,b)}function u(b){for(var a=0;a=0){y=w-d,d===0&&(y=1);do if((d-=y)<0&&(d+=w),h[d]===g){e=n[d];continue a}while(h[d]>=0)}l(e,r),e=t,k<1<0&&(a.writeByte(f),a.writeBytes(r,0,f),f=0)}function p(a){return(1<0?g|=a<=8)w(g&255,c),g>>=8,e-=8;if((k>m||j)&&(j?(m=p(n_bits=q),j=!1):(++n_bits,n_bits==b?m=1<0)w(g&255,c),g>>=8,e-=8;t(c)}}var s=Math.max(2,B),r=new Uint8Array(256),h=new Int32Array(a),n=new Int32Array(a),g,e=0,f,k=0,m,j=!1,q,i,o;this.encode=z}var c=-1,b=12,a=5003,d=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];e.exports=f}),a.define('/SimpleQuant.js',function(b,d,e,f){function a(a,b,c){return[a,b,c].join('.')}function c(c,d,b){this.pixels=c,this.palette=[],this.paletteIndex={},this.getColormap=function(){return this.palette},this.buildColormap=function(){var d=this.pixels.length/3,a=0;for(var c=0;c>3);var c,d;for(c=0;c>=b,o[c][1]>>=b,o[c][2]>>=b,o[c][3]=c}function K(b,a,c,e,f){o[a][0]-=b*(o[a][0]-c)/d,o[a][1]-=b*(o[a][1]-e)/d,o[a][2]-=b*(o[a][2]-f)/d}function L(j,e,n,l,k){var h=Math.abs(e-j),i=Math.min(e+j,a),g=e+1,f=e-1,m=1,b,d;while(gh)d=z[m++],gh&&(b=o[f--],b[0]-=d*(b[0]-n)/c,b[1]-=d*(b[1]-l)/c,b[2]-=d*(b[2]-k)/c)}function C(p,s,q){var h=2147483647,k=h,d=-1,m=d,c,j,e,n,l;for(c=0;c>i-b),n>g,y[c]-=l,t[c]+=l<>1,b=f+1;b>1,b=f+1;b<256;b++)q[b]=n}function E(j,i,k){var b,d,c,e=1e3,h=-1,f=q[i],g=f-1;while(f=0)f=e?f=a:(f++,c<0&&(c=-c),b=d[0]-j,b<0&&(b=-b),c+=b,c=0&&(d=o[g],c=i-d[1],c>=e?g=-1:(g--,c<0&&(c=-c),b=d[0]-j,b<0&&(b=-b),c+=b,c>h;for(a<=1&&(a=0),c=0;c=f&&(g-=f),c++,q===0&&(q=1),c%q===0)for(n-=n/D,o-=o/v,a=o>>h,a<=1&&(a=0),e=0;e>g,r=e<>3,h=6,t=1< to avoid XSS via location.hash (#9521) + rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/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(); + }, + + // The ready event handler and self cleanup method + DOMContentLoaded = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + } else if ( document.readyState === "complete" ) { + // we're here because readyState === "complete" in oldIE + // which is good enough for us to call the dom ready! + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( 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; + doc = ( context && context.nodeType ? context.ownerDocument || context : document ); + + // scripts is true for back-compat + selector = jQuery.parseHTML( match[1], doc, true ); + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + this.attr.call( selector, context, true ); + } + + return jQuery.merge( this, selector ); + + // 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 ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we 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: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.8.0", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_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 a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // 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 ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ), + "slice", core_slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +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; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( 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({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // 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; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // 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.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // 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 || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ core_toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // scripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, scripts ) { + var parsed; + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + scripts = context; + context = 0; + } + context = context || document; + + // Single tag + if ( (parsed = rsingleTag.exec( data )) ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); + return jQuery.merge( [], + (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); + }, + + parseJSON: function( data ) { + if ( !data || typeof data !== "string") { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && core_rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // 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.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var name, + i = 0, + length = obj.length, + isObj = length === undefined || jQuery.isFunction( obj ); + + if ( args ) { + if ( isObj ) { + for ( name in obj ) { + if ( callback.apply( obj[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( obj[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in obj ) { + if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var type, + ret = results || []; + + if ( arr != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + type = jQuery.type( arr ); + + if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { + core_push.call( ret, arr ); + } else { + jQuery.merge( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, + ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.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 = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context, args.concat( core_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 || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, pass ) { + var exec, + bulk = key == null, + i = 0, + length = elems.length; + + // Sets many values + if ( key && typeof key === "object" ) { + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); + } + chainable = 1; + + // Sets one value + } else if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = pass === undefined && jQuery.isFunction( value ); + + if ( bulk ) { + // Bulk operations only iterate when executing function values + if ( exec ) { + exec = fn; + fn = function( elem, key, value ) { + return exec.call( jQuery( elem ), value ); + }; + + // Otherwise they run against the entire set + } else { + fn.call( elems, value ); + fn = null; + } + } + + if ( fn ) { + for (; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + } + + chainable = 1; + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" || ( document.readyState !== "loading" && document.addEventListener ) ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready, 1 ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// 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.split( core_rspace ), 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 ) { + if ( jQuery.isFunction( arg ) && ( !options.unique || !self.has( arg ) ) ) { + list.push( arg ); + } else if ( arg && arg.length ) { + // 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; + }, + // Control if a given callback is in the list + has: function( fn ) { + return jQuery.inArray( fn, list ) > -1; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + 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 ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + 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 action = tuple[ 0 ], + fn = fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? + function() { + var returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + } : + newDefer[ action ] + ); + }); + 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 typeof obj === "object" ? 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 ] = list.fire + deferred[ tuple[0] ] = list.fire; + 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 = core_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 ? core_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(); + } +}); +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + fragment, + eventName, + i, + isSupported, + clickFn, + div = document.createElement("div"); + + // Preliminary tests + div.setAttribute( "className", "t" ); + div.innerHTML = "
        a"; + + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + a.style.cssText = "top:1px;float:left;opacity:.5"; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: ( document.compatMode === "CSS1Compat" ), + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // 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; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", clickFn = function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent("onclick"); + div.detachEvent( "onclick", clickFn ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + input.setAttribute( "checked", "checked" ); + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for ( i in { + submit: true, + change: true, + focusin: true + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + // Run tests that need a body at doc ready + jQuery(function() { + var container, div, tds, marginDiv, + divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
        t
        "; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // NOTE: To any future maintainer, window.getComputedStyle was used here + // instead of getComputedStyle because it gave a better gzip size. + // The difference between window.getComputedStyle and getComputedStyle is + // 7 bytes + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = document.createElement("div"); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = "block"; + div.style.overflow = "visible"; + div.innerHTML = "
        "; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + container.style.zoom = 1; + } + + // Null elements to avoid leaks in IE + body.removeChild( container ); + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + fragment.removeChild( div ); + all = a = select = opt = input = fragment = div = null; + + return support; +})(); +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + deletedIds: [], + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = jQuery.deletedIds.pop() || ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, part, attr, name, l, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attr = elem.attributes; + for ( l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split( ".", 2 ); + parts[1] = parts[1] ? "." + parts[1] : ""; + part = parts[1] + "!"; + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + data = this.triggerHandler( "getData" + part, [ parts[0] ] ); + + // Try to fetch any internally stored data first + if ( data === undefined && elem ) { + data = jQuery.data( elem, key ); + data = dataAttr( elem, key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } + + parts[1] = value; + this.each(function() { + var self = jQuery( this ); + + self.triggerHandler( "setData" + part, parts ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + part, parts ); + }); + }, null, value, arguments.length > 1, null, false ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var 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 + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + 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(); + } + + 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 ( !queue.length && 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 jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery.removeData( elem, type + "queue", true ); + jQuery.removeData( elem, key, true ); + }) + }); + } +}); + +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 ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + 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 ); + }; + }); + }, + 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-- ) { + if ( (tmp = jQuery._data( elements[ i ], type + "queueHooks" )) && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, fixSpecified, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea|)$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var removes, className, elem, c, cl, i, l; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + if ( (value && typeof value === "string") || value === undefined ) { + removes = ( value || "" ).split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + if ( elem.nodeType === 1 && elem.className ) { + + className = (" " + elem.className + " ").replace( rclass, " " ); + + // loop over each item in the removal list + for ( c = 0, cl = removes.length; c < cl; c++ ) { + // Remove until there is nothing to remove, + while ( className.indexOf(" " + removes[ c ] + " ") > -1 ) { + className = className.replace( " " + removes[ c ] + " " , " " ); + } + } + elem.className = value ? jQuery.trim( className ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + 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 ), + state = stateVal, + classNames = value.split( core_rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( 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 ) > -1 ) { + return true; + } + } + + return false; + }, + + 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, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.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 ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.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 ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 + attrFn: {}, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, isBool, + i = 0; + + if ( value && elem.nodeType === 1 ) { + + attrNames = value.split( core_rspace ); + + for ( ; i < attrNames.length; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + isBool = rboolean.test( name ); + + // See #9699 for explanation of this approach (setting first, then removal) + // Do not do this for boolean attributes (see #10870) + if ( !isBool ) { + jQuery.attr( elem, name, "" ); + } + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( isBool && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.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 it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + 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 ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true, + coords: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.value = value + "" ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, + rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + 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 + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = 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 !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // 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: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + 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; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var t, tns, type, origType, namespaces, origCount, + j, events, special, eventType, handleObj, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // 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; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.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 ( eventType.length === 0 && origCount !== eventType.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; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, "events", true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, + type = event.type || event, + namespaces = []; + + // 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 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // 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 ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( 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) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + for ( old = elem; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old === (elem.ownerDocument || document) ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === 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( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + 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 ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related, + handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments ), + run_all = !event.exclusive && !event.namespace, + special = jQuery.event.special[ event.type ] || {}, + handlerQueue = []; + + // 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 that should run if there are delegated events + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery(this); + jqcur.context = this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + + // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #xxxx) + if ( cur.disabled !== true || event.type !== "click" ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = jqcur.is( sel ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( 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; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement 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 fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // 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 relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // 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, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) + event.metaKey = !!event.metaKey; + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + 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(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 – + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === "undefined" ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +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.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? 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; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector; + + // 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; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "_submit_attached" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "_submit_attached", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "_change_attached", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +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" ) { // && selector != null + // ( 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 ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + 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 ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +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 ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var cachedruns, + dirruns, + sortOrder, + siblingCheck, + assertGetIdNotName, + + document = window.document, + docElem = document.documentElement, + + strundefined = "undefined", + hasDuplicate = false, + baseHasDuplicate = true, + done = 0, + slice = [].slice, + push = [].push, + + expando = ( "sizcache" + Math.random() ).replace( ".", "" ), + + // Regex + + // 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#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|((?:[^,]|\\\\,|(?:,(?=[^\\[]*\\]))|(?:,(?=[^\\(]*\\))))*))\\)|)", + pos = ":(nth|eq|gt|lt|first|last|even|odd)(?:\\((\\d*)\\)|)(?=[^-]|$)", + combinators = whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*", + groups = "(?=[^\\x20\\t\\r\\n\\f])(?:\\\\.|" + attributes + "|" + pseudos.replace( 2, 7 ) + "|[^\\\\(),])+", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcombinators = new RegExp( "^" + combinators ), + + // All simple (non-comma) selectors, excluding insignifant trailing whitespace + rgroups = new RegExp( groups + "?(?=" + whitespace + "*,|$)", "g" ), + + // A selector, or everything after leading whitespace + // Optionally followed in either case by a ")" for terminating sub-selectors + rselector = new RegExp( "^(?:(?!,)(?:(?:^|,)" + whitespace + "*" + groups + ")*?|" + whitespace + "*(.*?))(\\)|$)" ), + + // All combinators and selector components (attribute test, tag, pseudo, etc.), the latter appearing together when consecutive + rtokens = new RegExp( groups.slice( 19, -6 ) + "\\x20\\t\\r\\n\\f>+~])+|" + combinators, "g" ), + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, + + rsibling = /[\x20\t\r\n\f]*[+~]/, + rendsWithNot = /:not\($/, + + rheader = /h\d/i, + rinputs = /input|select|textarea|button/i, + + rbackslash = /\\(?!\\)/g, + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "[-", "[-\\*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|nth|last|first)-child(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "POS": new RegExp( pos, "ig" ), + // For use in libraries implementing .is() + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) + }, + + classCache = {}, + cachedClasses = [], + compilerCache = {}, + cachedSelectors = [], + + // Mark a function for use in filtering + markFunction = function( fn ) { + fn.sizzleFilter = true; + return fn; + }, + + // Returns a function to use in pseudos for input types + createInputFunction = function( type ) { + return function( elem ) { + // Check the input's nodeName and type + return elem.nodeName.toLowerCase() === "input" && elem.type === type; + }; + }, + + // Returns a function to use in pseudos for buttons + createButtonFunction = function( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; + }, + + // Used for testing something on an element + assert = function( fn ) { + var pass = false, + div = document.createElement("div"); + try { + pass = fn( div ); + } catch (e) {} + // release memory in IE + div = null; + return pass; + }, + + // Check if attributes should be retrieved by attribute nodes + assertAttributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }), + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + assertUsableName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
        "; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = document.getElementsByName && + // buggy browsers will return fewer than the correct 2 + document.getElementsByName( expando ).length === + // buggy browsers will return more than the correct 0 + 2 + document.getElementsByName( expando + 0 ).length; + assertGetIdNotName = !document.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }), + + // Check if the browser returns only elements + // when doing getElementsByTagName("*") + assertTagNameNoComments = assert(function( div ) { + div.appendChild( document.createComment("") ); + return div.getElementsByTagName("*").length === 0; + }), + + // Check if getAttribute returns normalized href attributes + assertHrefNotNormalized = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }), + + // Check if getElementsByClassName can be trusted + assertUsableClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return false; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length !== 1; + }); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + var match, elem, xml, m, + nodeType = context.nodeType; + + if ( nodeType !== 1 && nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + xml = isXML( context ); + + if ( !xml && !seed ) { + 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 #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, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + } + + // All others + return select( selector, context, results, seed, xml ); +}; + +var Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + match: matchExpr, + + order: [ "ID", "TAG" ], + + attrHandle: {}, + + createPseudo: markFunction, + + find: { + "ID": assertGetIdNotName ? + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + 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] : []; + } + } : + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }, + + "TAG": assertTagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + var elem, + tmp = [], + i = 0; + + for ( ; (elem = results[i]); i++ ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + } + }, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( rbackslash, "" ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr.CHILD + 1 type (only|nth|...) + 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 3 xn-component of xn+y argument ([+-]?\d*n|) + 4 sign of xn-component + 5 x of xn-component + 6 sign of y-component + 7 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1] === "nth" ) { + // nth-child requires argument + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); + match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); + + // other types prohibit arguments + } else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var argument, + unquoted = match[4]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Relinquish our claim on characters in `unquoted` from a closing parenthesis on + if ( unquoted && (argument = rselector.exec( unquoted )) && argument.pop() ) { + + match[0] = match[0].slice( 0, argument[0].length - unquoted.length - 1 ); + unquoted = argument[0].slice( 0, -1 ); + } + + // Quoted or unquoted, we have the full argument + // Return only captures needed by the pseudo filter method (type and argument) + match.splice( 2, 3, unquoted || match[3] ); + return match; + } + }, + + filter: { + "ID": assertGetIdNotName ? + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + return elem.getAttribute("id") === id; + }; + } : + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === id; + }; + }, + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); + + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className ]; + if ( !pattern ) { + pattern = classCache[ className ] = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ); + cachedClasses.push( className ); + // Avoid too large of a cache + if ( cachedClasses.length > Expr.cacheLength ) { + delete classCache[ cachedClasses.shift() ]; + } + } + return function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }; + }, + + "ATTR": function( name, operator, check ) { + if ( !operator ) { + return function( elem ) { + return Sizzle.attr( elem, name ) != null; + }; + } + + return function( elem ) { + var result = Sizzle.attr( elem, name ), + value = result + ""; + + if ( result == null ) { + return operator === "!="; + } + + switch ( operator ) { + case "=": + return value === check; + case "!=": + return value !== check; + case "^=": + return check && value.indexOf( check ) === 0; + case "*=": + return check && value.indexOf( check ) > -1; + case "$=": + return check && value.substr( value.length - check.length ) === check; + case "~=": + return ( " " + value + " " ).indexOf( check ) > -1; + case "|=": + return value === check || value.substr( 0, check.length + 1 ) === check + "-"; + } + }; + }, + + "CHILD": function( type, argument, first, last ) { + + if ( type === "nth" ) { + var doneName = done++; + + return function( elem ) { + var parent, diff, + count = 0, + node = elem; + + if ( first === 1 && last === 0 ) { + return true; + } + + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.sizset) ) { + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.sizset = ++count; + if ( node === elem ) { + break; + } + } + } + + parent[ expando ] = doneName; + } + + diff = elem.sizset - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + }; + } + + return function( elem ) { + var node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + /* falls through */ + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + } + }; + }, + + "PSEUDO": function( pseudo, argument, context, xml ) { + // 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 + var fn = Expr.pseudos[ pseudo ] || Expr.pseudos[ pseudo.toLowerCase() ]; + + if ( !fn ) { + Sizzle.error( "unsupported pseudo: " + pseudo ); + } + + // The user may set fn.sizzleFilter to indicate + // that arguments are needed to create the filter function + // just as Sizzle does + if ( !fn.sizzleFilter ) { + return fn; + } + + return fn( argument, context, xml ); + } + }, + + pseudos: { + "not": markFunction(function( selector, context, xml ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var matcher = compile( selector.replace( rtrim, "$1" ), context, xml ); + return function( elem ) { + return !matcher( elem ); + }; + }), + + "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; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + var nodeType; + elem = elem.firstChild; + while ( elem ) { + if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { + return false; + } + elem = elem.nextSibling; + } + return true; + }, + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "text": function( elem ) { + var type, attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + (type = elem.type) === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); + }, + + // Input types + "radio": createInputFunction("radio"), + "checkbox": createInputFunction("checkbox"), + "file": createInputFunction("file"), + "password": createInputFunction("password"), + "image": createInputFunction("image"), + + "submit": createButtonFunction("submit"), + "reset": createButtonFunction("reset"), + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "focus": function( elem ) { + var doc = elem.ownerDocument; + return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); + }, + + "active": function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + + setFilters: { + "first": function( elements, argument, not ) { + return not ? elements.slice( 1 ) : [ elements[0] ]; + }, + + "last": function( elements, argument, not ) { + var elem = elements.pop(); + return not ? elements : [ elem ]; + }, + + "even": function( elements, argument, not ) { + var results = [], + i = not ? 1 : 0, + len = elements.length; + for ( ; i < len; i = i + 2 ) { + results.push( elements[i] ); + } + return results; + }, + + "odd": function( elements, argument, not ) { + var results = [], + i = not ? 0 : 1, + len = elements.length; + for ( ; i < len; i = i + 2 ) { + results.push( elements[i] ); + } + return results; + }, + + "lt": function( elements, argument, not ) { + return not ? elements.slice( +argument ) : elements.slice( 0, +argument ); + }, + + "gt": function( elements, argument, not ) { + return not ? elements.slice( 0, +argument + 1 ) : elements.slice( +argument + 1 ); + }, + + "eq": function( elements, argument, not ) { + var elem = elements.splice( +argument, 1 ); + return not ? elements : elem; + } + } +}; + +// Deprecated +Expr.setFilters["nth"] = Expr.setFilters["eq"]; + +// Back-compat +Expr.filters = Expr.pseudos; + +// IE6/7 return a modified href +if ( !assertHrefNotNormalized ) { + Expr.attrHandle = { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }; +} + +// Add getElementsByName if usable +if ( assertUsableName ) { + Expr.order.push("NAME"); + Expr.find["NAME"] = function( name, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }; +} + +// Add getElementsByClassName if usable +if ( assertUsableClassName ) { + Expr.order.splice( 1, 0, "CLASS" ); + Expr.find["CLASS"] = function( className, context, xml ) { + if ( typeof context.getElementsByClassName !== strundefined && !xml ) { + return context.getElementsByClassName( className ); + } + }; +} + +// If slice is not available, provide a backup +try { + slice.call( docElem.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, results = []; + for ( ; (elem = this[i]); i++ ) { + results.push( elem ); + } + return results; + }; +} + +var 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; +}; + +// Element contains another +var contains = Sizzle.contains = docElem.compareDocumentPosition ? + function( a, b ) { + return !!( a.compareDocumentPosition( b ) & 16 ); + } : + docElem.contains ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); + } : + function( a, b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + return false; + }; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #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 + } else { + + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } + return ret; +}; + +Sizzle.attr = function( elem, name ) { + var attr, + xml = isXML( elem ); + + if ( !xml ) { + name = name.toLowerCase(); + } + if ( Expr.attrHandle[ name ] ) { + return Expr.attrHandle[ name ]( elem ); + } + if ( assertAttributes || xml ) { + return elem.getAttribute( name ); + } + attr = elem.getAttributeNode( name ); + return attr ? + typeof elem[ name ] === "boolean" ? + elem[ name ] ? name : null : + attr.specified ? attr.value : null : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +// Check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + return (baseHasDuplicate = 0); +}); + + +if ( docElem.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? + a.compareDocumentPosition : + a.compareDocumentPosition(b) & 4 + ) ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + i = 1; + + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +function multipleContexts( selector, contexts, results, seed ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results, seed ); + } +} + +function handlePOSGroup( selector, posfilter, argument, contexts, seed, not ) { + var results, + fn = Expr.setFilters[ posfilter.toLowerCase() ]; + + if ( !fn ) { + Sizzle.error( posfilter ); + } + + if ( selector || !(results = seed) ) { + multipleContexts( selector || "*", contexts, (results = []), seed ); + } + + return results.length > 0 ? fn( results, argument, not ) : []; +} + +function handlePOS( selector, context, results, seed, groups ) { + var match, not, anchor, ret, elements, currentContexts, part, lastIndex, + i = 0, + len = groups.length, + rpos = matchExpr["POS"], + // This is generated here in case matchExpr["POS"] is extended + rposgroups = new RegExp( "^" + rpos.source + "(?!" + whitespace + ")", "i" ), + // This is for making sure non-participating + // matching groups are represented cross-browser (IE6-8) + setUndefined = function() { + var i = 1, + len = arguments.length - 2; + for ( ; i < len; i++ ) { + if ( arguments[i] === undefined ) { + match[i] = undefined; + } + } + }; + + for ( ; i < len; i++ ) { + // Reset regex index to 0 + rpos.exec(""); + selector = groups[i]; + ret = []; + anchor = 0; + elements = seed; + while ( (match = rpos.exec( selector )) ) { + lastIndex = rpos.lastIndex = match.index + match[0].length; + if ( lastIndex > anchor ) { + part = selector.slice( anchor, match.index ); + anchor = lastIndex; + currentContexts = [ context ]; + + if ( rcombinators.test(part) ) { + if ( elements ) { + currentContexts = elements; + } + elements = seed; + } + + if ( (not = rendsWithNot.test( part )) ) { + part = part.slice( 0, -5 ).replace( rcombinators, "$&*" ); + } + + if ( match.length > 1 ) { + match[0].replace( rposgroups, setUndefined ); + } + elements = handlePOSGroup( part, match[1], match[2], currentContexts, elements, not ); + } + } + + if ( elements ) { + ret = ret.concat( elements ); + + if ( (part = selector.slice( anchor )) && part !== ")" ) { + if ( rcombinators.test(part) ) { + multipleContexts( part, ret, results, seed ); + } else { + Sizzle( part, context, results, seed ? seed.concat(elements) : elements ); + } + } else { + push.apply( results, ret ); + } + } else { + Sizzle( selector, context, results, seed ); + } + } + + // Do not sort if this is a single filter + return len === 1 ? results : Sizzle.uniqueSort( results ); +} + +function tokenize( selector, context, xml ) { + var tokens, soFar, type, + groups = [], + i = 0, + + // Catch obvious selector issues: terminal ")"; nonempty fallback match + // rselector never fails to match *something* + match = rselector.exec( selector ), + matched = !match.pop() && !match.pop(), + selectorGroups = matched && selector.match( rgroups ) || [""], + + preFilters = Expr.preFilter, + filters = Expr.filter, + checkContext = !xml && context !== document; + + for ( ; (soFar = selectorGroups[i]) != null && matched; i++ ) { + groups.push( tokens = [] ); + + // Need to make sure we're within a narrower context if necessary + // Adding a descendant combinator will generate what is needed + if ( checkContext ) { + soFar = " " + soFar; + } + + while ( soFar ) { + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + soFar = soFar.slice( match[0].length ); + + // Cast descendant combinators to space + matched = tokens.push({ part: match.pop().replace( rtrim, " " ), captures: match }); + } + + // Filters + for ( type in filters ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match, context, xml )) ) ) { + + soFar = soFar.slice( match.shift().length ); + matched = tokens.push({ part: type, captures: match }); + } + } + + if ( !matched ) { + break; + } + } + } + + if ( !matched ) { + Sizzle.error( selector ); + } + + return groups; +} + +function addCombinator( matcher, combinator, context ) { + var dir = combinator.dir, + doneName = done++; + + if ( !matcher ) { + // If there is no matcher to check, check against the context + matcher = function( elem ) { + return elem === context; + }; + } + return combinator.first ? + function( elem, context ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 ) { + return matcher( elem, context ) && elem; + } + } + } : + function( elem, context ) { + var cache, + dirkey = doneName + "." + dirruns, + cachedkey = dirkey + "." + cachedruns; + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 ) { + if ( (cache = elem[ expando ]) === cachedkey ) { + return elem.sizset; + } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { + if ( elem.sizset ) { + return elem; + } + } else { + elem[ expando ] = cachedkey; + if ( matcher( elem, context ) ) { + elem.sizset = true; + return elem; + } + elem.sizset = false; + } + } + } + }; +} + +function addMatcher( higher, deeper ) { + return higher ? + function( elem, context ) { + var result = deeper( elem, context ); + return result && higher( result === true ? elem : result, context ); + } : + deeper; +} + +// ["TAG", ">", "ID", " ", "CLASS"] +function matcherFromTokens( tokens, context, xml ) { + var token, matcher, + i = 0; + + for ( ; (token = tokens[i]); i++ ) { + if ( Expr.relative[ token.part ] ) { + matcher = addCombinator( matcher, Expr.relative[ token.part ], context ); + } else { + token.captures.push( context, xml ); + matcher = addMatcher( matcher, Expr.filter[ token.part ].apply( null, token.captures ) ); + } + } + + return matcher; +} + +function matcherFromGroupMatchers( matchers ) { + return function( elem, context ) { + var matcher, + j = 0; + for ( ; (matcher = matchers[j]); j++ ) { + if ( matcher(elem, context) ) { + return true; + } + } + return false; + }; +} + +var compile = Sizzle.compile = function( selector, context, xml ) { + var tokens, group, i, + cached = compilerCache[ selector ]; + + // Return a cached group function if already generated (context dependent) + if ( cached && cached.context === context ) { + return cached; + } + + // Generate a function of recursive functions that can be used to check each element + group = tokenize( selector, context, xml ); + for ( i = 0; (tokens = group[i]); i++ ) { + group[i] = matcherFromTokens( tokens, context, xml ); + } + + // Cache the compiled function + cached = compilerCache[ selector ] = matcherFromGroupMatchers( group ); + cached.context = context; + cached.runs = cached.dirruns = 0; + cachedSelectors.push( selector ); + // Ensure only the most recent are cached + if ( cachedSelectors.length > Expr.cacheLength ) { + delete compilerCache[ cachedSelectors.shift() ]; + } + return cached; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + return Sizzle( expr, null, null, [ elem ] ).length > 0; +}; + +var select = function( selector, context, results, seed, xml ) { + // Remove excessive whitespace + selector = selector.replace( rtrim, "$1" ); + var elements, matcher, i, len, elem, token, + type, findContext, notTokens, + match = selector.match( rgroups ), + tokens = selector.match( rtokens ), + contextNodeType = context.nodeType; + + // POS handling + if ( matchExpr["POS"].test(selector) ) { + return handlePOS( selector, context, results, seed, match ); + } + + if ( seed ) { + elements = slice.call( seed, 0 ); + + // To maintain document order, only narrow the + // set if there is one group + } else if ( match && match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + if ( tokens.length > 1 && contextNodeType === 9 && !xml && + (match = matchExpr["ID"].exec( tokens[0] )) ) { + + context = Expr.find["ID"]( match[1], context, xml )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().length ); + } + + findContext = ( (match = rsibling.exec( tokens[0] )) && !match.index && context.parentNode ) || context; + + // Get the last token, excluding :not + notTokens = tokens.pop(); + token = notTokens.split(":not")[0]; + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = matchExpr[ type ].exec( token )) ) { + elements = Expr.find[ type ]( (match[1] || "").replace( rbackslash, "" ), findContext, xml ); + + if ( elements == null ) { + continue; + } + + if ( token === notTokens ) { + selector = selector.slice( 0, selector.length - notTokens.length ) + + token.replace( matchExpr[ type ], "" ); + + if ( !selector ) { + push.apply( results, slice.call(elements, 0) ); + } + } + break; + } + } + } + + // Only loop over the given elements once + // If selector is empty, we're already done + if ( selector ) { + matcher = compile( selector, context, xml ); + dirruns = matcher.dirruns++; + + if ( elements == null ) { + elements = Expr.find["TAG"]( "*", (rsibling.test( selector ) && context.parentNode) || context ); + } + for ( i = 0; (elem = elements[i]); i++ ) { + cachedruns = matcher.runs++; + if ( matcher(elem, context) ) { + results.push( elem ); + } + } + } + + return results; +}; + +if ( document.querySelectorAll ) { + (function() { + var disconnectedMatch, + oldSelect = select, + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + rbuggyQSA = [], + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + // A support test would require too much code (would include document ready) + // just skip matchesSelector for :active + rbuggyMatches = [":active"], + matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector; + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here (do not put tests after this one) + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE9 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = "

        "; + if ( div.querySelectorAll("[test^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here (do not put tests after this one) + div.innerHTML = ""; + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push(":enabled", ":disabled"); + } + }); + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + + select = function( selector, context, results, seed, xml ) { + // Only use querySelectorAll when not filtering, + // when this is not xml, + // and when no QSA bugs apply + if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + if ( context.nodeType === 9 ) { + try { + push.apply( results, slice.call(context.querySelectorAll( selector ), 0) ); + return results; + } catch(qsaError) {} + // 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 + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var old = context.getAttribute("id"), + nid = old || expando, + newContext = rsibling.test( selector ) && context.parentNode || context; + + if ( old ) { + nid = nid.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + + try { + push.apply( results, slice.call( newContext.querySelectorAll( + selector.replace( rgroups, "[id='" + nid + "'] $&" ) + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + + return oldSelect( selector, context, results, seed, xml ); + }; + + if ( matches ) { + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + try { + matches.call( div, "[test!='']:sizzle" ); + rbuggyMatches.push( Expr.match.PSEUDO ); + } catch ( e ) {} + }); + + // rbuggyMatches always contains :active, so no need for a length check + rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); + + Sizzle.matchesSelector = function( elem, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyMatches always contains :active, so no need for an existence check + if ( !isXML( elem ) && !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 || 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, null, null, [ elem ] ).length > 0; + }; + } + })(); +} + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +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; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, l, length, n, r, ret, + self = this; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + ret = this.pushStack( "", "find", selector ); + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // 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". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // 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.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && 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 jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /]", "i"), + rcheckableType = /^(?:checkbox|radio)$/, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /\/(java|ecma)script/i, + rcleanScript = /^\s*\s*$/g, + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
        ", "
        " ], + thead: [ 1, "", "
        " ], + tr: [ 2, "", "
        " ], + td: [ 3, "", "
        " ], + col: [ 2, "", "
        " ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, +// unless wrapped in a div with non-breaking characters in front of it. +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "X
        ", "
        " ]; +} + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + wrapAll: function( html ) { + 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 + var 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.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + 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(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); + } + }, + + after: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + 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 jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName( "*" ) ); + 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( value ) { + if ( !isDisconnected( this[0] ) ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery( value ).detach(); + } + + return this.each(function() { + var next = this.nextSibling, + parent = this.parentNode; + + jQuery( this ).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } + + return this.length ? + this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : + this; + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = [].concat.apply( [], args ); + + var results, first, fragment, iNoClone, + i = 0, + value = args[0], + scripts = [], + l = this.length; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call( this, i, table ? self.html() : undefined ); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + results = jQuery.buildFragment( args, this, scripts ); + fragment = results.fragment; + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + // Fragments from the fragment cache must always be cloned and never used in place. + for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + i === iNoClone ? + fragment : + jQuery.clone( fragment, true, true ) + ); + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + + if ( scripts.length ) { + jQuery.each( scripts, function( i, elem ) { + if ( elem.src ) { + if ( jQuery.ajax ) { + jQuery.ajax({ + url: elem.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.error("no ajax"); + } + } else { + jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + }); + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function cloneFixAttributes( src, dest ) { + var nodeName; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + // clearAttributes removes the attributes, which we don't want, + // but also removes the attachEvent events, which we *do* want + if ( dest.clearAttributes ) { + dest.clearAttributes(); + } + + // mergeAttributes, in contrast, only merges back on the + // original attributes, not the events + if ( dest.mergeAttributes ) { + dest.mergeAttributes( src ); + } + + nodeName = dest.nodeName.toLowerCase(); + + if ( nodeName === "object" ) { + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + + // IE blanks contents when cloning scripts + } else if ( nodeName === "script" && dest.text !== src.text ) { + dest.text = src.text; + } + + // Event data gets referenced instead of copied if the expando + // gets copied too + dest.removeAttribute( jQuery.expando ); +} + +jQuery.buildFragment = function( args, context, scripts ) { + var fragment, cacheable, cachehit, + first = args[ 0 ]; + + // Set context from what may come in as undefined or a jQuery collection or a node + context = context || document; + context = (context[0] || context).ownerDocument || context[0] || context; + + // Ensure that an attr object doesn't incorrectly stand in as a document object + // Chrome and Firefox seem to allow this to occur and will throw exception + // Fixes #8950 + if ( typeof context.createDocumentFragment === "undefined" ) { + context = document; + } + + // Only cache "small" (1/2 KB) HTML strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put or elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 + if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && + first.charAt(0) === "<" && !rnocache.test( first ) && + (jQuery.support.checkClone || !rchecked.test( first )) && + (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { + + // Mark cacheable and look for a hit + cacheable = true; + fragment = jQuery.fragments[ first ]; + cachehit = fragment !== undefined; + } + + if ( !fragment ) { + fragment = context.createDocumentFragment(); + jQuery.clean( args, context, fragment, scripts ); + + // Update the cache, but only store false + // unless this is a second parsing of the same content + if ( cacheable ) { + jQuery.fragments[ first ] = cachehit && fragment; + } + } + + return { fragment: fragment, cacheable: cacheable }; +}; + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + l = insert.length, + parent = this.length === 1 && this[0].parentNode; + + if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { + insert[ original ]( this[0] ); + return this; + } else { + for ( ; i < l; i++ ) { + elems = ( i > 0 ? this.clone(true) : this ).get(); + jQuery( insert[i] )[ original ]( elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +function getAll( elem ) { + if ( typeof elem.getElementsByTagName !== "undefined" ) { + return elem.getElementsByTagName( "*" ); + + } else if ( typeof elem.querySelectorAll !== "undefined" ) { + return elem.querySelectorAll( "*" ); + + } else { + return []; + } +} + +// Used in clean, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var srcElements, + destElements, + i, + clone; + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + // IE copies events bound via attachEvent when using cloneNode. + // Calling detachEvent on the clone will also remove the events + // from the original. In order to get around this, we use some + // proprietary methods to clear the events. Thanks to MooTools + // guys for this hotness. + + cloneFixAttributes( elem, clone ); + + // Using Sizzle here is crazy slow, so we use getElementsByTagName instead + srcElements = getAll( elem ); + destElements = getAll( clone ); + + // Weird iteration because IE will replace the length property + // with an element if you are cloning the body and one of the + // elements on the page has a name or id of "length" + for ( i = 0; srcElements[i]; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + cloneFixAttributes( srcElements[i], destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + cloneCopyEvent( elem, clone ); + + if ( deepDataAndEvents ) { + srcElements = getAll( elem ); + destElements = getAll( clone ); + + for ( i = 0; srcElements[i]; ++i ) { + cloneCopyEvent( srcElements[i], destElements[i] ); + } + } + } + + srcElements = destElements = null; + + // Return the cloned set + return clone; + }, + + clean: function( elems, context, fragment, scripts ) { + var j, safe, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, + i = 0, + ret = []; + + // Ensure that context is a document + if ( !context || typeof context.createDocumentFragment === "undefined" ) { + context = document; + } + + // Use the already-created safe fragment if context permits + for ( safe = context === document && safeFragment; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + if ( !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + } else { + // Ensure a safe container in which to render the html + safe = safe || createSafeFragment( context ); + div = div || safe.appendChild( context.createElement("div") ); + + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, "<$1>"); + + // Go to html and back, then peel off extra wrappers + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + depth = wrap[0]; + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted from table fragments + if ( !jQuery.support.tbody ) { + + // String was a , *may* have spurious + hasBody = rtbody.test(elem); + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare or + wrap[1] === "
        " && !hasBody ? + div.childNodes : + []; + + for ( j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + + // Remember the top-level container for proper cleanup + div = safe.lastChild; + } + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + ret = jQuery.merge( ret, elem ); + } + } + + // Fix #11356: Clear elements from safeFragment + if ( div ) { + safe.removeChild( div ); + elem = div = safe = null; + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + for ( i = 0; (elem = ret[i]) != null; i++ ) { + if ( jQuery.nodeName( elem, "input" ) ) { + fixDefaultChecked( elem ); + } else if ( typeof elem.getElementsByTagName !== "undefined" ) { + jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); + } + } + } + + // Append elements to a provided document fragment + if ( fragment ) { + // Special handling of each script element + handleScript = function( elem ) { + // Check if we consider it executable + if ( !elem.type || rscriptType.test( elem.type ) ) { + // Detach the script and store it in the scripts array (if provided) or the fragment + // Return truthy to indicate that it has been handled + return scripts ? + scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : + fragment.appendChild( elem ); + } + }; + + for ( i = 0; (elem = ret[i]) != null; i++ ) { + // Check if we're done after handling an executable script + if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { + // Append to fragment and handle embedded scripts + fragment.appendChild( elem ); + if ( typeof elem.getElementsByTagName !== "undefined" ) { + // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration + jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); + + // Splice the scripts into ret after their former ancestor and advance our index beyond them + ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); + i += jsTags.length; + } + } + } + } + + return ret; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var data, id, elem, type, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + 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 ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + jQuery.deletedIds.push( id ); + } + } + } + } + } +}); +// Limit scope pollution from any deprecated API +(function() { + +var matched, browser; + +// Use of jQuery.browser is frowned upon. +// More details: http://api.jquery.com/jQuery.browser +// jQuery.uaMatch maintained for back-compat +jQuery.uaMatch = function( ua ) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || + /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; +}; + +matched = jQuery.uaMatch( navigator.userAgent ); +browser = {}; + +if ( matched.browser ) { + browser[ matched.browser ] = true; + browser.version = matched.version; +} + +// Deprecated, use jQuery.browser.webkit instead +// Maintained for back-compat only +if ( browser.webkit ) { + browser.safari = true; +} + +jQuery.browser = browser; + +jQuery.sub = function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; +}; + +})(); +var curCSS, iframe, iframeDoc, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity=([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), + elemdisplay = {}, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400, + lineHeight: 1 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], + + eventsToggle = jQuery.fn.toggle; + +// 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.charAt(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 isHidden( elem, el ) { + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var elem, display, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + values[ index ] = jQuery._data( elem, "olddisplay" ); + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && elem.style.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 ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + display = curCSS( elem, "display" ); + + if ( !values[ index ] && display !== "none" ) { + jQuery._data( elem, "olddisplay", 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.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + 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, fn2 ) { + var bool = typeof state === "boolean"; + + if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { + return eventsToggle.apply( this, arguments ); + } + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +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; + + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": 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": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // 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 NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( 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"; + } + + // 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 ) { + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } 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, numeric, extra ) { + 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 ); + } + + //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 ( numeric || extra !== undefined ) { + num = parseFloat( val ); + return numeric || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + 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.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: To any future maintainer, we've used both window.getComputedStyle +// and getComputedStyle here to produce a better gzip size +if ( window.getComputedStyle ) { + curCSS = function( elem, name ) { + var ret, width, minWidth, maxWidth, + computed = getComputedStyle( elem, null ), + style = elem.style; + + if ( computed ) { + + ret = computed[ name ]; + if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (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 ) ) { + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + curCSS = function( elem, name ) { + var left, rsLeft, + ret = elem.currentStyle && elem.currentStyle[ name ], + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + elem.runtimeStyle.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + elem.runtimeStyle.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { + 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" ) { + // we use jQuery.css instead of curCSS here + // because of the reliableMarginRight CSS hook! + val += jQuery.css( elem, extra + cssExpand[ i ], true ); + } + + // From this point on we use curCSS for maximum performance (relevant in animations) + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } else { + // at this point, extra isn't content, so add padding + val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + valueIsBorderBox = true, + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; + + if ( val <= 0 ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name ); + 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 && ( jQuery.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 + ) + ) + "px"; +} + + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + if ( elemdisplay[ nodeName ] ) { + return elemdisplay[ nodeName ]; + } + + var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), + display = elem.css("display"); + elem.remove(); + + // If the simple way fails, + // get element's real default display by attaching it to a temp iframe + if ( display === "none" || display === "" ) { + // Use the already-created iframe if possible + iframe = document.body.appendChild( + iframe || jQuery.extend( document.createElement("iframe"), { + frameBorder: 0, + width: 0, + height: 0 + }) + ); + + // Create a cacheable copy of the iframe document on first call. + // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML + // document to it; WebKit & Firefox won't allow reusing the iframe document. + if ( !iframeDoc || !iframe.createElement ) { + iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; + iframeDoc.write(""); + iframeDoc.close(); + } + + elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); + + display = curCSS( elem, "display" ); + document.body.removeChild( iframe ); + } + + // Store the correct default display + elemdisplay[ nodeName ] = display; + + return display; +} + +jQuery.each([ "height", "width" ], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + if ( elem.offsetWidth !== 0 || curCSS( elem, "display" ) !== "none" ) { + return getWidthOrHeight( elem, name, extra ); + } else { + return jQuery.swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + }); + } + } + }, + + set: function( elem, value, extra ) { + return setPositiveNumber( elem, value, extra ? + augmentWidthOrHeight( + elem, + name, + extra, + jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" + ) : 0 + ); + } + }; +}); + +if ( !jQuery.support.opacity ) { + jQuery.cssHooks.opacity = { + get: function( elem, computed ) { + // IE uses filters for opacity + return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? + ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : + computed ? "1" : ""; + }, + + set: function( elem, value ) { + var style = elem.style, + currentStyle = elem.currentStyle, + opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", + filter = currentStyle && currentStyle.filter || style.filter || ""; + + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 + if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && + style.removeAttribute ) { + + // Setting style.filter to null, "" & " " still leave "filter:" in the cssText + // if "filter:" is present at all, clearType is disabled, we want to avoid this + // style.removeAttribute is IE Only, but so apparently is this code path... + style.removeAttribute( "filter" ); + + // if there there is no filter style applied in a css rule, we are done + if ( currentStyle && !currentStyle.filter ) { + return; + } + } + + // otherwise, set new filter values + style.filter = ralpha.test( filter ) ? + filter.replace( ralpha, opacity ) : + filter + " " + opacity; + } + }; +} + +// These hooks cannot be added until DOM ready because the support test +// for it is not run until after DOM ready +jQuery(function() { + if ( !jQuery.support.reliableMarginRight ) { + jQuery.cssHooks.marginRight = { + get: function( elem, 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" }, function() { + if ( computed ) { + return curCSS( elem, "marginRight" ); + } + }); + } + }; + } + + // 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 + if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { + jQuery.each( [ "top", "left" ], function( i, prop ) { + jQuery.cssHooks[ prop ] = { + get: function( elem, computed ) { + if ( computed ) { + var ret = curCSS( elem, prop ); + // if curCSS returns percentage, fallback to offset + return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; + } + } + }; + }); + } + +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} + +// 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, + + // assumes a single number if not a string + parts = typeof value === "string" ? value.split(" ") : [ value ], + expanded = {}; + + for ( i = 0; 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; + } +}); +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + rselectTextarea = /^(?:select|textarea)/i; + +jQuery.fn.extend({ + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map(function(){ + return this.elements ? jQuery.makeArray( this.elements ) : this; + }) + .filter(function(){ + return this.name && !this.disabled && + ( this.checked || rselectTextarea.test( this.nodeName ) || + rinput.test( this.type ) ); + }) + .map(function( i, elem ){ + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val, i ){ + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }).get(); + } +}); + +//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, "+" ); +}; + +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 { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + 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 ); + } +} +var // Document location + ajaxLocation, + // Document location segments + ajaxLocParts, + + rhash = /#.*$/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + rquery = /\?/, + rscript = /)<[^<]*)*<\/script>/gi, + rts = /([?&])_=[^&]*/, + rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, + + // Keep a copy of the old load method + _load = jQuery.fn.load, + + /* 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 = ["*/"] + ["*"]; + +// #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, list, placeBefore, + dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), + i = 0, + length = dataTypes.length; + + if ( jQuery.isFunction( func ) ) { + // For each dataType in the dataTypeExpression + for ( ; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var selection, + list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ); + + for ( ; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jqXHR ); + // If we got redirected to another dataType + // we try there if executing only and not done already + if ( typeof selection === "string" ) { + if ( !executeOnly || inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} + +// 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 ); + } +} + +jQuery.fn.load = function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + } + + // Don't do a request if no elements are being requested + if ( !this.length ) { + return this; + } + + var selector, type, response, + self = this, + off = url.indexOf(" "); + + if ( off >= 0 ) { + selector = url.slice( off, url.length ); + 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 ( typeof params === "object" ) { + type = "POST"; + } + + // Request the remote document + jQuery.ajax({ + url: url, + + // if "type" variable is undefined, then "GET" method will be used + type: type, + dataType: "html", + data: params, + complete: function( jqXHR, status ) { + if ( callback ) { + self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); + } + } + }).done(function( responseText ) { + + // Save response for use in complete callback + response = arguments; + + // See if a selector was specified + self.html( selector ? + + // Create a dummy div to hold the results + jQuery("
        ") + + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append( responseText.replace( rscript, "" ) ) + + // Locate the specified elements + .find( selector ) : + + // If not, just inject the full result + responseText ); + + }); + + return this; +}; + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ + jQuery.fn[ o ] = function( f ){ + return this.on( o, f ); + }; +}); + +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({ + type: method, + url: url, + data: data, + success: callback, + dataType: type + }); + }; +}); + +jQuery.extend({ + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + // 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 ) { + if ( settings ) { + // Building a settings object + ajaxExtend( target, jQuery.ajaxSettings ); + } else { + // Extending ajaxSettings + settings = target; + target = jQuery.ajaxSettings; + } + ajaxExtend( target, settings ); + return target; + }, + + ajaxSettings: { + url: ajaxLocation, + isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + processData: true, + async: true, + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + text: "text/plain", + json: "application/json, text/javascript", + "*": allTypes + }, + + contents: { + xml: /xml/, + html: /html/, + json: /json/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText" + }, + + // List of data converters + // 1) key format is "source_type destination_type" (a single space in-between) + // 2) the catchall symbol "*" can be used for source_type + converters: { + + // Convert anything to text + "* text": window.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: { + context: true, + url: true + } + }, + + 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 // ifModified key + ifModifiedKey, + // Response headers + responseHeadersString, + responseHeaders, + // transport + transport, + // 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 + // It's the callbackContext if one was provided in the options + // and if it's a DOM node or a jQuery collection + globalEventContext = callbackContext !== s && + ( callbackContext.nodeType || callbackContext instanceof 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, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( !state ) { + var lname = name.toLowerCase(); + name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // 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 === undefined ? null : match; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( !state ) { + s.mimeType = type; + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + statusText = statusText || strAbort; + if ( transport ) { + transport.abort( statusText ); + } + done( 0, statusText ); + return this; + } + }; + + // Callback for when everything is done + // It is defined here because jslint complains if it is declared + // at the end of the function (which would be more logical and readable) + 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; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // If successful, handle type chaining + if ( status >= 200 && status < 300 || status === 304 ) { + + // 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[ ifModifiedKey ] = modified; + } + modified = jqXHR.getResponseHeader("Etag"); + if ( modified ) { + jQuery.etag[ ifModifiedKey ] = modified; + } + } + + // If not modified + if ( status === 304 ) { + + statusText = "notmodified"; + isSuccess = true; + + // If we have data + } else { + + isSuccess = ajaxConvert( s, response ); + statusText = isSuccess.state; + success = isSuccess.data; + error = isSuccess.error; + isSuccess = !error; + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if ( !statusText || status ) { + 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( "ajax" + ( isSuccess ? "Success" : "Error" ), + [ 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" ); + } + } + } + + // Attach deferreds + deferred.promise( jqXHR ); + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + jqXHR.complete = completeDeferred.add; + + // Status-dependent callbacks + jqXHR.statusCode = function( map ) { + if ( map ) { + var tmp; + if ( state < 2 ) { + for ( tmp in map ) { + statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; + } + } else { + tmp = map[ jqXHR.status ]; + jqXHR.always( tmp ); + } + } + return this; + }; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) + // We also use the url parameter if available + s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); + + // Determine if a cross-domain request is in order + 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; + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Get ifModifiedKey before adding the anti-cache parameter + ifModifiedKey = s.url; + + // Add anti-cache in url if needed + if ( s.cache === false ) { + + var ts = jQuery.now(), + // try replacing _= if it is there + ret = s.url.replace( rts, "$1_=" + ts ); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); + } + } + + // 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + ifModifiedKey = ifModifiedKey || s.url; + if ( jQuery.lastModified[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); + } + if ( jQuery.etag[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); + } + } + + // 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; + } + } + } + + return jqXHR; + }, + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {} + +}); + +/* Handles responses to an ajax request: + * - sets all responseXXX fields accordingly + * - 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, + responseFields = s.responseFields; + + // Fill responseXXX fields + for ( type in responseFields ) { + if ( type in responses ) { + jqXHR[ responseFields[type] ] = responses[ type ]; + } + } + + // 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 +function ajaxConvert( s, response ) { + + var conv, conv2, current, tmp, + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(), + prev = dataTypes[ 0 ], + converters = {}, + i = 0; + + // Apply the dataFilter if provided + if ( s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + // Convert to each sequential dataType, tolerating list modification + for ( ; (current = dataTypes[++i]); ) { + + // There's only work to do if current dataType is non-auto + if ( current !== "*" ) { + + // Convert response if prev dataType is non-auto and differs from current + 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.splice( i--, 0, current ); + } + + 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 }; + } + } + } + } + + // Update prev for next iteration + prev = current; + } + } + + return { state: "success", data: response }; +} +var oldCallbacks = [], + rquestion = /\?/, + rjsonp = /(=)\?(?=&|$)|\?\?/, + nonce = jQuery.now(); + +// 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, + data = s.data, + url = s.url, + hasCallback = s.jsonp !== false, + replaceInUrl = hasCallback && rjsonp.test( url ), + replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && + !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && + rjsonp.test( data ); + + // Handle iff the expected data type is "jsonp" or we have a parameter to set + if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { + + // Get callback name, remembering preexisting value associated with it + callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? + s.jsonpCallback() : + s.jsonpCallback; + overwritten = window[ callbackName ]; + + // Insert callback into url or form data + if ( replaceInUrl ) { + s.url = url.replace( rjsonp, "$1" + callbackName ); + } else if ( replaceInData ) { + s.data = data.replace( rjsonp, "$1" + callbackName ); + } else if ( hasCallback ) { + s.url += ( rquestion.test( 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 + 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"; + } +}); +// Install script dataType +jQuery.ajaxSetup({ + accepts: { + script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /javascript|ecmascript/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +}); + +// Handle cache's special case and global +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + s.global = false; + } +}); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function(s) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + + var script, + head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; + + return { + + send: function( _, callback ) { + + script = document.createElement( "script" ); + + script.async = "async"; + + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + script.src = s.url; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function( _, isAbort ) { + + if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + + // Remove the script + if ( head && script.parentNode ) { + head.removeChild( script ); + } + + // Dereference the script + script = undefined; + + // Callback if not abort + if ( !isAbort ) { + callback( 200, "success" ); + } + } + }; + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + }, + + abort: function() { + if ( script ) { + script.onload( 0, 1 ); + } + } + }; + } +}); +var xhrCallbacks, + // #5280: Internet Explorer will keep connections alive if we don't abort on unload + xhrOnUnloadAbort = window.ActiveXObject ? function() { + // Abort all pending requests + for ( var key in xhrCallbacks ) { + xhrCallbacks[ key ]( 0, 1 ); + } + } : false, + xhrId = 0; + +// Functions to create xhrs +function createStandardXHR() { + try { + return new window.XMLHttpRequest(); + } catch( e ) {} +} + +function createActiveXHR() { + try { + return new window.ActiveXObject( "Microsoft.XMLHTTP" ); + } catch( e ) {} +} + +// Create the request object +// (This is still attached to ajaxSettings for backward compatibility) +jQuery.ajaxSettings.xhr = window.ActiveXObject ? + /* Microsoft failed to properly + * implement the XMLHttpRequest in IE7 (can't request local files), + * so we use the ActiveXObject when it is available + * Additionally XMLHttpRequest can be disabled in IE7/IE8 so + * we need a fallback. + */ + function() { + return !this.isLocal && createStandardXHR() || createActiveXHR(); + } : + // For all other browsers, use the standard XMLHttpRequest object + createStandardXHR; + +// Determine support properties +(function( xhr ) { + jQuery.extend( jQuery.support, { + ajax: !!xhr, + cors: !!xhr && ( "withCredentials" in xhr ) + }); +})( jQuery.ajaxSettings.xhr() ); + +// Create transport if the browser can provide an xhr +if ( jQuery.support.ajax ) { + + jQuery.ajaxTransport(function( s ) { + // Cross domain only allowed if supported through XMLHttpRequest + if ( !s.crossDomain || jQuery.support.cors ) { + + var callback; + + return { + send: function( headers, complete ) { + + // Get a new xhr + var handle, i, + xhr = s.xhr(); + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open( s.type, s.url, s.async, s.username, s.password ); + } else { + xhr.open( s.type, s.url, s.async ); + } + + // Apply custom fields if provided + if ( s.xhrFields ) { + for ( i in s.xhrFields ) { + xhr[ i ] = s.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( s.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( s.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 ( !s.crossDomain && !headers["X-Requested-With"] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + } catch( _ ) {} + + // Do send the request + // This may raise an exception which is actually + // handled in jQuery.ajax (so no try/catch here) + xhr.send( ( s.hasContent && s.data ) || null ); + + // Listener + callback = function( _, isAbort ) { + + var status, + statusText, + responseHeaders, + responses, + xml; + + // Firefox throws exceptions when accessing properties + // of an xhr when a network error occurred + // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) + try { + + // Was never called and is aborted or complete + if ( callback && ( isAbort || xhr.readyState === 4 ) ) { + + // Only called once + callback = undefined; + + // Do not keep as active anymore + if ( handle ) { + xhr.onreadystatechange = jQuery.noop; + if ( xhrOnUnloadAbort ) { + delete xhrCallbacks[ handle ]; + } + } + + // If it's an abort + if ( isAbort ) { + // Abort it manually if needed + if ( xhr.readyState !== 4 ) { + xhr.abort(); + } + } else { + status = xhr.status; + responseHeaders = xhr.getAllResponseHeaders(); + responses = {}; + xml = xhr.responseXML; + + // Construct response list + if ( xml && xml.documentElement /* #4958 */ ) { + responses.xml = xml; + } + + // When requesting binary data, IE6-9 will throw an exception + // on any attempt to access responseText (#11426) + try { + responses.text = xhr.responseText; + } catch( _ ) { + } + + // Firefox throws an exception when accessing + // statusText for faulty cross-domain requests + try { + statusText = xhr.statusText; + } catch( e ) { + // We normalize with Webkit giving an empty statusText + statusText = ""; + } + + // Filter status for non standard behaviors + + // If the request is local and we have data: assume a success + // (success with no data won't get notified, that's the best we + // can do given current implementations) + if ( !status && s.isLocal && !s.crossDomain ) { + status = responses.text ? 200 : 404; + // IE - #1450: sometimes returns 1223 when it should be 204 + } else if ( status === 1223 ) { + status = 204; + } + } + } + } catch( firefoxAccessException ) { + if ( !isAbort ) { + complete( -1, firefoxAccessException ); + } + } + + // Call complete if needed + if ( responses ) { + complete( status, statusText, responses, responseHeaders ); + } + }; + + if ( !s.async ) { + // if we're in sync mode we fire the callback + callback(); + } else if ( xhr.readyState === 4 ) { + // (IE6 & IE7) if it's in cache and has been + // retrieved directly we need to fire the callback + setTimeout( callback, 0 ); + } else { + handle = ++xhrId; + if ( xhrOnUnloadAbort ) { + // Create the active xhrs callbacks list if needed + // and attach the unload handler + if ( !xhrCallbacks ) { + xhrCallbacks = {}; + jQuery( window ).unload( xhrOnUnloadAbort ); + } + // Add to list of active xhrs callbacks + xhrCallbacks[ handle ] = callback; + } + xhr.onreadystatechange = callback; + } + }, + + abort: function() { + if ( callback ) { + callback(0,1); + } + } + }; + } + }); +} +var fxNow, timerId, + rfxtypes = /^(?:toggle|show|hide)$/, + rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), + rrun = /queueHooks$/, + animationPrefilters = [ defaultPrefilter ], + tweeners = { + "*": [function( prop, value ) { + var end, unit, prevScale, + tween = this.createTween( prop, value ), + parts = rfxnum.exec( value ), + target = tween.cur(), + start = +target || 0, + scale = 1; + + if ( parts ) { + end = +parts[2]; + unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + + // We need to compute starting value + if ( unit !== "px" && start ) { + // Iteratively approximate from a nonzero starting point + // Prefer the current property, because this process will be trivial if it uses the same units + // Fallback to end or a simple constant + start = jQuery.css( tween.elem, prop, true ) || end || 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 + prevScale = scale = scale || ".5"; + + // Adjust and apply + start = start / scale; + jQuery.style( tween.elem, prop, start + unit ); + + // Update scale, tolerating zeroes from tween.cur() + scale = tween.cur() / target; + + // Stop looping if we've hit the mark or scale is unchanged + } while ( scale !== 1 && scale !== prevScale ); + } + + tween.unit = unit; + tween.start = start; + // If a +=/-= token was provided, we're doing a relative animation + tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; + } + return tween; + }] + }; + +// Animations created synchronously will run synchronously +function createFxNow() { + setTimeout(function() { + fxNow = undefined; + }, 0 ); + return ( fxNow = jQuery.now() ); +} + +function createTweens( animation, props ) { + jQuery.each( props, function( prop, value ) { + var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( collection[ index ].call( animation, prop, value ) ) { + + // we're done with this property + return; + } + } + }); +} + +function Animation( elem, properties, options ) { + var result, + index = 0, + tweenerIndex = 0, + length = animationPrefilters.length, + deferred = jQuery.Deferred().always( function() { + // don't match elem in the :animated selector + delete tick.elem; + }), + tick = function() { + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + percent = 1 - ( remaining / animation.duration || 0 ), + 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, easing ) { + 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; + + 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; + } + } + + createTweens( animation, props ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + jQuery.fx.timer( + jQuery.extend( tick, { + anim: animation, + queue: animation.opts.queue, + elem: elem + }) + ); + + // 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 ); +} + +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; + } + } +} + +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 ); + } + } +}); + +function defaultPrefilter( elem, props, opts ) { + var index, prop, value, length, dataShow, tween, hooks, oldfire, + anim = this, + style = elem.style, + orig = {}, + handled = [], + hidden = elem.nodeType && isHidden( elem ); + + // 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 IE does 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 + if ( jQuery.css( elem, "display" ) === "inline" && + jQuery.css( elem, "float" ) === "none" ) { + + // inline-level elements accept inline-block; + // block-level elements need to be inline with layout + if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { + style.display = "inline-block"; + + } else { + style.zoom = 1; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + if ( !jQuery.support.shrinkWrapBlocks ) { + anim.done(function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + }); + } + } + + + // show/hide pass + for ( index in props ) { + value = props[ index ]; + if ( rfxtypes.exec( value ) ) { + delete props[ index ]; + if ( value === ( hidden ? "hide" : "show" ) ) { + continue; + } + handled.push( index ); + } + } + + length = handled.length; + if ( length ) { + dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); + if ( hidden ) { + jQuery( elem ).show(); + } else { + anim.done(function() { + jQuery( elem ).hide(); + }); + } + anim.done(function() { + var prop; + jQuery.removeData( elem, "fxshow", true ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + }); + for ( index = 0 ; index < length ; index++ ) { + prop = handled[ index ]; + tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); + orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); + + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = tween.start; + if ( hidden ) { + tween.end = tween.start; + tween.start = prop === "width" || prop === "height" ? 1 : 0; + } + } + } + } +} + +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 ]; + + this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); + 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 any value as a 4th 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, false, "" ); + // 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; + } + } + } +}; + +// Remove in 2.0 - this supports IE8's 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.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" || + // special check for .toggle( handler, handler, ... ) + ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +}); + +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 resolve immediately + if ( empty ) { + anim.stop( true ); + } + }; + + 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 = jQuery._data( 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 ); + } + }); + } +}); + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + attrs = { height: type }, + i = 0; + + // 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 + 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; +} + +// 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.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.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p*Math.PI ) / 2; + } +}; + +jQuery.timers = []; +jQuery.fx = Tween.prototype.init; +jQuery.fx.tick = function() { + var timer, + timers = jQuery.timers, + i = 0; + + 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(); + } +}; + +jQuery.fx.timer = function( timer ) { + if ( timer() && jQuery.timers.push( timer ) && !timerId ) { + timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); + } +}; + +jQuery.fx.interval = 13; + +jQuery.fx.stop = function() { + clearInterval( timerId ); + timerId = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + // Default speed + _default: 400 +}; + +// Back Compat <1.8 extension point +jQuery.fx.step = {}; + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} +var rroot = /^(?:body|html)$/i; + +jQuery.fn.offset = function( options ) { + if ( arguments.length ) { + return options === undefined ? + this : + this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + var box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left, + elem = this[ 0 ], + doc = elem && elem.ownerDocument; + + if ( !doc ) { + return; + } + + if ( (body = doc.body) === elem ) { + return jQuery.offset.bodyOffset( elem ); + } + + docElem = doc.documentElement; + + // Make sure we're not dealing with a disconnected DOM node + if ( !jQuery.contains( docElem, elem ) ) { + return { top: 0, left: 0 }; + } + + box = elem.getBoundingClientRect(); + win = getWindow( doc ); + clientTop = docElem.clientTop || body.clientTop || 0; + clientLeft = docElem.clientLeft || body.clientLeft || 0; + scrollTop = win.pageYOffset || docElem.scrollTop; + scrollLeft = win.pageXOffset || docElem.scrollLeft; + top = box.top + scrollTop - clientTop; + left = box.left + scrollLeft - clientLeft; + + return { top: top, left: left }; +}; + +jQuery.offset = { + + bodyOffset: function( body ) { + var top = body.offsetTop, + left = body.offsetLeft; + + if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.css(body, "marginTop") ) || 0; + left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + var position = jQuery.css( elem, "position" ); + + // set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curCSSTop = jQuery.css( elem, "top" ), + curCSSLeft = jQuery.css( elem, "left" ), + calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, + props = {}, curPosition = {}, curTop, curLeft; + + // 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({ + + position: function() { + if ( !this[0] ) { + return; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; + offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; + parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || document.body; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { + var top = /Y/.test( prop ); + + jQuery.fn[ method ] = function( val ) { + return jQuery.access( this, function( elem, method, val ) { + var win = getWindow( elem ); + + if ( val === undefined ) { + return win ? (prop in win) ? win[ prop ] : + win.document.documentElement[ method ] : + elem[ method ]; + } + + if ( win ) { + win.scrollTo( + !top ? val : jQuery( win ).scrollLeft(), + top ? val : jQuery( win ).scrollTop() + ); + + } else { + elem[ method ] = val; + } + }, method, val, arguments.length, null ); + }; +}); + +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} +// 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 jQuery.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 + // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. + 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, value, extra ) : + + // Set width or height on the element + jQuery.style( elem, type, value, extra ); + }, type, chainable ? margin : undefined, chainable ); + }; + }); +}); +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +// Expose jQuery as an AMD module, but only for AMD loaders that +// understand the issues with loading multiple versions of jQuery +// in a page that all might call define(). The loader will indicate +// they have special allowances for multiple jQuery versions by +// specifying define.amd.jQuery = true. Register as a named module, +// since jQuery can be concatenated with other files that may use define, +// but not use 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. +if ( typeof define === "function" && define.amd && define.amd.jQuery ) { + define( "jquery", [], function () { return jQuery; } ); +} + +})( window );;/*! jQuery UI - v1.10.3 - 2013-06-12 +* http://jqueryui.com +* Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.sortable.js +* Copyright 2013 jQuery Foundation and other contributors Licensed MIT */ + +(function( $, undefined ) { + +var uuid = 0, + runiqueId = /^ui-id-\d+$/; + +// $.ui might exist from components with no dependencies, e.g., $.ui.position +$.ui = $.ui || {}; + +$.extend( $.ui, { + version: "1.10.3", + + keyCode: { + BACKSPACE: 8, + COMMA: 188, + DELETE: 46, + DOWN: 40, + END: 35, + ENTER: 13, + ESCAPE: 27, + HOME: 36, + LEFT: 37, + NUMPAD_ADD: 107, + NUMPAD_DECIMAL: 110, + NUMPAD_DIVIDE: 111, + NUMPAD_ENTER: 108, + NUMPAD_MULTIPLY: 106, + NUMPAD_SUBTRACT: 109, + PAGE_DOWN: 34, + PAGE_UP: 33, + PERIOD: 190, + RIGHT: 39, + SPACE: 32, + TAB: 9, + UP: 38 + } +}); + +// plugins +$.fn.extend({ + focus: (function( orig ) { + return function( delay, fn ) { + return typeof delay === "number" ? + this.each(function() { + var elem = this; + setTimeout(function() { + $( elem ).focus(); + if ( fn ) { + fn.call( elem ); + } + }, delay ); + }) : + orig.apply( this, arguments ); + }; + })( $.fn.focus ), + + scrollParent: function() { + var scrollParent; + if (($.ui.ie && (/(static|relative)/).test(this.css("position"))) || (/absolute/).test(this.css("position"))) { + scrollParent = this.parents().filter(function() { + return (/(relative|absolute|fixed)/).test($.css(this,"position")) && (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); + }).eq(0); + } else { + scrollParent = this.parents().filter(function() { + return (/(auto|scroll)/).test($.css(this,"overflow")+$.css(this,"overflow-y")+$.css(this,"overflow-x")); + }).eq(0); + } + + return (/fixed/).test(this.css("position")) || !scrollParent.length ? $(document) : scrollParent; + }, + + zIndex: function( zIndex ) { + if ( zIndex !== undefined ) { + return this.css( "zIndex", zIndex ); + } + + if ( this.length ) { + var elem = $( this[ 0 ] ), position, value; + while ( elem.length && elem[ 0 ] !== document ) { + // Ignore z-index if position is set to a value where z-index is ignored by the browser + // This makes behavior of this function consistent across browsers + // WebKit always returns auto if the element is positioned + position = elem.css( "position" ); + if ( position === "absolute" || position === "relative" || position === "fixed" ) { + // IE returns 0 when zIndex is not specified + // other browsers return a string + // we ignore the case of nested elements with an explicit value of 0 + //
        + value = parseInt( elem.css( "zIndex" ), 10 ); + if ( !isNaN( value ) && value !== 0 ) { + return value; + } + } + elem = elem.parent(); + } + } + + return 0; + }, + + uniqueId: function() { + return this.each(function() { + if ( !this.id ) { + this.id = "ui-id-" + (++uuid); + } + }); + }, + + removeUniqueId: function() { + return this.each(function() { + if ( runiqueId.test( this.id ) ) { + $( this ).removeAttr( "id" ); + } + }); + } +}); + +// selectors +function focusable( element, isTabIndexNotNaN ) { + var map, mapName, img, + nodeName = element.nodeName.toLowerCase(); + if ( "area" === nodeName ) { + map = element.parentNode; + mapName = map.name; + if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { + return false; + } + img = $( "img[usemap=#" + mapName + "]" )[0]; + return !!img && visible( img ); + } + return ( /input|select|textarea|button|object/.test( nodeName ) ? + !element.disabled : + "a" === nodeName ? + element.href || isTabIndexNotNaN : + isTabIndexNotNaN) && + // the element and all of its ancestors must be visible + visible( element ); +} + +function visible( element ) { + return $.expr.filters.visible( element ) && + !$( element ).parents().addBack().filter(function() { + return $.css( this, "visibility" ) === "hidden"; + }).length; +} + +$.extend( $.expr[ ":" ], { + data: $.expr.createPseudo ? + $.expr.createPseudo(function( dataName ) { + return function( elem ) { + return !!$.data( elem, dataName ); + }; + }) : + // support: jQuery <1.8 + function( elem, i, match ) { + return !!$.data( elem, match[ 3 ] ); + }, + + focusable: function( element ) { + return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); + }, + + tabbable: function( element ) { + var tabIndex = $.attr( element, "tabindex" ), + isTabIndexNaN = isNaN( tabIndex ); + return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); + } +}); + +// support: jQuery <1.8 +if ( !$( "" ).outerWidth( 1 ).jquery ) { + $.each( [ "Width", "Height" ], function( i, name ) { + var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], + type = name.toLowerCase(), + orig = { + innerWidth: $.fn.innerWidth, + innerHeight: $.fn.innerHeight, + outerWidth: $.fn.outerWidth, + outerHeight: $.fn.outerHeight + }; + + function reduce( elem, size, border, margin ) { + $.each( side, function() { + size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; + if ( border ) { + size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; + } + if ( margin ) { + size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; + } + }); + return size; + } + + $.fn[ "inner" + name ] = function( size ) { + if ( size === undefined ) { + return orig[ "inner" + name ].call( this ); + } + + return this.each(function() { + $( this ).css( type, reduce( this, size ) + "px" ); + }); + }; + + $.fn[ "outer" + name] = function( size, margin ) { + if ( typeof size !== "number" ) { + return orig[ "outer" + name ].call( this, size ); + } + + return this.each(function() { + $( this).css( type, reduce( this, size, true, margin ) + "px" ); + }); + }; + }); +} + +// support: jQuery <1.8 +if ( !$.fn.addBack ) { + $.fn.addBack = function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + }; +} + +// support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) +if ( $( "" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { + $.fn.removeData = (function( removeData ) { + return function( key ) { + if ( arguments.length ) { + return removeData.call( this, $.camelCase( key ) ); + } else { + return removeData.call( this ); + } + }; + })( $.fn.removeData ); +} + + + + + +// deprecated +$.ui.ie = !!/msie [\w.]+/.exec( navigator.userAgent.toLowerCase() ); + +$.support.selectstart = "onselectstart" in document.createElement( "div" ); +$.fn.extend({ + disableSelection: function() { + return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + + ".ui-disableSelection", function( event ) { + event.preventDefault(); + }); + }, + + enableSelection: function() { + return this.unbind( ".ui-disableSelection" ); + } +}); + +$.extend( $.ui, { + // $.ui.plugin is deprecated. Use $.widget() extensions instead. + plugin: { + add: function( module, option, set ) { + var i, + proto = $.ui[ module ].prototype; + for ( i in set ) { + proto.plugins[ i ] = proto.plugins[ i ] || []; + proto.plugins[ i ].push( [ option, set[ i ] ] ); + } + }, + call: function( instance, name, args ) { + var i, + set = instance.plugins[ name ]; + if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { + return; + } + + for ( i = 0; i < set.length; i++ ) { + if ( instance.options[ set[ i ][ 0 ] ] ) { + set[ i ][ 1 ].apply( instance.element, args ); + } + } + } + }, + + // only used by resizable + hasScroll: function( el, a ) { + + //If overflow is hidden, the element might have extra content, but the user wants to hide it + if ( $( el ).css( "overflow" ) === "hidden") { + return false; + } + + var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", + has = false; + + if ( el[ scroll ] > 0 ) { + return true; + } + + // TODO: determine which cases actually cause this to happen + // if the element doesn't have the scroll set, see if it's possible to + // set the scroll + el[ scroll ] = 1; + has = ( el[ scroll ] > 0 ); + el[ scroll ] = 0; + return has; + } +}); + +})( jQuery ); +(function( $, undefined ) { + +var uuid = 0, + slice = Array.prototype.slice, + _cleanData = $.cleanData; +$.cleanData = function( elems ) { + for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { + try { + $( elem ).triggerHandler( "remove" ); + // http://bugs.jquery.com/ticket/8235 + } catch( e ) {} + } + _cleanData( elems ); +}; + +$.widget = function( name, base, prototype ) { + var fullName, existingConstructor, constructor, basePrototype, + // proxiedPrototype allows the provided prototype to remain unmodified + // so that it can be used as a mixin for multiple widgets (#8876) + proxiedPrototype = {}, + namespace = name.split( "." )[ 0 ]; + + name = name.split( "." )[ 1 ]; + fullName = namespace + "-" + name; + + if ( !prototype ) { + prototype = base; + base = $.Widget; + } + + // create selector for plugin + $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { + return !!$.data( elem, fullName ); + }; + + $[ namespace ] = $[ namespace ] || {}; + existingConstructor = $[ namespace ][ name ]; + constructor = $[ namespace ][ name ] = function( options, element ) { + // allow instantiation without "new" keyword + if ( !this._createWidget ) { + return new constructor( options, element ); + } + + // allow instantiation without initializing for simple inheritance + // must use "new" keyword (the code above always passes args) + if ( arguments.length ) { + this._createWidget( options, element ); + } + }; + // extend with the existing constructor to carry over any static properties + $.extend( constructor, existingConstructor, { + version: prototype.version, + // copy the object used to create the prototype in case we need to + // redefine the widget later + _proto: $.extend( {}, prototype ), + // track widgets that inherit from this widget in case this widget is + // redefined after a widget inherits from it + _childConstructors: [] + }); + + basePrototype = new base(); + // we need to make the options hash a property directly on the new instance + // otherwise we'll modify the options hash on the prototype that we're + // inheriting from + basePrototype.options = $.widget.extend( {}, basePrototype.options ); + $.each( prototype, function( prop, value ) { + if ( !$.isFunction( value ) ) { + proxiedPrototype[ prop ] = value; + return; + } + proxiedPrototype[ prop ] = (function() { + var _super = function() { + return base.prototype[ prop ].apply( this, arguments ); + }, + _superApply = function( args ) { + return base.prototype[ prop ].apply( this, args ); + }; + return function() { + var __super = this._super, + __superApply = this._superApply, + returnValue; + + this._super = _super; + this._superApply = _superApply; + + returnValue = value.apply( this, arguments ); + + this._super = __super; + this._superApply = __superApply; + + return returnValue; + }; + })(); + }); + constructor.prototype = $.widget.extend( basePrototype, { + // TODO: remove support for widgetEventPrefix + // always use the name + a colon as the prefix, e.g., draggable:start + // don't prefix for widgets that aren't DOM-based + widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name + }, proxiedPrototype, { + constructor: constructor, + namespace: namespace, + widgetName: name, + widgetFullName: fullName + }); + + // If this widget is being redefined then we need to find all widgets that + // are inheriting from it and redefine all of them so that they inherit from + // the new version of this widget. We're essentially trying to replace one + // level in the prototype chain. + if ( existingConstructor ) { + $.each( existingConstructor._childConstructors, function( i, child ) { + var childPrototype = child.prototype; + + // redefine the child widget using the same prototype that was + // originally used, but inherit from the new version of the base + $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); + }); + // remove the list of existing child constructors from the old constructor + // so the old child constructors can be garbage collected + delete existingConstructor._childConstructors; + } else { + base._childConstructors.push( constructor ); + } + + $.widget.bridge( name, constructor ); +}; + +$.widget.extend = function( target ) { + var input = slice.call( arguments, 1 ), + inputIndex = 0, + inputLength = input.length, + key, + value; + for ( ; inputIndex < inputLength; inputIndex++ ) { + for ( key in input[ inputIndex ] ) { + value = input[ inputIndex ][ key ]; + if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { + // Clone objects + if ( $.isPlainObject( value ) ) { + target[ key ] = $.isPlainObject( target[ key ] ) ? + $.widget.extend( {}, target[ key ], value ) : + // Don't extend strings, arrays, etc. with objects + $.widget.extend( {}, value ); + // Copy everything else by reference + } else { + target[ key ] = value; + } + } + } + } + return target; +}; + +$.widget.bridge = function( name, object ) { + var fullName = object.prototype.widgetFullName || name; + $.fn[ name ] = function( options ) { + var isMethodCall = typeof options === "string", + args = slice.call( arguments, 1 ), + returnValue = this; + + // allow multiple hashes to be passed on init + options = !isMethodCall && args.length ? + $.widget.extend.apply( null, [ options ].concat(args) ) : + options; + + if ( isMethodCall ) { + this.each(function() { + var methodValue, + instance = $.data( this, fullName ); + if ( !instance ) { + return $.error( "cannot call methods on " + name + " prior to initialization; " + + "attempted to call method '" + options + "'" ); + } + if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { + return $.error( "no such method '" + options + "' for " + name + " widget instance" ); + } + methodValue = instance[ options ].apply( instance, args ); + if ( methodValue !== instance && methodValue !== undefined ) { + returnValue = methodValue && methodValue.jquery ? + returnValue.pushStack( methodValue.get() ) : + methodValue; + return false; + } + }); + } else { + this.each(function() { + var instance = $.data( this, fullName ); + if ( instance ) { + instance.option( options || {} )._init(); + } else { + $.data( this, fullName, new object( options, this ) ); + } + }); + } + + return returnValue; + }; +}; + +$.Widget = function( /* options, element */ ) {}; +$.Widget._childConstructors = []; + +$.Widget.prototype = { + widgetName: "widget", + widgetEventPrefix: "", + defaultElement: "
        ", + options: { + disabled: false, + + // callbacks + create: null + }, + _createWidget: function( options, element ) { + element = $( element || this.defaultElement || this )[ 0 ]; + this.element = $( element ); + this.uuid = uuid++; + this.eventNamespace = "." + this.widgetName + this.uuid; + this.options = $.widget.extend( {}, + this.options, + this._getCreateOptions(), + options ); + + this.bindings = $(); + this.hoverable = $(); + this.focusable = $(); + + if ( element !== this ) { + $.data( element, this.widgetFullName, this ); + this._on( true, this.element, { + remove: function( event ) { + if ( event.target === element ) { + this.destroy(); + } + } + }); + this.document = $( element.style ? + // element within the document + element.ownerDocument : + // element is window or document + element.document || element ); + this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); + } + + this._create(); + this._trigger( "create", null, this._getCreateEventData() ); + this._init(); + }, + _getCreateOptions: $.noop, + _getCreateEventData: $.noop, + _create: $.noop, + _init: $.noop, + + destroy: function() { + this._destroy(); + // we can probably remove the unbind calls in 2.0 + // all event bindings should go through this._on() + this.element + .unbind( this.eventNamespace ) + // 1.9 BC for #7810 + // TODO remove dual storage + .removeData( this.widgetName ) + .removeData( this.widgetFullName ) + // support: jquery <1.6.3 + // http://bugs.jquery.com/ticket/9413 + .removeData( $.camelCase( this.widgetFullName ) ); + this.widget() + .unbind( this.eventNamespace ) + .removeAttr( "aria-disabled" ) + .removeClass( + this.widgetFullName + "-disabled " + + "ui-state-disabled" ); + + // clean up events and states + this.bindings.unbind( this.eventNamespace ); + this.hoverable.removeClass( "ui-state-hover" ); + this.focusable.removeClass( "ui-state-focus" ); + }, + _destroy: $.noop, + + widget: function() { + return this.element; + }, + + option: function( key, value ) { + var options = key, + parts, + curOption, + i; + + if ( arguments.length === 0 ) { + // don't return a reference to the internal hash + return $.widget.extend( {}, this.options ); + } + + if ( typeof key === "string" ) { + // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } + options = {}; + parts = key.split( "." ); + key = parts.shift(); + if ( parts.length ) { + curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); + for ( i = 0; i < parts.length - 1; i++ ) { + curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; + curOption = curOption[ parts[ i ] ]; + } + key = parts.pop(); + if ( value === undefined ) { + return curOption[ key ] === undefined ? null : curOption[ key ]; + } + curOption[ key ] = value; + } else { + if ( value === undefined ) { + return this.options[ key ] === undefined ? null : this.options[ key ]; + } + options[ key ] = value; + } + } + + this._setOptions( options ); + + return this; + }, + _setOptions: function( options ) { + var key; + + for ( key in options ) { + this._setOption( key, options[ key ] ); + } + + return this; + }, + _setOption: function( key, value ) { + this.options[ key ] = value; + + if ( key === "disabled" ) { + this.widget() + .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) + .attr( "aria-disabled", value ); + this.hoverable.removeClass( "ui-state-hover" ); + this.focusable.removeClass( "ui-state-focus" ); + } + + return this; + }, + + enable: function() { + return this._setOption( "disabled", false ); + }, + disable: function() { + return this._setOption( "disabled", true ); + }, + + _on: function( suppressDisabledCheck, element, handlers ) { + var delegateElement, + instance = this; + + // no suppressDisabledCheck flag, shuffle arguments + if ( typeof suppressDisabledCheck !== "boolean" ) { + handlers = element; + element = suppressDisabledCheck; + suppressDisabledCheck = false; + } + + // no element argument, shuffle and use this.element + if ( !handlers ) { + handlers = element; + element = this.element; + delegateElement = this.widget(); + } else { + // accept selectors, DOM elements + element = delegateElement = $( element ); + this.bindings = this.bindings.add( element ); + } + + $.each( handlers, function( event, handler ) { + function handlerProxy() { + // allow widgets to customize the disabled handling + // - disabled as an array instead of boolean + // - disabled class as method for disabling individual parts + if ( !suppressDisabledCheck && + ( instance.options.disabled === true || + $( this ).hasClass( "ui-state-disabled" ) ) ) { + return; + } + return ( typeof handler === "string" ? instance[ handler ] : handler ) + .apply( instance, arguments ); + } + + // copy the guid so direct unbinding works + if ( typeof handler !== "string" ) { + handlerProxy.guid = handler.guid = + handler.guid || handlerProxy.guid || $.guid++; + } + + var match = event.match( /^(\w+)\s*(.*)$/ ), + eventName = match[1] + instance.eventNamespace, + selector = match[2]; + if ( selector ) { + delegateElement.delegate( selector, eventName, handlerProxy ); + } else { + element.bind( eventName, handlerProxy ); + } + }); + }, + + _off: function( element, eventName ) { + eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; + element.unbind( eventName ).undelegate( eventName ); + }, + + _delay: function( handler, delay ) { + function handlerProxy() { + return ( typeof handler === "string" ? instance[ handler ] : handler ) + .apply( instance, arguments ); + } + var instance = this; + return setTimeout( handlerProxy, delay || 0 ); + }, + + _hoverable: function( element ) { + this.hoverable = this.hoverable.add( element ); + this._on( element, { + mouseenter: function( event ) { + $( event.currentTarget ).addClass( "ui-state-hover" ); + }, + mouseleave: function( event ) { + $( event.currentTarget ).removeClass( "ui-state-hover" ); + } + }); + }, + + _focusable: function( element ) { + this.focusable = this.focusable.add( element ); + this._on( element, { + focusin: function( event ) { + $( event.currentTarget ).addClass( "ui-state-focus" ); + }, + focusout: function( event ) { + $( event.currentTarget ).removeClass( "ui-state-focus" ); + } + }); + }, + + _trigger: function( type, event, data ) { + var prop, orig, + callback = this.options[ type ]; + + data = data || {}; + event = $.Event( event ); + event.type = ( type === this.widgetEventPrefix ? + type : + this.widgetEventPrefix + type ).toLowerCase(); + // the original event may come from any element + // so we need to reset the target on the new event + event.target = this.element[ 0 ]; + + // copy original event properties over to the new event + orig = event.originalEvent; + if ( orig ) { + for ( prop in orig ) { + if ( !( prop in event ) ) { + event[ prop ] = orig[ prop ]; + } + } + } + + this.element.trigger( event, data ); + return !( $.isFunction( callback ) && + callback.apply( this.element[0], [ event ].concat( data ) ) === false || + event.isDefaultPrevented() ); + } +}; + +$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { + $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { + if ( typeof options === "string" ) { + options = { effect: options }; + } + var hasOptions, + effectName = !options ? + method : + options === true || typeof options === "number" ? + defaultEffect : + options.effect || defaultEffect; + options = options || {}; + if ( typeof options === "number" ) { + options = { duration: options }; + } + hasOptions = !$.isEmptyObject( options ); + options.complete = callback; + if ( options.delay ) { + element.delay( options.delay ); + } + if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { + element[ method ]( options ); + } else if ( effectName !== method && element[ effectName ] ) { + element[ effectName ]( options.duration, options.easing, callback ); + } else { + element.queue(function( next ) { + $( this )[ method ](); + if ( callback ) { + callback.call( element[ 0 ] ); + } + next(); + }); + } + }; +}); + +})( jQuery ); +(function( $, undefined ) { + +var mouseHandled = false; +$( document ).mouseup( function() { + mouseHandled = false; +}); + +$.widget("ui.mouse", { + version: "1.10.3", + options: { + cancel: "input,textarea,button,select,option", + distance: 1, + delay: 0 + }, + _mouseInit: function() { + var that = this; + + this.element + .bind("mousedown."+this.widgetName, function(event) { + return that._mouseDown(event); + }) + .bind("click."+this.widgetName, function(event) { + if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) { + $.removeData(event.target, that.widgetName + ".preventClickEvent"); + event.stopImmediatePropagation(); + return false; + } + }); + + this.started = false; + }, + + // TODO: make sure destroying one instance of mouse doesn't mess with + // other instances of mouse + _mouseDestroy: function() { + this.element.unbind("."+this.widgetName); + if ( this._mouseMoveDelegate ) { + $(document) + .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) + .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); + } + }, + + _mouseDown: function(event) { + // don't let more than one widget handle mouseStart + if( mouseHandled ) { return; } + + // we may have missed mouseup (out of window) + (this._mouseStarted && this._mouseUp(event)); + + this._mouseDownEvent = event; + + var that = this, + btnIsLeft = (event.which === 1), + // event.target.nodeName works around a bug in IE 8 with + // disabled inputs (#7620) + elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); + if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { + return true; + } + + this.mouseDelayMet = !this.options.delay; + if (!this.mouseDelayMet) { + this._mouseDelayTimer = setTimeout(function() { + that.mouseDelayMet = true; + }, this.options.delay); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = (this._mouseStart(event) !== false); + if (!this._mouseStarted) { + event.preventDefault(); + return true; + } + } + + // Click event may never have fired (Gecko & Opera) + if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) { + $.removeData(event.target, this.widgetName + ".preventClickEvent"); + } + + // these delegates are required to keep context + this._mouseMoveDelegate = function(event) { + return that._mouseMove(event); + }; + this._mouseUpDelegate = function(event) { + return that._mouseUp(event); + }; + $(document) + .bind("mousemove."+this.widgetName, this._mouseMoveDelegate) + .bind("mouseup."+this.widgetName, this._mouseUpDelegate); + + event.preventDefault(); + + mouseHandled = true; + return true; + }, + + _mouseMove: function(event) { + // IE mouseup check - mouseup happened when mouse was out of window + if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) { + return this._mouseUp(event); + } + + if (this._mouseStarted) { + this._mouseDrag(event); + return event.preventDefault(); + } + + if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { + this._mouseStarted = + (this._mouseStart(this._mouseDownEvent, event) !== false); + (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); + } + + return !this._mouseStarted; + }, + + _mouseUp: function(event) { + $(document) + .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate) + .unbind("mouseup."+this.widgetName, this._mouseUpDelegate); + + if (this._mouseStarted) { + this._mouseStarted = false; + + if (event.target === this._mouseDownEvent.target) { + $.data(event.target, this.widgetName + ".preventClickEvent", true); + } + + this._mouseStop(event); + } + + return false; + }, + + _mouseDistanceMet: function(event) { + return (Math.max( + Math.abs(this._mouseDownEvent.pageX - event.pageX), + Math.abs(this._mouseDownEvent.pageY - event.pageY) + ) >= this.options.distance + ); + }, + + _mouseDelayMet: function(/* event */) { + return this.mouseDelayMet; + }, + + // These are placeholder methods, to be overriden by extending plugin + _mouseStart: function(/* event */) {}, + _mouseDrag: function(/* event */) {}, + _mouseStop: function(/* event */) {}, + _mouseCapture: function(/* event */) { return true; } +}); + +})(jQuery); +(function( $, undefined ) { + +/*jshint loopfunc: true */ + +function isOverAxis( x, reference, size ) { + return ( x > reference ) && ( x < ( reference + size ) ); +} + +function isFloating(item) { + return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display")); +} + +$.widget("ui.sortable", $.ui.mouse, { + version: "1.10.3", + widgetEventPrefix: "sort", + ready: false, + options: { + appendTo: "parent", + axis: false, + connectWith: false, + containment: false, + cursor: "auto", + cursorAt: false, + dropOnEmpty: true, + forcePlaceholderSize: false, + forceHelperSize: false, + grid: false, + handle: false, + helper: "original", + items: "> *", + opacity: false, + placeholder: false, + revert: false, + scroll: true, + scrollSensitivity: 20, + scrollSpeed: 20, + scope: "default", + tolerance: "intersect", + zIndex: 1000, + + // callbacks + activate: null, + beforeStop: null, + change: null, + deactivate: null, + out: null, + over: null, + receive: null, + remove: null, + sort: null, + start: null, + stop: null, + update: null + }, + _create: function() { + + var o = this.options; + this.containerCache = {}; + this.element.addClass("ui-sortable"); + + //Get the items + this.refresh(); + + //Let's determine if the items are being displayed horizontally + this.floating = this.items.length ? o.axis === "x" || isFloating(this.items[0].item) : false; + + //Let's determine the parent's offset + this.offset = this.element.offset(); + + //Initialize mouse events for interaction + this._mouseInit(); + + //We're ready to go + this.ready = true; + + }, + + _destroy: function() { + this.element + .removeClass("ui-sortable ui-sortable-disabled"); + this._mouseDestroy(); + + for ( var i = this.items.length - 1; i >= 0; i-- ) { + this.items[i].item.removeData(this.widgetName + "-item"); + } + + return this; + }, + + _setOption: function(key, value){ + if ( key === "disabled" ) { + this.options[ key ] = value; + + this.widget().toggleClass( "ui-sortable-disabled", !!value ); + } else { + // Don't call widget base _setOption for disable as it adds ui-state-disabled class + $.Widget.prototype._setOption.apply(this, arguments); + } + }, + + _mouseCapture: function(event, overrideHandle) { + var currentItem = null, + validHandle = false, + that = this; + + if (this.reverting) { + return false; + } + + if(this.options.disabled || this.options.type === "static") { + return false; + } + + //We have to refresh the items data once first + this._refreshItems(event); + + //Find out if the clicked node (or one of its parents) is a actual item in this.items + $(event.target).parents().each(function() { + if($.data(this, that.widgetName + "-item") === that) { + currentItem = $(this); + return false; + } + }); + if($.data(event.target, that.widgetName + "-item") === that) { + currentItem = $(event.target); + } + + if(!currentItem) { + return false; + } + if(this.options.handle && !overrideHandle) { + $(this.options.handle, currentItem).find("*").addBack().each(function() { + if(this === event.target) { + validHandle = true; + } + }); + if(!validHandle) { + return false; + } + } + + this.currentItem = currentItem; + this._removeCurrentsFromItems(); + return true; + + }, + + _mouseStart: function(event, overrideHandle, noActivation) { + + var i, body, + o = this.options; + + this.currentContainer = this; + + //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture + this.refreshPositions(); + + //Create and append the visible helper + this.helper = this._createHelper(event); + + //Cache the helper size + this._cacheHelperProportions(); + + /* + * - Position generation - + * This block generates everything position related - it's the core of draggables. + */ + + //Cache the margins of the original element + this._cacheMargins(); + + //Get the next scrolling parent + this.scrollParent = this.helper.scrollParent(); + + //The element's absolute position on the page minus margins + this.offset = this.currentItem.offset(); + this.offset = { + top: this.offset.top - this.margins.top, + left: this.offset.left - this.margins.left + }; + + $.extend(this.offset, { + click: { //Where the click happened, relative to the element + left: event.pageX - this.offset.left, + top: event.pageY - this.offset.top + }, + parent: this._getParentOffset(), + relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper + }); + + // Only after we got the offset, we can change the helper's position to absolute + // TODO: Still need to figure out a way to make relative sorting possible + this.helper.css("position", "absolute"); + this.cssPosition = this.helper.css("position"); + + //Generate the original position + this.originalPosition = this._generatePosition(event); + this.originalPageX = event.pageX; + this.originalPageY = event.pageY; + + //Adjust the mouse offset relative to the helper if "cursorAt" is supplied + (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); + + //Cache the former DOM position + this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; + + //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way + if(this.helper[0] !== this.currentItem[0]) { + this.currentItem.hide(); + } + + //Create the placeholder + this._createPlaceholder(); + + //Set a containment if given in the options + if(o.containment) { + this._setContainment(); + } + + if( o.cursor && o.cursor !== "auto" ) { // cursor option + body = this.document.find( "body" ); + + // support: IE + this.storedCursor = body.css( "cursor" ); + body.css( "cursor", o.cursor ); + + this.storedStylesheet = $( "" ).appendTo( body ); + } + + if(o.opacity) { // opacity option + if (this.helper.css("opacity")) { + this._storedOpacity = this.helper.css("opacity"); + } + this.helper.css("opacity", o.opacity); + } + + if(o.zIndex) { // zIndex option + if (this.helper.css("zIndex")) { + this._storedZIndex = this.helper.css("zIndex"); + } + this.helper.css("zIndex", o.zIndex); + } + + //Prepare scrolling + if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { + this.overflowOffset = this.scrollParent.offset(); + } + + //Call callbacks + this._trigger("start", event, this._uiHash()); + + //Recache the helper size + if(!this._preserveHelperProportions) { + this._cacheHelperProportions(); + } + + + //Post "activate" events to possible containers + if( !noActivation ) { + for ( i = this.containers.length - 1; i >= 0; i-- ) { + this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) ); + } + } + + //Prepare possible droppables + if($.ui.ddmanager) { + $.ui.ddmanager.current = this; + } + + if ($.ui.ddmanager && !o.dropBehaviour) { + $.ui.ddmanager.prepareOffsets(this, event); + } + + this.dragging = true; + + this.helper.addClass("ui-sortable-helper"); + this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position + return true; + + }, + + _mouseDrag: function(event) { + var i, item, itemElement, intersection, + o = this.options, + scrolled = false; + + //Compute the helpers position + this.position = this._generatePosition(event); + this.positionAbs = this._convertPositionTo("absolute"); + + if (!this.lastPositionAbs) { + this.lastPositionAbs = this.positionAbs; + } + + //Do scrolling + if(this.options.scroll) { + if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") { + + if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) { + this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; + } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) { + this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; + } + + if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) { + this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; + } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) { + this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; + } + + } else { + + if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) { + scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); + } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) { + scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); + } + + if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) { + scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); + } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) { + scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); + } + + } + + if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) { + $.ui.ddmanager.prepareOffsets(this, event); + } + } + + //Regenerate the absolute position used for position checks + this.positionAbs = this._convertPositionTo("absolute"); + + //Set the helper position + if(!this.options.axis || this.options.axis !== "y") { + this.helper[0].style.left = this.position.left+"px"; + } + if(!this.options.axis || this.options.axis !== "x") { + this.helper[0].style.top = this.position.top+"px"; + } + + //Rearrange + for (i = this.items.length - 1; i >= 0; i--) { + + //Cache variables and intersection, continue if no intersection + item = this.items[i]; + itemElement = item.item[0]; + intersection = this._intersectsWithPointer(item); + if (!intersection) { + continue; + } + + // Only put the placeholder inside the current Container, skip all + // items form other containers. This works because when moving + // an item from one container to another the + // currentContainer is switched before the placeholder is moved. + // + // Without this moving items in "sub-sortables" can cause the placeholder to jitter + // beetween the outer and inner container. + if (item.instance !== this.currentContainer) { + continue; + } + + // cannot intersect with itself + // no useless actions that have been done before + // no action if the item moved is the parent of the item checked + if (itemElement !== this.currentItem[0] && + this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement && + !$.contains(this.placeholder[0], itemElement) && + (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true) + ) { + + this.direction = intersection === 1 ? "down" : "up"; + + if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) { + this._rearrange(event, item); + } else { + break; + } + + this._trigger("change", event, this._uiHash()); + break; + } + } + + //Post events to containers + this._contactContainers(event); + + //Interconnect with droppables + if($.ui.ddmanager) { + $.ui.ddmanager.drag(this, event); + } + + //Call callbacks + this._trigger("sort", event, this._uiHash()); + + this.lastPositionAbs = this.positionAbs; + return false; + + }, + + _mouseStop: function(event, noPropagation) { + + if(!event) { + return; + } + + //If we are using droppables, inform the manager about the drop + if ($.ui.ddmanager && !this.options.dropBehaviour) { + $.ui.ddmanager.drop(this, event); + } + + if(this.options.revert) { + var that = this, + cur = this.placeholder.offset(), + axis = this.options.axis, + animation = {}; + + if ( !axis || axis === "x" ) { + animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft); + } + if ( !axis || axis === "y" ) { + animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop); + } + this.reverting = true; + $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() { + that._clear(event); + }); + } else { + this._clear(event, noPropagation); + } + + return false; + + }, + + cancel: function() { + + if(this.dragging) { + + this._mouseUp({ target: null }); + + if(this.options.helper === "original") { + this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); + } else { + this.currentItem.show(); + } + + //Post deactivating events to containers + for (var i = this.containers.length - 1; i >= 0; i--){ + this.containers[i]._trigger("deactivate", null, this._uiHash(this)); + if(this.containers[i].containerCache.over) { + this.containers[i]._trigger("out", null, this._uiHash(this)); + this.containers[i].containerCache.over = 0; + } + } + + } + + if (this.placeholder) { + //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! + if(this.placeholder[0].parentNode) { + this.placeholder[0].parentNode.removeChild(this.placeholder[0]); + } + if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) { + this.helper.remove(); + } + + $.extend(this, { + helper: null, + dragging: false, + reverting: false, + _noFinalSort: null + }); + + if(this.domPosition.prev) { + $(this.domPosition.prev).after(this.currentItem); + } else { + $(this.domPosition.parent).prepend(this.currentItem); + } + } + + return this; + + }, + + serialize: function(o) { + + var items = this._getItemsAsjQuery(o && o.connected), + str = []; + o = o || {}; + + $(items).each(function() { + var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/)); + if (res) { + str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2])); + } + }); + + if(!str.length && o.key) { + str.push(o.key + "="); + } + + return str.join("&"); + + }, + + toArray: function(o) { + + var items = this._getItemsAsjQuery(o && o.connected), + ret = []; + + o = o || {}; + + items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); }); + return ret; + + }, + + /* Be careful with the following core functions */ + _intersectsWith: function(item) { + + var x1 = this.positionAbs.left, + x2 = x1 + this.helperProportions.width, + y1 = this.positionAbs.top, + y2 = y1 + this.helperProportions.height, + l = item.left, + r = l + item.width, + t = item.top, + b = t + item.height, + dyClick = this.offset.click.top, + dxClick = this.offset.click.left, + isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ), + isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ), + isOverElement = isOverElementHeight && isOverElementWidth; + + if ( this.options.tolerance === "pointer" || + this.options.forcePointerForContainers || + (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"]) + ) { + return isOverElement; + } else { + + return (l < x1 + (this.helperProportions.width / 2) && // Right Half + x2 - (this.helperProportions.width / 2) < r && // Left Half + t < y1 + (this.helperProportions.height / 2) && // Bottom Half + y2 - (this.helperProportions.height / 2) < b ); // Top Half + + } + }, + + _intersectsWithPointer: function(item) { + + var isOverElementHeight = (this.options.axis === "x") || isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), + isOverElementWidth = (this.options.axis === "y") || isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), + isOverElement = isOverElementHeight && isOverElementWidth, + verticalDirection = this._getDragVerticalDirection(), + horizontalDirection = this._getDragHorizontalDirection(); + + if (!isOverElement) { + return false; + } + + return this.floating ? + ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 ) + : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) ); + + }, + + _intersectsWithSides: function(item) { + + var isOverBottomHalf = isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), + isOverRightHalf = isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), + verticalDirection = this._getDragVerticalDirection(), + horizontalDirection = this._getDragHorizontalDirection(); + + if (this.floating && horizontalDirection) { + return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf)); + } else { + return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf)); + } + + }, + + _getDragVerticalDirection: function() { + var delta = this.positionAbs.top - this.lastPositionAbs.top; + return delta !== 0 && (delta > 0 ? "down" : "up"); + }, + + _getDragHorizontalDirection: function() { + var delta = this.positionAbs.left - this.lastPositionAbs.left; + return delta !== 0 && (delta > 0 ? "right" : "left"); + }, + + refresh: function(event) { + this._refreshItems(event); + this.refreshPositions(); + return this; + }, + + _connectWith: function() { + var options = this.options; + return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith; + }, + + _getItemsAsjQuery: function(connected) { + + var i, j, cur, inst, + items = [], + queries = [], + connectWith = this._connectWith(); + + if(connectWith && connected) { + for (i = connectWith.length - 1; i >= 0; i--){ + cur = $(connectWith[i]); + for ( j = cur.length - 1; j >= 0; j--){ + inst = $.data(cur[j], this.widgetFullName); + if(inst && inst !== this && !inst.options.disabled) { + queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), inst]); + } + } + } + } + + queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"), this]); + + for (i = queries.length - 1; i >= 0; i--){ + queries[i][0].each(function() { + items.push(this); + }); + } + + return $(items); + + }, + + _removeCurrentsFromItems: function() { + + var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); + + this.items = $.grep(this.items, function (item) { + for (var j=0; j < list.length; j++) { + if(list[j] === item.item[0]) { + return false; + } + } + return true; + }); + + }, + + _refreshItems: function(event) { + + this.items = []; + this.containers = [this]; + + var i, j, cur, inst, targetData, _queries, item, queriesLength, + items = this.items, + queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]], + connectWith = this._connectWith(); + + if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down + for (i = connectWith.length - 1; i >= 0; i--){ + cur = $(connectWith[i]); + for (j = cur.length - 1; j >= 0; j--){ + inst = $.data(cur[j], this.widgetFullName); + if(inst && inst !== this && !inst.options.disabled) { + queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); + this.containers.push(inst); + } + } + } + } + + for (i = queries.length - 1; i >= 0; i--) { + targetData = queries[i][1]; + _queries = queries[i][0]; + + for (j=0, queriesLength = _queries.length; j < queriesLength; j++) { + item = $(_queries[j]); + + item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager) + + items.push({ + item: item, + instance: targetData, + width: 0, height: 0, + left: 0, top: 0 + }); + } + } + + }, + + refreshPositions: function(fast) { + + //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change + if(this.offsetParent && this.helper) { + this.offset.parent = this._getParentOffset(); + } + + var i, item, t, p; + + for (i = this.items.length - 1; i >= 0; i--){ + item = this.items[i]; + + //We ignore calculating positions of all connected containers when we're not over them + if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) { + continue; + } + + t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; + + if (!fast) { + item.width = t.outerWidth(); + item.height = t.outerHeight(); + } + + p = t.offset(); + item.left = p.left; + item.top = p.top; + } + + if(this.options.custom && this.options.custom.refreshContainers) { + this.options.custom.refreshContainers.call(this); + } else { + for (i = this.containers.length - 1; i >= 0; i--){ + p = this.containers[i].element.offset(); + this.containers[i].containerCache.left = p.left; + this.containers[i].containerCache.top = p.top; + this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); + this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); + } + } + + return this; + }, + + _createPlaceholder: function(that) { + that = that || this; + var className, + o = that.options; + + if(!o.placeholder || o.placeholder.constructor === String) { + className = o.placeholder; + o.placeholder = { + element: function() { + + var nodeName = that.currentItem[0].nodeName.toLowerCase(), + element = $( "<" + nodeName + ">", that.document[0] ) + .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") + .removeClass("ui-sortable-helper"); + + if ( nodeName === "tr" ) { + that.currentItem.children().each(function() { + $( "
        ", that.document[0] ) + .attr( "colspan", $( this ).attr( "colspan" ) || 1 ) + .appendTo( element ); + }); + } else if ( nodeName === "img" ) { + element.attr( "src", that.currentItem.attr( "src" ) ); + } + + if ( !className ) { + element.css( "visibility", "hidden" ); + } + + return element; + }, + update: function(container, p) { + + // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that + // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified + if(className && !o.forcePlaceholderSize) { + return; + } + + //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item + if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); } + if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); } + } + }; + } + + //Create the placeholder + that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); + + //Append it after the actual current item + that.currentItem.after(that.placeholder); + + //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) + o.placeholder.update(that, that.placeholder); + + }, + + _contactContainers: function(event) { + var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, base, cur, nearBottom, floating, + innermostContainer = null, + innermostIndex = null; + + // get innermost container that intersects with item + for (i = this.containers.length - 1; i >= 0; i--) { + + // never consider a container that's located within the item itself + if($.contains(this.currentItem[0], this.containers[i].element[0])) { + continue; + } + + if(this._intersectsWith(this.containers[i].containerCache)) { + + // if we've already found a container and it's more "inner" than this, then continue + if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) { + continue; + } + + innermostContainer = this.containers[i]; + innermostIndex = i; + + } else { + // container doesn't intersect. trigger "out" event if necessary + if(this.containers[i].containerCache.over) { + this.containers[i]._trigger("out", event, this._uiHash(this)); + this.containers[i].containerCache.over = 0; + } + } + + } + + // if no intersecting containers found, return + if(!innermostContainer) { + return; + } + + // move the item into the container if it's not there already + if(this.containers.length === 1) { + if (!this.containers[innermostIndex].containerCache.over) { + this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); + this.containers[innermostIndex].containerCache.over = 1; + } + } else { + + //When entering a new container, we will find the item with the least distance and append our item near it + dist = 10000; + itemWithLeastDistance = null; + floating = innermostContainer.floating || isFloating(this.currentItem); + posProperty = floating ? "left" : "top"; + sizeProperty = floating ? "width" : "height"; + base = this.positionAbs[posProperty] + this.offset.click[posProperty]; + for (j = this.items.length - 1; j >= 0; j--) { + if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) { + continue; + } + if(this.items[j].item[0] === this.currentItem[0]) { + continue; + } + if (floating && !isOverAxis(this.positionAbs.top + this.offset.click.top, this.items[j].top, this.items[j].height)) { + continue; + } + cur = this.items[j].item.offset()[posProperty]; + nearBottom = false; + if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){ + nearBottom = true; + cur += this.items[j][sizeProperty]; + } + + if(Math.abs(cur - base) < dist) { + dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; + this.direction = nearBottom ? "up": "down"; + } + } + + //Check if dropOnEmpty is enabled + if(!itemWithLeastDistance && !this.options.dropOnEmpty) { + return; + } + + if(this.currentContainer === this.containers[innermostIndex]) { + return; + } + + itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); + this._trigger("change", event, this._uiHash()); + this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); + this.currentContainer = this.containers[innermostIndex]; + + //Update the placeholder + this.options.placeholder.update(this.currentContainer, this.placeholder); + + this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); + this.containers[innermostIndex].containerCache.over = 1; + } + + + }, + + _createHelper: function(event) { + + var o = this.options, + helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem); + + //Add the helper to the DOM if that didn't happen already + if(!helper.parents("body").length) { + $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); + } + + if(helper[0] === this.currentItem[0]) { + this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") }; + } + + if(!helper[0].style.width || o.forceHelperSize) { + helper.width(this.currentItem.width()); + } + if(!helper[0].style.height || o.forceHelperSize) { + helper.height(this.currentItem.height()); + } + + return helper; + + }, + + _adjustOffsetFromHelper: function(obj) { + if (typeof obj === "string") { + obj = obj.split(" "); + } + if ($.isArray(obj)) { + obj = {left: +obj[0], top: +obj[1] || 0}; + } + if ("left" in obj) { + this.offset.click.left = obj.left + this.margins.left; + } + if ("right" in obj) { + this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; + } + if ("top" in obj) { + this.offset.click.top = obj.top + this.margins.top; + } + if ("bottom" in obj) { + this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; + } + }, + + _getParentOffset: function() { + + + //Get the offsetParent and cache its position + this.offsetParent = this.helper.offsetParent(); + var po = this.offsetParent.offset(); + + // This is a special case where we need to modify a offset calculated on start, since the following happened: + // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent + // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that + // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag + if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) { + po.left += this.scrollParent.scrollLeft(); + po.top += this.scrollParent.scrollTop(); + } + + // This needs to be actually done for all browsers, since pageX/pageY includes this information + // with an ugly IE fix + if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) { + po = { top: 0, left: 0 }; + } + + return { + top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), + left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) + }; + + }, + + _getRelativeOffset: function() { + + if(this.cssPosition === "relative") { + var p = this.currentItem.position(); + return { + top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), + left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft() + }; + } else { + return { top: 0, left: 0 }; + } + + }, + + _cacheMargins: function() { + this.margins = { + left: (parseInt(this.currentItem.css("marginLeft"),10) || 0), + top: (parseInt(this.currentItem.css("marginTop"),10) || 0) + }; + }, + + _cacheHelperProportions: function() { + this.helperProportions = { + width: this.helper.outerWidth(), + height: this.helper.outerHeight() + }; + }, + + _setContainment: function() { + + var ce, co, over, + o = this.options; + if(o.containment === "parent") { + o.containment = this.helper[0].parentNode; + } + if(o.containment === "document" || o.containment === "window") { + this.containment = [ + 0 - this.offset.relative.left - this.offset.parent.left, + 0 - this.offset.relative.top - this.offset.parent.top, + $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left, + ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top + ]; + } + + if(!(/^(document|window|parent)$/).test(o.containment)) { + ce = $(o.containment)[0]; + co = $(o.containment).offset(); + over = ($(ce).css("overflow") !== "hidden"); + + this.containment = [ + co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, + co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, + co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, + co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top + ]; + } + + }, + + _convertPositionTo: function(d, pos) { + + if(!pos) { + pos = this.position; + } + var mod = d === "absolute" ? 1 : -1, + scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, + scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); + + return { + top: ( + pos.top + // The absolute mouse position + this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) + ), + left: ( + pos.left + // The absolute mouse position + this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) + ) + }; + + }, + + _generatePosition: function(event) { + + var top, left, + o = this.options, + pageX = event.pageX, + pageY = event.pageY, + scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); + + // This is another very weird special case that only happens for relative elements: + // 1. If the css position is relative + // 2. and the scroll parent is the document or similar to the offset parent + // we have to refresh the relative offset during the scroll so there are no jumps + if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) { + this.offset.relative = this._getRelativeOffset(); + } + + /* + * - Position constraining - + * Constrain the position to a mix of grid, containment. + */ + + if(this.originalPosition) { //If we are not dragging yet, we won't check for options + + if(this.containment) { + if(event.pageX - this.offset.click.left < this.containment[0]) { + pageX = this.containment[0] + this.offset.click.left; + } + if(event.pageY - this.offset.click.top < this.containment[1]) { + pageY = this.containment[1] + this.offset.click.top; + } + if(event.pageX - this.offset.click.left > this.containment[2]) { + pageX = this.containment[2] + this.offset.click.left; + } + if(event.pageY - this.offset.click.top > this.containment[3]) { + pageY = this.containment[3] + this.offset.click.top; + } + } + + if(o.grid) { + top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; + pageY = this.containment ? ( (top - this.offset.click.top >= this.containment[1] && top - this.offset.click.top <= this.containment[3]) ? top : ((top - this.offset.click.top >= this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; + + left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; + pageX = this.containment ? ( (left - this.offset.click.left >= this.containment[0] && left - this.offset.click.left <= this.containment[2]) ? left : ((left - this.offset.click.left >= this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; + } + + } + + return { + top: ( + pageY - // The absolute mouse position + this.offset.click.top - // Click offset (relative to the element) + this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.top + // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) + ), + left: ( + pageX - // The absolute mouse position + this.offset.click.left - // Click offset (relative to the element) + this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.left + // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) + ) + }; + + }, + + _rearrange: function(event, i, a, hardRefresh) { + + a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction === "down" ? i.item[0] : i.item[0].nextSibling)); + + //Various things done here to improve the performance: + // 1. we create a setTimeout, that calls refreshPositions + // 2. on the instance, we have a counter variable, that get's higher after every append + // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same + // 4. this lets only the last addition to the timeout stack through + this.counter = this.counter ? ++this.counter : 1; + var counter = this.counter; + + this._delay(function() { + if(counter === this.counter) { + this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove + } + }); + + }, + + _clear: function(event, noPropagation) { + + this.reverting = false; + // We delay all events that have to be triggered to after the point where the placeholder has been removed and + // everything else normalized again + var i, + delayedTriggers = []; + + // We first have to update the dom position of the actual currentItem + // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) + if(!this._noFinalSort && this.currentItem.parent().length) { + this.placeholder.before(this.currentItem); + } + this._noFinalSort = null; + + if(this.helper[0] === this.currentItem[0]) { + for(i in this._storedCSS) { + if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") { + this._storedCSS[i] = ""; + } + } + this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); + } else { + this.currentItem.show(); + } + + if(this.fromOutside && !noPropagation) { + delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); }); + } + if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) { + delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed + } + + // Check if the items Container has Changed and trigger appropriate + // events. + if (this !== this.currentContainer) { + if(!noPropagation) { + delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); + delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); + delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); + } + } + + + //Post events to containers + for (i = this.containers.length - 1; i >= 0; i--){ + if(!noPropagation) { + delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); + } + if(this.containers[i].containerCache.over) { + delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); + this.containers[i].containerCache.over = 0; + } + } + + //Do what was originally in plugins + if ( this.storedCursor ) { + this.document.find( "body" ).css( "cursor", this.storedCursor ); + this.storedStylesheet.remove(); + } + if(this._storedOpacity) { + this.helper.css("opacity", this._storedOpacity); + } + if(this._storedZIndex) { + this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex); + } + + this.dragging = false; + if(this.cancelHelperRemoval) { + if(!noPropagation) { + this._trigger("beforeStop", event, this._uiHash()); + for (i=0; i < delayedTriggers.length; i++) { + delayedTriggers[i].call(this, event); + } //Trigger all delayed events + this._trigger("stop", event, this._uiHash()); + } + + this.fromOutside = false; + return false; + } + + if(!noPropagation) { + this._trigger("beforeStop", event, this._uiHash()); + } + + //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! + this.placeholder[0].parentNode.removeChild(this.placeholder[0]); + + if(this.helper[0] !== this.currentItem[0]) { + this.helper.remove(); + } + this.helper = null; + + if(!noPropagation) { + for (i=0; i < delayedTriggers.length; i++) { + delayedTriggers[i].call(this, event); + } //Trigger all delayed events + this._trigger("stop", event, this._uiHash()); + } + + this.fromOutside = false; + return true; + + }, + + _trigger: function() { + if ($.Widget.prototype._trigger.apply(this, arguments) === false) { + this.cancel(); + } + }, + + _uiHash: function(_inst) { + var inst = _inst || this; + return { + helper: inst.helper, + placeholder: inst.placeholder || $([]), + position: inst.position, + originalPosition: inst.originalPosition, + offset: inst.positionAbs, + item: inst.currentItem, + sender: _inst ? _inst.element : null + }; + } + +}); + +})(jQuery); +;/* jQuery Tiny Pub/Sub - v0.7 - 10/27/2011 + * http://benalman.com/ + * Copyright (c) 2011 "Cowboy" Ben Alman; Licensed MIT, GPL */ + +(function($) { + + var o = $({}); + + $.subscribe = function() { + //console.log("SUBSCRIBE: " + arguments[0]); + o.on.apply(o, arguments); + }; + + $.unsubscribe = function() { + o.off.apply(o, arguments); + }; + + $.publish = function() { + //console.log("PUBLISH: " + arguments[0]); + o.trigger.apply(o, arguments); + }; + +}(jQuery)); + + +;/* =========================================================== + * bootstrap-tooltip.js v2.1.1 + * http://twitter.github.com/bootstrap/javascript.html#tooltips + * Inspired by the original jQuery.tipsy by Jason Frame + * =========================================================== + * Copyright 2012 Twitter, 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. + * ========================================================== */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* TOOLTIP PUBLIC CLASS DEFINITION + * =============================== */ + + var Tooltip = function (element, options) { + this.init('tooltip', element, options) + } + + Tooltip.prototype = { + + constructor: Tooltip + + , init: function (type, element, options) { + var eventIn + , eventOut + + this.type = type + this.$element = $(element) + this.options = this.getOptions(options) + this.enabled = true + + if (this.options.trigger == 'click') { + this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) + } else if (this.options.trigger != 'manual') { + eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus' + eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur' + 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() + } + + , getOptions: function (options) { + options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data()) + + if (options.delay && typeof options.delay == 'number') { + options.delay = { + show: options.delay + , hide: options.delay + } + } + + return options + } + + , enter: function (e) { + var self = $(e.currentTarget)[this.type](this._options).data(this.type) + + if (!self.options.delay || !self.options.delay.show) return self.show() + + clearTimeout(this.timeout) + self.hoverState = 'in' + this.timeout = setTimeout(function() { + if (self.hoverState == 'in') self.show() + }, self.options.delay.show) + } + + , leave: function (e) { + var self = $(e.currentTarget)[this.type](this._options).data(this.type) + + if (this.timeout) clearTimeout(this.timeout) + if (!self.options.delay || !self.options.delay.hide) return self.hide() + + self.hoverState = 'out' + this.timeout = setTimeout(function() { + if (self.hoverState == 'out') self.hide() + }, self.options.delay.hide) + } + + , show: function () { + var $tip + , inside + , pos + , actualWidth + , actualHeight + , placement + , tp + + if (this.hasContent() && this.enabled) { + $tip = this.tip() + this.setContent() + + if (this.options.animation) { + $tip.addClass('fade') + } + + placement = typeof this.options.placement == 'function' ? + this.options.placement.call(this, $tip[0], this.$element[0]) : + this.options.placement + + inside = /in/.test(placement) + + $tip + .remove() + .css({ top: 0, left: 0, display: 'block' }) + .appendTo(inside ? this.$element : document.body) + + pos = this.getPosition(inside) + + actualWidth = $tip[0].offsetWidth + actualHeight = $tip[0].offsetHeight + + switch (inside ? placement.split(' ')[1] : placement) { + case 'bottom': + tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} + break + case 'top': + tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} + break + case 'left': + tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} + break + case 'right': + tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width} + break + } + + $tip + .css(tp) + .addClass(placement) + .addClass('in') + } + } + + , setContent: function () { + var $tip = this.tip() + , title = this.getTitle() + + $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) + $tip.removeClass('fade in top bottom left right') + } + + , hide: function () { + var that = this + , $tip = this.tip() + + $tip.removeClass('in') + + function removeWithAnimation() { + var timeout = setTimeout(function () { + $tip.off($.support.transition.end).remove() + }, 500) + + $tip.one($.support.transition.end, function () { + clearTimeout(timeout) + $tip.remove() + }) + } + + $.support.transition && this.$tip.hasClass('fade') ? + removeWithAnimation() : + $tip.remove() + + return this + } + + , 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') || '').removeAttr('title') + } + } + + , hasContent: function () { + return this.getTitle() + } + + , getPosition: function (inside) { + return $.extend({}, (inside ? {top: 0, left: 0} : this.$element.offset()), { + width: this.$element[0].offsetWidth + , height: this.$element[0].offsetHeight + }) + } + + , getTitle: function () { + var title + , $e = this.$element + , o = this.options + + title = $e.attr('data-original-title') + || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) + + return title + } + + , tip: function () { + return this.$tip = this.$tip || $(this.options.template) + } + + , validate: function () { + if (!this.$element[0].parentNode) { + this.hide() + this.$element = null + this.options = null + } + } + + , enable: function () { + this.enabled = true + } + + , disable: function () { + this.enabled = false + } + + , toggleEnabled: function () { + this.enabled = !this.enabled + } + + , toggle: function () { + this[this.tip().hasClass('in') ? 'hide' : 'show']() + } + + , destroy: function () { + this.hide().$element.off('.' + this.type).removeData(this.type) + } + + } + + + /* TOOLTIP PLUGIN DEFINITION + * ========================= */ + + $.fn.tooltip = function ( option ) { + return this.each(function () { + var $this = $(this) + , data = $this.data('tooltip') + , options = typeof option == 'object' && option + if (!data) $this.data('tooltip', (data = new Tooltip(this, options))) + if (typeof option == 'string') data[option]() + }) + } + + $.fn.tooltip.Constructor = Tooltip + + $.fn.tooltip.defaults = { + animation: true + , placement: 'top' + , selector: false + , template: '
        ' + , trigger: 'hover' + , title: '' + , delay: 0 + , html: true + } + +}(window.jQuery); +;// TODO(grosbouddha): put under pskl namespace. +// biome-ignore lint/correctness/noUnusedVariables: global +var Constants = { + DEFAULT: { + HEIGHT: 32, + WIDTH: 32, + FPS: 12, + LAYER_OPACITY: 0.2 + }, + + MODEL_VERSION: 2, + + MAX_HEIGHT: 1024, + MAX_WIDTH: 1024, + + MAX_PALETTE_COLORS: 256, + // allow current colors service to get up to 256 colors. + // GIF generation is different if the color count goes over 256. + MAX_WORKER_COLORS: 256, + + PREVIEW_FILM_SIZE: 96, + ANIMATED_PREVIEW_WIDTH: 200, + // Keep in sync with padding-left: 10px in layout.css + RIGHT_COLUMN_PADDING_LEFT: 10, + + DEFAULT_PEN_COLOR: "#000000", + TRANSPARENT_COLOR: "rgba(0, 0, 0, 0)", + SEAMLESS_MODE_OVERLAY_COLOR: "rgba(255, 255, 255, 0)", + + CURRENT_COLORS_PALETTE_ID: "__current-colors", + + /* + * Fake semi-transparent color used to highlight transparent + * strokes and rectangles: + */ + SELECTION_TRANSPARENT_COLOR: "rgba(160, 215, 240, 0.6)", + + /* + * When a tool is hovering the drawing canvas, we highlight the eventual + * pixel target with this color: + */ + TOOL_HIGHLIGHT_COLOR_LIGHT: "rgba(255, 255, 255, 0.2)", + TOOL_HIGHLIGHT_COLOR_DARK: "rgba(0, 0, 0, 0.2)", + + ZOOMED_OUT_BACKGROUND_COLOR: "#A0A0A0", + + LEFT_BUTTON: 0, + MIDDLE_BUTTON: 1, + RIGHT_BUTTON: 2, + MOUSEMOVE_THROTTLING: 10, + + ABSTRACT_FUNCTION: function () { + throw "abstract method should be implemented"; + }, + EMPTY_FUNCTION: function () {}, + + // TESTS + DRAWING_TEST_FOLDER: "drawing", + + // Maximum size of a sprite that can be saved on piskelapp datastore. + // This size will be compared to the length of the stringified serialization of the sprite. + // This is an approximation at best but gives correct results in most cases. + // The datastore limit is 1 MiB, which we roughly approximate to 1 million characters. + APPENGINE_SAVE_LIMIT: 1 * 1024 * 1024, + + // Message displayed when an action will lead to erase the current animation. + CONFIRM_OVERWRITE: + "This will replace your current animation, are you sure you want to continue?", + + // SERVICE URLS + APPENGINE_SAVE_URL: "save" +}; +;// TODO(grosbouddha): put under pskl namespace. +// biome-ignore lint/correctness/noUnusedVariables: global +var Events = { + TOOL_SELECTED: "TOOL_SELECTED", + SELECT_TOOL: "SELECT_TOOL", + + TOOL_RELEASED: "TOOL_RELEASED", + TOOL_PRESSED: "TOOL_PRESSED", + SELECT_PRIMARY_COLOR: "SELECT_PRIMARY_COLOR", + SELECT_SECONDARY_COLOR: "SELECT_SECONDARY_COLOR", + PRIMARY_COLOR_SELECTED: "PRIMARY_COLOR_SELECTED", + SECONDARY_COLOR_SELECTED: "SECONDARY_COLOR_SELECTED", + + CURSOR_MOVED: "CURSOR_MOVED", + DRAG_START: "DRAG_START", + DRAG_END: "DRAG_END", + + DIALOG_SHOW: "DIALOG_SHOW", + DIALOG_HIDE: "DIALOG_HIDE", + + PALETTE_LIST_UPDATED: "PALETTE_LIST_UPDATED", + + /** + * Fired each time a user setting change. + * The payload will be: + * 1st argument: Name of the settings + * 2nd argument: New value + */ + USER_SETTINGS_CHANGED: "USER_SETTINGS_CHANGED", + SHORTCUTS_CHANGED: "SHORTCUTS_CHANGED", + + CLOSE_SETTINGS_DRAWER: "CLOSE_SETTINGS_DRAWER", + + /** + * The framesheet was reseted and is now probably drastically different. + * Number of frames, content of frames, color used for the palette may have changed. + */ + PISKEL_RESET: "PISKEL_RESET", + PISKEL_SAVE_STATE: "PISKEL_SAVE_STATE", + PISKEL_DESCRIPTOR_UPDATED: "PISKEL_DESCRIPTOR_UPDATED", + PISKEL_SAVED_STATUS_UPDATE: "PISKEL_SAVED_STATUS_UPDATE", + + HISTORY_STATE_SAVED: "HISTORY_STATE_SAVED", + HISTORY_STATE_LOADED: "HISTORY_STATE_LOADED", + + PEN_SIZE_CHANGED: "PEN_SIZE_CHANGED", + + /** + * Fired when a Piskel is successfully saved + */ + PISKEL_SAVED: "PISKEL_SAVED", + /** + * Fired when a save action starts + */ + BEFORE_SAVING_PISKEL: "BEFORE_SAVING_PISKEL", + /** + * Fired when a save action ends. Always fires, even if saving was not successful + */ + AFTER_SAVING_PISKEL: "AFTER_SAVING_PISKEL", + + FRAME_SIZE_CHANGED: "FRAME_SIZE_CHANGED", + FPS_CHANGED: "FPS_CHANGED", + + SELECTION_CREATED: "SELECTION_CREATED", + SELECTION_MOVE_REQUEST: "SELECTION_MOVE_REQUEST", + SELECTION_DISMISSED: "SELECTION_DISMISSED", + + CLIPBOARD_COPY: "CLIPBOARD_COPY", + CLIPBOARD_CUT: "CLIPBOARD_CUT", + CLIPBOARD_PASTE: "CLIPBOARD_PASTE", + + SHOW_NOTIFICATION: "SHOW_NOTIFICATION", + HIDE_NOTIFICATION: "HIDE_NOTIFICATION", + + SHOW_PROGRESS: "SHOW_PROGRESS", + UPDATE_PROGRESS: "UPDATE_PROGRESS", + HIDE_PROGRESS: "HIDE_PROGRESS", + + ZOOM_CHANGED: "ZOOM_CHANGED", + EXPORT_SCALE_CHANGED: "EXPORT_SCALE_CHANGED", + + CURRENT_COLORS_UPDATED: "CURRENT_COLORS_UPDATED", + + PERFORMANCE_REPORT_CHANGED: "PERFORMANCE_REPORT_CHANGED", + + PISKEL_FILE_IMPORT_FAILED: "PISKEL_FILE_IMPORT_FAILED", + + // Tests + MOUSE_EVENT: "MOUSE_EVENT", + KEYBOARD_EVENT: "KEYBOARD_EVENT", + TRANSFORMATION_EVENT: "TRANSFORMATION_EVENT", + TEST_RECORD_END: "TEST_RECORD_END", + TEST_CASE_END: "TEST_CASE_END", + TEST_SUITE_END: "TEST_SUITE_END", + + // A piskel external to the editor has been loaded and attached + // to window._externalPiskel to be applied. + EXTERNAL_PISKEL_READY: "EXTERNAL_PISKEL_READY" +}; +;jQuery.namespace = function () { + var a = arguments; + var o = null; + for (var i = 0; i < a.length; i++) { + var d = a[i].split("."); + o = window; + for (var j = 0; j < d.length; j++) { + o[d[j]] = o[d[j]] || {}; + o = o[d[j]]; + } + } + return o; +}; + +/** + * Need a polyfill for PhantomJS + */ +if (!Function.prototype.bind) { + Function.prototype.bind = function (oThis) { + if (typeof this !== "function") { + // closest thing possible to the ECMAScript 5 + // internal IsCallable function + throw new TypeError( + "Function.prototype.bind - what is trying to be bound is not callable" + ); + } + + var bindArgs = Array.prototype.slice.call(arguments, 1); + var fToBind = this; + var FNOP = function () {}; + var fBound = function () { + var args = bindArgs.concat(Array.prototype.slice.call(arguments)); + return fToBind.apply(this instanceof FNOP && oThis ? this : oThis, args); + }; + + FNOP.prototype = this.prototype; + fBound.prototype = new FNOP(); + + return fBound; + }; +} + +/** + * Polyfill for typedarrays' fill method for PhantomJS + */ +if (!Uint32Array.prototype.fill) { + Uint32Array.prototype.fill = function (value, start, end) { + start = typeof start === "undefined" ? 0 : start; + end = typeof end === "undefined" ? this.length : end; + + if (start < 0) { + start = this.length + start; + } + + if (end < 0) { + end = this.length + end; + } + + for (var i = start; i < end; i++) { + this[i] = value; + } + }; +} + +/** + * @provide pskl.utils + * + * @require Constants + */ +(function () { + // namespace: pskl.utils + + var ns = $.namespace("pskl.utils"); + + /** + * Convert a rgb(Number, Number, Number) color to hexadecimal representation + * @param {Number} r red value, between 0 and 255 + * @param {Number} g green value, between 0 and 255 + * @param {Number} b blue value, between 0 and 255 + * @return {String} hex representation of the color '#ABCDEF' + */ + ns.rgbToHex = function (r, g, b) { + return ( + "#" + + pskl.utils.componentToHex(r) + + pskl.utils.componentToHex(g) + + pskl.utils.componentToHex(b) + ); + }; + + /** + * Convert a color component (as a Number between 0 and 255) to its string hexa representation + * @param {Number} c component value, between 0 and 255 + * @return {String} eg. '0A' + */ + ns.componentToHex = function (c) { + var hex = c.toString(16); + return hex.length == 1 ? "0" + hex : hex; + }; + + var intHexCache = {}; + ns.intToHex = function (int) { + if (intHexCache[int]) { + return intHexCache[int]; + } + + var hex = ns.rgbToHex(int & 0xff, (int >> 8) & 0xff, (int >> 16) & 0xff); + intHexCache[int] = hex; + return hex; + }; + + ns.normalize = function (value, def) { + if (typeof value === "undefined" || value === null) { + return def; + } else { + return value; + } + }; + + ns.inherit = function (extendedObject, inheritFrom) { + extendedObject.prototype = Object.create(inheritFrom.prototype); + extendedObject.prototype.constructor = extendedObject; + extendedObject.prototype.superclass = inheritFrom.prototype; + }; + + ns.wrap = function (wrapper, wrappedObject) { + for (var prop in wrappedObject) { + if ( + typeof wrappedObject[prop] === "function" && + typeof wrapper[prop] === "undefined" + ) { + wrapper[prop] = wrappedObject[prop].bind(wrappedObject); + } + } + }; + + ns.hashCode = function (str) { + var hash = 0; + if (str.length === 0) { + return hash; + } + + for (var i = 0, len = str.length, chr; i < len; i++) { + chr = str.charCodeAt(i); + hash = hash * 31 + chr; + hash |= 0; // Convert to 32bit integer + } + + return hash; + }; + + ns.copy = function (object) { + return JSON.parse(JSON.stringify(object)); + }; + + var entityMap = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + "/": "/" + }; + ns.escapeHtml = function (string) { + return String(string).replace(/[&<>"'\/]/g, function (s) { + return entityMap[s]; + }); + }; + + var colorCache = {}; + var colorCacheReverse = {}; + ns.colorToInt = function (color) { + if (typeof color === "number") { + return color; + } + + if (typeof colorCache[color] !== "undefined") { + return colorCache[color]; + } + + var tc = window.tinycolor(color); + if (tc && tc.ok) { + var rgb = tc.toRgb(); + var a = Math.round(rgb.a * 255); + var intValue = ((a << 24) >>> 0) + (rgb.b << 16) + (rgb.g << 8) + rgb.r; + if (a === 0) { + // assign all 'transparent' colors to 0, theoretically mapped to rgba(0,0,0,0) only + intValue = 0; + } + colorCache[color] = intValue; + colorCacheReverse[intValue] = color; + return intValue; + } else { + // If tinycolor failed, determine color by using the browser + var d = document.createElement("div"); + d.style.color = color; + document.body.appendChild(d); + + // Color in RGB + color = window.getComputedStyle(d).color; + document.body.removeChild(d); + + return pskl.utils.colorToInt(color); + } + }; + + ns.intToColor = function (intValue) { + if (typeof intValue === "string") { + return intValue; + } + + if (typeof colorCacheReverse[intValue] !== "undefined") { + return colorCacheReverse[intValue]; + } + + var r = intValue & 0xff; + var g = (intValue >> 8) & 0xff; + var b = (intValue >> 16) & 0xff; + var a = (((intValue >> 24) >>> 0) & 0xff) / 255; + var color = "rgba(" + r + "," + g + "," + b + "," + a + ")"; + + colorCache[color] = intValue; + colorCacheReverse[intValue] = color; + return color; + }; + + var reEntityMap = {}; + ns.unescapeHtml = function (string) { + Object.keys(entityMap).forEach(function (key) { + reEntityMap[key] = reEntityMap[key] || new RegExp(entityMap[key], "g"); + string = string.replace(reEntityMap[key], key); + }); + return string; + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + var ua = navigator.userAgent; + + ns.UserAgent = { + isIE: /MSIE/i.test(ua), + isIE11: /trident/i.test(ua), + isEdge: /edge\//i.test(ua), + isFirefox: /Firefox/i.test(ua), + isMac: /Mac/.test(ua), + isOpera: /OPR\//.test(ua), + hasChrome: /Chrome/i.test(ua), + hasSafari: /Safari\//.test(ua) + }; + + ns.UserAgent.isChrome = + ns.UserAgent.hasChrome && !ns.UserAgent.isOpera && !ns.UserAgent.isEdge; + ns.UserAgent.isSafari = + ns.UserAgent.hasSafari && !ns.UserAgent.isOpera && !ns.UserAgent.isEdge; + + ns.UserAgent.supportedUserAgents = [ + "isIE11", + "isEdge", + "isChrome", + "isFirefox" + ]; + + ns.UserAgent.version = (function () { + if (pskl.utils.UserAgent.isIE) { + return parseInt(/MSIE\s?(\d+)/i.exec(ua)[1], 10); + } else if (pskl.utils.UserAgent.isChrome) { + return parseInt(/Chrome\/(\d+)/i.exec(ua)[1], 10); + } else if (pskl.utils.UserAgent.isFirefox) { + return parseInt(/Firefox\/(\d+)/i.exec(ua)[1], 10); + } + })(); + + ns.UserAgent.isUnsupported = function () { + // Check that none of the supported UAs are set to true. + return ns.UserAgent.supportedUserAgents.every(function (uaTest) { + return !ns.UserAgent[uaTest]; + }); + }; + + ns.UserAgent.getDisplayName = function () { + if (ns.UserAgent.isIE) { + return "Internet Explorer"; + } else if (ns.UserAgent.isChrome) { + return "Chrome"; + } else if (ns.UserAgent.isFirefox) { + return "Firefox"; + } else if (ns.UserAgent.isSafari) { + return "Safari"; + } else if (ns.UserAgent.isOpera) { + return "Opera"; + } else { + return ua; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.Array = { + find: function (array, filterFn) { + var match = null; + array = Array.isArray(array) ? array : []; + var filtered = array.filter(filterFn); + if (filtered.length) { + match = filtered[0]; + } + return match; + }, + + /** + * Split a provided array in a given amount of chunks. + * For instance [1,2,3,4] chunked in 2 parts will be [1,2] & [3,4]. + * @param {Array} array the array to chunk + * @param {Number} chunksCount the number of chunks to create + * @return {Array} array of arrays containing the items of the original array + */ + chunk: function (array, chunksCount) { + var chunks = []; + + // We cannot have more chunks than array items. + chunksCount = Math.min(chunksCount, array.length); + + // chunksCount should be at least 1 + chunksCount = Math.max(1, chunksCount); + + var step = Math.round(array.length / chunksCount); + for (var i = 0; i < chunksCount; i++) { + var isLast = i == chunksCount - 1; + var end = isLast ? array.length : (i + 1) * step; + chunks.push(array.slice(i * step, end)); + } + return chunks; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var base64Ranks; + if (Uint8Array) { + base64Ranks = new Uint8Array([ + 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 0, + -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, + 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51 + ]); + } + + ns.Base64 = { + toText: function (base64) { + return window.atob(base64.replace(/data\:.*?\;base64\,/, "")); + }, + + decode: function (base64) { + var outptr = 0; + var last = [0, 0]; + var state = 0; + var save = 0; + + var undef; + var len = base64.length; + var i = 0; + var buffer = new Uint8Array(((len / 4) * 3) | 0); + while (len--) { + var code = base64.charCodeAt(i++); + var rank = base64Ranks[code - 43]; + if (rank !== 255 && rank !== undef) { + last[1] = last[0]; + last[0] = code; + save = (save << 6) | rank; + state++; + if (state === 4) { + buffer[outptr++] = save >>> 16; + if (last[1] !== 61 /* padding character */) { + buffer[outptr++] = save >>> 8; + } + if (last[0] !== 61 /* padding character */) { + buffer[outptr++] = save; + } + state = 0; + } + } + } + // 2/3 chance there's going to be some null bytes at the end, but that + // doesn't really matter with most image formats. + // If it somehow matters for you, truncate the buffer up outptr. + return buffer.buffer; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var BASE64_REGEX = /\s*;\s*base64\s*(?:;|$)/i; + + ns.BlobUtils = { + dataToBlob: function (dataURI, type, callback) { + var headerEnd = dataURI.indexOf(","); + var data = dataURI.substring(headerEnd + 1); + var isBase64 = BASE64_REGEX.test(dataURI.substring(0, headerEnd)); + var blob; + + if (Blob.fake) { + // no reason to decode a data: URI that's just going to become a data URI again + blob = new Blob(); + blob.encoding = isBase64 ? "base64" : "URI"; + blob.data = data; + blob.size = data.length; + } else if (Uint8Array) { + var blobData = isBase64 + ? pskl.utils.Base64.decode(data) + : decodeURIComponent(data); + blob = new Blob([blobData], { type: type }); + } + callback(blob); + }, + + canvasToBlob: function (canvas, callback, type /*, ...args*/) { + type = type || "image/png"; + + if (canvas.mozGetAsFile) { + callback(canvas.mozGetAsFile("canvas", type)); + } else { + var args = Array.prototype.slice.call(arguments, 2); + var dataURI = canvas.toDataURL.apply(canvas, args); + pskl.utils.BlobUtils.dataToBlob(dataURI, type, callback); + } + }, + + stringToBlob: function (string, callback, type) { + type = type || "text/plain"; + pskl.utils.BlobUtils.dataToBlob( + "data:" + type + "," + string, + type, + callback + ); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.CanvasUtils = { + createCanvas: function (width, height, classList) { + var canvas = document.createElement("canvas"); + canvas.setAttribute("width", width); + canvas.setAttribute("height", height); + + if (typeof classList == "string") { + classList = [classList]; + } + if (Array.isArray(classList)) { + for (var i = 0; i < classList.length; i++) { + canvas.classList.add(classList[i]); + } + } + + return canvas; + }, + + createFromImageData: function (imageData) { + var canvas = pskl.utils.CanvasUtils.createCanvas( + imageData.width, + imageData.height + ); + var context = canvas.getContext("2d"); + context.putImageData(imageData, 0, 0); + return canvas; + }, + + createFromImage: function (image) { + var canvas = pskl.utils.CanvasUtils.createCanvas( + image.width, + image.height + ); + var context = canvas.getContext("2d"); + context.drawImage(image, 0, 0); + return canvas; + }, + + /** + * Splits the specified image into several new canvas elements based on the + * supplied offset and frame sizes + * @param image The source image that will be split + * @param {Number} offsetX The padding from the left side of the source image + * @param {Number} offsetY The padding from the top side of the source image + * @param {Number} width The width of an individual frame + * @param {Number} height The height of an individual frame + * @param {Boolean} useHorizonalStrips True if the frames should be layed out from left to + * right, False if it should use top to bottom + * @param {Boolean} ignoreEmptyFrames True to ignore empty frames, false to keep them + * @returns {Array} An array of canvas elements that contain the split frames + */ + createFramesFromImage: function ( + image, + offsetX, + offsetY, + width, + height, + useHorizonalStrips, + ignoreEmptyFrames + ) { + var canvasArray = []; + var x = offsetX; + var y = offsetY; + var blankData = pskl.utils.CanvasUtils.createCanvas( + width, + height + ).toDataURL(); + + while (x + width <= image.width && y + height <= image.height) { + // Create a new canvas element + var canvas = pskl.utils.CanvasUtils.createCanvas(width, height); + var context = canvas.getContext("2d"); + + // Blit the correct part of the source image into the new canvas + context.drawImage(image, x, y, width, height, 0, 0, width, height); + + if (!ignoreEmptyFrames || canvas.toDataURL() !== blankData) { + canvasArray.push(canvas); + } + + if (useHorizonalStrips) { + // Move from left to right + x += width; + if (x + width > image.width) { + x = offsetX; + y += height; + } + } else { + // Move from top to bottom + y += height; + if (y + height > image.height) { + x += width; + y = offsetY; + } + } + } + + return canvasArray; + }, + + /** + * By default, all scaling operations on a Canvas 2D Context are performed using antialiasing. + * Resizing a 32x32 image to 320x320 will lead to a blurry output. + * On Chrome, FF and IE>=11, this can be disabled by setting a property on the Canvas 2D Context. + * In this case the browser will use a nearest-neighbor scaling. + * @param {Canvas} canvas + */ + disableImageSmoothing: function (canvas) { + pskl.utils.CanvasUtils.setImageSmoothing(canvas, false); + }, + + enableImageSmoothing: function (canvas) { + pskl.utils.CanvasUtils.setImageSmoothing(canvas, true); + }, + + setImageSmoothing: function (canvas, smoothing) { + var context = canvas.getContext("2d"); + context.imageSmoothingEnabled = smoothing; + context.mozImageSmoothingEnabled = smoothing; + context.oImageSmoothingEnabled = smoothing; + context.webkitImageSmoothingEnabled = smoothing; + context.msImageSmoothingEnabled = smoothing; + }, + + clear: function (canvas) { + if (canvas) { + canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height); + } + }, + + clone: function (canvas) { + var clone = pskl.utils.CanvasUtils.createCanvas( + canvas.width, + canvas.height + ); + + //apply the old canvas to the new one + clone.getContext("2d").drawImage(canvas, 0, 0); + + //return the new canvas + return clone; + }, + + getImageDataFromCanvas: function (canvas) { + var sourceContext = canvas.getContext("2d"); + return sourceContext.getImageData(0, 0, canvas.width, canvas.height).data; + }, + + getBase64FromCanvas: function (canvas, format) { + format = format || "png"; + var data = canvas.toDataURL("image/" + format); + return data.substr(data.indexOf(",") + 1); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.ColorUtils = { + getUnusedColor: function (usedColors) { + usedColors = usedColors || []; + // create check map + var colorMap = {}; + usedColors.forEach(function (color) { + colorMap[color.toUpperCase()] = true; + }); + + // start with white + var color = { + r: 255, + g: 255, + b: 0 + }; + var match = null; + while (true) { + var hex = window.tinycolor(color).toHexString().toUpperCase(); + + if (!colorMap[hex]) { + match = hex; + break; + } else { + // pick a non null component to decrease its value + var component = + (color.r && "r") || (color.g && "g") || (color.b && "b"); + if (component) { + color[component] = color[component] - 1; + } else { + // no component available, no match found + break; + } + } + } + + return match; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var pad = function (num) { + if (num < 10) { + return "0" + num; + } else { + return "" + num; + } + }; + + ns.DateUtils = { + format: function (date, format) { + date = new Date(date); + return pskl.utils.Template.replace(format, { + Y: date.getFullYear(), + M: pad(date.getMonth() + 1), + D: pad(date.getDate()), + H: pad(date.getHours()), + m: pad(date.getMinutes()), + s: pad(date.getSeconds()) + }); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.Dom = { + /** + * Check if a given HTML element is nested inside another + * @param {HTMLElement} node Element to test + * @param {HTMLElement} parent Potential Ancestor for node + * @param {Boolean} excludeParent set to true if the parent should be excluded from potential matches + * @return {Boolean} true if parent was found amongst the parentNode chain of node + */ + isParent: function (node, parent, excludeParent) { + if (node && parent) { + if (excludeParent) { + node = node.parentNode; + } + + while (node) { + if (node === parent) { + return true; + } + node = node.parentNode; + } + } + return false; + }, + + getParentWithData: function (node, dataName) { + while (node) { + if (node.dataset && typeof node.dataset[dataName] !== "undefined") { + return node; + } + node = node.parentNode; + } + return null; + }, + + getData: function (node, dataName) { + var parent = ns.Dom.getParentWithData(node, dataName); + if (parent !== null) { + return parent.dataset[dataName]; + } + }, + + removeClass: function (className, container) { + container = container || document; + var elements = container.querySelectorAll("." + className); + for (var i = 0; i < elements.length; i++) { + elements[i].classList.remove(className); + } + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.Event = {}; + + ns.Event.addEventListener = function (el, type, callback, scope, args) { + if (typeof el === "string") { + el = document.querySelector(el); + } + + var listener = { + el: el, + type: type, + callback: callback, + handler: args ? callback.bind(scope, args) : callback.bind(scope) + }; + + scope.__pskl_listeners = scope.__pskl_listeners || []; + scope.__pskl_listeners.push(listener); + el.addEventListener(type, listener.handler); + }; + + ns.Event.removeEventListener = function (el, type, callback, scope) { + if (scope && scope.__pskl_listeners) { + var listeners = scope.__pskl_listeners; + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + if ( + listener.callback === callback && + listener.el === el && + listener.type === type + ) { + el.removeEventListener(type, listeners[i].handler); + listeners.splice(i, 1); + break; + } + } + } + }; + + ns.Event.removeAllEventListeners = function (scope) { + if (scope && scope.__pskl_listeners) { + var listeners = scope.__pskl_listeners; + for (var i = 0; i < listeners.length; i++) { + var listener = listeners[i]; + listener.el.removeEventListener(listener.type, listener.handler); + } + scope.__pskl_listeners = []; + } + }; +})(); +;/** + * detection method from: + * http://videlais.com/2014/08/23/lessons-learned-from-detecting-node-webkit/ + */ + +(function () { + var ns = $.namespace("pskl.utils"); + + ns.Environment = { + detectNodeWebkit: function () { + var isNode = + typeof window.process !== "undefined" && + typeof window.require !== "undefined"; + var isNodeWebkit = false; + if (isNode) { + try { + isNodeWebkit = typeof window.require("nw.gui") !== "undefined"; + } catch { + isNodeWebkit = false; + } + } + return isNodeWebkit; + }, + + isIntegrationTest: function () { + return window.location.href.indexOf("integration-test") !== -1; + }, + + isHttps: function () { + return window.location.href.indexOf("https://") === 0; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.FunctionUtils = { + /** + * Returns a memoized version of the provided function. + */ + memo: function (fn, cache, scope) { + var memoized = function () { + var key = Array.prototype.join.call(arguments, "-"); + if (!cache[key]) { + cache[key] = fn.apply(scope, arguments); + } + return cache[key]; + }; + return memoized; + }, + + /** + * Returns a throttled version of the provided method, that will be called at most + * every X milliseconds, where X is the provided interval. + */ + throttle: function (fn, interval) { + var last; + var timer; + return function () { + var now = Date.now(); + if (last && now < last + interval) { + clearTimeout(timer); + timer = setTimeout(function () { + last = now; + fn(); + }, interval); + } else { + last = now; + fn(); + } + }; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.Math = { + minmax: function (val, min, max) { + return Math.max(Math.min(val, max), min); + }, + + /** + * Calculate the distance between {x0, y0} and {x1, y1} + */ + distance: function (x0, x1, y0, y1) { + var dx = Math.abs(x1 - x0); + var dy = Math.abs(y1 - y0); + return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var stopPropagation = function (e) { + e.stopPropagation(); + }; + + ns.FileUtils = { + readFile: function (file, callback) { + var reader = new FileReader(); + reader.addEventListener("loadend", function () { + callback(reader.result); + }); + reader.readAsDataURL(file); + }, + + readFileAsArrayBuffer: function (file, callback) { + var reader = new FileReader(); + reader.addEventListener("loadend", function () { + callback(reader.result); + }); + reader.readAsArrayBuffer(file); + }, + + readImageFile: function (file, callback) { + ns.FileUtils.readFile(file, function (content) { + var image = new Image(); + image.onload = callback.bind(null, image); + image.src = content; + }); + }, + + downloadAsFile: function (content, filename) { + var saveAs = + window.saveAs || + (navigator.msSaveBlob && navigator.msSaveBlob.bind(navigator)); + if (saveAs) { + saveAs(content, filename); + } else { + var downloadLink = document.createElement("a"); + content = window.URL.createObjectURL(content); + downloadLink.setAttribute("href", content); + downloadLink.setAttribute("download", filename); + document.body.appendChild(downloadLink); + downloadLink.addEventListener("click", stopPropagation); + downloadLink.click(); + downloadLink.removeEventListener("click", stopPropagation); + document.body.removeChild(downloadLink); + } + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var getFileInputElement = function (nwsaveas, accept) { + var fileInputElement = document.createElement("INPUT"); + fileInputElement.setAttribute("type", "file"); + fileInputElement.setAttribute("nwworkingdir", ""); + if (nwsaveas) { + fileInputElement.setAttribute("nwsaveas", nwsaveas); + } + if (accept) { + fileInputElement.setAttribute("accept", accept); + } + + return fileInputElement; + }; + + ns.FileUtilsDesktop = { + chooseFilenameDialog: function (nwsaveas, accept) { + var deferred = Q.defer(); + var fileInputElement = getFileInputElement(nwsaveas, accept); + var changeListener = function (evt) { + fileInputElement.removeEventListener("change", changeListener); + document.removeEventListener("click", changeListener); + deferred.resolve(fileInputElement.value); + }; + + // fix for issue #322 : + window.setTimeout(function () { + fileInputElement.click(); + fileInputElement.addEventListener("change", changeListener); + // there is no way to detect a cancelled fileInput popup + // as a crappy workaround we add a click listener on the document + // on top the change event listener + // todo : listen to dirty check instead + document.addEventListener("mousedown", changeListener); + }, 50); + + return deferred.promise; + }, + + /** + * Save data directly to disk, without showing a save dialog + * Requires Node-Webkit environment for file system access + * @param content - data to be saved + * @param {string} filename - fill path to the file + * @callback callback + */ + saveToFile: function (content, filename) { + var deferred = Q.defer(); + var fs = window.require("fs"); + fs.writeFile(filename, content, function (err) { + if (err) { + deferred.reject( + "FileUtilsDesktop::savetoFile() - error saving file: " + + filename + + " Error: " + + err + ); + } else { + deferred.resolve(); + } + }); + + return deferred.promise; + }, + + readFile: function (filename) { + var deferred = Q.defer(); + var fs = window.require("fs"); + // NOTE: currently loading everything as utf8, which may not be desirable in future + fs.readFile(filename, "utf8", function (err, data) { + if (err) { + deferred.reject( + "FileUtilsDesktop::readFile() - error reading file: " + + filename + + " Error: " + + err + ); + } else { + deferred.resolve(data); + } + }); + return deferred.promise; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + var offCanvasPool = {}; + var imageDataPool = {}; + ns.FrameUtils = { + /** + * Render a Frame object as an image. + * Can optionally scale it (zoom) + * @param frame {Frame} frame + * @param zoom {Number} zoom + * @return {Image} + */ + toImage: function (frame, zoom, opacity) { + zoom = zoom || 1; + opacity = isNaN(opacity) ? 1 : opacity; + + var canvasRenderer = new pskl.rendering.CanvasRenderer(frame, zoom); + canvasRenderer.drawTransparentAs(Constants.TRANSPARENT_COLOR); + canvasRenderer.setOpacity(opacity); + return canvasRenderer.render(); + }, + + /** + * Draw the provided frame in a 2d canvas + * + * @param {Frame|RenderedFrame} frame the frame to draw + * @param {Canvas} canvas the canvas target + * @param {String} transparentColor (optional) color to use to represent transparent pixels. + * @param {String} globalAlpha (optional) global frame opacity + */ + drawToCanvas: function (frame, canvas, transparentColor, globalAlpha) { + var context = canvas.getContext("2d"); + globalAlpha = isNaN(globalAlpha) ? 1 : globalAlpha; + context.globalAlpha = globalAlpha; + transparentColor = transparentColor || Constants.TRANSPARENT_COLOR; + + if (frame instanceof pskl.model.frame.RenderedFrame) { + context.fillRect( + transparentColor, + 0, + 0, + frame.getWidth(), + frame.getHeight() + ); + context.drawImage(frame.getRenderedFrame(), 0, 0); + } else { + var w = frame.getWidth(); + var h = frame.getHeight(); + var pixels = frame.pixels; + + // Replace transparent color + var constantTransparentColorInt = pskl.utils.colorToInt( + Constants.TRANSPARENT_COLOR + ); + var transparentColorInt = pskl.utils.colorToInt(transparentColor); + if (transparentColorInt != constantTransparentColorInt) { + pixels = frame.getPixels(); + for (var i = 0, length = pixels.length; i < length; i++) { + if (pixels[i] == constantTransparentColorInt) { + pixels[i] = transparentColorInt; + } + } + } + + // Imagedata from cache + var imageDataKey = w + "-" + h; + var imageData; + if (!imageDataPool[imageDataKey]) { + imageData = imageDataPool[imageDataKey] = context.createImageData( + w, + h + ); + } else { + imageData = imageDataPool[imageDataKey]; + } + + // Convert to uint8 and set the data + var data = new Uint8ClampedArray(pixels.buffer); + var imgDataData = imageData.data; + imgDataData.set(data); + + // Offcanvas from cache + var offCanvasKey = w + "-" + h; + var offCanvas; + if (!offCanvasPool[offCanvasKey]) { + offCanvas = offCanvasPool[offCanvasKey] = + pskl.utils.CanvasUtils.createCanvas(w, h); + offCanvas.context = offCanvas.getContext("2d"); + } else { + offCanvas = offCanvasPool[offCanvasKey]; + } + + // Put pixel data to offcanvas and draw the offcanvas onto the canvas + offCanvas.context.putImageData(imageData, 0, 0); + context.drawImage(offCanvas, 0, 0, w, h); + context.globalAlpha = 1; + } + }, + + /** + * Render a line of a single color in a given canvas 2D context. + * + * @param color {String} color to draw + * @param x {Number} x coordinate + * @param y {Number} y coordinate + * @param width {Number} width of the line to draw, in pixels + * @param context {CanvasRenderingContext2D} context of the canvas target + */ + renderLine_: function (color, x, y, width, context) { + if (color === Constants.TRANSPARENT_COLOR || color === null) { + return; + } + context.fillStyle = color; + context.fillRect(x, y, 1, width); + }, + + merge: function (frames) { + var merged = null; + if (frames.length) { + merged = frames[0].clone(); + for (var i = 1; i < frames.length; i++) { + pskl.utils.FrameUtils.mergeFrames_(merged, frames[i]); + } + } + return merged; + }, + + mergeFrames_: function (frameA, frameB) { + var transparentColorInt = pskl.utils.colorToInt( + Constants.TRANSPARENT_COLOR + ); + for ( + var i = 0, length = frameA.getWidth() * frameA.getHeight(); + i < length; + ++i + ) { + if ( + frameB.pixels[i] != transparentColorInt && + frameA.pixels[i] != frameB.pixels[i] + ) { + frameA.pixels[i] = frameB.pixels[i]; + } + } + }, + + /** + * Insert the provided image in the provided frame, at the x, y sprite coordinates. + * Coordinates will be adjusted so that the image fits in the frame, if possible. + */ + addImageToFrame: function (frame, image, x, y) { + var imageFrame = pskl.utils.FrameUtils.createFromImage(image); + x = x - Math.floor(imageFrame.width / 2); + y = y - Math.floor(imageFrame.height / 2); + + x = Math.max(0, x); + y = Math.max(0, y); + + if (imageFrame.width <= frame.width) { + x = Math.min(x, frame.width - imageFrame.width); + } + + if (imageFrame.height <= frame.height) { + y = Math.min(y, frame.height - imageFrame.height); + } + + imageFrame.forEachPixel(function (color, frameX, frameY) { + if (color != pskl.utils.colorToInt(Constants.TRANSPARENT_COLOR)) { + frame.setPixel(x + frameX, y + frameY, color); + } + }); + }, + + resize: function (frame, targetWidth, targetHeight, smoothing) { + var image = pskl.utils.FrameUtils.toImage(frame); + var resizedImage = pskl.utils.ImageResizer.resize( + image, + targetWidth, + targetHeight, + smoothing + ); + return pskl.utils.FrameUtils.createFromImage(resizedImage); + }, + + removeTransparency: function (frame) { + frame.forEachPixel(function (color, x, y) { + var alpha = ((color >> 24) >>> 0) & 0xff; + if (alpha && alpha !== 255) { + var rounded = Math.round(alpha / 255) * 255; + var roundedColor = + color - ((alpha << 24) >>> 0) + ((rounded << 24) >>> 0); + frame.setPixel(x, y, roundedColor); + } + }); + }, + + createFromCanvas: function (canvas, x, y, w, h, preserveOpacity) { + var imgData = canvas.getContext("2d").getImageData(x, y, w, h).data; + return pskl.utils.FrameUtils.createFromImageData_( + imgData, + w, + h, + preserveOpacity + ); + }, + + createFromImageSrc: function (src, preserveOpacity, cb) { + var image = new Image(); + image.addEventListener("load", function onImageLoaded() { + image.removeEventListener("load", onImageLoaded); + var frame = ns.FrameUtils.createFromImage(image, preserveOpacity); + cb(frame); + }); + image.src = src; + }, + + /* + * Create a pskl.model.Frame from an Image object. By default transparent + * pixels will be converted to completely opaque or completely transparent + * pixels. If preserveOpacity is true the actual opacity of the pixel will + * be used and the generated frame will contain rgba pixels. + * + * @param {Image} image source image + * @param {boolean} preserveOpacity set to true to preserve the opacity + * @return {pskl.model.Frame} corresponding frame + */ + createFromImage: function (image, preserveOpacity) { + var w = image.width; + var h = image.height; + var canvas = pskl.utils.CanvasUtils.createCanvas(w, h); + var context = canvas.getContext("2d"); + + context.drawImage(image, 0, 0, w, h, 0, 0, w, h); + var imgData = context.getImageData(0, 0, w, h).data; + return pskl.utils.FrameUtils.createFromImageData_( + imgData, + w, + h, + preserveOpacity + ); + }, + + createFromImageData_: function (imageData, width, height, preserveOpacity) { + var frame = new pskl.model.Frame(width, height); + frame.pixels = new Uint32Array(imageData.buffer); + if (!preserveOpacity) { + pskl.utils.FrameUtils.removeTransparency(frame); + } + + return frame; + }, + + /** + * Create a Frame array from an Image object. + * Transparent pixels will either be converted to completely opaque or completely transparent pixels. + * + * @param {Image} image source image + * @param {Number} frameCount number of frames in the spritesheet + * @return {Array} + */ + createFramesFromSpritesheet: function (image, frameCount) { + var layout = []; + for (var i = 0; i < frameCount; i++) { + layout.push([i]); + } + var chunkFrames = pskl.utils.FrameUtils.createFramesFromChunk( + image, + layout + ); + return chunkFrames.map(function (chunkFrame) { + return chunkFrame.frame; + }); + }, + + /** + * Create a Frame array from an Image object. + * Transparent pixels will either be converted to completely opaque or completely transparent pixels. + * + * @param {Image} image source image + * @param {Array } layout description of the frame indexes expected to be found in the chunk + * @return {Array} array of objects containing: {index: frame index, frame: frame instance} + */ + createFramesFromChunk: function (image, layout) { + var width = image.width; + var height = image.height; + + // Recalculate the expected frame dimensions from the layout information + var frameWidth = width / layout.length; + var frameHeight = height / layout[0].length; + + // Create a canvas adapted to the image size + var canvas = pskl.utils.CanvasUtils.createCanvas(frameWidth, frameHeight); + var context = canvas.getContext("2d"); + + // Draw the zoomed-up pixels to a different canvas context + var chunkFrames = []; + for (var i = 0; i < layout.length; i++) { + var row = layout[i]; + for (var j = 0; j < row.length; j++) { + context.clearRect(0, 0, frameWidth, frameHeight); + context.drawImage( + image, + frameWidth * i, + frameHeight * j, + frameWidth, + frameHeight, + 0, + 0, + frameWidth, + frameHeight + ); + var frame = pskl.utils.FrameUtils.createFromCanvas( + canvas, + 0, + 0, + frameWidth, + frameHeight + ); + chunkFrames.push({ + index: layout[i][j], + frame: frame + }); + } + } + + return chunkFrames; + }, + + toFrameGrid: function (normalGrid) { + var frameGrid = []; + var w = normalGrid[0].length; + var h = normalGrid.length; + for (var x = 0; x < w; x++) { + frameGrid[x] = []; + for (var y = 0; y < h; y++) { + frameGrid[x][y] = normalGrid[y][x]; + } + } + return frameGrid; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.ImageResizer = { + scale: function (image, factor, smoothingEnabled) { + return ns.ImageResizer.resize( + image, + image.width * factor, + image.height * factor, + smoothingEnabled + ); + }, + + resize: function (image, targetWidth, targetHeight, smoothingEnabled) { + var canvas = pskl.utils.CanvasUtils.createCanvas( + targetWidth, + targetHeight + ); + var context = canvas.getContext("2d"); + context.save(); + + if (!smoothingEnabled) { + pskl.utils.CanvasUtils.disableImageSmoothing(canvas); + } + + context.translate(canvas.width / 2, canvas.height / 2); + context.scale(targetWidth / image.width, targetHeight / image.height); + context.drawImage(image, -image.width / 2, -image.height / 2); + context.restore(); + + return canvas; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.LayerUtils = { + clone: function (layer) { + var clonedFrames = layer.getFrames().map(function (frame) { + return frame.clone(); + }); + return pskl.model.Layer.fromFrames( + layer.getName() + " (clone)", + clonedFrames + ); + }, + + mergeLayers: function (layerA, layerB) { + var framesA = layerA.getFrames(); + var framesB = layerB.getFrames(); + var mergedFrames = []; + framesA.forEach(function (frame, index) { + var otherFrame = framesB[index]; + mergedFrames.push(pskl.utils.FrameUtils.merge([otherFrame, frame])); + }); + var mergedLayer = pskl.model.Layer.fromFrames( + layerA.getName(), + mergedFrames + ); + return mergedLayer; + }, + + getFrameHashAt: function (layers, index) { + var hashBuffer = []; + layers.forEach(function (l) { + var frame = l.getFrameAt(index); + hashBuffer.push(frame.getHash()); + hashBuffer.push(l.getOpacity()); + return frame; + }); + return hashBuffer.join("-"); + }, + + /** + * Create a frame instance merging all the frames from the layers array at + * the provided index. + * + * @param {Array} layers array of layers to use + * @param {Number} index frame index to merge + * @return {Frame} Frame instance (can be a fake frame when using + * transparency) + */ + mergeFrameAt: function (layers, index) { + var isTransparent = layers.some(function (l) { + return l.isTransparent(); + }); + if (isTransparent) { + return pskl.utils.LayerUtils.mergeTransparentFrameAt_(layers, index); + } else { + return pskl.utils.LayerUtils.mergeOpaqueFrameAt_(layers, index); + } + }, + + mergeTransparentFrameAt_: function (layers, index) { + var hash = pskl.utils.LayerUtils.getFrameHashAt(layers, index); + var width = layers[0].frames[0].getWidth(); + var height = layers[0].frames[0].getHeight(); + var renderFn = function () { + return pskl.utils.LayerUtils.flattenFrameAt(layers, index, true); + }; + return new pskl.model.frame.RenderedFrame(renderFn, width, height, hash); + }, + + mergeOpaqueFrameAt_: function (layers, index) { + var hash = pskl.utils.LayerUtils.getFrameHashAt(layers, index); + var frames = layers.map(function (l) { + return l.getFrameAt(index); + }); + var mergedFrame = pskl.utils.FrameUtils.merge(frames); + mergedFrame.id = hash; + mergedFrame.version = 0; + return mergedFrame; + }, + + renderFrameAt: function (layer, index, preserveOpacity) { + var opacity = preserveOpacity ? layer.getOpacity() : 1; + var frame = layer.getFrameAt(index); + return pskl.utils.FrameUtils.toImage(frame, 1, opacity); + }, + + flattenFrameAt: function (layers, index, preserveOpacity) { + var width = layers[0].getFrameAt(index).getWidth(); + var height = layers[0].getFrameAt(index).getHeight(); + var canvas = pskl.utils.CanvasUtils.createCanvas(width, height); + + var context = canvas.getContext("2d"); + layers.forEach(function (l) { + var render = ns.LayerUtils.renderFrameAt(l, index, preserveOpacity); + context.drawImage(render, 0, 0, width, height, 0, 0, width, height); + }); + + return canvas; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.MergeUtils = { + /** + * Merge two piskel instances in a new piskel instance + * @param {Piskel} piskel + * The original piskel (name and description will be preserved) + * @param {Piskel} importedPiskel + * The imported piskel + * @param {Object} options + * - index: {Number} index where the new frames should be appended + * - resize: {String} either "expand" or "keep" + * - origin: {String} can be any of the existing AnchorWidget origins. + * - insertMode: {String} either "insert" or "add" + * + * @return {Piskel} The new Piskel instance created + */ + merge: function (piskel, importedPiskel, options) { + var isImportedPiskelBigger = + importedPiskel.getWidth() > piskel.getWidth() || + importedPiskel.getHeight() > piskel.getHeight(); + + // First make sure both the piskel and the imported piskel use the target dimensions. + if (isImportedPiskelBigger && options.resize === "expand") { + piskel = pskl.utils.ResizeUtils.resizePiskel(piskel, { + width: Math.max(piskel.getWidth(), importedPiskel.getWidth()), + height: Math.max(piskel.getHeight(), importedPiskel.getHeight()), + origin: options.origin, + resizeContent: false + }); + } else { + importedPiskel = pskl.utils.ResizeUtils.resizePiskel(importedPiskel, { + width: piskel.getWidth(), + height: piskel.getHeight(), + origin: options.origin, + resizeContent: false + }); + } + + var insertIndex = options.insertIndex; + if (options.insertMode === "insert") { + // The index provided by the frame picker is 1-based. + // When adding new frames, this works out fine, but if we want to + // insert the new content in existing frames, we need to get the real + // 0-based index of the selected frame. + insertIndex = insertIndex - 1; + } + // Add necessary frames in the original piskel. + var importedFrameCount = importedPiskel.getFrameCount(); + for (var i = 0; i < importedFrameCount; i++) { + var index = i + insertIndex; + // For a given index, a new frame should be added either if we are using "add" insert mode + // or if the current index is not supported by the original piskel. + if (options.insertMode === "add" || index >= piskel.getFrameCount()) { + ns.MergeUtils.addFrameToLayers_(piskel, index); + } + } + + // Import the layers in the original piskel. + importedPiskel.getLayers().forEach(function (layer) { + var name = layer.getName() + " (imported)"; + var importedLayer = new pskl.model.Layer(name); + for (var i = 0; i < piskel.getFrameCount(); i++) { + var importedIndex = i - insertIndex; + var frame = layer.getFrameAt(importedIndex); + if (!frame) { + frame = ns.MergeUtils.createEmptyFrame_(piskel); + } + + importedLayer.addFrame(frame); + } + piskel.addLayer(importedLayer); + }); + + return piskel; + }, + + createEmptyFrame_: function (piskel) { + return new pskl.model.Frame(piskel.getWidth(), piskel.getHeight()); + }, + + addFrameToLayers_: function (piskel, index) { + piskel.getLayers().forEach(function (l) { + l.addFrameAt(ns.MergeUtils.createEmptyFrame_(piskel), index); + }); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl"); + + ns.PixelUtils = { + getRectanglePixels: function (x0, y0, x1, y1) { + var rectangle = this.getOrderedRectangleCoordinates(x0, y0, x1, y1); + var pixels = []; + + for (var x = rectangle.x0; x <= rectangle.x1; x++) { + for (var y = rectangle.y0; y <= rectangle.y1; y++) { + pixels.push({ col: x, row: y }); + } + } + + return pixels; + }, + + /** + * Return an object of ordered rectangle coordinate. + * In returned object {x0, y0} => top left corner - {x1, y1} => bottom right corner + * @private + */ + getOrderedRectangleCoordinates: function (x0, y0, x1, y1) { + return { + x0: Math.min(x0, x1), + y0: Math.min(y0, y1), + x1: Math.max(x0, x1), + y1: Math.max(y0, y1) + }; + }, + + /** + * Return the list of pixels that would have been filled by a paintbucket tool applied + * on pixel at coordinate (x,y). + * This function is not altering the Frame object argument. + * + * @param frame pskl.model.Frame The frame target in which we want to paintbucket + * @param col number Column coordinate in the frame + * @param row number Row coordinate in the frame + * + * @return an array of the pixel coordinates paint with the replacement color + */ + getSimilarConnectedPixelsFromFrame: function (frame, col, row) { + var targetColor = frame.getPixel(col, row); + if (targetColor === null) { + return []; + } + + var startPixel = { + col: col, + row: row + }; + + var visited = {}; + return pskl.PixelUtils.visitConnectedPixels( + startPixel, + frame, + function (pixel) { + var key = pixel.col + "-" + pixel.row; + if (visited[key]) { + return false; + } + visited[key] = true; + return frame.getPixel(pixel.col, pixel.row) == targetColor; + } + ); + }, + + /** + * Resize the pixel at {col, row} for the provided size. Will return the array of pixels centered + * around the original pixel, forming a pixel square of side=size + * + * @param {Number} row x-coordinate of the original pixel + * @param {Number} col y-coordinate of the original pixel + * @param {Number} size >= 1 && <= 32 + * @return {Array} array of arrays of 2 Numbers (eg. [[0,0], [0,1], [1,0], [1,1]]) + */ + resizePixel: function (col, row, size) { + var pixels = []; + + for (var j = 0; j < size; j++) { + for (var i = 0; i < size; i++) { + pixels.push([ + col - Math.floor(size / 2) + i, + row - Math.floor(size / 2) + j + ]); + } + } + + return pixels; + }, + + /** + * Shortcut to reduce the output of pskl.PixelUtils.resizePixel for several pixels + * @param {Array} pixels Array of pixels (objects {col:Number, row:Number}) + * @param {Number} >= 1 && <= 4 + * @return {Array} array of arrays of 2 Numbers (eg. [[0,0], [0,1], [1,0], [1,1]]) + */ + resizePixels: function (pixels, size) { + return pixels.reduce(function (p, pixel) { + return p.concat( + pskl.PixelUtils.resizePixel(pixel.col, pixel.row, size) + ); + }, []); + }, + + /** + * Apply the paintbucket tool in a frame at the (col, row) initial position + * with the replacement color. + * + * @param frame pskl.model.Frame The frame target in which we want to paintbucket + * @param col number Column coordinate in the frame + * @param row number Row coordinate in the frame + * @param replacementColor string Hexadecimal color used to fill the area + * + * @return an array of the pixel coordinates paint with the replacement color + */ + paintSimilarConnectedPixelsFromFrame: function ( + frame, + col, + row, + replacementColor + ) { + /** + * Queue linear Flood-fill (node, target-color, replacement-color): + * 1. Set Q to the empty queue. + * 2. If the color of node is not equal to target-color, return. + * 3. Add node to Q. + * 4. For each element n of Q: + * 5. If the color of n is equal to target-color: + * 6. Set w and e equal to n. + * 7. Move w to the west until the color of the node to the west of w no longer matches target-color. + * 8. Move e to the east until the color of the node to the east of e no longer matches target-color. + * 9. Set the color of nodes between w and e to replacement-color. + * 10. For each node n between w and e: + * 11. If the color of the node to the north of n is target-color, add that node to Q. + * 12. If the color of the node to the south of n is target-color, add that node to Q. + * 13. Continue looping until Q is exhausted. + * 14. Return. + */ + if (typeof replacementColor == "string") { + replacementColor = pskl.utils.colorToInt(replacementColor); + } + + var targetColor; + try { + targetColor = frame.getPixel(col, row); + } catch { + // Frame out of bound exception. + } + + if (targetColor === null || targetColor == replacementColor) { + return; + } + + var startPixel = { + col: col, + row: row + }; + var paintedPixels = pskl.PixelUtils.visitConnectedPixels( + startPixel, + frame, + function (pixel) { + if (frame.getPixel(pixel.col, pixel.row) == targetColor) { + frame.setPixel(pixel.col, pixel.row, replacementColor); + return true; + } + return false; + } + ); + return paintedPixels; + }, + + /** + * Starting from a provided origin, visit connected pixels using a visitor function. + * After visiting a pixel, select the 4 connected pixels (up, right, down, left). + * Call the provided visitor on each pixel. The visitor should return true if the + * pixel should be considered as connected. If the pixel is connected repeat the + * process with its own connected pixels + * + * TODO : Julian : The visitor is also responsible for making sure a pixel is never + * visited twice. This could be handled by default by this method. + * + * @return {Array} the array of visited pixels {col, row} + */ + visitConnectedPixels: function (pixel, frame, pixelVisitor) { + var queue = []; + var visitedPixels = []; + var dy = [-1, 0, 1, 0]; + var dx = [0, 1, 0, -1]; + + queue.push(pixel); + visitedPixels.push(pixel); + pixelVisitor(pixel); + + var loopCount = 0; + var cellCount = frame.getWidth() * frame.getHeight(); + while (queue.length > 0) { + loopCount++; + + var currentItem = queue.pop(); + + for (var i = 0; i < 4; i++) { + var nextCol = currentItem.col + dx[i]; + var nextRow = currentItem.row + dy[i]; + try { + var connectedPixel = { col: nextCol, row: nextRow }; + var isValid = pixelVisitor(connectedPixel); + if (isValid) { + queue.push(connectedPixel); + visitedPixels.push(connectedPixel); + } + } catch { + // Frame out of bound exception. + } + } + + // Security loop breaker: + if (loopCount > 10 * cellCount) { + console.log("loop breaker called"); + break; + } + } + + return visitedPixels; + }, + + /** + * Calculate and return the maximal zoom level to display a picture in a given container. + * + * @param container jQueryObject Container where the picture should be displayed + * @param number pictureHeight height in pixels of the picture to display + * @param number pictureWidth width in pixels of the picture to display + * @return number maximal zoom + */ + calculateZoomForContainer: function ( + container, + pictureHeight, + pictureWidth + ) { + return this.calculateZoom( + container.height(), + container.width(), + pictureHeight, + pictureWidth + ); + }, + + /** + * Bresenham line algorithm: Get an array of pixels from + * start and end coordinates. + * + * http://en.wikipedia.org/wiki/Bresenham's_line_algorithm + * http://stackoverflow.com/questions/4672279/bresenham-algorithm-in-javascript + */ + getLinePixels: function (x0, x1, y0, y1) { + var pixels = []; + + x1 = pskl.utils.normalize(x1, 0); + y1 = pskl.utils.normalize(y1, 0); + + var dx = Math.abs(x1 - x0); + var dy = Math.abs(y1 - y0); + + var sx = x0 < x1 ? 1 : -1; + var sy = y0 < y1 ? 1 : -1; + + var err = dx - dy; + while (true) { + // Do what you need to for this + pixels.push({ col: x0, row: y0 }); + + if (x0 == x1 && y0 == y1) { + break; + } + + var e2 = 2 * err; + if (e2 > -dy) { + err -= dy; + x0 += sx; + } + if (e2 < dx) { + err += dx; + y0 += sy; + } + } + + return pixels; + }, + + /** + * Create a uniform line using the same number of pixel at each step, between the provided + * origin and target coordinates. + */ + getUniformLinePixels: function (x0, x1, y0, y1) { + var pixels = []; + + x1 = pskl.utils.normalize(x1, 0); + y1 = pskl.utils.normalize(y1, 0); + + var dx = Math.abs(x1 - x0) + 1; + var dy = Math.abs(y1 - y0) + 1; + + var sx = x0 < x1 ? 1 : -1; + var sy = y0 < y1 ? 1 : -1; + + var ratio = Math.max(dx, dy) / Math.min(dx, dy); + // in pixel art, lines should use uniform number of pixels for each step + var pixelStep = Math.round(ratio) || 0; + + if (pixelStep > Math.min(dx, dy)) { + pixelStep = Infinity; + } + + var maxDistance = pskl.utils.Math.distance(x0, x1, y0, y1); + + var x = x0; + var y = y0; + var i = 0; + while (true) { + i++; + + pixels.push({ col: x, row: y }); + if (pskl.utils.Math.distance(x0, x, y0, y) >= maxDistance) { + break; + } + + var isAtStep = i % pixelStep === 0; + if (dx >= dy || isAtStep) { + x += sx; + } + if (dy >= dx || isAtStep) { + y += sy; + } + } + + return pixels; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.PiskelFileUtils = { + FAILURE: { + EMPTY: "No data found in piskel file", + INVALID: "Invalid piskel file, contact us on twitter @piskelapp", + DESERIALIZATION: "Piskel data deserialization failed" + }, + + /** + * Load a piskel from a piskel file. + * After deserialization is successful, the provided success callback will be called. + * Success callback is expected to receive a single Piskel object argument + * @param {File} file the .piskel file to load + * @param {Function} onSuccess Called if the deserialization of the piskel is successful + * @param {Function} onError NOT USED YET + */ + loadFromFile: function (file, onSuccess, onError) { + pskl.utils.FileUtils.readFile(file, function (content) { + var rawPiskel = pskl.utils.Base64.toText(content); + ns.PiskelFileUtils.decodePiskelFile( + rawPiskel, + function (piskel) { + // if using Node-Webkit, store the savePath on load + // Note: the 'path' property is unique to Node-Webkit, and holds the full path + if (pskl.utils.Environment.detectNodeWebkit()) { + piskel.savePath = file.path; + } + onSuccess(piskel); + }, + onError + ); + }); + }, + + decodePiskelFile: function (rawPiskel, onSuccess, onError) { + var serializedPiskel; + if (rawPiskel.length === 0) { + onError(ns.PiskelFileUtils.FAILURE.EMPTY); + return; + } + + try { + serializedPiskel = JSON.parse(rawPiskel); + } catch (_e) { + onError(ns.PiskelFileUtils.FAILURE.INVALID); + return; + } + + var _piskel = serializedPiskel.piskel; + pskl.utils.serialization.Deserializer.deserialize( + serializedPiskel, + onSuccess, + function () { + onError(ns.PiskelFileUtils.FAILURE.DESERIALIZATION); + } + ); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.ResizeUtils = { + /** + * Resize the provided piskel instance and return a new instance using the provided resize options + * @param {Piskel} piskel [description] + * @param {Object} options + * - width {Number} target width after the resize + * - height {Number} target height after the resize + * - resizeContent {Booleam} true of the sprite content should be resized + * - origin {String} should be a valid AnchorWidget origin + * @return {Piskel} The resized piskel + */ + resizePiskel: function (piskel, options) { + var fps = piskel.getFPS(); + var resizedLayers = piskel.getLayers().map(function (layer) { + return ns.ResizeUtils.resizeLayer(layer, options); + }); + + var resizedPiskel = pskl.model.Piskel.fromLayers( + resizedLayers, + fps, + piskel.getDescriptor() + ); + // propagate savepath to new Piskel + resizedPiskel.savePath = piskel.savePath; + + return resizedPiskel; + }, + + resizeLayer: function (layer, options) { + var opacity = layer.getOpacity(); + var resizedFrames = layer.getFrames().map(function (frame) { + return ns.ResizeUtils.resizeFrame(frame, options); + }); + var resizedLayer = pskl.model.Layer.fromFrames( + layer.getName(), + resizedFrames + ); + resizedLayer.setOpacity(opacity); + return resizedLayer; + }, + + resizeFrame: function (frame, options) { + var width = options.width; + var height = options.height; + var origin = options.origin; + + if (options.resizeContent) { + return pskl.utils.FrameUtils.resize(frame, width, height, false); + } else { + var resizedFrame = new pskl.model.Frame(width, height); + frame.forEachPixel(function (color, x, y) { + var translated = ns.ResizeUtils.translateCoordinates( + x, + y, + frame, + resizedFrame, + origin + ); + if (resizedFrame.containsPixel(translated.x, translated.y)) { + resizedFrame.setPixel(translated.x, translated.y, color); + } + }); + + return resizedFrame; + } + }, + + translateCoordinates: function (x, y, frame, resizedFrame, origin) { + return { + x: ns.ResizeUtils.translateX( + x, + frame.width, + resizedFrame.width, + origin + ), + y: ns.ResizeUtils.translateY( + y, + frame.height, + resizedFrame.height, + origin + ) + }; + }, + + translateX: function (x, width, resizedWidth, origin) { + if (origin.indexOf("LEFT") != -1) { + return x; + } else if (origin.indexOf("RIGHT") != -1) { + return x - (width - resizedWidth); + } else { + return x - Math.round((width - resizedWidth) / 2); + } + }, + + translateY: function (y, height, resizedHeight, origin) { + if (origin.indexOf("TOP") != -1) { + return y; + } else if (origin.indexOf("BOTTOM") != -1) { + return y - (height - resizedHeight); + } else { + return y - Math.round((height - resizedHeight) / 2); + } + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.StringUtils = { + leftPad: function (input, length, pad) { + var padding = new Array(length).join(pad); + return (padding + input).slice(-length); + }, + + formatSize: function (width, height) { + return width + "\u00D7" + height; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + var templates = {}; + + ns.Template = { + get: function (templateId) { + if (!templates[templateId]) { + var template = document.getElementById(templateId); + if (template) { + templates[templateId] = template.innerHTML; + } else { + console.error("Could not find template for id :", templateId); + } + } + return templates[templateId]; + }, + + getAsHTML: function (templateId) { + var template = ns.Template.get(templateId); + if (!template) { + return; + } + + return ns.Template.createFromHTML(template); + }, + + createFromHTML: function (html) { + var dummyEl = ns.Template._getDummyEl(); + dummyEl.innerHTML = html; + var element = dummyEl.children[0]; + + if (!pskl.utils.UserAgent.isIE11) { + dummyEl.innerHTML = ""; + } + + return element; + }, + + replace: function (template, dict) { + for (var key in dict) { + if (dict.hasOwnProperty(key)) { + var value = dict[key]; + + // special boolean keys keys key:default + // if the value is a boolean, use default as value + if (key.indexOf(":") !== -1) { + if (value === true) { + value = key.split(":")[1]; + } else if (value === false) { + value = ""; + } + } + + // Sanitize all values expect if the key is surrounded by `!` + if (!/^!.*!$/.test(key)) { + value = ns.Template.sanitize(value); + } + + template = template.replace( + new RegExp("\\{\\{" + key + "\\}\\}", "g"), + value + ); + } + } + return template; + }, + + getAndReplace: function (templateId, dict) { + var result = ""; + var tpl = pskl.utils.Template.get(templateId); + if (tpl) { + result = pskl.utils.Template.replace(tpl, dict); + } + return result; + }, + + /** + * Sanitize the provided string to make it safer for using in templates. + */ + sanitize: function (string) { + var dummyEl = ns.Template._getDummyEl(); + + // Apply the unsafe string as text content and + dummyEl.textContent = string; + var sanitizedString = dummyEl.innerHTML; + + if (!pskl.utils.UserAgent.isIE11) { + dummyEl.innerHTML = ""; + } + + return sanitizedString; + }, + + _getDummyEl: pskl.utils.UserAgent.isIE11 + ? // IE11 specific implementation + function () { + return document.createElement("div"); + } + : // Normal, sane browsers implementation. + function () { + if (!ns.Template._dummyEl) { + ns.Template._dummyEl = document.createElement("div"); + } + return ns.Template._dummyEl; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + ns.TooltipFormatter = {}; + + ns.TooltipFormatter.format = function (helpText, shortcut, descriptors) { + var tpl = pskl.utils.Template.get("tooltip-container-template"); + shortcut = shortcut ? "(" + shortcut.getDisplayKey() + ")" : ""; + return pskl.utils.Template.replace(tpl, { + helptext: helpText, + shortcut: shortcut, + // Avoid sanitization for descriptors (markup) + "!descriptors!": this.formatDescriptors_(descriptors) + }); + }; + + ns.TooltipFormatter.formatDescriptors_ = function (descriptors) { + descriptors = descriptors || []; + return descriptors.reduce( + function (p, descriptor) { + return (p += this.formatDescriptor_(descriptor)); + }.bind(this), + "" + ); + }; + + ns.TooltipFormatter.formatDescriptor_ = function (descriptor) { + var tpl; + if (descriptor.key) { + tpl = pskl.utils.Template.get("tooltip-modifier-descriptor-template"); + descriptor.key = descriptor.key.toUpperCase(); + if (pskl.utils.UserAgent.isMac) { + descriptor.key = descriptor.key.replace("CTRL", "CMD"); + descriptor.key = descriptor.key.replace("ALT", "OPTION"); + } + } else { + tpl = pskl.utils.Template.get("tooltip-simple-descriptor-template"); + } + return pskl.utils.Template.replace(tpl, descriptor); + }; +})(); +;(function () { + var ns = $.namespace("pskl"); + + ns.UserSettings = { + GRID_COLOR: "GRID_COLOR", + GRID_ENABLED: "GRID_ENABLED", + GRID_WIDTH: "GRID_WIDTH", + GRID_SPACING: "GRID_SPACING", + MAX_FPS: "MAX_FPS", + DEFAULT_SIZE: "DEFAULT_SIZE", + CANVAS_BACKGROUND: "CANVAS_BACKGROUND", + SELECTED_PALETTE: "SELECTED_PALETTE", + SEAMLESS_OPACITY: "SEAMLESS_OPACITY", + SEAMLESS_MODE: "SEAMLESS_MODE", + PREVIEW_SIZE: "PREVIEW_SIZE", + ONION_SKIN: "ONION_SKIN", + LAYER_PREVIEW: "LAYER_PREVIEW", + LAYER_OPACITY: "LAYER_OPACITY", + EXPORT_SCALE: "EXPORT_SCALE", + EXPORT_TAB: "EXPORT_TAB", + EXPORT_GIF_REPEAT: "EXPORT_GIF_REPEAT", + PEN_SIZE: "PEN_SIZE", + RESIZE_SETTINGS: "RESIZE_SETTINGS", + COLOR_FORMAT: "COLOR_FORMAT", + TRANSFORM_SHOW_MORE: "TRANSFORM_SHOW_MORE", + PREFERENCES_TAB: "PREFERENCES_TAB", + KEY_TO_DEFAULT_VALUE_MAP_: { + GRID_COLOR: Constants.TRANSPARENT_COLOR, + GRID_ENABLED: false, + GRID_WIDTH: 1, + GRID_SPACING: 1, + MAX_FPS: 24, + DEFAULT_SIZE: { + width: Constants.DEFAULT.WIDTH, + height: Constants.DEFAULT.HEIGHT + }, + CANVAS_BACKGROUND: "lowcont-dark-canvas-background", + SELECTED_PALETTE: Constants.CURRENT_COLORS_PALETTE_ID, + SEAMLESS_OPACITY: 0.3, + SEAMLESS_MODE: false, + PREVIEW_SIZE: "original", + ONION_SKIN: false, + LAYER_OPACITY: 0.2, + LAYER_PREVIEW: true, + EXPORT_SCALE: 1, + EXPORT_TAB: "gif", + EXPORT_GIF_REPEAT: true, + PEN_SIZE: 1, + RESIZE_SETTINGS: { + maintainRatio: true, + resizeContent: false, + origin: "TOPLEFT" + }, + COLOR_FORMAT: "hex", + TRANSFORM_SHOW_MORE: false, + PREFERENCES_TAB: "misc" + }, + + /** + * @private + */ + cache_: {}, + + /** + * Static method to access a user defined settings value ot its default + * value if not defined yet. + */ + get: function (key) { + this.checkKeyValidity_(key); + if (!(key in this.cache_)) { + var storedValue = this.readFromLocalStorage_(key); + if (typeof storedValue !== "undefined" && storedValue !== null) { + this.cache_[key] = storedValue; + } else { + this.cache_[key] = this.readFromDefaults_(key); + } + } + return this.cache_[key]; + }, + + set: function (key, value) { + this.checkKeyValidity_(key); + this.cache_[key] = value; + this.writeToLocalStorage_(key, value); + + $.publish(Events.USER_SETTINGS_CHANGED, [key, value]); + }, + + /** + * @private + */ + readFromLocalStorage_: function (key) { + var value = window.localStorage[key]; + if (typeof value != "undefined") { + value = JSON.parse(value); + } + return value; + }, + + /** + * @private + */ + writeToLocalStorage_: function (key, value) { + // TODO(grosbouddha): Catch storage exception here. + window.localStorage[key] = JSON.stringify(value); + }, + + /** + * @private + */ + readFromDefaults_: function (key) { + return this.KEY_TO_DEFAULT_VALUE_MAP_[key]; + }, + + /** + * @private + */ + checkKeyValidity_: function (key) { + if ( + key.indexOf(pskl.service.keyboard.Shortcut.USER_SETTINGS_PREFIX) === 0 + ) { + return true; + } + + var isValidKey = key in this.KEY_TO_DEFAULT_VALUE_MAP_; + if (!isValidKey) { + console.error( + "UserSettings key <" + key + "> not found in supported keys." + ); + } + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var s4 = function () { + return Math.floor((1 + Math.random()) * 0x10000) + .toString(16) + .substring(1); + }; + + ns.Uuid = { + generate: function () { + return "ss-s-s-s-sss".replace(/s/g, function () { + return s4(); + }); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + + var workers = {}; + + ns.WorkerUtils = { + createWorker: function (worker, workerId) { + if (!workers[workerId]) { + workers[workerId] = ns.WorkerUtils.createWorkerURL(worker); + } + + return new Worker(workers[workerId]); + }, + + createWorkerURL: function (worker) { + // remove "function () {" at the start of the worker string and the last "}" before the end + var typedArray = [ + (worker + "") + .replace(/function\s*\(\)\s*\{/, "") + .replace(/\}[^}]*$/, "") + ]; + var blob = new Blob(typedArray, { type: "application/javascript" }); + return window.URL.createObjectURL(blob); + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils"); + ns.Xhr = { + get: function (url, success, error) { + var xhr = ns.Xhr.xhr_(url, "GET", success, error); + xhr.send(); + }, + + post: function (url, data, success, error) { + var xhr = ns.Xhr.xhr_(url, "POST", success, error); + var formData = new FormData(); + + if (typeof data == "object") { + for (var key in data) { + if (data.hasOwnProperty(key)) { + formData.append(key, data[key]); + } + } + } + + xhr.send(formData); + }, + + xhr_: function (url, method, success, error) { + success = success || function () {}; + error = error || function () {}; + + var xhr = new XMLHttpRequest(); + xhr.open(method, url, true); + + xhr.onload = function (e) { + if (this.status == 200) { + success(this); + } else { + this.onerror(this, e); + } + }; + + xhr.onerror = function (e) { + error(e, this); + }; + + return xhr; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils.serialization"); + + var areChunksValid = function (chunks) { + return ( + chunks.length && + chunks.every(function (chunk) { + return chunk.base64PNG && chunk.base64PNG !== "data:,"; + }) + ); + }; + + var createLineLayout = function (size, offset) { + var layout = []; + for (var i = 0; i < size; i++) { + layout.push([i + offset]); + } + + return layout; + }; + + ns.Serializer = { + serialize: function (piskel) { + var serializedLayers = piskel.getLayers().map(function (l) { + return pskl.utils.serialization.Serializer.serializeLayer(l); + }); + + return JSON.stringify({ + modelVersion: Constants.MODEL_VERSION, + piskel: { + name: piskel.getDescriptor().name, + description: piskel.getDescriptor().description, + fps: pskl.app.piskelController.getFPS(), + height: piskel.getHeight(), + width: piskel.getWidth(), + layers: serializedLayers, + hiddenFrames: piskel.hiddenFrames + } + }); + }, + + serializeLayer: function (layer) { + var frames = layer.getFrames(); + var layerToSerialize = { + name: layer.getName(), + opacity: layer.getOpacity(), + frameCount: frames.length + }; + + // A layer spritesheet data can be chunked in case the spritesheet PNG is to big to be + // converted to a dataURL. + // Frames are divided equally amongst chunks and each chunk is converted to a spritesheet + // PNG. If any chunk contains an invalid base64 PNG, we increase the number of chunks and + // retry. + var chunks = []; + while (!areChunksValid(chunks)) { + if (chunks.length >= frames.length) { + // Something went horribly wrong. + chunks = []; + break; + } + + // Chunks are invalid, increase the number of chunks by one, and chunk the frames array. + var frameChunks = pskl.utils.Array.chunk(frames, chunks.length + 1); + + // Reset chunks array. + chunks = []; + + // After each chunk update the offset by te number of frames that have been processed. + var offset = 0; + for (var i = 0; i < frameChunks.length; i++) { + var chunkFrames = frameChunks[i]; + chunks.push({ + // create a layout array, containing the indices of the frames extracted in this chunk + layout: createLineLayout(chunkFrames.length, offset), + base64PNG: ns.Serializer.serializeFramesToBase64(chunkFrames) + }); + + offset += chunkFrames.length; + } + } + + layerToSerialize.chunks = chunks; + return JSON.stringify(layerToSerialize); + }, + + serializeFramesToBase64: function (frames) { + try { + var renderer = new pskl.rendering.FramesheetRenderer(frames); + return renderer.renderAsCanvas().toDataURL(); + } catch { + return ""; + } + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils.serialization"); + + ns.Deserializer = function (data, callback) { + this.layersToLoad_ = 0; + this.data_ = data; + this.callback_ = callback; + this.piskel_ = null; + this.layers_ = []; + }; + + ns.Deserializer.deserialize = function (data, onSuccess, onError) { + try { + var deserializer; + if (data.modelVersion == Constants.MODEL_VERSION) { + deserializer = new ns.Deserializer(data, onSuccess); + } else if (data.modelVersion == 1) { + deserializer = new ns.backward.Deserializer_v1(data, onSuccess); + } else { + deserializer = new ns.backward.Deserializer_v0(data, onSuccess); + } + deserializer.deserialize(); + } catch (e) { + console.error(e); + if (typeof onError === "function") { + onError(e); + } + } + }; + + ns.Deserializer.prototype.deserialize = function () { + var data = this.data_; + var piskelData = data.piskel; + var name = piskelData.name || "Deserialized piskel"; + var description = piskelData.description || ""; + var fps = typeof piskelData.fps != "undefined" ? piskelData.fps : 12; + + var descriptor = new pskl.model.piskel.Descriptor(name, description); + this.piskel_ = new pskl.model.Piskel( + piskelData.width, + piskelData.height, + fps, + descriptor + ); + this.hiddenFrames = piskelData.hiddenFrames || []; + + this.layersToLoad_ = piskelData.layers.length; + piskelData.layers.forEach(this.deserializeLayer.bind(this)); + }; + + ns.Deserializer.prototype.deserializeLayer = function (layerString, index) { + var layerData = JSON.parse(layerString); + var layer = new pskl.model.Layer(layerData.name); + layer.setOpacity(layerData.opacity); + + // Backward compatibility: if the layerData is not chunked but contains a single base64PNG, + // create a fake chunk, expected to represent all frames side-by-side. + if (typeof layerData.chunks === "undefined" && layerData.base64PNG) { + this.normalizeLayerData_(layerData); + } + + var chunks = layerData.chunks; + + // Prepare a frames array to store frame objects extracted from the chunks. + var frames = []; + Q.all( + chunks.map(function (chunk) { + // Create a promise for each chunk. + var deferred = Q.defer(); + var image = new Image(); + // Load the chunk image in an Image object. + image.onload = function () { + // extract the chunkFrames from the chunk image + var chunkFrames = pskl.utils.FrameUtils.createFramesFromChunk( + image, + chunk.layout + ); + // add each image to the frames array, at the extracted index + chunkFrames.forEach(function (chunkFrame) { + frames[chunkFrame.index] = chunkFrame.frame; + }); + deferred.resolve(); + }; + image.src = chunk.base64PNG; + return deferred.promise; + }) + ) + .then( + function () { + frames.forEach(function (frame) { + layer.addFrame(frame); + }); + this.layers_[index] = layer; + this.onLayerLoaded_(); + }.bind(this) + ) + .catch(function (error) { + console.error("Failed to deserialize layer"); + console.error(error); + }); + + return layer; + }; + + ns.Deserializer.prototype.onLayerLoaded_ = function () { + this.layersToLoad_ = this.layersToLoad_ - 1; + if (this.layersToLoad_ === 0) { + this.layers_.forEach( + function (layer) { + this.piskel_.addLayer(layer); + }.bind(this) + ); + this.piskel_.hiddenFrames = this.hiddenFrames; + this.callback_(this.piskel_); + } + }; + + /** + * Backward comptibility only. Create a chunk for layerData objects that only contain + * an single base64PNG without chunk/layout information. + */ + ns.Deserializer.prototype.normalizeLayerData_ = function (layerData) { + var layout = []; + for (var i = 0; i < layerData.frameCount; i++) { + layout.push([i]); + } + layerData.chunks = [ + { + base64PNG: layerData.base64PNG, + layout: layout + } + ]; + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils.serialization.arraybuffer"); + + /** + * The array buffer serialization-deserialization should only be used when when backing + * up the animation in memory. If you actually need to dump the animation to a string + * use the regular serialization helpers. + * + * This is due to the lacking support on TypedArray::toString on some browsers. + * Will revisit the option of using this across the whole project when the APIs are less + * green. + * + */ + ns.ArrayBufferDeserializer = { + deserialize: function (data, callback) { + var i; + var j; + var buffer = data; + var arr8 = new Uint8Array(buffer); + var arr16 = new Uint16Array(arr8.buffer); + + /********/ + /* META */ + /********/ + // Piskel meta + // var _modelVersion = arr16[0]; + var width = arr16[1]; + var height = arr16[2]; + var fps = arr16[3]; + + // Descriptor meta + var descriptorNameLength = arr16[4]; + var descriptorDescriptionLength = arr16[5]; + + // Layers meta + var layerCount = arr16[6]; + + // Layers meta + var serializedHiddenFramesLength = arr16[7]; + + var currentIndex = 8; + /********/ + /* DATA */ + /********/ + // Descriptor name + var descriptorName = ""; + for (i = 0; i < descriptorNameLength; i++) { + descriptorName += String.fromCharCode(arr16[currentIndex + i]); + } + currentIndex += descriptorNameLength; + + // Descriptor description + var descriptorDescription = ""; + for (i = 0; i < descriptorDescriptionLength; i++) { + descriptorDescription = String.fromCharCode( + arr16[8 + descriptorNameLength + i] + ); + } + currentIndex += descriptorDescriptionLength; + + // Hidden frames + var serializedHiddenFrames = ""; + for (i = 0; i < serializedHiddenFramesLength; i++) { + serializedHiddenFrames = String.fromCharCode( + arr16[8 + descriptorNameLength + i] + ); + } + var hiddenFrames = serializedHiddenFrames.split("-"); + currentIndex += serializedHiddenFramesLength; + + // Layers + var layers = []; + var layer; + for (i = 0; i < layerCount; i++) { + layer = {}; + + // Meta + var layerNameLength = arr16[currentIndex]; + var opacity = arr16[currentIndex + 1] / 65535; + var frameCount = arr16[currentIndex + 2]; + var dataUriLengthFirstHalf = arr16[currentIndex + 3]; + var dataUriLengthSecondHalf = arr16[currentIndex + 4]; + var dataUriLength = + (dataUriLengthSecondHalf >>> 0) | + ((dataUriLengthFirstHalf << 16) >>> 0); + + // Name + var layerName = ""; + for (j = 0; j < layerNameLength; j++) { + layerName += String.fromCharCode(arr16[currentIndex + 5 + j]); + } + + // Data URI + var dataUri = ""; + for (j = 0; j < dataUriLength; j++) { + dataUri += String.fromCharCode( + arr8[(currentIndex + 5 + layerNameLength) * 2 + j] + ); + } + dataUri = "data:image/png;base64," + dataUri; + + currentIndex += Math.ceil(5 + layerNameLength + dataUriLength / 2); + + layer.name = layerName; + layer.opacity = opacity; + layer.frameCount = frameCount; + layer.dataUri = dataUri; + layers.push(layer); + } + + var descriptor = new pskl.model.piskel.Descriptor( + descriptorName, + descriptorDescription + ); + var piskel = new pskl.model.Piskel(width, height, fps, descriptor); + piskel.hiddenFrames = hiddenFrames; + var loadedLayers = 0; + + var loadLayerImage = function (layer, cb) { + var image = new Image(); + image.onload = function () { + var frames = pskl.utils.FrameUtils.createFramesFromSpritesheet( + this, + layer.frameCount + ); + frames.forEach(function (frame) { + layer.model.addFrame(frame); + }); + + loadedLayers++; + if (loadedLayers == layerCount) { + cb(piskel); + } + }; + image.src = layer.dataUri; + }; + + for (i = 0; i < layerCount; i++) { + layer = layers[i]; + var nlayer = new pskl.model.Layer(layer.name); + layer.model = nlayer; + nlayer.setOpacity(layer.opacity); + piskel.addLayer(nlayer); + + loadLayerImage.bind(this, layer, callback)(); + } + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils.serialization.arraybuffer"); + + /** + * The array buffer serialization-deserialization should only be used when when backing + * up the animation in memory. If you actually need to dump the animation to a string + * use the regular serialization helpers. + * + * This is due to the lacking support on TypedArray::toString on some browsers. + * Will revisit the option of using this across the whole project when the APIs are less + * green. + * + ********* + * META * + ********* + * // Piskel + * [0] = model version + * [1] = width + * [2] = height + * [3] = fps + * + * // Descriptor + * [4] = name length + * [5] = description length + * + * // Layers + * [6] = layers count + * [layer data index start] = layer name length + * [layer data index start + 1] = opacity + * [layer data index start + 2] = frame count + * [layer data index start + 3] = base 64 png data url length (upper 16 bits) + * [layer data index start + 4] = base 64 png data url length (lower 16 bits) + * + ********* + * DATA * + ********* + * [7..name length-1] = name + * [name length..description length-1] = description + * [layer data index start + 4..layer name length-1] = layer name + * [layer name length..base 64 png data url length-1] = base 64 png data url + * + */ + + ns.ArrayBufferSerializer = { + calculateRequiredBytes: function (piskel, framesData) { + var descriptorNameLength = piskel.getDescriptor().name.length; + var descriptorDescriptionLength = + piskel.getDescriptor().description.length; + + var bytes = 0; + + /********/ + /* META */ + /********/ + // Piskel meta + bytes += 4 * 2; + + // Descriptor meta + bytes += 2 * 2; + + // Layers meta + bytes += 1 * 2; + + /********/ + /* DATA */ + /********/ + // Descriptor name + bytes += descriptorNameLength * 2; + + // Descriptor description + bytes += descriptorDescriptionLength * 2; + + // Layers + for (var i = 0, layers = piskel.getLayers(); i < layers.length; i++) { + bytes += 5 * 2; + bytes += layers[i].name.length * 2; + bytes += framesData[i].length; + if (bytes % 2 == 1) { + bytes++; + } + } + + return bytes; + }, + + serialize: function (piskel) { + var i; + var j; + var layers; + var dataUri; + var dataUriLength; + + // Render frames + var framesData = []; + for (i = 0, layers = piskel.getLayers(); i < layers.length; i++) { + var renderer = new pskl.rendering.FramesheetRenderer( + layers[i].getFrames() + ); + dataUri = renderer.renderAsCanvas().toDataURL().split(",")[1]; + dataUriLength = dataUri.length; + framesData.push({ uri: dataUri, length: dataUriLength }); + } + + var hiddenFrames = piskel.hiddenFrames; + var serializedHiddenFrames = hiddenFrames.join("-"); + + var bytes = ns.ArrayBufferSerializer.calculateRequiredBytes( + piskel, + framesData, + serializedHiddenFrames + ); + + var buffer = new ArrayBuffer(bytes); + var arr8 = new Uint8Array(buffer); + var arr16 = new Uint16Array(buffer); + + var width = piskel.getWidth(); + var height = piskel.getHeight(); + var descriptorName = piskel.getDescriptor().name; + var descriptorNameLength = descriptorName.length; + var descriptorDescription = piskel.getDescriptor().description; + var descriptorDescriptionLength = descriptorDescription.length; + + /********/ + /* META */ + /********/ + // Piskel meta + arr16[0] = Constants.MODEL_VERSION; + arr16[1] = width; + arr16[2] = height; + arr16[3] = pskl.app.piskelController.getFPS(); + + // Descriptor meta + arr16[4] = descriptorNameLength; + arr16[5] = descriptorDescriptionLength; + + // Layers meta + arr16[6] = piskel.getLayers().length; + + // Frames meta + arr16[7] = serializedHiddenFrames.length; + + var currentIndex = 8; + + /********/ + /* DATA */ + /********/ + // Descriptor name + for (i = 0; i < descriptorNameLength; i++) { + arr16[currentIndex + i] = descriptorName.charCodeAt(i); + } + currentIndex = currentIndex + descriptorNameLength; + + // Descriptor description + for (i = 0; i < descriptorDescriptionLength; i++) { + arr16[currentIndex + i] = descriptorDescription.charCodeAt(i); + } + currentIndex = currentIndex + descriptorDescriptionLength; + + // Hidden frames + for (i = 0; i < serializedHiddenFrames.length; i++) { + arr16[currentIndex + i] = serializedHiddenFrames.charCodeAt(i); + } + currentIndex = currentIndex + serializedHiddenFrames.length; + + // Layers + for (i = 0, layers = piskel.getLayers(); i < layers.length; i++) { + var layer = layers[i]; + var frames = layer.getFrames(); + + var layerName = layer.getName(); + var layerNameLength = layerName.length; + var opacity = layer.getOpacity(); + var frameCount = frames.length; + + dataUri = framesData[i].uri; + dataUriLength = framesData[i].length; + + // Meta + arr16[currentIndex] = layerNameLength; + arr16[currentIndex + 1] = Math.floor(opacity * 65535); + arr16[currentIndex + 2] = frameCount; + arr16[currentIndex + 3] = ((dataUriLength & 0xffff0000) >> 16) >>> 0; // Upper 16 + arr16[currentIndex + 4] = (dataUriLength & 0x0000ffff) >>> 0; // Lower 16 + + // Name + for (j = 0; j < layerNameLength; j++) { + arr16[currentIndex + 5 + j] = layerName.charCodeAt(j); + } + + // Data URI + for (j = 0; j < dataUriLength; j++) { + arr8[(currentIndex + 5 + layerNameLength) * 2 + j] = + dataUri.charCodeAt(j); + } + + currentIndex += Math.ceil(5 + layerNameLength + dataUriLength / 2); + } + + return buffer; + } + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils.serialization.backward"); + + ns.Deserializer_v0 = function (data, callback) { + this.data_ = data; + this.callback_ = callback; + }; + + ns.Deserializer_v0.prototype.deserialize = function () { + var pixelGrids = this.data_; + var frames = pixelGrids.map(function (grid) { + return pskl.model.Frame.fromPixelGrid(grid); + }); + var descriptor = new pskl.model.piskel.Descriptor( + "Deserialized piskel", + "" + ); + var layer = pskl.model.Layer.fromFrames("Layer 1", frames); + + this.callback_( + pskl.model.Piskel.fromLayers([layer], Constants.DEFAULT.FPS, descriptor) + ); + }; +})(); +;(function () { + var ns = $.namespace("pskl.utils.serialization.backward"); + + ns.Deserializer_v1 = function (data, callback) { + this.callback_ = callback; + this.data_ = data; + }; + + ns.Deserializer_v1.prototype.deserialize = function () { + var piskelData = this.data_.piskel; + var descriptor = new pskl.model.piskel.Descriptor( + "Deserialized piskel", + "" + ); + var piskel = new pskl.model.Piskel( + piskelData.width, + piskelData.height, + Constants.DEFAULT.FPS, + descriptor + ); + + piskelData.layers.forEach( + function (serializedLayer) { + var layer = this.deserializeLayer(serializedLayer); + piskel.addLayer(layer); + }.bind(this) + ); + + this.callback_(piskel); + }; + + ns.Deserializer_v1.prototype.deserializeLayer = function (layerString) { + var layerData = JSON.parse(layerString); + var layer = new pskl.model.Layer(layerData.name); + layerData.frames.forEach( + function (serializedFrame) { + var frame = this.deserializeFrame(serializedFrame); + layer.addFrame(frame); + }.bind(this) + ); + + return layer; + }; + + ns.Deserializer_v1.prototype.deserializeFrame = function (frameString) { + var framePixelGrid = JSON.parse(frameString); + return pskl.model.Frame.fromPixelGrid(framePixelGrid); + }; +})(); +;(function () { + try { + var url; + if (pskl.utils.UserAgent.isIE11) { + url = 'js/lib/gif/gif.ie.worker.js'; + if (window.pskl && window.pskl.appEngineToken_) { + url = '../' + url; + } + } else { + var workerAsString = "(function (b) { function a(b, d) { if ({}.hasOwnProperty.call(a.cache, b)) return a.cache[b]; var e = a.resolve(b); if (!e) throw new Error('Failed to resolve module ' + b); var c = { id: b, require: a, filename: b, exports: {}, loaded: !1, parent: d, children: [] }; d && d.children.push(c); var f = b.slice(0, b.lastIndexOf('/') + 1); return a.cache[b] = c.exports, e.call(c.exports, c, c.exports, f, b), c.loaded = !0, a.cache[b] = c.exports } a.modules = {}, a.cache = {}, a.resolve = function (b) { return {}.hasOwnProperty.call(a.modules, b) ? a.modules[b] : void 0 }, a.define = function (b, c) { a.modules[b] = c }, a.define('/gif.worker.coffee', function (d, e, f, g) { var b, c; b = a('/GIFEncoder.js', d), c = function (a) { var c, e, d, f; return c = new b(a.width, a.height), a.index === 0 ? c.writeHeader() : c.firstFrame = !1, c.setTransparent(a.transparent), c.setRepeat(a.repeat), c.setDelay(a.delay), c.setQuality(a.quality), c.setPreserveColors(a.preserveColors), c.addFrame(a.data), a.last && c.finish(), d = c.stream(), a.data = d.pages, a.cursor = d.cursor, a.pageSize = d.constructor.pageSize, a.canTransfer ? (f = function (c) { for (var b = 0, d = a.data.length; b < d; ++b)e = a.data[b], c.push(e.buffer); return c }.call(this, []), self.postMessage(a, f)) : self.postMessage(a) }, self.onmessage = function (a) { return c(a.data) } }), a.define('/GIFEncoder.js', function (e, k, i, j) { function c() { this.page = -1, this.pages = [], this.newPage() } function b(a, b) { this.width = ~~a, this.height = ~~b, this.transparent = null, this.transIndex = 0, this.repeat = -1, this.delay = 0, this.image = null, this.pixels = null, this.indexedPixels = null, this.colorDepth = null, this.colorTab = null, this.usedEntry = new Array, this.palSize = 7, this.dispose = -1, this.firstFrame = !0, this.sample = 10, this.out = new c } var f = a('/TypedNeuQuant.js', e), g = a('/SimpleQuant.js', e), h = a('/LZWEncoder.js', e); c.pageSize = 4096, c.charMap = {}; for (var d = 0; d < 256; d++)c.charMap[d] = String.fromCharCode(d); c.prototype.newPage = function () { this.pages[++this.page] = new Uint8Array(c.pageSize), this.cursor = 0 }, c.prototype.getData = function () { var d = ''; for (var a = 0; a < this.pages.length; a++)for (var b = 0; b < c.pageSize; b++)d += c.charMap[this.pages[a][b]]; return d }, c.prototype.writeByte = function (a) { this.cursor >= c.pageSize && this.newPage(), this.pages[this.page][this.cursor++] = a }, c.prototype.writeUTFBytes = function (b) { for (var c = b.length, a = 0; a < c; a++)this.writeByte(b.charCodeAt(a)) }, c.prototype.writeBytes = function (b, d, e) { for (var c = e || b.length, a = d || 0; a < c; a++)this.writeByte(b[a]) }, b.prototype.setDelay = function (a) { this.delay = Math.round(a / 10) }, b.prototype.setFrameRate = function (a) { this.delay = Math.round(100 / a) }, b.prototype.setDispose = function (a) { a >= 0 && (this.dispose = a) }, b.prototype.setRepeat = function (a) { this.repeat = a }, b.prototype.setTransparent = function (a) { this.transparent = a }, b.prototype.setPreserveColors = function (a) { this.preserveColors = a }, b.prototype.addFrame = function (a) { this.image = a, this.getImagePixels(), this.analyzePixels(), this.firstFrame && (this.writeLSD(), this.writePalette(), this.repeat >= 0 && this.writeNetscapeExt()), this.writeGraphicCtrlExt(), this.writeImageDesc(), this.firstFrame || this.writePalette(), this.writePixels(), this.firstFrame = !1 }, b.prototype.finish = function () { this.out.writeByte(59) }, b.prototype.setQuality = function (a) { a < 1 && (a = 1), this.sample = a }, b.prototype.writeHeader = function () { this.out.writeUTFBytes('GIF89a') }, b.prototype.analyzePixels = function () { var h = this.pixels.length, d = h / 3; this.indexedPixels = new Uint8Array(d); var a; if (this.preserveColors) { var i = this.toRGBComponents(this.transparent); a = new g(this.pixels, this.sample, i) } else a = new f(this.pixels, this.sample); a.buildColormap(), this.colorTab = a.getColormap(); var b = 0; for (var c = 0; c < d; c++) { var e = a.lookupRGB(this.pixels[b++] & 255, this.pixels[b++] & 255, this.pixels[b++] & 255); this.usedEntry[e] = !0, this.indexedPixels[c] = e } this.pixels = null, this.colorDepth = 8, this.palSize = 7, this.transparent !== null && (this.transIndex = this.findClosest(this.transparent)) }, b.prototype.toRGBComponents = function (a) { var b = null; return a && (b = { r: (a & 16711680) >> 16, g: (a & 65280) >> 8, b: a & 255 }), b }, b.prototype.findClosest = function (e) { if (this.colorTab === null) return -1; var k = (e & 16711680) >> 16, l = (e & 65280) >> 8, m = e & 255, c = 0, d = 16777216, j = this.colorTab.length; for (var a = 0; a < j;) { var f = k - (this.colorTab[a++] & 255), g = l - (this.colorTab[a++] & 255), h = m - (this.colorTab[a] & 255), i = f * f + g * g + h * h, b = parseInt(a / 3); (this.preserveColors || this.usedEntry[b]) && i < d && (d = i, c = b), a++ } return c }, b.prototype.getImagePixels = function () { var a = this.width, g = this.height; this.pixels = new Uint8Array(a * g * 3); var b = this.image, c = 0; for (var d = 0; d < g; d++)for (var e = 0; e < a; e++) { var f = d * a * 4 + e * 4; this.pixels[c++] = b[f], this.pixels[c++] = b[f + 1], this.pixels[c++] = b[f + 2] } }, b.prototype.writeGraphicCtrlExt = function () { this.out.writeByte(33), this.out.writeByte(249), this.out.writeByte(4); var b, a; this.transparent === null ? (b = 0, a = 0) : (b = 1, a = 2), this.dispose >= 0 && (a = dispose & 7), a <<= 2, this.out.writeByte(0 | a | 0 | b), this.writeShort(this.delay), this.out.writeByte(this.transIndex), this.out.writeByte(0) }, b.prototype.writeImageDesc = function () { this.out.writeByte(44), this.writeShort(0), this.writeShort(0), this.writeShort(this.width), this.writeShort(this.height), this.firstFrame ? this.out.writeByte(0) : this.out.writeByte(128 | this.palSize) }, b.prototype.writeLSD = function () { this.writeShort(this.width), this.writeShort(this.height), this.out.writeByte(240 | this.palSize), this.out.writeByte(0), this.out.writeByte(0) }, b.prototype.writeNetscapeExt = function () { this.out.writeByte(33), this.out.writeByte(255), this.out.writeByte(11), this.out.writeUTFBytes('NETSCAPE2.0'), this.out.writeByte(3), this.out.writeByte(1), this.writeShort(this.repeat), this.out.writeByte(0) }, b.prototype.writePalette = function () { this.out.writeBytes(this.colorTab); var b = 768 - this.colorTab.length; for (var a = 0; a < b; a++)this.out.writeByte(0) }, b.prototype.writeShort = function (a) { this.out.writeByte(a & 255), this.out.writeByte(a >> 8 & 255) }, b.prototype.writePixels = function () { var a = new h(this.width, this.height, this.indexedPixels, this.colorDepth); a.encode(this.out) }, b.prototype.stream = function () { return this.out }, e.exports = b }), a.define('/LZWEncoder.js', function (e, g, h, i) { function f(y, D, C, B) { function w(a, b) { r[f++] = a, f >= 254 && t(b) } function x(b) { u(a), k = i + 2, j = !0, l(i, b) } function u(b) { for (var a = 0; a < b; ++a)h[a] = -1 } function A(z, r) { var g, t, d, e, y, w, s; for (q = z, j = !1, n_bits = q, m = p(n_bits), i = 1 << z - 1, o = i + 1, k = i + 2, f = 0, e = v(), s = 0, g = a; g < 65536; g *= 2)++s; s = 8 - s, w = a, u(w), l(i, r); a: while ((t = v()) != c) { if (g = (t << b) + e, d = t << s ^ e, h[d] === g) { e = n[d]; continue } if (h[d] >= 0) { y = w - d, d === 0 && (y = 1); do if ((d -= y) < 0 && (d += w), h[d] === g) { e = n[d]; continue a } while (h[d] >= 0) } l(e, r), e = t, k < 1 << b ? (n[d] = k++, h[d] = g) : x(r) } l(e, r), l(o, r) } function z(a) { a.writeByte(s), remaining = y * D, curPixel = 0, A(s + 1, a), a.writeByte(0) } function t(a) { f > 0 && (a.writeByte(f), a.writeBytes(r, 0, f), f = 0) } function p(a) { return (1 << a) - 1 } function v() { if (remaining === 0) return c; --remaining; var a = C[curPixel++]; return a & 255 } function l(a, c) { g &= d[e], e > 0 ? g |= a << e : g = a, e += n_bits; while (e >= 8) w(g & 255, c), g >>= 8, e -= 8; if ((k > m || j) && (j ? (m = p(n_bits = q), j = !1) : (++n_bits, n_bits == b ? m = 1 << b : m = p(n_bits))), a == o) { while (e > 0) w(g & 255, c), g >>= 8, e -= 8; t(c) } } var s = Math.max(2, B), r = new Uint8Array(256), h = new Int32Array(a), n = new Int32Array(a), g, e = 0, f, k = 0, m, j = !1, q, i, o; this.encode = z } var c = -1, b = 12, a = 5003, d = [0, 1, 3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535]; e.exports = f }), a.define('/SimpleQuant.js', function (b, d, e, f) { function a(a, b, c) { return [a, b, c].join('.') } function c(c, d, b) { this.pixels = c, this.palette = [], this.paletteIndex = {}, this.getColormap = function () { return this.palette }, this.buildColormap = function () { var d = this.pixels.length / 3, a = 0; for (var c = 0; c < d; c++) { var e = this.pixels[a++], f = this.pixels[a++], g = this.pixels[a++]; this.addColorToPalette(e, f, g) } b && this.addColorToPalette(b.r, b.g, b.b) }, this.addColorToPalette = function (c, d, e) { var b = a(c, d, e); this.paletteIndex.hasOwnProperty(b) || (this.palette.push(c), this.palette.push(d), this.palette.push(e), this.paletteIndex[b] = this.palette.length / 3 - 1) }, this.lookupRGB = function (b, c, d) { return this.paletteIndex[a(b, c, d)] } } b.exports = c }), a.define('/TypedNeuQuant.js', function (A, F, E, D) { function C(A, B) { function I() { o = [], q = new Int32Array(256), t = new Int32Array(a), y = new Int32Array(a), z = new Int32Array(a >> 3); var c, d; for (c = 0; c < a; c++)d = (c << b + 8) / a, o[c] = new Float64Array([d, d, d, 0]), y[c] = e / a, t[c] = 0 } function J() { for (var c = 0; c < a; c++)o[c][0] >>= b, o[c][1] >>= b, o[c][2] >>= b, o[c][3] = c } function K(b, a, c, e, f) { o[a][0] -= b * (o[a][0] - c) / d, o[a][1] -= b * (o[a][1] - e) / d, o[a][2] -= b * (o[a][2] - f) / d } function L(j, e, n, l, k) { var h = Math.abs(e - j), i = Math.min(e + j, a), g = e + 1, f = e - 1, m = 1, b, d; while (g < i || f > h) d = z[m++], g < i && (b = o[g++], b[0] -= d * (b[0] - n) / c, b[1] -= d * (b[1] - l) / c, b[2] -= d * (b[2] - k) / c), f > h && (b = o[f--], b[0] -= d * (b[0] - n) / c, b[1] -= d * (b[1] - l) / c, b[2] -= d * (b[2] - k) / c) } function C(p, s, q) { var h = 2147483647, k = h, d = -1, m = d, c, j, e, n, l; for (c = 0; c < a; c++)j = o[c], e = Math.abs(j[0] - p) + Math.abs(j[1] - s) + Math.abs(j[2] - q), e < h && (h = e, d = c), n = e - (t[c] >> i - b), n < k && (k = n, m = c), l = y[c] >> g, y[c] -= l, t[c] += l << f; return y[d] += x, t[d] -= r, m } function D() { var d, b, e, c, h, g, f = 0, i = 0; for (d = 0; d < a; d++) { for (e = o[d], h = d, g = e[1], b = d + 1; b < a; b++)c = o[b], c[1] < g && (h = b, g = c[1]); if (c = o[h], d != h && (b = c[0], c[0] = e[0], e[0] = b, b = c[1], c[1] = e[1], e[1] = b, b = c[2], c[2] = e[2], e[2] = b, b = c[3], c[3] = e[3], e[3] = b), g != f) { for (q[f] = i + d >> 1, b = f + 1; b < g; b++)q[b] = d; f = g, i = d } } for (q[f] = i + n >> 1, b = f + 1; b < 256; b++)q[b] = n } function E(j, i, k) { var b, d, c, e = 1e3, h = -1, f = q[i], g = f - 1; while (f < a || g >= 0) f < a && (d = o[f], c = d[1] - i, c >= e ? f = a : (f++, c < 0 && (c = -c), b = d[0] - j, b < 0 && (b = -b), c += b, c < e && (b = d[2] - k, b < 0 && (b = -b), c += b, c < e && (e = c, h = d[3])))), g >= 0 && (d = o[g], c = i - d[1], c >= e ? g = -1 : (g--, c < 0 && (c = -c), b = d[0] - j, b < 0 && (b = -b), c += b, c < e && (b = d[2] - k, b < 0 && (b = -b), c += b, c < e && (e = c, h = d[3])))); return h } function F() { var c, f = A.length, D = 30 + (B - 1) / 3, y = f / (3 * B), q = ~~(y / w), n = d, o = u, a = o >> h; for (a <= 1 && (a = 0), c = 0; c < a; c++)z[c] = n * ((a * a - c * c) * m / (a * a)); var i; f < s ? (B = 1, i = 3) : f % l !== 0 ? i = 3 * l : f % k !== 0 ? i = 3 * k : f % p !== 0 ? i = 3 * p : i = 3 * j; var r, t, x, e, g = 0; c = 0; while (c < y) if (r = (A[g] & 255) << b, t = (A[g + 1] & 255) << b, x = (A[g + 2] & 255) << b, e = C(r, t, x), K(n, e, r, t, x), a !== 0 && L(a, e, r, t, x), g += i, g >= f && (g -= f), c++, q === 0 && (q = 1), c % q === 0) for (n -= n / D, o -= o / v, a = o >> h, a <= 1 && (a = 0), e = 0; e < a; e++)z[e] = n * ((a * a - e * e) * m / (a * a)) } function G() { I(), F(), J(), D() } function H() { var b = [], g = []; for (var c = 0; c < a; c++)g[o[c][3]] = c; var d = 0; for (var e = 0; e < a; e++) { var f = g[e]; b[d++] = o[f][0], b[d++] = o[f][1], b[d++] = o[f][2] } return b } var o, q, t, y, z; this.buildColormap = G, this.getColormap = H, this.lookupRGB = E } var w = 100, a = 256, n = a - 1, b = 4, i = 16, e = 1 << i, f = 10, B = 1 << f, g = 10, x = e >> g, r = e << f - g, z = a >> 3, h = 6, t = 1 << h, u = z * t, v = 30, o = 10, d = 1 << o, q = 8, m = 1 << q, y = o + q, c = 1 << y, l = 499, k = 491, p = 487, j = 503, s = 3 * j; A.exports = C }), a('/gif.worker.coffee') }.call(this, this))" + + var typedArray = [workerAsString]; + var blob = new Blob(typedArray, { + type: "application/javascript" + }); // pass a useful mime type here + url = URL.createObjectURL(blob); + } + window.GifWorkerURL = url; + } catch (e) { + console.error("Could not create worker", e.message); + } +})(); +;(function(c){function a(b,d){if({}.hasOwnProperty.call(a.cache,b))return a.cache[b];var e=a.resolve(b);if(!e)throw new Error('Failed to resolve module '+b);var c={id:b,require:a,filename:b,exports:{},loaded:!1,parent:d,children:[]};d&&d.children.push(c);var f=b.slice(0,b.lastIndexOf('/')+1);return a.cache[b]=c.exports,e.call(c.exports,c,c.exports,f,b),c.loaded=!0,a.cache[b]=c.exports}a.modules={},a.cache={},a.resolve=function(b){return{}.hasOwnProperty.call(a.modules,b)?a.modules[b]:void 0},a.define=function(b,c){a.modules[b]=c};var b=function(a){return a='/',{title:'browser',version:'v0.8.19',browser:!0,env:{},argv:[],nextTick:c.setImmediate||function(a){setTimeout(a,0)},cwd:function(){return a},chdir:function(b){a=b}}}();a.define('/gif.coffee',function(d,m,l,k){function g(a,b){return{}.hasOwnProperty.call(a,b)}function j(d,b){for(var a=0,c=b.length;athis.frames.length;0<=this.frames.length?++a:--a)b.push(a);return b}.apply(this,arguments),a=0,e=b.length;aa;0<=a?++b:--b)c.push(b);return c}.apply(this,arguments),b=0,e=c.length;ba;this.freeWorkers.length<=a?++b:--b)c.push(b);return c}.apply(this,arguments).forEach(function(a){return function(c){var b;return console.log('spawning worker '+c),b=new Worker(a.options.workerScript),b.onmessage=function(a){return function(c){return a.activeWorkers.splice(a.activeWorkers.indexOf(b),1),a.freeWorkers.push(b),a.frameFinished(c.data)}}(a),a.freeWorkers.push(b)}}(this)),a},a.prototype.frameFinished=function(a){return console.log('frame '+a.index+' finished - '+this.activeWorkers.length+' active'),this.finishedFrames++,this.emit('progress',this.finishedFrames/this.frames.length),this.imageParts[a.index]=a,j(null,this.imageParts)?this.renderNextFrame():this.finishRendering()},a.prototype.finishRendering=function(){var e,a,k,m,b,d,h;b=0;for(var f=0,j=this.imageParts.length;f=this.frames.length?void 0:(c=this.frames[this.nextFrame++],b=this.freeWorkers.shift(),a=this.getTask(c),console.log('starting frame '+(a.index+1)+' of '+this.frames.length),this.activeWorkers.push(b),b.postMessage(a))},a.prototype.getContextData=function(a){return a.getImageData(0,0,this.options.width,this.options.height).data},a.prototype.getImageData=function(b){var a;return null!=this._canvas||(this._canvas=document.createElement('canvas'),this._canvas.width=this.options.width,this._canvas.height=this.options.height),a=this._canvas.getContext('2d'),a.setFill=this.options.background,a.fillRect(0,0,this.options.width,this.options.height),a.drawImage(b,0,0),this.getContextData(a)},a.prototype.getTask=function(a){var c,b;if(c=this.frames.indexOf(a),b={index:c,last:c===this.frames.length-1,delay:a.delay,transparent:a.transparent,width:this.options.width,height:this.options.height,quality:this.options.quality,preserveColors:this.options.preserveColors,repeat:this.options.repeat,canTransfer:h.name==='chrome'},null!=a.data)b.data=a.data;else if(null!=a.context)b.data=this.getContextData(a.context);else if(null!=a.image)b.data=this.getImageData(a.image);else throw new Error('Invalid frame');return b},a}(f),d.exports=e}),a.define('/browser.coffee',function(f,g,h,i){var a,d,e,c,b;c=navigator.userAgent.toLowerCase(),e=navigator.platform.toLowerCase(),b=c.match(/(opera|ie|firefox|chrome|version)[\s\/:]([\w\d\.]+)?.*?(safari|version[\s\/:]([\w\d\.]+)|$)/)||[null,'unknown',0],d=b[1]==='ie'&&document.documentMode,a={name:b[1]==='version'?b[3]:b[1],version:d||parseFloat(b[1]==='opera'&&b[4]?b[4]:b[2]),platform:{name:c.match(/ip(?:ad|od|hone)/)?'ios':(c.match(/(?:webos|android)/)||e.match(/mac|win|linux/)||['other'])[0]}},a[a.name]=!0,a[a.name+parseInt(a.version,10)]=!0,a.platform[a.platform.name]=!0,f.exports=a}),a.define('events',function(f,e,g,h){b.EventEmitter||(b.EventEmitter=function(){});var a=e.EventEmitter=b.EventEmitter,c=typeof Array.isArray==='function'?Array.isArray:function(a){return Object.prototype.toString.call(a)==='[object Array]'},d=10;a.prototype.setMaxListeners=function(a){this._events||(this._events={}),this._events.maxListeners=a},a.prototype.emit=function(f){if(f==='error'&&(!(this._events&&this._events.error)||c(this._events.error)&&!this._events.error.length))throw arguments[1]instanceof Error?arguments[1]:new Error("Uncaught, unspecified 'error' event.");if(!this._events)return!1;var a=this._events[f];if(!a)return!1;if(!(typeof a=='function'))if(c(a)){var b=Array.prototype.slice.call(arguments,1),e=a.slice();for(var d=0,g=e.length;d0&&this._events[a].length>e&&(this._events[a].warned=!0,console.error('(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.',this._events[a].length),console.trace())}this._events[a].push(b)}else this._events[a]=[this._events[a],b];return this},a.prototype.on=a.prototype.addListener,a.prototype.once=function(b,c){var a=this;return a.on(b,function d(){a.removeListener(b,d),c.apply(this,arguments)}),this},a.prototype.removeListener=function(a,d){if('function'!==typeof d)throw new Error('removeListener only takes instances of Function');if(!(this._events&&this._events[a]))return this;var b=this._events[a];if(c(b)){var e=b.indexOf(d);if(e<0)return this;b.splice(e,1),b.length==0&&delete this._events[a]}else this._events[a]===d&&delete this._events[a];return this},a.prototype.removeAllListeners=function(a){return a&&this._events&&this._events[a]&&(this._events[a]=null),this},a.prototype.listeners=function(a){return this._events||(this._events={}),this._events[a]||(this._events[a]=[]),c(this._events[a])||(this._events[a]=[this._events[a]]),this._events[a]}}),c.GIF=a('/gif.coffee')}.call(this,this)) +//# sourceMappingURL=gif.js.map +// gif.js 0.1.6 - https://github.com/jnordberg/gif.js +;( function( window ) { 'use strict'; + +// Stream +/** + * @constructor + */ +// Make compiler happy. +var Stream = function (data) { + this.data = data; + this.len = this.data.length; + this.pos = 0; +}; + +Stream.prototype.readByte = function () { + if (this.pos >= this.data.length) { + throw new Error('Attempted to read past end of stream.'); + } + return this.data.charCodeAt(this.pos++) & 0xFF; +}; + +Stream.prototype.readBytes = function (n) { + var bytes = []; + for (var i = 0; i < n; i++) { + bytes.push(this.readByte()); + } + return bytes; +}; + +Stream.prototype.read = function (n) { + var s = ''; + for (var i = 0; i < n; i++) { + s += String.fromCharCode(this.readByte()); + } + return s; +}; + +Stream.prototype.readUnsigned = function () { // Little-endian. + var a = this.readBytes(2); + return (a[1] << 8) + a[0]; +}; + +var SuperGIF = window.SuperGIF = window.SuperGIF || {}; +SuperGIF.Stream = Stream; + +})( window ); + +/* + SuperGif + + Example usage: + + + + + + Image tag attributes: + + data-animated-src - If this url is specified, it's loaded into the player instead of src. + This allows a preview frame to be shown until animated gif data is streamed into the canvas + + Constructor options args + + gif Required. The DOM element of an img tag. + + Instance methods + + // loading + load( callback ) Loads the gif into a canvas element and then calls callback if one is passed + + For additional customization (viewport inside iframe) these params may be passed: + c_w, c_h - width and height of canvas + vp_t, vp_l, vp_ w, vp_h - top, left, width and height of the viewport + + A bonus: few articles to understand what is going on + http://enthusiasms.org/post/16976438906 + http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp + http://humpy77.deviantart.com/journal/Frame-Delay-Times-for-Animated-GIFs-214150546 + +*/ + +( function( window ) { 'use strict'; + +// Generic functions +var bitsToNum = function (ba) { + return ba.reduce(function (s, n) { + return s * 2 + n; + }, 0); +}; + +var byteToBitArr = function (bite) { + var a = []; + for (var i = 7; i >= 0; i--) { + a.push( !! (bite & (1 << i))); + } + return a; +}; + +// Stream +/** + * @constructor + */ +// Make compiler happy. +var Stream = function (data) { + this.data = data; + this.len = this.data.length; + this.pos = 0; + + this.readByte = function () { + if (this.pos >= this.data.length) { + throw new Error('Attempted to read past end of stream.'); + } + return data.charCodeAt(this.pos++) & 0xFF; + }; + + this.readBytes = function (n) { + var bytes = []; + for (var i = 0; i < n; i++) { + bytes.push(this.readByte()); + } + return bytes; + }; + + this.read = function (n) { + var s = ''; + for (var i = 0; i < n; i++) { + s += String.fromCharCode(this.readByte()); + } + return s; + }; + + this.readUnsigned = function () { // Little-endian. + var a = this.readBytes(2); + return (a[1] << 8) + a[0]; + }; +}; + +var lzwDecode = function (minCodeSize, data) { + // TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String? + var pos = 0; // Maybe this streaming thing should be merged with the Stream? + var readCode = function (size) { + var code = 0; + for (var i = 0; i < size; i++) { + if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) { + code |= 1 << i; + } + pos++; + } + return code; + }; + + var output = []; + + var clearCode = 1 << minCodeSize; + var eoiCode = clearCode + 1; + + var codeSize = minCodeSize + 1; + + var dict = []; + + var clear = function () { + dict = []; + codeSize = minCodeSize + 1; + for (var i = 0; i < clearCode; i++) { + dict[i] = [i]; + } + dict[clearCode] = []; + dict[eoiCode] = null; + + }; + + var code; + var last; + + while (true) { + last = code; + code = readCode(codeSize); + + if (code === clearCode) { + clear(); + continue; + } + if (code === eoiCode) break; + + if (code < dict.length) { + if (last !== clearCode) { + dict.push(dict[last].concat(dict[code][0])); + } + } + else { + if (code !== dict.length) throw new Error('Invalid LZW code.'); + dict.push(dict[last].concat(dict[last][0])); + } + output.push.apply(output, dict[code]); + + if (dict.length === (1 << codeSize) && codeSize < 12) { + // If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long. + codeSize++; + } + } + + // I don't know if this is technically an error, but some GIFs do it. + //if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.'); + return output; +}; + + +// The actual parsing; returns an object with properties. +var parseGIF = function (st, handler) { + handler || (handler = {}); + + // LZW (GIF-specific) + var parseCT = function (entries) { // Each entry is 3 bytes, for RGB. + var ct = []; + for (var i = 0; i < entries; i++) { + ct.push(st.readBytes(3)); + } + return ct; + }; + + var readSubBlocks = function () { + var size, data; + data = ''; + do { + size = st.readByte(); + data += st.read(size); + } while (size !== 0); + return data; + }; + + var parseHeader = function () { + var hdr = {}; + hdr.sig = st.read(3); + hdr.ver = st.read(3); + if (hdr.sig !== 'GIF') { + handler.onError(); // XXX: This should probably be handled more nicely. + throw new Error('Not a GIF file.'); + } + hdr.width = st.readUnsigned(); + hdr.height = st.readUnsigned(); + + var bits = byteToBitArr(st.readByte()); + hdr.gctFlag = bits.shift(); + hdr.colorRes = bitsToNum(bits.splice(0, 3)); + hdr.sorted = bits.shift(); + hdr.gctSize = bitsToNum(bits.splice(0, 3)); + + hdr.bgColor = st.readByte(); + hdr.pixelAspectRatio = st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64 + if (hdr.gctFlag) { + hdr.gct = parseCT(1 << (hdr.gctSize + 1)); + } + handler.hdr && handler.hdr(hdr); + }; + + var parseExt = function (block) { + var parseGCExt = function (block) { + var blockSize = st.readByte(); // Always 4 + var bits = byteToBitArr(st.readByte()); + block.reserved = bits.splice(0, 3); // Reserved; should be 000. + block.disposalMethod = bitsToNum(bits.splice(0, 3)); + block.userInput = bits.shift(); + block.transparencyGiven = bits.shift(); + + block.delayTime = st.readUnsigned(); + + block.transparencyIndex = st.readByte(); + + block.terminator = st.readByte(); + + handler.gce && handler.gce(block); + }; + + var parseComExt = function (block) { + block.comment = readSubBlocks(); + handler.com && handler.com(block); + }; + + var parsePTExt = function (block) { + // No one *ever* uses this. If you use it, deal with parsing it yourself. + var blockSize = st.readByte(); // Always 12 + block.ptHeader = st.readBytes(12); + block.ptData = readSubBlocks(); + handler.pte && handler.pte(block); + }; + + var parseAppExt = function (block) { + var parseNetscapeExt = function (block) { + var blockSize = st.readByte(); // Always 3 + block.unknown = st.readByte(); // ??? Always 1? What is this? + block.iterations = st.readUnsigned(); + block.terminator = st.readByte(); + handler.app && handler.app.NETSCAPE && handler.app.NETSCAPE(block); + }; + + var parseUnknownAppExt = function (block) { + block.appData = readSubBlocks(); + // FIXME: This won't work if a handler wants to match on any identifier. + handler.app && handler.app[block.identifier] && handler.app[block.identifier](block); + }; + + var blockSize = st.readByte(); // Always 11 + block.identifier = st.read(8); + block.authCode = st.read(3); + switch (block.identifier) { + case 'NETSCAPE': + parseNetscapeExt(block); + break; + default: + parseUnknownAppExt(block); + break; + } + }; + + var parseUnknownExt = function (block) { + block.data = readSubBlocks(); + handler.unknown && handler.unknown(block); + }; + + block.label = st.readByte(); + switch (block.label) { + case 0xF9: + block.extType = 'gce'; + parseGCExt(block); + break; + case 0xFE: + block.extType = 'com'; + parseComExt(block); + break; + case 0x01: + block.extType = 'pte'; + parsePTExt(block); + break; + case 0xFF: + block.extType = 'app'; + parseAppExt(block); + break; + default: + block.extType = 'unknown'; + parseUnknownExt(block); + break; + } + }; + + var parseImg = function (img) { + var deinterlace = function (pixels, width) { + // Of course this defeats the purpose of interlacing. And it's *probably* + // the least efficient way it's ever been implemented. But nevertheless... + var newPixels = new Array(pixels.length); + var rows = pixels.length / width; + var cpRow = function (toRow, fromRow) { + var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width); + newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels)); + }; + + // See appendix E. + var offsets = [0, 4, 2, 1]; + var steps = [8, 8, 4, 2]; + + var fromRow = 0; + for (var pass = 0; pass < 4; pass++) { + for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) { + cpRow(toRow, fromRow) + fromRow++; + } + } + + return newPixels; + }; + + img.leftPos = st.readUnsigned(); + img.topPos = st.readUnsigned(); + img.width = st.readUnsigned(); + img.height = st.readUnsigned(); + + var bits = byteToBitArr(st.readByte()); + img.lctFlag = bits.shift(); + img.interlaced = bits.shift(); + img.sorted = bits.shift(); + img.reserved = bits.splice(0, 2); + img.lctSize = bitsToNum(bits.splice(0, 3)); + + if (img.lctFlag) { + img.lct = parseCT(1 << (img.lctSize + 1)); + } + + img.lzwMinCodeSize = st.readByte(); + + var lzwData = readSubBlocks(); + + img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData); + + if (img.interlaced) { // Move + img.pixels = deinterlace(img.pixels, img.width); + } + + handler.img && handler.img(img); + }; + + var parseBlock = function () { + var block = {}; + block.sentinel = st.readByte(); + + switch (String.fromCharCode(block.sentinel)) { // For ease of matching + case '!': + block.type = 'ext'; + parseExt(block); + break; + case ',': + block.type = 'img'; + parseImg(block); + break; + case ';': + block.type = 'eof'; + handler.eof && handler.eof(block); + break; + default: + return handler.onError(new Error('Unknown block: 0x' + block.sentinel.toString(16))); // TODO: Pad this with a 0. + } + + if (block.type !== 'eof') { + setTimeout(parseBlock, 0); + } + }; + + var parse = function () { + parseHeader(); + setTimeout(parseBlock, 0); + }; + + parse(); +}; + + +var SuperGif = function ( opts ) { + var options = { + //viewport position + vp_l: 0, + vp_t: 0, + vp_w: null, + vp_h: null, + //canvas sizes + c_w: null, + c_h: null + }; + for (var i in opts ) { options[i] = opts[i] } + if (options.vp_w && options.vp_h) options.is_vp = true; + + var stream; + var hdr; + + var loadError = null; + var loading = false; + + var transparency = null; + var delay = null; + var disposalMethod = null; + var disposalRestoreFromIdx = 0; + var lastDisposalMethod = null; + var frame = null; + var lastImg = null; + + var frames = []; + + var gif = options.gif; + + var clear = function () { + transparency = null; + delay = null; + lastDisposalMethod = disposalMethod; + disposalMethod = null; + frame = null; + }; + + // XXX: There's probably a better way to handle catching exceptions when + // callbacks are involved. + var doParse = function () { + try { + parseGIF(stream, handler); + } + catch (err) { + doLoadError('parse'); + } + }; + + var setSizes = function(w, h) { + tmpCanvas.width = w; + tmpCanvas.height = h; + tmpCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0); + } + + var doLoadError = function (originOfError) { + + + loadError = originOfError; + hdr = { + width: gif.width, + height: gif.height + }; // Fake header. + frames = []; + }; + + var doHdr = function (_hdr) { + hdr = _hdr; + setSizes(hdr.width, hdr.height) + }; + + var doGCE = function (gce) { + pushFrame(); + clear(); + transparency = gce.transparencyGiven ? gce.transparencyIndex : null; + delay = gce.delayTime; + disposalMethod = gce.disposalMethod; + // We don't have much to do with the rest of GCE. + }; + + var pushFrame = function () { + if (!frame) return; + frames.push({ + data: frame.getImageData(0, 0, hdr.width, hdr.height), + delay: delay + }); + }; + + // flag for drawing initial frame + var isInitFrameDrawn = false; + + var doImg = function (img) { + if (!frame) frame = tmpCanvas.getContext('2d'); + + var currIdx = frames.length; + + //ct = color table, gct = global color table + var ct = img.lctFlag ? img.lct : hdr.gct; // TODO: What if neither exists? + + /* + Disposal method indicates the way in which the graphic is to + be treated after being displayed. + + Values : 0 - No disposal specified. The decoder is + not required to take any action. + 1 - Do not dispose. The graphic is to be left + in place. + 2 - Restore to background color. The area used by the + graphic must be restored to the background color. + 3 - Restore to previous. The decoder is required to + restore the area overwritten by the graphic with + what was there prior to rendering the graphic. + + Importantly, "previous" means the frame state + after the last disposal of method 0, 1, or 2. + */ + if (currIdx > 0) { + if (lastDisposalMethod === 3) { + // Restore to previous + frame.putImageData(frames[disposalRestoreFromIdx].data, 0, 0); + } else { + disposalRestoreFromIdx = currIdx - 1; + } + + if (lastDisposalMethod === 2) { + // Restore to background color + // Browser implementations historically restore to transparent; we do the same. + // http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=1&t=21172#p86079 + frame.clearRect(lastImg.leftPos, lastImg.topPos, lastImg.width, lastImg.height); + } + } + // else, Undefined/Do not dispose. + // frame contains final pixel data from the last frame; do nothing + + //Get existing pixels for img region after applying disposal method + var imgData = frame.getImageData(img.leftPos, img.topPos, img.width, img.height); + //apply color table colors + var cdd = imgData.data; + img.pixels.forEach(function (pixel, i) { + // imgData.data === [R,G,B,A,R,G,B,A,...] + if (pixel !== transparency) { + cdd[i * 4 + 0] = ct[pixel][0]; + cdd[i * 4 + 1] = ct[pixel][1]; + cdd[i * 4 + 2] = ct[pixel][2]; + cdd[i * 4 + 3] = 255; // Opaque. + } + }); + + frame.putImageData(imgData, img.leftPos, img.topPos); + + lastImg = img; + }; + + var doNothing = function () {}; + /** + * @param{boolean=} draw Whether to draw progress bar or not; this is not idempotent because of translucency. + * Note that this means that the text will be unsynchronized with the progress bar on non-frames; + * but those are typically so small (GCE etc.) that it doesn't really matter. TODO: Do this properly. + */ + var handler = { + hdr: doHdr, + gce: doGCE, + // I guess that's all for now. + // app: { + // // TODO: Is there much point in actually supporting iterations? + // NETSCAPE: withProgress(doNothing) + // }, + img: doImg, + eof: function (block) { + pushFrame(); + loading = false; + if (load_callback) { + load_callback(); + } + }, + + onError : function (error) { + if (error_callback) { + error_callback(); + } + } + }; + + var load_callback = false; + var step_callback = false; + var error_callback = false; + var tmpCanvas = document.createElement('canvas'); + + return { + + load: function (callback) { + + load_callback = callback.success; + step_callback = callback.step; + error_callback = callback.error; + + loading = true; + + if (gif.src.indexOf('data:') !== -1) { + var data = gif.src.substring(gif.src.indexOf(',')+1); + stream = new Stream(window.atob(data)); + doParse(); + } else { + var h = new XMLHttpRequest(); + h.overrideMimeType('text/plain; charset=x-user-defined'); + h.onload = function(e) { + stream = new Stream(h.responseText); + setTimeout(doParse, 0); + }; + h.onerror = function() { doLoadError('xhr'); }; + h.open('GET', gif.getAttribute('data-animated-src') || gif.src, true); + h.send(); + } + }, + + getFrames : function () { + return frames; + } + }; +}; + + +window.SuperGif = SuperGif; + +})( window );;/*! + +JSZip - A Javascript class for generating and reading zip files + + +(c) 2009-2014 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. + +JSZip uses the library zlib.js released under the following license : +zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License +*/ +!function(a){"object"==typeof exports?module.exports=a():"function"==typeof define&&define.amd?define(a):"undefined"!=typeof window?window.JSZip=a():"undefined"!=typeof global?global.JSZip=a():"undefined"!=typeof self&&(self.JSZip=a())}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error("Cannot find module '"+g+"'")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j="",k=0;for(a=a.replace(/[^A-Za-z0-9\+\/\=]/g,"");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){"use strict";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){"use strict";c.STORE={magic:"\x00\x00",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a("./flate")},{"./flate":6}],4:[function(a,b){"use strict";function c(){this.data=null,this.length=0,this.index=0}var d=a("./utils");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error("End of data reached (data length = "+this.length+", asked index = "+a+"). Corrupted zip ?")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo("string",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{"./utils":14}],5:[function(a,b,c){"use strict";c.base64=!1,c.binary=!1,c.dir=!1,c.date=null,c.compression=null},{}],6:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,e=a("zlibjs/bin/rawdeflate.min").Zlib,f=a("zlibjs/bin/rawinflate.min").Zlib;c.uncompressInputType=d?"uint8array":"array",c.compressInputType=d?"uint8array":"array",c.magic="\b\x00",c.compress=function(a){var b=new e.RawDeflate(a);return b.compress()},c.uncompress=function(a){var b=new f.RawInflate(a);return b.decompress()}},{"zlibjs/bin/rawdeflate.min":19,"zlibjs/bin/rawinflate.min":20}],7:[function(a,b){"use strict";function c(a,b){return this instanceof c?(this.files={},this.root="",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)"function"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}c.prototype=a("./object"),c.prototype.load=a("./load"),c.support=a("./support"),c.defaults=a("./defaults"),c.utils=a("./utils"),c.base64=a("./base64"),c.compressions=a("./compressions"),b.exports=c},{"./base64":1,"./compressions":3,"./defaults":5,"./load":8,"./object":9,"./support":12,"./utils":14}],8:[function(a,b){"use strict";var c=a("./base64"),d=a("./zipEntries");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},r=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):""},v=function(a){return"/"!=a.slice(-1)&&(a+="/"),this.files[a]||t.call(this,a,null,{dir:!0}),this.files[a]},w=function(a,b){var c,d=new k;return a._data instanceof k?(d.uncompressedSize=a._data.uncompressedSize,d.crc32=a._data.crc32,0===d.uncompressedSize||a.options.dir?(b=j.STORE,d.compressedContent="",d.crc32=0):a._data.compressionMethod===b.magic?d.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),d.compressedContent=b.compress(f.transformTo(b.compressInputType,c)))):(c=n(a),(!c||0===c.length||a.options.dir)&&(b=j.STORE,c=""),d.uncompressedSize=c.length,d.crc32=this.crc32(c),d.compressedContent=b.compress(f.transformTo(b.compressInputType,c))),d.compressedSize=d.compressedContent.length,d.compressionMethod=b.magic,d},x=function(a,b,c,d){var e,f,h=(c.compressedContent,this.utf8encode(b.name)),i=h!==b.name,j=b.options,k="",l="";e=j.date.getHours(),e<<=6,e|=j.date.getMinutes(),e<<=5,e|=j.date.getSeconds()/2,f=j.date.getFullYear()-1980,f<<=4,f|=j.date.getMonth()+1,f<<=5,f|=j.date.getDate(),i&&(l=q(1,1)+q(this.crc32(h),4)+h,k+="up"+q(l.length,2)+l);var m="";m+="\n\x00",m+=i?"\x00\b":"\x00\x00",m+=c.compressionMethod,m+=q(e,2),m+=q(f,2),m+=q(c.crc32,4),m+=q(c.compressedSize,4),m+=q(c.uncompressedSize,4),m+=q(h.length,2),m+=q(k.length,2);var n=g.LOCAL_FILE_HEADER+m+h+k,o=g.CENTRAL_FILE_HEADER+"\x00"+m+"\x00\x00\x00\x00\x00\x00"+(b.options.dir===!0?"\x00\x00\x00":"\x00\x00\x00\x00")+q(d,4)+h+k;return{fileRecord:n,dirRecord:o,compressedObject:c}},y=function(){this.data=[]};y.prototype={append:function(a){a=f.transformTo("string",a),this.data.push(a)},finalize:function(){return this.data.join("")}};var z=function(a){this.data=new Uint8Array(a),this.index=0};z.prototype={append:function(a){0!==a.length&&(a=f.transformTo("uint8array",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}};var A={load:function(){throw new Error("Load method is not defined. Is the file jszip-load.js included ?")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new p(d.name,d._data,r(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(f.isRegExp(a)){var d=a;return this.filter(function(a,b){return!b.options.dir&&d.test(a)})}return this.filter(function(b,c){return!c.options.dir&&b===a})[0]||null}return a=this.root+a,t.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(f.isRegExp(a))return this.filter(function(b,c){return c.options.dir&&a.test(b)});var b=this.root+a,c=v.call(this,b),d=this.clone();return d.root=c.name,d},remove:function(a){a=this.root+a;var b=this.files[a];if(b||("/"!=a.slice(-1)&&(a+="/"),b=this.files[a]),b)if(b.options.dir)for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;di;i++)h=c?a[i]:a.charCodeAt(i),g=255&(b^h),e=d[g],b=b>>>8^e;return-1^b},utf8encode:function(a){if(c){var b=c.encode(a);return f.transformTo("string",b)}if(e.nodebuffer)return f.transformTo("string",l(a,"utf-8"));for(var d=[],g=0,h=0;hi?d[g++]=String.fromCharCode(i):i>127&&2048>i?(d[g++]=String.fromCharCode(i>>6|192),d[g++]=String.fromCharCode(63&i|128)):(d[g++]=String.fromCharCode(i>>12|224),d[g++]=String.fromCharCode(i>>6&63|128),d[g++]=String.fromCharCode(63&i|128))}return d.join("")},utf8decode:function(a){var b=[],c=0,g=f.getTypeOf(a),h="string"!==g,i=0,j=0,k=0,l=0;if(d)return d.decode(f.transformTo("uint8array",a));if(e.nodebuffer)return f.transformTo("nodebuffer",a).toString("utf-8");for(;ij?(b[c++]=String.fromCharCode(j),i++):j>191&&224>j?(k=h?a[i+1]:a.charCodeAt(i+1),b[c++]=String.fromCharCode((31&j)<<6|63&k),i+=2):(k=h?a[i+1]:a.charCodeAt(i+1),l=h?a[i+2]:a.charCodeAt(i+2),b[c++]=String.fromCharCode((15&j)<<12|(63&k)<<6|63&l),i+=3);return b.join("")}};b.exports=A},{"./base64":1,"./compressedObject":2,"./compressions":3,"./defaults":5,"./nodeBuffer":17,"./signature":10,"./support":12,"./utils":14}],10:[function(a,b,c){"use strict";c.LOCAL_FILE_HEADER="PK",c.CENTRAL_FILE_HEADER="PK",c.CENTRAL_DIRECTORY_END="PK",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",c.ZIP64_CENTRAL_DIRECTORY_END="PK",c.DATA_DESCRIPTOR="PK\b"},{}],11:[function(a,b){"use strict";function c(a,b){this.data=a,b||(this.data=e.string2binary(this.data)),this.length=this.data.length,this.index=0}var d=a("./dataReader"),e=a("./utils");c.prototype=new d,c.prototype.byteAt=function(a){return this.data.charCodeAt(a)},c.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":4,"./utils":14}],12:[function(a,b,c){var d=a("__browserify_process");if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,c.nodebuffer=!d.browser,c.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)c.blob=!1;else{var e=new ArrayBuffer(0);try{c.blob=0===new Blob([e],{type:"application/zip"}).size}catch(f){try{var g=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,h=new g;h.append(e),c.blob=0===h.getBlob("application/zip").size}catch(f){c.blob=!1}}}},{__browserify_process:18}],13:[function(a,b){"use strict";function c(a){a&&(this.data=a,this.length=this.data.length,this.index=0)}var d=a("./dataReader");c.prototype=new d,c.prototype.byteAt=function(a){return this.data[a]},c.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{"./dataReader":4}],14:[function(a,b,c){"use strict";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push("array"===f||"nodebuffer"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join("")}function g(a,b){for(var c=0;cb?"0":"")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return"[object RegExp]"===Object.prototype.toString.call(a)}},{"./compressions":3,"./nodeBuffer":17,"./support":12}],15:[function(a,b){"use strict";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a("./stringReader"),e=a("./nodeBufferReader"),f=a("./uint8ArrayReader"),g=a("./utils"),h=a("./signature"),i=a("./zipEntry"),j=a("./support");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error("Corrupted zip or bug : unexpected signature ("+g.pretty(b)+", expected "+g.pretty(a)+")")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var a,b;for(a=0;a0)){var d=c.shift();d()}},!0),function(a){c.push(a),window.postMessage("process-tick","*")}}return function(a){setTimeout(a,0)}}(),c.title="browser",c.browser=!0,c.env={},c.argv=[],c.binding=function(){throw new Error("process.binding is not supported")},c.cwd=function(){return"/"},c.chdir=function(){throw new Error("process.chdir is not supported")}},{}],19:[function(){/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */ +(function(){"use strict";function a(a,b){var c=a.split("."),d=n;!(c[0]in d)&&d.execScript&&d.execScript("var "+c[0]);for(var e;c.length&&(e=c.shift());)c.length||b===l?d=d[e]?d[e]:d[e]={}:d[e]=b}function b(a,b){if(this.index="number"==typeof b?b:0,this.d=0,this.buffer=a instanceof(o?Uint8Array:Array)?a:new(o?Uint8Array:Array)(32768),2*this.buffer.length<=this.index)throw Error("invalid index");this.buffer.length<=this.index&&c(this)}function c(a){var b,c=a.buffer,d=c.length,e=new(o?Uint8Array:Array)(d<<1);if(o)e.set(c);else for(b=0;d>b;++b)e[b]=c[b];return a.buffer=e}function d(a){this.buffer=new(o?Uint16Array:Array)(2*a),this.length=0}function e(a,b){this.e=w,this.f=0,this.input=o&&a instanceof Array?new Uint8Array(a):a,this.c=0,b&&(b.lazy&&(this.f=b.lazy),"number"==typeof b.compressionType&&(this.e=b.compressionType),b.outputBuffer&&(this.b=o&&b.outputBuffer instanceof Array?new Uint8Array(b.outputBuffer):b.outputBuffer),"number"==typeof b.outputIndex&&(this.c=b.outputIndex)),this.b||(this.b=new(o?Uint8Array:Array)(32768))}function f(a,b){this.length=a,this.g=b}function g(a,b){function c(a,b){var c,d=a.g,e=[],f=0;c=z[a.length],e[f++]=65535&c,e[f++]=c>>16&255,e[f++]=c>>24;var g;switch(m){case 1===d:g=[0,d-1,0];break;case 2===d:g=[1,d-2,0];break;case 3===d:g=[2,d-3,0];break;case 4===d:g=[3,d-4,0];break;case 6>=d:g=[4,d-5,1];break;case 8>=d:g=[5,d-7,1];break;case 12>=d:g=[6,d-9,2];break;case 16>=d:g=[7,d-13,2];break;case 24>=d:g=[8,d-17,3];break;case 32>=d:g=[9,d-25,3];break;case 48>=d:g=[10,d-33,4];break;case 64>=d:g=[11,d-49,4];break;case 96>=d:g=[12,d-65,5];break;case 128>=d:g=[13,d-97,5];break;case 192>=d:g=[14,d-129,6];break;case 256>=d:g=[15,d-193,6];break;case 384>=d:g=[16,d-257,7];break;case 512>=d:g=[17,d-385,7];break;case 768>=d:g=[18,d-513,8];break;case 1024>=d:g=[19,d-769,8];break;case 1536>=d:g=[20,d-1025,9];break;case 2048>=d:g=[21,d-1537,9];break;case 3072>=d:g=[22,d-2049,10];break;case 4096>=d:g=[23,d-3073,10];break;case 6144>=d:g=[24,d-4097,11];break;case 8192>=d:g=[25,d-6145,11];break;case 12288>=d:g=[26,d-8193,12];break;case 16384>=d:g=[27,d-12289,12];break;case 24576>=d:g=[28,d-16385,13];break;case 32768>=d:g=[29,d-24577,13];break;default:throw"invalid distance"}c=g,e[f++]=c[0],e[f++]=c[1],e[f++]=c[2];var h,i;for(h=0,i=e.length;i>h;++h)r[s++]=e[h];u[e[0]]++,v[e[3]]++,t=a.length+b-1,n=null}var d,e,f,g,i,j,k,n,p,q={},r=o?new Uint16Array(2*b.length):[],s=0,t=0,u=new(o?Uint32Array:Array)(286),v=new(o?Uint32Array:Array)(30),w=a.f;if(!o){for(f=0;285>=f;)u[f++]=0;for(f=0;29>=f;)v[f++]=0}for(u[256]=1,d=0,e=b.length;e>d;++d){for(f=i=0,g=3;g>f&&d+f!==e;++f)i=i<<8|b[d+f];if(q[i]===l&&(q[i]=[]),j=q[i],!(0=e){for(n&&c(n,-1),f=0,g=e-d;g>f;++f)p=b[d+f],r[s++]=p,++u[p];break}0h;h++){if(d=c[j-h-1],g=3,k>3){for(i=k;i>3;i--)if(a[d+i-1]!==a[b+i-1])continue a;g=k}for(;258>g&&l>b+g&&a[d+g]===a[b+g];)++g;if(g>k&&(e=d,k=g),258===g)break}return new f(k,b-e)}function i(a,b){var c,e,f,g,h,i=a.length,k=new d(572),l=new(o?Uint8Array:Array)(i);if(!o)for(g=0;i>g;g++)l[g]=0;for(g=0;i>g;++g)0g;++g)c[g]=k.pop(),e[g]=c[g].value;for(f=j(e,e.length,b),g=0,h=c.length;h>g;++g)l[c[g].index]=f[g];return l}function j(a,b,c){function d(a){var c=n[a][p[a]];c===b?(d(a+1),d(a+1)):--l[c],++p[a]}var e,f,g,h,i,j=new(o?Uint16Array:Array)(c),k=new(o?Uint8Array:Array)(c),l=new(o?Uint8Array:Array)(b),m=Array(c),n=Array(c),p=Array(c),q=(1<f;++f)r>q?k[f]=0:(k[f]=1,q-=r),q<<=1,j[c-2-f]=(j[c-1-f]/2|0)+b;for(j[0]=k[0],m[0]=Array(j[0]),n[0]=Array(j[0]),f=1;c>f;++f)j[f]>2*j[f-1]+k[f]&&(j[f]=2*j[f-1]+k[f]),m[f]=Array(j[f]),n[f]=Array(j[f]);for(e=0;b>e;++e)l[e]=c;for(g=0;ge;++e)p[e]=0;for(1===k[c-1]&&(--l[0],++p[c-1]),f=c-2;f>=0;--f){for(h=e=0,i=p[f+1],g=0;ga[e]?(m[f][g]=h,n[f][g]=b,i+=2):(m[f][g]=a[e],n[f][g]=e,++e);p[f]=0,1===k[f]&&d(f)}return l}function k(a){var b,c,d,e,f=new(o?Uint16Array:Array)(a.length),g=[],h=[],i=0;for(b=0,c=a.length;c>b;b++)g[a[b]]=(0|g[a[b]])+1;for(b=1,c=16;c>=b;b++)h[b]=i,i+=0|g[b],i<<=1;for(b=0,c=a.length;c>b;b++)for(i=h[a[b]],h[a[b]]+=1,d=f[b]=0,e=a[b];e>d;d++)f[b]=f[b]<<1|1&i,i>>>=1;return f}var l=void 0,m=!0,n=this,o="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array&&"undefined"!=typeof DataView;b.prototype.a=function(a,b,d){var e,f=this.buffer,g=this.index,h=this.d,i=f[g];if(d&&b>1&&(a=b>8?(u[255&a]<<24|u[a>>>8&255]<<16|u[a>>>16&255]<<8|u[a>>>24&255])>>32-b:u[a]>>8-b),8>b+h)i=i<e;++e)i=i<<1|a>>b-e-1&1,8===++h&&(h=0,f[g++]=u[i],i=0,g===f.length&&(f=c(this)));f[g]=i,this.buffer=f,this.d=h,this.index=g},b.prototype.finish=function(){var a,b=this.buffer,c=this.index;return 0p;++p){for(var r=p,s=r,t=7,r=r>>>1;r;r>>>=1)s<<=1,s|=1&r,--t;q[p]=(s<>>0}var u=q;d.prototype.getParent=function(a){return 2*((a-2)/4|0)},d.prototype.push=function(a,b){var c,d,e,f=this.buffer;for(c=this.length,f[this.length++]=b,f[this.length++]=a;c>0&&(d=this.getParent(c),f[c]>f[d]);)e=f[c],f[c]=f[d],f[d]=e,e=f[c+1],f[c+1]=f[d+1],f[d+1]=e,c=d;return this.length},d.prototype.pop=function(){var a,b,c,d,e,f=this.buffer;for(b=f[0],a=f[1],this.length-=2,f[0]=f[this.length],f[1]=f[this.length+1],e=0;(d=2*e+2,!(d>=this.length))&&(d+2f[d]&&(d+=2),f[d]>f[e]);)c=f[e],f[e]=f[d],f[d]=c,c=f[e+1],f[e+1]=f[d+1],f[d+1]=c,e=d;return{index:a,value:b,length:this.length}};var v,w=2,x=[];for(v=0;288>v;v++)switch(m){case 143>=v:x.push([v+48,8]);break;case 255>=v:x.push([v-144+400,9]);break;case 279>=v:x.push([v-256+0,7]);break;case 287>=v:x.push([v-280+192,8]);break;default:throw"invalid literal: "+v}e.prototype.h=function(){var a,c,d,e,f=this.input;switch(this.e){case 0:for(d=0,e=f.length;e>d;){c=o?f.subarray(d,d+65535):f.slice(d,d+65535),d+=c.length;var h=c,j=d===e,n=l,p=l,q=l,r=l,s=l,t=this.b,u=this.c;if(o){for(t=new Uint8Array(this.b.buffer);t.length<=u+h.length+5;)t=new Uint8Array(t.length<<1);t.set(this.b)}if(n=j?1:0,t[u++]=0|n,p=h.length,q=~p+65536&65535,t[u++]=255&p,t[u++]=p>>>8&255,t[u++]=255&q,t[u++]=q>>>8&255,o)t.set(h,u),u+=h.length,t=t.subarray(0,u);else{for(r=0,s=h.length;s>r;++r)t[u++]=h[r];t.length=u}this.c=u,this.b=t}break;case 1:var v=new b(o?new Uint8Array(this.b.buffer):this.b,this.c);v.a(1,1,m),v.a(1,2,m);var y,z,A,B=g(this,f);for(y=0,z=B.length;z>y;y++)if(A=B[y],b.prototype.a.apply(v,x[A]),A>256)v.a(B[++y],B[++y],m),v.a(B[++y],5),v.a(B[++y],B[++y],m);else if(256===A)break;this.b=v.finish(),this.c=this.b.length;break;case w:var C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R=new b(o?new Uint8Array(this.b.buffer):this.b,this.c),S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],T=Array(19);for(C=w,R.a(1,1,m),R.a(C,2,m),D=g(this,f),H=i(this.j,15),I=k(H),J=i(this.i,7),K=k(J),E=286;E>257&&0===H[E-1];E--);for(F=30;F>1&&0===J[F-1];F--);var U,V,W,X,Y,Z,$=E,_=F,ab=new(o?Uint32Array:Array)($+_),bb=new(o?Uint32Array:Array)(316),cb=new(o?Uint8Array:Array)(19);for(U=V=0;$>U;U++)ab[V++]=H[U];for(U=0;_>U;U++)ab[V++]=J[U];if(!o)for(U=0,X=cb.length;X>U;++U)cb[U]=0;for(U=Y=0,X=ab.length;X>U;U+=V){for(V=1;X>U+V&&ab[U+V]===ab[U];++V);if(W=V,0===ab[U])if(3>W)for(;00;)Z=138>W?W:138,Z>W-3&&W>Z&&(Z=W-3),10>=Z?(bb[Y++]=17,bb[Y++]=Z-3,cb[17]++):(bb[Y++]=18,bb[Y++]=Z-11,cb[18]++),W-=Z;else if(bb[Y++]=ab[U],cb[ab[U]]++,W--,3>W)for(;00;)Z=6>W?W:6,Z>W-3&&W>Z&&(Z=W-3),bb[Y++]=16,bb[Y++]=Z-3,cb[16]++,W-=Z}for(a=o?bb.subarray(0,Y):bb.slice(0,Y),L=i(cb,7),P=0;19>P;P++)T[P]=L[S[P]];for(G=19;G>4&&0===T[G-1];G--);for(M=k(L),R.a(E-257,5,m),R.a(F-1,5,m),R.a(G-4,4,m),P=0;G>P;P++)R.a(T[P],3,m);for(P=0,Q=a.length;Q>P;P++)if(N=a[P],R.a(M[N],L[N],m),N>=16){switch(P++,N){case 16:O=2;break;case 17:O=3;break;case 18:O=7;break;default:throw"invalid code: "+N}R.a(a[P],O,m)}var db,eb,fb,gb,hb,ib,jb,kb,lb=[I,H],mb=[K,J];for(hb=lb[0],ib=lb[1],jb=mb[0],kb=mb[1],db=0,eb=D.length;eb>db;++db)if(fb=D[db],R.a(hb[fb],ib[fb],m),fb>256)R.a(D[++db],D[++db],m),gb=D[++db],R.a(jb[gb],kb[gb],m),R.a(D[++db],D[++db],m);else if(256===fb)break;this.b=R.finish(),this.c=this.b.length;break;default:throw"invalid compression type"}return this.b};var y=function(){function a(a){switch(m){case 3===a:return[257,a-3,0];case 4===a:return[258,a-4,0];case 5===a:return[259,a-5,0];case 6===a:return[260,a-6,0];case 7===a:return[261,a-7,0];case 8===a:return[262,a-8,0];case 9===a:return[263,a-9,0];case 10===a:return[264,a-10,0];case 12>=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:throw"invalid length: "+a}}var b,c,d=[];for(b=3;258>=b;b++)c=a(b),d[b]=c[2]<<24|c[1]<<16|c[0];return d}(),z=o?new Uint32Array(y):y;a("Zlib.RawDeflate",e),a("Zlib.RawDeflate.prototype.compress",e.prototype.h);var A,B,C,D,E={NONE:0,FIXED:1,DYNAMIC:w};if(Object.keys)A=Object.keys(E);else for(B in A=[],C=0,E)A[C++]=B;for(C=0,D=A.length;D>C;++C)B=A[C],a("Zlib.RawDeflate.CompressionType."+B,E[B])}).call(this)},{}],20:[function(){/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */ +(function(){"use strict";function a(a,b){var c=a.split("."),d=g;!(c[0]in d)&&d.execScript&&d.execScript("var "+c[0]);for(var e;c.length&&(e=c.shift());)c.length||void 0===b?d=d[e]?d[e]:d[e]={}:d[e]=b}function b(a){var b,c,d,e,f,g,i,j,k,l,m=a.length,n=0,o=Number.POSITIVE_INFINITY;for(j=0;m>j;++j)a[j]>n&&(n=a[j]),a[j]=d;){for(j=0;m>j;++j)if(a[j]===d){for(g=0,i=e,k=0;d>k;++k)g=g<<1|1&i,i>>=1;for(l=d<<16|j,k=g;b>k;k+=f)c[k]=l;++e}++d,e<<=1,f<<=1}return[c,n,o]}function c(a,b){switch(this.g=[],this.h=32768,this.c=this.f=this.d=this.k=0,this.input=h?new Uint8Array(a):a,this.l=!1,this.i=j,this.q=!1,(b||!(b={}))&&(b.index&&(this.d=b.index),b.bufferSize&&(this.h=b.bufferSize),b.bufferType&&(this.i=b.bufferType),b.resize&&(this.q=b.resize)),this.i){case i:this.a=32768,this.b=new(h?Uint8Array:Array)(32768+this.h+258);break;case j:this.a=0,this.b=new(h?Uint8Array:Array)(this.h),this.e=this.v,this.m=this.s,this.j=this.t;break;default:throw Error("invalid inflate mode")}}function d(a,b){for(var c,d=a.f,e=a.c,f=a.input,g=a.d,h=f.length;b>e;){if(g>=h)throw Error("input buffer is broken");d|=f[g++]<>>b,a.c=e-b,a.d=g,c}function e(a,b){for(var c,d,e=a.f,f=a.c,g=a.input,h=a.d,i=g.length,j=b[0],k=b[1];k>f&&!(h>=i);)e|=g[h++]<>>16,a.f=e>>d,a.c=f-d,a.d=h,65535&c}function f(a){function c(a,b,c){var f,g,h,i=this.p;for(h=0;a>h;)switch(f=e(this,b)){case 16:for(g=3+d(this,2);g--;)c[h++]=i;break;case 17:for(g=3+d(this,3);g--;)c[h++]=0;i=0;break;case 18:for(g=11+d(this,7);g--;)c[h++]=0;i=0;break;default:i=c[h++]=f}return this.p=i,c}var f,g,i,j,k=d(a,5)+257,l=d(a,5)+1,m=d(a,4)+4,o=new(h?Uint8Array:Array)(n.length);for(j=0;m>j;++j)o[n[j]]=d(a,3);if(!h)for(j=m,m=o.length;m>j;++j)o[n[j]]=0;f=b(o),g=new(h?Uint8Array:Array)(k),i=new(h?Uint8Array:Array)(l),a.p=0,a.j(b(c.call(a,k,f,g)),b(c.call(a,l,f,i)))}var g=this,h="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array&&"undefined"!=typeof DataView,i=0,j=1;c.prototype.u=function(){for(;!this.l;){var a=d(this,3);switch(1&a&&(this.l=!0),a>>>=1){case 0:var b=this.input,c=this.d,e=this.b,g=this.a,k=b.length,l=void 0,m=void 0,n=e.length,o=void 0;if(this.c=this.f=0,c+1>=k)throw Error("invalid uncompressed block header: LEN");if(l=b[c++]|b[c++]<<8,c+1>=k)throw Error("invalid uncompressed block header: NLEN");if(m=b[c++]|b[c++]<<8,l===~m)throw Error("invalid uncompressed block header: length verify");if(c+l>b.length)throw Error("input buffer is broken");switch(this.i){case i:for(;g+l>e.length;){if(o=n-g,l-=o,h)e.set(b.subarray(c,c+o),g),g+=o,c+=o;else for(;o--;)e[g++]=b[c++];this.a=g,e=this.e(),g=this.a}break;case j:for(;g+l>e.length;)e=this.e({o:2});break;default:throw Error("invalid inflate mode")}if(h)e.set(b.subarray(c,c+l),g),g+=l,c+=l;else for(;l--;)e[g++]=b[c++];this.d=c,this.a=g,this.b=e;break;case 1:this.j(z,B);break;case 2:f(this);break;default:throw Error("unknown BTYPE: "+a)}}return this.m()};var k,l,m=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],n=h?new Uint16Array(m):m,o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],p=h?new Uint16Array(o):o,q=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],r=h?new Uint8Array(q):q,s=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],t=h?new Uint16Array(s):s,u=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],v=h?new Uint8Array(u):u,w=new(h?Uint8Array:Array)(288);for(k=0,l=w.length;l>k;++k)w[k]=143>=k?8:255>=k?9:279>=k?7:8;var x,y,z=b(w),A=new(h?Uint8Array:Array)(30);for(x=0,y=A.length;y>x;++x)A[x]=5;var B=b(A);c.prototype.j=function(a,b){var c=this.b,f=this.a;this.n=a;for(var g,h,i,j,k=c.length-258;256!==(g=e(this,a));)if(256>g)f>=k&&(this.a=f,c=this.e(),f=this.a),c[f++]=g;else for(h=g-257,j=p[h],0=k&&(this.a=f,c=this.e(),f=this.a);j--;)c[f]=c[f++-i];for(;8<=this.c;)this.c-=8,this.d--;this.a=f},c.prototype.t=function(a,b){var c=this.b,f=this.a;this.n=a;for(var g,h,i,j,k=c.length;256!==(g=e(this,a));)if(256>g)f>=k&&(c=this.e(),k=c.length),c[f++]=g;else for(h=g-257,j=p[h],0k&&(c=this.e(),k=c.length);j--;)c[f]=c[f++-i];for(;8<=this.c;)this.c-=8,this.d--;this.a=f},c.prototype.e=function(){var a,b,c=new(h?Uint8Array:Array)(this.a-32768),d=this.a-32768,e=this.b;if(h)c.set(e.subarray(32768,c.length));else for(a=0,b=c.length;b>a;++a)c[a]=e[a+32768];if(this.g.push(c),this.k+=c.length,h)e.set(e.subarray(d,d+32768));else for(a=0;32768>a;++a)e[a]=e[d+a];return this.a=32768,e},c.prototype.v=function(a){var b,c,d,e,f=this.input.length/this.d+1|0,g=this.input,i=this.b;return a&&("number"==typeof a.o&&(f=a.o),"number"==typeof a.r&&(f+=a.r)),2>f?(c=(g.length-this.d)/this.n[2],e=258*(c/2)|0,d=eb;++b)for(a=i[b],d=0,e=a.length;e>d;++d)j[f++]=a[d];for(b=32768,c=this.a;c>b;++b)j[f++]=g[b];return this.g=[],this.buffer=j},c.prototype.s=function(){var a,b=this.a;return h?this.q?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b),this.buffer=a},a("Zlib.RawInflate",c),a("Zlib.RawInflate.prototype.decompress",c.prototype.u);var C,D,E,F,G={ADAPTIVE:j,BLOCK:i};if(Object.keys)C=Object.keys(G);else for(D in C=[],E=0,G)C[E++]=D;for(E=0,F=C.length;F>E;++E)D=C[E],a("Zlib.RawInflate.BufferType."+D,G[D])}).call(this)},{}]},{},[7])(7)});;// Spectrum Colorpicker v1.1.2 +// https://github.com/bgrins/spectrum +// Author: Brian Grinstead +// License: MIT + +(function (window, $, undefined) { + var defaultOpts = { + + // Callbacks + beforeShow: noop, + move: noop, + change: noop, + show: noop, + hide: noop, + + // Options + color: false, + flat: false, + showInput: false, + showButtons: true, + clickoutFiresChange: false, + showInitial: false, + showPalette: false, + showPaletteOnly: false, + showSelectionPalette: true, + localStorageKey: false, + appendTo: "body", + maxSelectionSize: 7, + cancelText: "cancel", + chooseText: "choose", + preferredFormat: false, + className: "", + showAlpha: false, + theme: "sp-light", + palette: ['fff', '000'], + selectionPalette: [], + disabled: false + }, + spectrums = [], + IE = !!/msie/i.exec( window.navigator.userAgent ), + rgbaSupport = (function() { + function contains( str, substr ) { + return !!~('' + str).indexOf(substr); + } + + var elem = document.createElement('div'); + var style = elem.style; + style.cssText = 'background-color:rgba(0,0,0,.5)'; + return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla'); + })(), + replaceInput = [ + "
        ", + "
        ", + "
        ", + "
        " + ].join(''), + markup = (function () { + + // IE does not support gradients with multiple stops, so we need to simulate + // that for the rainbow slider with 8 divs that each have a single gradient + var gradientFix = ""; + if (IE) { + for (var i = 1; i <= 6; i++) { + gradientFix += "
        "; + } + } + + return [ + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + gradientFix, + "
        ", + "
        ", + "
        ", + "
        ", + "
        ", + "", + "
        ", + "
        ", + "
        ", + "", + "", + "
        ", + "
        ", + "
        " + ].join(""); + })(); + + function paletteTemplate (p, color, className) { + var html = []; + for (var i = 0; i < p.length; i++) { + var tiny = tinycolor(p[i]); + var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light"; + c += (tinycolor.equals(color, p[i])) ? " sp-thumb-active" : ""; + + var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter(); + html.push(''); + } + return "
        " + html.join('') + "
        "; + } + + function hideAll() { + for (var i = 0; i < spectrums.length; i++) { + if (spectrums[i]) { + spectrums[i].hide(); + } + } + } + + function instanceOptions(o, callbackContext) { + var opts = $.extend({}, defaultOpts, o); + opts.callbacks = { + 'move': bind(opts.move, callbackContext), + 'change': bind(opts.change, callbackContext), + 'show': bind(opts.show, callbackContext), + 'hide': bind(opts.hide, callbackContext), + 'beforeShow': bind(opts.beforeShow, callbackContext) + }; + + return opts; + } + + function spectrum(element, o) { + + var opts = instanceOptions(o, element), + flat = opts.flat, + showSelectionPalette = opts.showSelectionPalette, + localStorageKey = opts.localStorageKey, + theme = opts.theme, + callbacks = opts.callbacks, + resize = throttle(reflow, 10), + visible = false, + dragWidth = 0, + dragHeight = 0, + dragHelperHeight = 0, + slideHeight = 0, + slideWidth = 0, + alphaWidth = 0, + alphaSlideHelperWidth = 0, + slideHelperHeight = 0, + currentHue = 0, + currentSaturation = 0, + currentValue = 0, + currentAlpha = 1, + palette = opts.palette.slice(0), + paletteArray = $.isArray(palette[0]) ? palette : [palette], + selectionPalette = opts.selectionPalette.slice(0), + maxSelectionSize = opts.maxSelectionSize, + draggingClass = "sp-dragging", + shiftMovementDirection = null; + + var doc = element.ownerDocument, + body = doc.body, + boundElement = $(element), + disabled = false, + container = $(markup, doc).addClass(theme), + dragger = container.find(".sp-color"), + dragHelper = container.find(".sp-dragger"), + slider = container.find(".sp-hue"), + slideHelper = container.find(".sp-slider"), + alphaSliderInner = container.find(".sp-alpha-inner"), + alphaSlider = container.find(".sp-alpha"), + alphaSlideHelper = container.find(".sp-alpha-handle"), + textInput = container.find(".sp-input"), + paletteContainer = container.find(".sp-palette"), + initialColorContainer = container.find(".sp-initial"), + cancelButton = container.find(".sp-cancel"), + chooseButton = container.find(".sp-choose"), + isInput = boundElement.is("input"), + shouldReplace = isInput && !flat, + replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className) : $([]), + offsetElement = (shouldReplace) ? replacer : boundElement, + previewElement = replacer.find(".sp-preview-inner"), + initialColor = opts.color || (isInput && boundElement.val()), + colorOnShow = false, + preferredFormat = opts.preferredFormat, + currentPreferredFormat = preferredFormat, + clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange; + + + function applyOptions() { + + if (opts.showPaletteOnly) { + opts.showPalette = true; + } + + container.toggleClass("sp-flat", flat); + container.toggleClass("sp-input-disabled", !opts.showInput); + container.toggleClass("sp-alpha-enabled", opts.showAlpha); + container.toggleClass("sp-buttons-disabled", !opts.showButtons); + container.toggleClass("sp-palette-disabled", !opts.showPalette); + container.toggleClass("sp-palette-only", opts.showPaletteOnly); + container.toggleClass("sp-initial-disabled", !opts.showInitial); + container.addClass(opts.className); + + reflow(); + } + + function initialize() { + + if (IE) { + container.find("*:not(input)").attr("unselectable", "on"); + } + + applyOptions(); + + if (shouldReplace) { + boundElement.after(replacer).hide(); + } + + if (flat) { + boundElement.after(container).hide(); + } + else { + + var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo); + if (appendTo.length !== 1) { + appendTo = $("body"); + } + + appendTo.append(container); + } + + if (localStorageKey && window.localStorage) { + + // Migrate old palettes over to new format. May want to remove this eventually. + try { + var oldPalette = window.localStorage[localStorageKey].split(",#"); + if (oldPalette.length > 1) { + delete window.localStorage[localStorageKey]; + $.each(oldPalette, function(i, c) { + addColorToSelectionPalette(c); + }); + } + } + catch(e) { } + + try { + selectionPalette = window.localStorage[localStorageKey].split(";"); + } + catch (e) { } + } + + offsetElement.bind("click.spectrum touchstart.spectrum", function (e) { + if (!disabled) { + toggle(); + } + + e.stopPropagation(); + + if (!$(e.target).is("input")) { + e.preventDefault(); + } + }); + + if(boundElement.is(":disabled") || (opts.disabled === true)) { + disable(); + } + + // Prevent clicks from bubbling up to document. This would cause it to be hidden. + container.click(stopPropagation); + + // Handle user typed input + textInput.change(setFromTextInput); + textInput.bind("paste", function () { + setTimeout(setFromTextInput, 1); + }); + textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } }); + + cancelButton.text(opts.cancelText); + cancelButton.bind("click.spectrum", function (e) { + e.stopPropagation(); + e.preventDefault(); + hide("cancel"); + }); + + chooseButton.text(opts.chooseText); + chooseButton.bind("click.spectrum", function (e) { + e.stopPropagation(); + e.preventDefault(); + + if (isValid()) { + updateOriginalInput(true); + hide(); + } + }); + + draggable(alphaSlider, function (dragX, dragY, e) { + currentAlpha = (dragX / alphaWidth); + if (e.shiftKey) { + currentAlpha = Math.round(currentAlpha * 10) / 10; + } + + move(); + }); + + draggable(slider, function (dragX, dragY) { + currentHue = parseFloat(dragY / slideHeight); + move(); + }, dragStart, dragStop); + + draggable(dragger, function (dragX, dragY, e) { + + // shift+drag should snap the movement to either the x or y axis. + if (!e.shiftKey) { + shiftMovementDirection = null; + } + else if (!shiftMovementDirection) { + var oldDragX = currentSaturation * dragWidth; + var oldDragY = dragHeight - (currentValue * dragHeight); + var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY); + + shiftMovementDirection = furtherFromX ? "x" : "y"; + } + + var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x"; + var setValue = !shiftMovementDirection || shiftMovementDirection === "y"; + + if (setSaturation) { + currentSaturation = parseFloat(dragX / dragWidth); + } + if (setValue) { + currentValue = parseFloat((dragHeight - dragY) / dragHeight); + } + + move(); + + }, dragStart, dragStop); + + if (!!initialColor) { + set(initialColor); + + // In case color was black - update the preview UI and set the format + // since the set function will not run (default color is black). + updateUI(); + currentPreferredFormat = preferredFormat || tinycolor(initialColor).format; + + addColorToSelectionPalette(initialColor); + } + else { + updateUI(); + } + + if (flat) { + show(); + } + + function palletElementClick(e) { + if (e.data && e.data.ignore) { + set($(this).data("color")); + move(); + } + else { + set($(this).data("color")); + updateOriginalInput(true); + move(); + hide(); + } + + return false; + } + + var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum"; + paletteContainer.delegate(".sp-thumb-el", paletteEvent, palletElementClick); + initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, palletElementClick); + } + + function addColorToSelectionPalette(color) { + if (showSelectionPalette) { + var colorRgb = tinycolor(color).toRgbString(); + if ($.inArray(colorRgb, selectionPalette) === -1) { + selectionPalette.push(colorRgb); + while(selectionPalette.length > maxSelectionSize) { + selectionPalette.shift(); + } + } + + if (localStorageKey && window.localStorage) { + try { + window.localStorage[localStorageKey] = selectionPalette.join(";"); + } + catch(e) { } + } + } + } + + function getUniqueSelectionPalette() { + var unique = []; + var p = selectionPalette; + var paletteLookup = {}; + var rgb; + + if (opts.showPalette) { + + for (var i = 0; i < paletteArray.length; i++) { + for (var j = 0; j < paletteArray[i].length; j++) { + rgb = tinycolor(paletteArray[i][j]).toRgbString(); + paletteLookup[rgb] = true; + } + } + + for (i = 0; i < p.length; i++) { + rgb = tinycolor(p[i]).toRgbString(); + + if (!paletteLookup.hasOwnProperty(rgb)) { + unique.push(p[i]); + paletteLookup[rgb] = true; + } + } + } + + return unique.reverse().slice(0, opts.maxSelectionSize); + } + + function drawPalette() { + + var currentColor = get(); + + var html = $.map(paletteArray, function (palette, i) { + return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i); + }); + + if (selectionPalette) { + html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection")); + } + + paletteContainer.html(html.join("")); + } + + function drawInitial() { + if (opts.showInitial) { + var initial = colorOnShow; + var current = get(); + initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial")); + } + } + + function dragStart() { + if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) { + reflow(); + } + container.addClass(draggingClass); + shiftMovementDirection = null; + } + + function dragStop() { + container.removeClass(draggingClass); + } + + function setFromTextInput() { + var tiny = tinycolor(textInput.val()); + if (tiny.ok) { + set(tiny); + } + else { + textInput.addClass("sp-validation-error"); + } + } + + function toggle() { + if (visible) { + hide(); + } + else { + show(); + } + } + + function show() { + var event = $.Event('beforeShow.spectrum'); + + if (visible) { + reflow(); + return; + } + + colorOnShow = get(); + boundElement.trigger(event, [ colorOnShow ]); + + if (callbacks.beforeShow(colorOnShow) === false || event.isDefaultPrevented()) { + return; + } + + // if color has changed + set(colorOnShow); + + hideAll(); + visible = true; + + $(doc).bind("mousedown.spectrum", onMousedown); + + if (!flat) { + // Piskel-specific : change the color as soon as the user does a mouseup + $(doc).bind("mouseup.spectrum", updateColor); + } + + $(window).bind("resize.spectrum", resize); + replacer.addClass("sp-active"); + container.removeClass("sp-hidden"); + + if (opts.showPalette) { + drawPalette(); + } + reflow(); + updateUI(); + + drawInitial(); + callbacks.show(colorOnShow); + boundElement.trigger('show.spectrum', [ colorOnShow ]); + } + + function onMousedown (e) { + var target = $(e.target); + var parents = target.parents(); + var isClickOutsideWidget = !parents.is(container) && !target.is(container); + + if (isClickOutsideWidget) { + hide(e); + } + } + + // Piskel-specific (code extracted to method) + function updateColor(e) { + var colorHasChanged = !tinycolor.equals(get(), colorOnShow); + + if (colorHasChanged) { + if (clickoutFiresChange && e !== "cancel") { + updateOriginalInput(true); + } + else { + revert(); + } + } + } + + function hide(e) { + + // Return on right click + if (e && e.type == "click" && e.button == 2) { return; } + + // Return if hiding is unnecessary + if (!visible || flat) { return; } + visible = false; + + $(doc).unbind("mousedown.spectrum", onMousedown); + + // Piskel-specific + $(doc).unbind("mouseup.spectrum", updateColor); + + $(window).unbind("resize.spectrum", resize); + + replacer.removeClass("sp-active"); + container.addClass("sp-hidden"); + + updateColor(e); + + // Piskel-specific + addColorToSelectionPalette(get()); + + callbacks.hide(get()); + boundElement.trigger('hide.spectrum', [ get() ]); + } + + function revert() { + set(colorOnShow, true); + } + + function set(color, ignoreFormatChange) { + if (tinycolor.equals(color, get())) { + return; + } + + var newColor = tinycolor(color); + var newHsv = newColor.toHsv(); + + currentHue = (newHsv.h % 360) / 360; + currentSaturation = newHsv.s; + currentValue = newHsv.v; + currentAlpha = newHsv.a; + + updateUI(); + + if (newColor.ok && !ignoreFormatChange) { + currentPreferredFormat = preferredFormat || newColor.format; + } + } + + function get(opts) { + opts = opts || { }; + return tinycolor.fromRatio({ + h: currentHue, + s: currentSaturation, + v: currentValue, + a: Math.round(currentAlpha * 100) / 100 + }, { format: opts.format || currentPreferredFormat }); + } + + function isValid() { + return !textInput.hasClass("sp-validation-error"); + } + + function move() { + updateUI(); + + callbacks.move(get()); + boundElement.trigger('move.spectrum', [ get() ]); + } + + function updateUI() { + + textInput.removeClass("sp-validation-error"); + + updateHelperLocations(); + + // Update dragger background color (gradients take care of saturation and value). + var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 }); + dragger.css("background-color", flatColor.toHexString()); + + // Get a format that alpha will be included in (hex and names ignore alpha) + var format = currentPreferredFormat; + if (currentAlpha < 1) { + if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") { + format = "rgb"; + } + } + + var realColor = get({ format: format }), + realHex = realColor.toHexString(), + realRgb = realColor.toRgbString(); + + // Update the replaced elements background color (with actual selected color) + if (rgbaSupport || realColor.alpha === 1) { + previewElement.css("background-color", realRgb); + } + else { + previewElement.css("background-color", "transparent"); + previewElement.css("filter", realColor.toFilter()); + } + + if (opts.showAlpha) { + var rgb = realColor.toRgb(); + rgb.a = 0; + var realAlpha = tinycolor(rgb).toRgbString(); + var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")"; + + if (IE) { + alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex)); + } + else { + alphaSliderInner.css("background", "-webkit-" + gradient); + alphaSliderInner.css("background", "-moz-" + gradient); + alphaSliderInner.css("background", "-ms-" + gradient); + alphaSliderInner.css("background", gradient); + } + } + + // Update the text entry input as it changes happen + if (opts.showInput) { + var displayFormat = pskl.UserSettings.get(pskl.UserSettings.COLOR_FORMAT); + textInput.val(realColor.toString(displayFormat)); + } + + if (opts.showPalette) { + drawPalette(); + } + + drawInitial(); + } + + function updateHelperLocations() { + var s = currentSaturation; + var v = currentValue; + + // Where to show the little circle in that displays your current selected color + var dragX = s * dragWidth; + var dragY = (dragHeight) - (v * dragHeight); + dragX = Math.max( + -dragHelperHeight/2, + Math.min(dragWidth - dragHelperHeight/2, dragX - dragHelperHeight/2) + ); + dragY = Math.max( + -dragHelperHeight/2, + Math.min(dragHeight - dragHelperHeight/2, dragY - dragHelperHeight/2) + ); + dragHelper.css({ + "top": dragY, + "left": dragX + }); + + var alphaX = currentAlpha * alphaWidth; + alphaSlideHelper.css({ + "left": alphaX - (alphaSlideHelperWidth / 2) + }); + + // Where to show the bar that displays your current selected hue + var slideY = (currentHue) * slideHeight; + slideHelper.css({ + "top": slideY - (slideHelperHeight/2) + }); + } + + function updateOriginalInput(fireCallback) { + var color = get(); + + if (isInput) { + boundElement.val(color.toString(currentPreferredFormat)); + } + + var hasChanged = !tinycolor.equals(color, colorOnShow); + colorOnShow = color; + + // Update the selection palette with the current color + + // Piskel-specific : commented-out, palette update is done on hide + // addColorToSelectionPalette(color); + + if (fireCallback && hasChanged) { + callbacks.change(color); + boundElement.trigger('change', [ color ]); + } + } + + function reflow() { + dragWidth = dragger.width(); + dragHeight = dragger.height(); + dragHelperHeight = dragHelper.height() + 4; + slideWidth = slider.width(); + slideHeight = slider.height(); + slideHelperHeight = slideHelper.height() + 4; + alphaWidth = alphaSlider.width(); + alphaSlideHelperWidth = alphaSlideHelper.width(); + + if (!flat) { + container.css("position", "absolute"); + container.offset(getOffset(container, offsetElement)); + } + + updateHelperLocations(); + } + + function destroy() { + boundElement.show(); + offsetElement.unbind("click.spectrum touchstart.spectrum"); + container.remove(); + replacer.remove(); + spectrums[spect.id] = null; + } + + function option(optionName, optionValue) { + if (optionName === undefined) { + return $.extend({}, opts); + } + if (optionValue === undefined) { + return opts[optionName]; + } + + opts[optionName] = optionValue; + applyOptions(); + } + + function enable() { + disabled = false; + boundElement.attr("disabled", false); + offsetElement.removeClass("sp-disabled"); + } + + function disable() { + hide(); + disabled = true; + boundElement.attr("disabled", true); + offsetElement.addClass("sp-disabled"); + } + + initialize(); + + var spect = { + show: show, + hide: hide, + toggle: toggle, + reflow: reflow, + option: option, + enable: enable, + disable: disable, + set: function (c) { + set(c); + updateOriginalInput(); + }, + get: get, + destroy: destroy, + container: container + }; + + spect.id = spectrums.push(spect) - 1; + + return spect; + } + + /** + * checkOffset - get the offset below/above and left/right element depending on screen position + * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js + */ + function getOffset(picker, input) { + var extraY = 0; + var dpWidth = picker.outerWidth(); + var dpHeight = picker.outerHeight(); + var inputHeight = input.outerHeight(); + var doc = picker[0].ownerDocument; + var docElem = doc.documentElement; + var viewWidth = docElem.clientWidth + $(doc).scrollLeft(); + var viewHeight = docElem.clientHeight + $(doc).scrollTop(); + var offset = input.offset(); + offset.top += inputHeight; + + if (Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth))) { + offset.left -= Math.abs(offset.left + dpWidth - viewWidth); + picker.attr('data-x-position','right'); + } else { + offset.left -= 0; + picker.attr('data-x-position','left'); + } + + if (Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight))) { + offset.top -= Math.abs(dpHeight + inputHeight - extraY); + picker.attr('data-y-position','top'); + } else { + offset.top -= extraY; + picker.attr('data-y-position','bottom'); + } + + return offset; + } + + /** + * noop - do nothing + */ + function noop() { + + } + + /** + * stopPropagation - makes the code only doing this a little easier to read in line + */ + function stopPropagation(e) { + e.stopPropagation(); + } + + /** + * Create a function bound to a given object + * Thanks to underscore.js + */ + function bind(func, obj) { + var slice = Array.prototype.slice; + var args = slice.call(arguments, 2); + return function () { + return func.apply(obj, args.concat(slice.call(arguments))); + }; + } + + /** + * Lightweight drag helper. Handles containment within the element, so that + * when dragging, the x is within [0,element.width] and y is within [0,element.height] + */ + function draggable(element, onmove, onstart, onstop) { + onmove = onmove || function () { }; + onstart = onstart || function () { }; + onstop = onstop || function () { }; + var doc = element.ownerDocument || document; + var dragging = false; + var offset = {}; + var maxHeight = 0; + var maxWidth = 0; + var hasTouch = ('ontouchstart' in window); + + var duringDragEvents = {}; + duringDragEvents["selectstart"] = prevent; + duringDragEvents["dragstart"] = prevent; + duringDragEvents["touchmove mousemove"] = move; + duringDragEvents["touchend mouseup"] = stop; + + function prevent(e) { + if (e.stopPropagation) { + e.stopPropagation(); + } + if (e.preventDefault) { + e.preventDefault(); + } + e.returnValue = false; + } + + function move(e) { + if (dragging) { + // Mouseup happened outside of window + if (IE && document.documentMode < 9 && !e.button) { + return stop(); + } + + var touches = e.originalEvent.touches; + var pageX = touches ? touches[0].pageX : e.pageX; + var pageY = touches ? touches[0].pageY : e.pageY; + + var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth)); + var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight)); + + if (hasTouch) { + // Stop scrolling in iOS + prevent(e); + } + + onmove.apply(element, [dragX, dragY, e]); + } + } + function start(e) { + var rightclick = (e.which) ? (e.which == 3) : (e.button == 2); + var touches = e.originalEvent.touches; + + if (!rightclick && !dragging) { + if (onstart.apply(element, arguments) !== false) { + dragging = true; + maxHeight = $(element).height(); + maxWidth = $(element).width(); + offset = $(element).offset(); + + $(doc).bind(duringDragEvents); + $(doc.body).addClass("sp-dragging"); + + if (!hasTouch) { + move(e); + } + + prevent(e); + } + } + } + function stop() { + if (dragging) { + $(doc).unbind(duringDragEvents); + $(doc.body).removeClass("sp-dragging"); + onstop.apply(element, arguments); + } + dragging = false; + } + + $(element).bind("touchstart mousedown", start); + } + + function throttle(func, wait, debounce) { + var timeout; + return function () { + var context = this, args = arguments; + var throttler = function () { + timeout = null; + func.apply(context, args); + }; + if (debounce) clearTimeout(timeout); + if (debounce || !timeout) timeout = setTimeout(throttler, wait); + }; + } + + + function log(){/* jshint -W021 */if(window.console){if(Function.prototype.bind)log=Function.prototype.bind.call(console.log,console);else log=function(){Function.prototype.apply.call(console.log,console,arguments);};log.apply(this,arguments);}} + + /** + * Define a jQuery plugin + */ + var dataID = "spectrum.id"; + $.fn.spectrum = function (opts, extra) { + + if (typeof opts == "string") { + + var returnValue = this; + var args = Array.prototype.slice.call( arguments, 1 ); + + this.each(function () { + var spect = spectrums[$(this).data(dataID)]; + if (spect) { + + var method = spect[opts]; + if (!method) { + throw new Error( "Spectrum: no such method: '" + opts + "'" ); + } + + if (opts == "get") { + returnValue = spect.get(); + } + else if (opts == "container") { + returnValue = spect.container; + } + else if (opts == "option") { + returnValue = spect.option.apply(spect, args); + } + else if (opts == "destroy") { + spect.destroy(); + $(this).removeData(dataID); + } + else { + method.apply(spect, args); + } + } + }); + + return returnValue; + } + + // Initializing a new instance of spectrum + return this.spectrum("destroy").each(function () { + var spect = spectrum(this, opts); + $(this).data(dataID, spect.id); + }); + }; + + $.fn.spectrum.load = true; + $.fn.spectrum.loadOpts = {}; + $.fn.spectrum.draggable = draggable; + $.fn.spectrum.defaults = defaultOpts; + + $.spectrum = { }; + $.spectrum.localization = { }; + $.spectrum.palettes = { }; + + $.fn.spectrum.processNativeColorInputs = function () { + var colorInput = $("")[0]; + var supportsColor = colorInput.type === "color" && colorInput.value != "!"; + + if (!supportsColor) { + $("input[type=color]").spectrum({ + preferredFormat: "hex6" + }); + } + }; + + // TinyColor v0.9.16 + // https://github.com/bgrins/TinyColor + // 2013-08-10, Brian Grinstead, MIT License + + (function() { + + var trimLeft = /^[\s,#]+/, + trimRight = /\s+$/, + tinyCounter = 0, + math = Math, + mathRound = math.round, + mathMin = math.min, + mathMax = math.max, + mathRandom = math.random; + + function tinycolor (color, opts) { + + color = (color) ? color : ''; + opts = opts || { }; + + // If input is already a tinycolor, return itself + if (typeof color == "object" && color.hasOwnProperty("_tc_id")) { + return color; + } + + var rgb = inputToRGB(color); + var r = rgb.r, + g = rgb.g, + b = rgb.b, + a = rgb.a, + roundA = mathRound(100*a) / 100, + format = opts.format || rgb.format; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (r < 1) { r = mathRound(r); } + if (g < 1) { g = mathRound(g); } + if (b < 1) { b = mathRound(b); } + + return { + ok: rgb.ok, + format: format, + _tc_id: tinyCounter++, + alpha: a, + getAlpha: function() { + return a; + }, + setAlpha: function(value) { + a = boundAlpha(value); + roundA = mathRound(100*a) / 100; + }, + toHsv: function() { + var hsv = rgbToHsv(r, g, b); + return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: a }; + }, + toHsvString: function() { + var hsv = rgbToHsv(r, g, b); + var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); + return (a == 1) ? + "hsv(" + h + ", " + s + "%, " + v + "%)" : + "hsva(" + h + ", " + s + "%, " + v + "%, "+ roundA + ")"; + }, + toHsl: function() { + var hsl = rgbToHsl(r, g, b); + return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: a }; + }, + toHslString: function() { + var hsl = rgbToHsl(r, g, b); + var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); + return (a == 1) ? + "hsl(" + h + ", " + s + "%, " + l + "%)" : + "hsla(" + h + ", " + s + "%, " + l + "%, "+ roundA + ")"; + }, + toHex: function(allow3Char) { + return rgbToHex(r, g, b, allow3Char); + }, + toHexString: function(allow3Char) { + return '#' + rgbToHex(r, g, b, allow3Char); + }, + toRgb: function() { + return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a }; + }, + toRgbString: function() { + return (a == 1) ? + "rgb(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ")" : + "rgba(" + mathRound(r) + ", " + mathRound(g) + ", " + mathRound(b) + ", " + roundA + ")"; + }, + toPercentageRgb: function() { + return { r: mathRound(bound01(r, 255) * 100) + "%", g: mathRound(bound01(g, 255) * 100) + "%", b: mathRound(bound01(b, 255) * 100) + "%", a: a }; + }, + toPercentageRgbString: function() { + return (a == 1) ? + "rgb(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%)" : + "rgba(" + mathRound(bound01(r, 255) * 100) + "%, " + mathRound(bound01(g, 255) * 100) + "%, " + mathRound(bound01(b, 255) * 100) + "%, " + roundA + ")"; + }, + toName: function() { + if (a === 0) { + return "transparent"; + } + + return hexNames[rgbToHex(r, g, b, true)] || false; + }, + toFilter: function(secondColor) { + var hex = rgbToHex(r, g, b); + var secondHex = hex; + var alphaHex = Math.round(parseFloat(a) * 255).toString(16); + var secondAlphaHex = alphaHex; + var gradientType = opts && opts.gradientType ? "GradientType = 1, " : ""; + + if (secondColor) { + var s = tinycolor(secondColor); + secondHex = s.toHex(); + secondAlphaHex = Math.round(parseFloat(s.alpha) * 255).toString(16); + } + + return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr=#" + pad2(alphaHex) + hex + ",endColorstr=#" + pad2(secondAlphaHex) + secondHex + ")"; + }, + toString: function(format) { + var formatSet = !!format; + format = format || this.format; + + var formattedString = false; + var hasAlphaAndFormatNotSet = !formatSet && a < 1 && a > 0; + var formatWithAlpha = hasAlphaAndFormatNotSet && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); + + if (format === "rgb") { + formattedString = this.toRgbString(); + } + if (format === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format === "hex" || format === "hex6") { + formattedString = this.toHexString(); + } + if (format === "hex3") { + formattedString = this.toHexString(true); + } + if (format === "name") { + formattedString = this.toName(); + } + if (format === "hsl") { + formattedString = this.toHslString(); + } + if (format === "hsv") { + formattedString = this.toHsvString(); + } + + if (formatWithAlpha) { + return this.toRgbString(); + } + + return formattedString || this.toHexString(); + } + }; + } + + // If input is an object, force 1 into "1.0" to handle ratios properly + // String input requires "1.0" as input, so 1 will be treated as 1 + tinycolor.fromRatio = function(color, opts) { + if (typeof color == "object") { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color[i]; + } + else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; + } + + return tinycolor(color, opts); + }; + + // Given a string or object, convert that input to RGB + // Possible string inputs: + // + // "red" + // "#f00" or "f00" + // "#ff0000" or "ff0000" + // "rgb 255 0 0" or "rgb (255, 0, 0)" + // "rgb 1.0 0 0" or "rgb (1, 0, 0)" + // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" + // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" + // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" + // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" + // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" + // + function inputToRGB(color) { + + var rgb = { r: 0, g: 0, b: 0 }; + var a = 1; + var ok = false; + var format = false; + + if (typeof color == "string") { + color = stringInputToObject(color); + } + + if (typeof color == "object") { + if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { + color.s = convertToPercentage(color.s); + color.v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, color.s, color.v); + ok = true; + format = "hsv"; + } + else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { + color.s = convertToPercentage(color.s); + color.l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, color.s, color.l); + ok = true; + format = "hsl"; + } + + if (color.hasOwnProperty("a")) { + a = color.a; + } + } + + a = boundAlpha(a); + + return { + ok: ok, + format: color.format || format, + r: mathMin(255, mathMax(rgb.r, 0)), + g: mathMin(255, mathMax(rgb.g, 0)), + b: mathMin(255, mathMax(rgb.b, 0)), + a: a + }; + } + + + // Conversion Functions + // -------------------- + + // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: + // + + // `rgbToRgb` + // Handle bounds / percentage checking to conform to CSS color spec + // + // *Assumes:* r, g, b in [0, 255] or [0, 1] + // *Returns:* { r, g, b } in [0, 255] + function rgbToRgb(r, g, b){ + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + + // `rgbToHsl` + // Converts an RGB color value to HSL. + // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] + // *Returns:* { h, s, l } in [0,1] + function rgbToHsl(r, g, b) { + + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, l = (max + min) / 2; + + if(max == min) { + h = s = 0; // achromatic + } + else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + + h /= 6; + } + + return { h: h, s: s, l: l }; + } + + // `hslToRgb` + // Converts an HSL color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hslToRgb(h, s, l) { + var r, g, b; + + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + + function hue2rgb(p, q, t) { + if(t < 0) t += 1; + if(t > 1) t -= 1; + if(t < 1/6) return p + (q - p) * 6 * t; + if(t < 1/2) return q; + if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; + return p; + } + + 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 = hue2rgb(p, q, h + 1/3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1/3); + } + + return { r: r * 255, g: g * 255, b: b * 255 }; + } + + // `rgbToHsv` + // Converts an RGB color value to HSV + // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] + // *Returns:* { h, s, v } in [0,1] + function rgbToHsv(r, g, b) { + + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), min = mathMin(r, g, b); + var h, s, v = max; + + var d = max - min; + s = max === 0 ? 0 : d / max; + + if(max == min) { + h = 0; // achromatic + } + else { + switch(max) { + case r: h = (g - b) / d + (g < b ? 6 : 0); break; + case g: h = (b - r) / d + 2; break; + case b: h = (r - g) / d + 4; break; + } + h /= 6; + } + return { h: h, s: s, v: v }; + } + + // `hsvToRgb` + // Converts an HSV color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + + var i = math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + + return { r: r * 255, g: g * 255, b: b * 255 }; + } + + // `rgbToHex` + // Converts an RGB color to hex + // Assumes r, g, and b are contained in the set [0, 255] + // Returns a 3 or 6 character hex + function rgbToHex(r, g, b, allow3Char) { + + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + // Return a 3 character hex if possible + if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); + } + + return hex.join(""); + } + + // `equals` + // Can be called with any tinycolor input + tinycolor.equals = function (color1, color2) { + if (!color1 || !color2) { return false; } + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); + }; + tinycolor.random = function() { + return tinycolor.fromRatio({ + r: mathRandom(), + g: mathRandom(), + b: mathRandom() + }); + }; + + + // Modification Functions + // ---------------------- + // Thanks to less.js for some of the basics here + // + + tinycolor.desaturate = function (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + }; + tinycolor.saturate = function (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + }; + tinycolor.greyscale = function(color) { + return tinycolor.desaturate(color, 100); + }; + tinycolor.lighten = function(color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + }; + tinycolor.darken = function (color, amount) { + amount = (amount === 0) ? 0 : (amount || 10); + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + }; + tinycolor.complement = function(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); + }; + + + // Combination Functions + // --------------------- + // Thanks to jQuery xColor for some of the ideas behind these + // + + tinycolor.triad = function(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) + ]; + }; + tinycolor.tetrad = function(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) + ]; + }; + tinycolor.splitcomplement = function(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), + tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) + ]; + }; + tinycolor.analogous = function(color, results, slices) { + results = results || 6; + slices = slices || 30; + + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + + for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; + }; + tinycolor.monochromatic = function(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, s = hsv.s, v = hsv.v; + var ret = []; + var modification = 1 / results; + + while (results--) { + ret.push(tinycolor({ h: h, s: s, v: v})); + v = (v + modification) % 1; + } + + return ret; + }; + + + // Readability Functions + // --------------------- + // + + // `readability` + // Analyze the 2 colors and returns an object with the following properties: + // `brightness`: difference in brightness between the two colors + // `color`: difference in color/hue between the two colors + tinycolor.readability = function(color1, color2) { + var a = tinycolor(color1).toRgb(); + var b = tinycolor(color2).toRgb(); + var brightnessA = (a.r * 299 + a.g * 587 + a.b * 114) / 1000; + var brightnessB = (b.r * 299 + b.g * 587 + b.b * 114) / 1000; + var colorDiff = ( + Math.max(a.r, b.r) - Math.min(a.r, b.r) + + Math.max(a.g, b.g) - Math.min(a.g, b.g) + + Math.max(a.b, b.b) - Math.min(a.b, b.b) + ); + + return { + brightness: Math.abs(brightnessA - brightnessB), + color: colorDiff + }; + }; + + // `readable` + // http://www.w3.org/TR/AERT#color-contrast + // Ensure that foreground and background color combinations provide sufficient contrast. + // *Example* + // tinycolor.readable("#000", "#111") => false + tinycolor.readable = function(color1, color2) { + var readability = tinycolor.readability(color1, color2); + return readability.brightness > 125 && readability.color > 500; + }; + + // `mostReadable` + // Given a base color and a list of possible foreground or background + // colors for that base, returns the most readable color. + // *Example* + // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000" + tinycolor.mostReadable = function(baseColor, colorList) { + var bestColor = null; + var bestScore = 0; + var bestIsReadable = false; + for (var i=0; i < colorList.length; i++) { + + // We normalize both around the "acceptable" breaking point, + // but rank brightness constrast higher than hue. + + var readability = tinycolor.readability(baseColor, colorList[i]); + var readable = readability.brightness > 125 && readability.color > 500; + var score = 3 * (readability.brightness / 125) + (readability.color / 500); + + if ((readable && ! bestIsReadable) || + (readable && bestIsReadable && score > bestScore) || + ((! readable) && (! bestIsReadable) && score > bestScore)) { + bestIsReadable = readable; + bestScore = score; + bestColor = tinycolor(colorList[i]); + } + } + return bestColor; + }; + + + // Big List of Colors + // ------------------ + // + var names = tinycolor.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" + }; + + // Make it easy to access colors via `hexNames[hex]` + var hexNames = tinycolor.hexNames = flip(names); + + + // Utilities + // --------- + + // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` + function flip(o) { + var flipped = { }; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } + + // Return a valid alpha value [0,1] with all invalid values being set to 1 + function boundAlpha(a) { + a = parseFloat(a); + + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + + return a; + } + + // Take input from [0, n] and return it as [0, 1] + function bound01(n, max) { + if (isOnePointZero(n)) { n = "100%"; } + + var processPercent = isPercentage(n); + n = mathMin(max, mathMax(0, parseFloat(n))); + + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + + // Handle floating point rounding errors + if ((math.abs(n - max) < 0.000001)) { + return 1; + } + + // Convert into [0, 1] range if it isn't already + return (n % max) / parseFloat(max); + } + + // Force a number between 0 and 1 + function clamp01(val) { + return mathMin(1, mathMax(0, val)); + } + + // Parse an integer into hex + function parseHex(val) { + return parseInt(val, 16); + } + + // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 + // + function isOnePointZero(n) { + return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; + } + + // Check to see if string passed in is a percentage + function isPercentage(n) { + return typeof n === "string" && n.indexOf('%') != -1; + } + + // Force a hex value to have 2 characters + function pad2(c) { + return c.length == 1 ? '0' + c : '' + c; + } + + // Replace a decimal with it's percentage value + function convertToPercentage(n) { + if (n <= 1) { + n = (n * 100) + "%"; + } + + return n; + } + + var matchers = (function() { + + // + var CSS_INTEGER = "[-\\+]?\\d+%?"; + + // + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + + return { + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + })(); + + // `stringInputToObject` + // Permissive string parsing. Take in a number of formats, and output an object + // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` + function stringInputToObject(color) { + + color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } + else if (color == 'transparent') { + return { r: 0, g: 0, b: 0, a: 0, format: "name" }; + } + + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if ((match = matchers.rgb.exec(color))) { + return { r: match[1], g: match[2], b: match[3] }; + } + if ((match = matchers.rgba.exec(color))) { + return { r: match[1], g: match[2], b: match[3], a: match[4] }; + } + if ((match = matchers.hsl.exec(color))) { + return { h: match[1], s: match[2], l: match[3] }; + } + if ((match = matchers.hsla.exec(color))) { + return { h: match[1], s: match[2], l: match[3], a: match[4] }; + } + if ((match = matchers.hsv.exec(color))) { + return { h: match[1], s: match[2], v: match[3] }; + } + if ((match = matchers.hex6.exec(color))) { + return { + r: parseHex(match[1]), + g: parseHex(match[2]), + b: parseHex(match[3]), + format: named ? "name" : "hex" + }; + } + if ((match = matchers.hex3.exec(color))) { + return { + r: parseHex(match[1] + '' + match[1]), + g: parseHex(match[2] + '' + match[2]), + b: parseHex(match[3] + '' + match[3]), + format: named ? "name" : "hex" + }; + } + + return false; + } + + // Expose tinycolor to window, does not need to run in non-browser context. + window.tinycolor = tinycolor; + + })(); + var tinycolor = window.tinycolor; + + $(function () { + if ($.fn.spectrum.load) { + $.fn.spectrum.processNativeColorInputs(); + } + }); + +})(window, jQuery); +;// vim:ts=4:sts=4:sw=4: +/*! + * + * Copyright 2009-2012 Kris Kowal under the terms of the MIT + * license found at http://github.com/kriskowal/q/raw/master/LICENSE + * + * With parts by Tyler Close + * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found + * at http://www.opensource.org/licenses/mit-license.html + * Forked at ref_send.js version: 2009-05-11 + * + * With parts by Mark Miller + * Copyright (C) 2011 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. + * + */ + +(function (definition) { + "use strict"; + + // This file will function properly as a \n\n Image tag attributes:\n\n data-animated-src - If this url is specified, it's loaded into the player instead of src.\n This allows a preview frame to be shown until animated gif data is streamed into the canvas\n\n Constructor options args\n\n gif Required. The DOM element of an img tag.\n\n Instance methods\n\n // loading\n load( callback ) Loads the gif into a canvas element and then calls callback if one is passed\n\n For additional customization (viewport inside iframe) these params may be passed:\n c_w, c_h - width and height of canvas\n vp_t, vp_l, vp_ w, vp_h - top, left, width and height of the viewport\n\n A bonus: few articles to understand what is going on\n http://enthusiasms.org/post/16976438906\n http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp\n http://humpy77.deviantart.com/journal/Frame-Delay-Times-for-Animated-GIFs-214150546\n\n*/\n\n( function( window ) { 'use strict';\n\n// Generic functions\nvar bitsToNum = function (ba) {\n return ba.reduce(function (s, n) {\n return s * 2 + n;\n }, 0);\n};\n\nvar byteToBitArr = function (bite) {\n var a = [];\n for (var i = 7; i >= 0; i--) {\n a.push( !! (bite & (1 << i)));\n }\n return a;\n};\n\n// Stream\n/**\n * @constructor\n */\n// Make compiler happy.\nvar Stream = function (data) {\n this.data = data;\n this.len = this.data.length;\n this.pos = 0;\n\n this.readByte = function () {\n if (this.pos >= this.data.length) {\n throw new Error('Attempted to read past end of stream.');\n }\n return data.charCodeAt(this.pos++) & 0xFF;\n };\n\n this.readBytes = function (n) {\n var bytes = [];\n for (var i = 0; i < n; i++) {\n bytes.push(this.readByte());\n }\n return bytes;\n };\n\n this.read = function (n) {\n var s = '';\n for (var i = 0; i < n; i++) {\n s += String.fromCharCode(this.readByte());\n }\n return s;\n };\n\n this.readUnsigned = function () { // Little-endian.\n var a = this.readBytes(2);\n return (a[1] << 8) + a[0];\n };\n};\n\nvar lzwDecode = function (minCodeSize, data) {\n // TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String?\n var pos = 0; // Maybe this streaming thing should be merged with the Stream?\n var readCode = function (size) {\n var code = 0;\n for (var i = 0; i < size; i++) {\n if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) {\n code |= 1 << i;\n }\n pos++;\n }\n return code;\n };\n\n var output = [];\n\n var clearCode = 1 << minCodeSize;\n var eoiCode = clearCode + 1;\n\n var codeSize = minCodeSize + 1;\n\n var dict = [];\n\n var clear = function () {\n dict = [];\n codeSize = minCodeSize + 1;\n for (var i = 0; i < clearCode; i++) {\n dict[i] = [i];\n }\n dict[clearCode] = [];\n dict[eoiCode] = null;\n\n };\n\n var code;\n var last;\n\n while (true) {\n last = code;\n code = readCode(codeSize);\n\n if (code === clearCode) {\n clear();\n continue;\n }\n if (code === eoiCode) break;\n\n if (code < dict.length) {\n if (last !== clearCode) {\n dict.push(dict[last].concat(dict[code][0]));\n }\n }\n else {\n if (code !== dict.length) throw new Error('Invalid LZW code.');\n dict.push(dict[last].concat(dict[last][0]));\n }\n output.push.apply(output, dict[code]);\n\n if (dict.length === (1 << codeSize) && codeSize < 12) {\n // If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long.\n codeSize++;\n }\n }\n\n // I don't know if this is technically an error, but some GIFs do it.\n //if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.');\n return output;\n};\n\n\n// The actual parsing; returns an object with properties.\nvar parseGIF = function (st, handler) {\n handler || (handler = {});\n\n // LZW (GIF-specific)\n var parseCT = function (entries) { // Each entry is 3 bytes, for RGB.\n var ct = [];\n for (var i = 0; i < entries; i++) {\n ct.push(st.readBytes(3));\n }\n return ct;\n };\n\n var readSubBlocks = function () {\n var size, data;\n data = '';\n do {\n size = st.readByte();\n data += st.read(size);\n } while (size !== 0);\n return data;\n };\n\n var parseHeader = function () {\n var hdr = {};\n hdr.sig = st.read(3);\n hdr.ver = st.read(3);\n if (hdr.sig !== 'GIF') {\n handler.onError(); // XXX: This should probably be handled more nicely.\n throw new Error('Not a GIF file.');\n }\n hdr.width = st.readUnsigned();\n hdr.height = st.readUnsigned();\n\n var bits = byteToBitArr(st.readByte());\n hdr.gctFlag = bits.shift();\n hdr.colorRes = bitsToNum(bits.splice(0, 3));\n hdr.sorted = bits.shift();\n hdr.gctSize = bitsToNum(bits.splice(0, 3));\n\n hdr.bgColor = st.readByte();\n hdr.pixelAspectRatio = st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64\n if (hdr.gctFlag) {\n hdr.gct = parseCT(1 << (hdr.gctSize + 1));\n }\n handler.hdr && handler.hdr(hdr);\n };\n\n var parseExt = function (block) {\n var parseGCExt = function (block) {\n var blockSize = st.readByte(); // Always 4\n var bits = byteToBitArr(st.readByte());\n block.reserved = bits.splice(0, 3); // Reserved; should be 000.\n block.disposalMethod = bitsToNum(bits.splice(0, 3));\n block.userInput = bits.shift();\n block.transparencyGiven = bits.shift();\n\n block.delayTime = st.readUnsigned();\n\n block.transparencyIndex = st.readByte();\n\n block.terminator = st.readByte();\n\n handler.gce && handler.gce(block);\n };\n\n var parseComExt = function (block) {\n block.comment = readSubBlocks();\n handler.com && handler.com(block);\n };\n\n var parsePTExt = function (block) {\n // No one *ever* uses this. If you use it, deal with parsing it yourself.\n var blockSize = st.readByte(); // Always 12\n block.ptHeader = st.readBytes(12);\n block.ptData = readSubBlocks();\n handler.pte && handler.pte(block);\n };\n\n var parseAppExt = function (block) {\n var parseNetscapeExt = function (block) {\n var blockSize = st.readByte(); // Always 3\n block.unknown = st.readByte(); // ??? Always 1? What is this?\n block.iterations = st.readUnsigned();\n block.terminator = st.readByte();\n handler.app && handler.app.NETSCAPE && handler.app.NETSCAPE(block);\n };\n\n var parseUnknownAppExt = function (block) {\n block.appData = readSubBlocks();\n // FIXME: This won't work if a handler wants to match on any identifier.\n handler.app && handler.app[block.identifier] && handler.app[block.identifier](block);\n };\n\n var blockSize = st.readByte(); // Always 11\n block.identifier = st.read(8);\n block.authCode = st.read(3);\n switch (block.identifier) {\n case 'NETSCAPE':\n parseNetscapeExt(block);\n break;\n default:\n parseUnknownAppExt(block);\n break;\n }\n };\n\n var parseUnknownExt = function (block) {\n block.data = readSubBlocks();\n handler.unknown && handler.unknown(block);\n };\n\n block.label = st.readByte();\n switch (block.label) {\n case 0xF9:\n block.extType = 'gce';\n parseGCExt(block);\n break;\n case 0xFE:\n block.extType = 'com';\n parseComExt(block);\n break;\n case 0x01:\n block.extType = 'pte';\n parsePTExt(block);\n break;\n case 0xFF:\n block.extType = 'app';\n parseAppExt(block);\n break;\n default:\n block.extType = 'unknown';\n parseUnknownExt(block);\n break;\n }\n };\n\n var parseImg = function (img) {\n var deinterlace = function (pixels, width) {\n // Of course this defeats the purpose of interlacing. And it's *probably*\n // the least efficient way it's ever been implemented. But nevertheless...\n var newPixels = new Array(pixels.length);\n var rows = pixels.length / width;\n var cpRow = function (toRow, fromRow) {\n var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);\n newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));\n };\n\n // See appendix E.\n var offsets = [0, 4, 2, 1];\n var steps = [8, 8, 4, 2];\n\n var fromRow = 0;\n for (var pass = 0; pass < 4; pass++) {\n for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {\n cpRow(toRow, fromRow)\n fromRow++;\n }\n }\n\n return newPixels;\n };\n\n img.leftPos = st.readUnsigned();\n img.topPos = st.readUnsigned();\n img.width = st.readUnsigned();\n img.height = st.readUnsigned();\n\n var bits = byteToBitArr(st.readByte());\n img.lctFlag = bits.shift();\n img.interlaced = bits.shift();\n img.sorted = bits.shift();\n img.reserved = bits.splice(0, 2);\n img.lctSize = bitsToNum(bits.splice(0, 3));\n\n if (img.lctFlag) {\n img.lct = parseCT(1 << (img.lctSize + 1));\n }\n\n img.lzwMinCodeSize = st.readByte();\n\n var lzwData = readSubBlocks();\n\n img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData);\n\n if (img.interlaced) { // Move\n img.pixels = deinterlace(img.pixels, img.width);\n }\n\n handler.img && handler.img(img);\n };\n\n var parseBlock = function () {\n var block = {};\n block.sentinel = st.readByte();\n\n switch (String.fromCharCode(block.sentinel)) { // For ease of matching\n case '!':\n block.type = 'ext';\n parseExt(block);\n break;\n case ',':\n block.type = 'img';\n parseImg(block);\n break;\n case ';':\n block.type = 'eof';\n handler.eof && handler.eof(block);\n break;\n default:\n return handler.onError(new Error('Unknown block: 0x' + block.sentinel.toString(16))); // TODO: Pad this with a 0.\n }\n\n if (block.type !== 'eof') {\n setTimeout(parseBlock, 0);\n }\n };\n\n var parse = function () {\n parseHeader();\n setTimeout(parseBlock, 0);\n };\n\n parse();\n};\n\n\nvar SuperGif = function ( opts ) {\n var options = {\n //viewport position\n vp_l: 0,\n vp_t: 0,\n vp_w: null,\n vp_h: null,\n //canvas sizes\n c_w: null,\n c_h: null\n };\n for (var i in opts ) { options[i] = opts[i] }\n if (options.vp_w && options.vp_h) options.is_vp = true;\n\n var stream;\n var hdr;\n\n var loadError = null;\n var loading = false;\n\n var transparency = null;\n var delay = null;\n var disposalMethod = null;\n var disposalRestoreFromIdx = 0;\n var lastDisposalMethod = null;\n var frame = null;\n var lastImg = null;\n\n var frames = [];\n\n var gif = options.gif;\n\n var clear = function () {\n transparency = null;\n delay = null;\n lastDisposalMethod = disposalMethod;\n disposalMethod = null;\n frame = null;\n };\n\n // XXX: There's probably a better way to handle catching exceptions when\n // callbacks are involved.\n var doParse = function () {\n try {\n parseGIF(stream, handler);\n }\n catch (err) {\n doLoadError('parse');\n }\n };\n\n var setSizes = function(w, h) {\n tmpCanvas.width = w;\n tmpCanvas.height = h;\n tmpCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);\n }\n\n var doLoadError = function (originOfError) {\n\n\n loadError = originOfError;\n hdr = {\n width: gif.width,\n height: gif.height\n }; // Fake header.\n frames = [];\n };\n\n var doHdr = function (_hdr) {\n hdr = _hdr;\n setSizes(hdr.width, hdr.height)\n };\n\n var doGCE = function (gce) {\n pushFrame();\n clear();\n transparency = gce.transparencyGiven ? gce.transparencyIndex : null;\n delay = gce.delayTime;\n disposalMethod = gce.disposalMethod;\n // We don't have much to do with the rest of GCE.\n };\n\n var pushFrame = function () {\n if (!frame) return;\n frames.push({\n data: frame.getImageData(0, 0, hdr.width, hdr.height),\n delay: delay\n });\n };\n\n // flag for drawing initial frame\n var isInitFrameDrawn = false;\n\n var doImg = function (img) {\n if (!frame) frame = tmpCanvas.getContext('2d');\n\n var currIdx = frames.length;\n\n //ct = color table, gct = global color table\n var ct = img.lctFlag ? img.lct : hdr.gct; // TODO: What if neither exists?\n\n /*\n Disposal method indicates the way in which the graphic is to\n be treated after being displayed.\n\n Values : 0 - No disposal specified. The decoder is\n not required to take any action.\n 1 - Do not dispose. The graphic is to be left\n in place.\n 2 - Restore to background color. The area used by the\n graphic must be restored to the background color.\n 3 - Restore to previous. The decoder is required to\n restore the area overwritten by the graphic with\n what was there prior to rendering the graphic.\n\n Importantly, \"previous\" means the frame state\n after the last disposal of method 0, 1, or 2.\n */\n if (currIdx > 0) {\n if (lastDisposalMethod === 3) {\n // Restore to previous\n frame.putImageData(frames[disposalRestoreFromIdx].data, 0, 0);\n } else {\n disposalRestoreFromIdx = currIdx - 1;\n }\n\n if (lastDisposalMethod === 2) {\n // Restore to background color\n // Browser implementations historically restore to transparent; we do the same.\n // http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=1&t=21172#p86079\n frame.clearRect(lastImg.leftPos, lastImg.topPos, lastImg.width, lastImg.height);\n }\n }\n // else, Undefined/Do not dispose.\n // frame contains final pixel data from the last frame; do nothing\n\n //Get existing pixels for img region after applying disposal method\n var imgData = frame.getImageData(img.leftPos, img.topPos, img.width, img.height);\n //apply color table colors\n var cdd = imgData.data;\n img.pixels.forEach(function (pixel, i) {\n // imgData.data === [R,G,B,A,R,G,B,A,...]\n if (pixel !== transparency) {\n cdd[i * 4 + 0] = ct[pixel][0];\n cdd[i * 4 + 1] = ct[pixel][1];\n cdd[i * 4 + 2] = ct[pixel][2];\n cdd[i * 4 + 3] = 255; // Opaque.\n }\n });\n\n frame.putImageData(imgData, img.leftPos, img.topPos);\n\n lastImg = img;\n };\n\n var doNothing = function () {};\n /**\n * @param{boolean=} draw Whether to draw progress bar or not; this is not idempotent because of translucency.\n * Note that this means that the text will be unsynchronized with the progress bar on non-frames;\n * but those are typically so small (GCE etc.) that it doesn't really matter. TODO: Do this properly.\n */\n var handler = {\n hdr: doHdr,\n gce: doGCE,\n // I guess that's all for now.\n // app: {\n // // TODO: Is there much point in actually supporting iterations?\n // NETSCAPE: withProgress(doNothing)\n // },\n img: doImg,\n eof: function (block) {\n pushFrame();\n loading = false;\n if (load_callback) {\n load_callback();\n }\n },\n\n onError : function (error) {\n if (error_callback) {\n error_callback();\n }\n }\n };\n\n var load_callback = false;\n var step_callback = false;\n var error_callback = false;\n var tmpCanvas = document.createElement('canvas');\n\n return {\n\n load: function (callback) {\n\n load_callback = callback.success;\n step_callback = callback.step;\n error_callback = callback.error;\n\n loading = true;\n\n if (gif.src.indexOf('data:') !== -1) {\n var data = gif.src.substring(gif.src.indexOf(',')+1);\n stream = new Stream(window.atob(data));\n doParse();\n } else {\n var h = new XMLHttpRequest();\n h.overrideMimeType('text/plain; charset=x-user-defined');\n h.onload = function(e) {\n stream = new Stream(h.responseText);\n setTimeout(doParse, 0);\n };\n h.onerror = function() { doLoadError('xhr'); };\n h.open('GET', gif.getAttribute('data-animated-src') || gif.src, true);\n h.send();\n }\n },\n\n getFrames : function () {\n return frames;\n }\n };\n};\n\n\nwindow.SuperGif = SuperGif;\n\n})( window );","/*!\n\nJSZip - A Javascript class for generating and reading zip files\n\n\n(c) 2009-2014 Stuart Knightley \nDual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.\n\nJSZip uses the library zlib.js released under the following license :\nzlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License\n*/\n!function(a){\"object\"==typeof exports?module.exports=a():\"function\"==typeof define&&define.amd?define(a):\"undefined\"!=typeof window?window.JSZip=a():\"undefined\"!=typeof global?global.JSZip=a():\"undefined\"!=typeof self&&(self.JSZip=a())}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i=\"function\"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error(\"Cannot find module '\"+g+\"'\")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f=\"function\"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j=\"\",k=0;for(a=a.replace(/[^A-Za-z0-9\\+\\/\\=]/g,\"\");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){\"use strict\";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){\"use strict\";c.STORE={magic:\"\\x00\\x00\",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a(\"./flate\")},{\"./flate\":6}],4:[function(a,b){\"use strict\";function c(){this.data=null,this.length=0,this.index=0}var d=a(\"./utils\");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error(\"End of data reached (data length = \"+this.length+\", asked index = \"+a+\"). Corrupted zip ?\")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo(\"string\",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{\"./utils\":14}],5:[function(a,b,c){\"use strict\";c.base64=!1,c.binary=!1,c.dir=!1,c.date=null,c.compression=null},{}],6:[function(a,b,c){\"use strict\";var d=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Uint32Array,e=a(\"zlibjs/bin/rawdeflate.min\").Zlib,f=a(\"zlibjs/bin/rawinflate.min\").Zlib;c.uncompressInputType=d?\"uint8array\":\"array\",c.compressInputType=d?\"uint8array\":\"array\",c.magic=\"\\b\\x00\",c.compress=function(a){var b=new e.RawDeflate(a);return b.compress()},c.uncompress=function(a){var b=new f.RawInflate(a);return b.decompress()}},{\"zlibjs/bin/rawdeflate.min\":19,\"zlibjs/bin/rawinflate.min\":20}],7:[function(a,b){\"use strict\";function c(a,b){return this instanceof c?(this.files={},this.root=\"\",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)\"function\"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}c.prototype=a(\"./object\"),c.prototype.load=a(\"./load\"),c.support=a(\"./support\"),c.defaults=a(\"./defaults\"),c.utils=a(\"./utils\"),c.base64=a(\"./base64\"),c.compressions=a(\"./compressions\"),b.exports=c},{\"./base64\":1,\"./compressions\":3,\"./defaults\":5,\"./load\":8,\"./object\":9,\"./support\":12,\"./utils\":14}],8:[function(a,b){\"use strict\";var c=a(\"./base64\"),d=a(\"./zipEntries\");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},r=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):\"\"},v=function(a){return\"/\"!=a.slice(-1)&&(a+=\"/\"),this.files[a]||t.call(this,a,null,{dir:!0}),this.files[a]},w=function(a,b){var c,d=new k;return a._data instanceof k?(d.uncompressedSize=a._data.uncompressedSize,d.crc32=a._data.crc32,0===d.uncompressedSize||a.options.dir?(b=j.STORE,d.compressedContent=\"\",d.crc32=0):a._data.compressionMethod===b.magic?d.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),d.compressedContent=b.compress(f.transformTo(b.compressInputType,c)))):(c=n(a),(!c||0===c.length||a.options.dir)&&(b=j.STORE,c=\"\"),d.uncompressedSize=c.length,d.crc32=this.crc32(c),d.compressedContent=b.compress(f.transformTo(b.compressInputType,c))),d.compressedSize=d.compressedContent.length,d.compressionMethod=b.magic,d},x=function(a,b,c,d){var e,f,h=(c.compressedContent,this.utf8encode(b.name)),i=h!==b.name,j=b.options,k=\"\",l=\"\";e=j.date.getHours(),e<<=6,e|=j.date.getMinutes(),e<<=5,e|=j.date.getSeconds()/2,f=j.date.getFullYear()-1980,f<<=4,f|=j.date.getMonth()+1,f<<=5,f|=j.date.getDate(),i&&(l=q(1,1)+q(this.crc32(h),4)+h,k+=\"up\"+q(l.length,2)+l);var m=\"\";m+=\"\\n\\x00\",m+=i?\"\\x00\\b\":\"\\x00\\x00\",m+=c.compressionMethod,m+=q(e,2),m+=q(f,2),m+=q(c.crc32,4),m+=q(c.compressedSize,4),m+=q(c.uncompressedSize,4),m+=q(h.length,2),m+=q(k.length,2);var n=g.LOCAL_FILE_HEADER+m+h+k,o=g.CENTRAL_FILE_HEADER+\"\u0014\\x00\"+m+\"\\x00\\x00\\x00\\x00\\x00\\x00\"+(b.options.dir===!0?\"\u0010\\x00\\x00\\x00\":\"\\x00\\x00\\x00\\x00\")+q(d,4)+h+k;return{fileRecord:n,dirRecord:o,compressedObject:c}},y=function(){this.data=[]};y.prototype={append:function(a){a=f.transformTo(\"string\",a),this.data.push(a)},finalize:function(){return this.data.join(\"\")}};var z=function(a){this.data=new Uint8Array(a),this.index=0};z.prototype={append:function(a){0!==a.length&&(a=f.transformTo(\"uint8array\",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}};var A={load:function(){throw new Error(\"Load method is not defined. Is the file jszip-load.js included ?\")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new p(d.name,d._data,r(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(f.isRegExp(a)){var d=a;return this.filter(function(a,b){return!b.options.dir&&d.test(a)})}return this.filter(function(b,c){return!c.options.dir&&b===a})[0]||null}return a=this.root+a,t.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(f.isRegExp(a))return this.filter(function(b,c){return c.options.dir&&a.test(b)});var b=this.root+a,c=v.call(this,b),d=this.clone();return d.root=c.name,d},remove:function(a){a=this.root+a;var b=this.files[a];if(b||(\"/\"!=a.slice(-1)&&(a+=\"/\"),b=this.files[a]),b)if(b.options.dir)for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;di;i++)h=c?a[i]:a.charCodeAt(i),g=255&(b^h),e=d[g],b=b>>>8^e;return-1^b},utf8encode:function(a){if(c){var b=c.encode(a);return f.transformTo(\"string\",b)}if(e.nodebuffer)return f.transformTo(\"string\",l(a,\"utf-8\"));for(var d=[],g=0,h=0;hi?d[g++]=String.fromCharCode(i):i>127&&2048>i?(d[g++]=String.fromCharCode(i>>6|192),d[g++]=String.fromCharCode(63&i|128)):(d[g++]=String.fromCharCode(i>>12|224),d[g++]=String.fromCharCode(i>>6&63|128),d[g++]=String.fromCharCode(63&i|128))}return d.join(\"\")},utf8decode:function(a){var b=[],c=0,g=f.getTypeOf(a),h=\"string\"!==g,i=0,j=0,k=0,l=0;if(d)return d.decode(f.transformTo(\"uint8array\",a));if(e.nodebuffer)return f.transformTo(\"nodebuffer\",a).toString(\"utf-8\");for(;ij?(b[c++]=String.fromCharCode(j),i++):j>191&&224>j?(k=h?a[i+1]:a.charCodeAt(i+1),b[c++]=String.fromCharCode((31&j)<<6|63&k),i+=2):(k=h?a[i+1]:a.charCodeAt(i+1),l=h?a[i+2]:a.charCodeAt(i+2),b[c++]=String.fromCharCode((15&j)<<12|(63&k)<<6|63&l),i+=3);return b.join(\"\")}};b.exports=A},{\"./base64\":1,\"./compressedObject\":2,\"./compressions\":3,\"./defaults\":5,\"./nodeBuffer\":17,\"./signature\":10,\"./support\":12,\"./utils\":14}],10:[function(a,b,c){\"use strict\";c.LOCAL_FILE_HEADER=\"PK\u0003\u0004\",c.CENTRAL_FILE_HEADER=\"PK\u0001\u0002\",c.CENTRAL_DIRECTORY_END=\"PK\u0005\u0006\",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR=\"PK\u0006\u0007\",c.ZIP64_CENTRAL_DIRECTORY_END=\"PK\u0006\u0006\",c.DATA_DESCRIPTOR=\"PK\u0007\\b\"},{}],11:[function(a,b){\"use strict\";function c(a,b){this.data=a,b||(this.data=e.string2binary(this.data)),this.length=this.data.length,this.index=0}var d=a(\"./dataReader\"),e=a(\"./utils\");c.prototype=new d,c.prototype.byteAt=function(a){return this.data.charCodeAt(a)},c.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{\"./dataReader\":4,\"./utils\":14}],12:[function(a,b,c){var d=a(\"__browserify_process\");if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer=\"undefined\"!=typeof ArrayBuffer&&\"undefined\"!=typeof Uint8Array,c.nodebuffer=!d.browser,c.uint8array=\"undefined\"!=typeof Uint8Array,\"undefined\"==typeof ArrayBuffer)c.blob=!1;else{var e=new ArrayBuffer(0);try{c.blob=0===new Blob([e],{type:\"application/zip\"}).size}catch(f){try{var g=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,h=new g;h.append(e),c.blob=0===h.getBlob(\"application/zip\").size}catch(f){c.blob=!1}}}},{__browserify_process:18}],13:[function(a,b){\"use strict\";function c(a){a&&(this.data=a,this.length=this.data.length,this.index=0)}var d=a(\"./dataReader\");c.prototype=new d,c.prototype.byteAt=function(a){return this.data[a]},c.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{\"./dataReader\":4}],14:[function(a,b,c){\"use strict\";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push(\"array\"===f||\"nodebuffer\"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join(\"\")}function g(a,b){for(var c=0;cb?\"0\":\"\")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return\"[object RegExp]\"===Object.prototype.toString.call(a)}},{\"./compressions\":3,\"./nodeBuffer\":17,\"./support\":12}],15:[function(a,b){\"use strict\";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a(\"./stringReader\"),e=a(\"./nodeBufferReader\"),f=a(\"./uint8ArrayReader\"),g=a(\"./utils\"),h=a(\"./signature\"),i=a(\"./zipEntry\"),j=a(\"./support\");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error(\"Corrupted zip or bug : unexpected signature (\"+g.pretty(b)+\", expected \"+g.pretty(a)+\")\")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error(\"Multi-volumes zip are not supported\")},readLocalFiles:function(){var a,b;for(a=0;a0)){var d=c.shift();d()}},!0),function(a){c.push(a),window.postMessage(\"process-tick\",\"*\")}}return function(a){setTimeout(a,0)}}(),c.title=\"browser\",c.browser=!0,c.env={},c.argv=[],c.binding=function(){throw new Error(\"process.binding is not supported\")},c.cwd=function(){return\"/\"},c.chdir=function(){throw new Error(\"process.chdir is not supported\")}},{}],19:[function(){/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */\n(function(){\"use strict\";function a(a,b){var c=a.split(\".\"),d=n;!(c[0]in d)&&d.execScript&&d.execScript(\"var \"+c[0]);for(var e;c.length&&(e=c.shift());)c.length||b===l?d=d[e]?d[e]:d[e]={}:d[e]=b}function b(a,b){if(this.index=\"number\"==typeof b?b:0,this.d=0,this.buffer=a instanceof(o?Uint8Array:Array)?a:new(o?Uint8Array:Array)(32768),2*this.buffer.length<=this.index)throw Error(\"invalid index\");this.buffer.length<=this.index&&c(this)}function c(a){var b,c=a.buffer,d=c.length,e=new(o?Uint8Array:Array)(d<<1);if(o)e.set(c);else for(b=0;d>b;++b)e[b]=c[b];return a.buffer=e}function d(a){this.buffer=new(o?Uint16Array:Array)(2*a),this.length=0}function e(a,b){this.e=w,this.f=0,this.input=o&&a instanceof Array?new Uint8Array(a):a,this.c=0,b&&(b.lazy&&(this.f=b.lazy),\"number\"==typeof b.compressionType&&(this.e=b.compressionType),b.outputBuffer&&(this.b=o&&b.outputBuffer instanceof Array?new Uint8Array(b.outputBuffer):b.outputBuffer),\"number\"==typeof b.outputIndex&&(this.c=b.outputIndex)),this.b||(this.b=new(o?Uint8Array:Array)(32768))}function f(a,b){this.length=a,this.g=b}function g(a,b){function c(a,b){var c,d=a.g,e=[],f=0;c=z[a.length],e[f++]=65535&c,e[f++]=c>>16&255,e[f++]=c>>24;var g;switch(m){case 1===d:g=[0,d-1,0];break;case 2===d:g=[1,d-2,0];break;case 3===d:g=[2,d-3,0];break;case 4===d:g=[3,d-4,0];break;case 6>=d:g=[4,d-5,1];break;case 8>=d:g=[5,d-7,1];break;case 12>=d:g=[6,d-9,2];break;case 16>=d:g=[7,d-13,2];break;case 24>=d:g=[8,d-17,3];break;case 32>=d:g=[9,d-25,3];break;case 48>=d:g=[10,d-33,4];break;case 64>=d:g=[11,d-49,4];break;case 96>=d:g=[12,d-65,5];break;case 128>=d:g=[13,d-97,5];break;case 192>=d:g=[14,d-129,6];break;case 256>=d:g=[15,d-193,6];break;case 384>=d:g=[16,d-257,7];break;case 512>=d:g=[17,d-385,7];break;case 768>=d:g=[18,d-513,8];break;case 1024>=d:g=[19,d-769,8];break;case 1536>=d:g=[20,d-1025,9];break;case 2048>=d:g=[21,d-1537,9];break;case 3072>=d:g=[22,d-2049,10];break;case 4096>=d:g=[23,d-3073,10];break;case 6144>=d:g=[24,d-4097,11];break;case 8192>=d:g=[25,d-6145,11];break;case 12288>=d:g=[26,d-8193,12];break;case 16384>=d:g=[27,d-12289,12];break;case 24576>=d:g=[28,d-16385,13];break;case 32768>=d:g=[29,d-24577,13];break;default:throw\"invalid distance\"}c=g,e[f++]=c[0],e[f++]=c[1],e[f++]=c[2];var h,i;for(h=0,i=e.length;i>h;++h)r[s++]=e[h];u[e[0]]++,v[e[3]]++,t=a.length+b-1,n=null}var d,e,f,g,i,j,k,n,p,q={},r=o?new Uint16Array(2*b.length):[],s=0,t=0,u=new(o?Uint32Array:Array)(286),v=new(o?Uint32Array:Array)(30),w=a.f;if(!o){for(f=0;285>=f;)u[f++]=0;for(f=0;29>=f;)v[f++]=0}for(u[256]=1,d=0,e=b.length;e>d;++d){for(f=i=0,g=3;g>f&&d+f!==e;++f)i=i<<8|b[d+f];if(q[i]===l&&(q[i]=[]),j=q[i],!(0=e){for(n&&c(n,-1),f=0,g=e-d;g>f;++f)p=b[d+f],r[s++]=p,++u[p];break}0h;h++){if(d=c[j-h-1],g=3,k>3){for(i=k;i>3;i--)if(a[d+i-1]!==a[b+i-1])continue a;g=k}for(;258>g&&l>b+g&&a[d+g]===a[b+g];)++g;if(g>k&&(e=d,k=g),258===g)break}return new f(k,b-e)}function i(a,b){var c,e,f,g,h,i=a.length,k=new d(572),l=new(o?Uint8Array:Array)(i);if(!o)for(g=0;i>g;g++)l[g]=0;for(g=0;i>g;++g)0g;++g)c[g]=k.pop(),e[g]=c[g].value;for(f=j(e,e.length,b),g=0,h=c.length;h>g;++g)l[c[g].index]=f[g];return l}function j(a,b,c){function d(a){var c=n[a][p[a]];c===b?(d(a+1),d(a+1)):--l[c],++p[a]}var e,f,g,h,i,j=new(o?Uint16Array:Array)(c),k=new(o?Uint8Array:Array)(c),l=new(o?Uint8Array:Array)(b),m=Array(c),n=Array(c),p=Array(c),q=(1<f;++f)r>q?k[f]=0:(k[f]=1,q-=r),q<<=1,j[c-2-f]=(j[c-1-f]/2|0)+b;for(j[0]=k[0],m[0]=Array(j[0]),n[0]=Array(j[0]),f=1;c>f;++f)j[f]>2*j[f-1]+k[f]&&(j[f]=2*j[f-1]+k[f]),m[f]=Array(j[f]),n[f]=Array(j[f]);for(e=0;b>e;++e)l[e]=c;for(g=0;ge;++e)p[e]=0;for(1===k[c-1]&&(--l[0],++p[c-1]),f=c-2;f>=0;--f){for(h=e=0,i=p[f+1],g=0;ga[e]?(m[f][g]=h,n[f][g]=b,i+=2):(m[f][g]=a[e],n[f][g]=e,++e);p[f]=0,1===k[f]&&d(f)}return l}function k(a){var b,c,d,e,f=new(o?Uint16Array:Array)(a.length),g=[],h=[],i=0;for(b=0,c=a.length;c>b;b++)g[a[b]]=(0|g[a[b]])+1;for(b=1,c=16;c>=b;b++)h[b]=i,i+=0|g[b],i<<=1;for(b=0,c=a.length;c>b;b++)for(i=h[a[b]],h[a[b]]+=1,d=f[b]=0,e=a[b];e>d;d++)f[b]=f[b]<<1|1&i,i>>>=1;return f}var l=void 0,m=!0,n=this,o=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Uint32Array&&\"undefined\"!=typeof DataView;b.prototype.a=function(a,b,d){var e,f=this.buffer,g=this.index,h=this.d,i=f[g];if(d&&b>1&&(a=b>8?(u[255&a]<<24|u[a>>>8&255]<<16|u[a>>>16&255]<<8|u[a>>>24&255])>>32-b:u[a]>>8-b),8>b+h)i=i<e;++e)i=i<<1|a>>b-e-1&1,8===++h&&(h=0,f[g++]=u[i],i=0,g===f.length&&(f=c(this)));f[g]=i,this.buffer=f,this.d=h,this.index=g},b.prototype.finish=function(){var a,b=this.buffer,c=this.index;return 0p;++p){for(var r=p,s=r,t=7,r=r>>>1;r;r>>>=1)s<<=1,s|=1&r,--t;q[p]=(s<>>0}var u=q;d.prototype.getParent=function(a){return 2*((a-2)/4|0)},d.prototype.push=function(a,b){var c,d,e,f=this.buffer;for(c=this.length,f[this.length++]=b,f[this.length++]=a;c>0&&(d=this.getParent(c),f[c]>f[d]);)e=f[c],f[c]=f[d],f[d]=e,e=f[c+1],f[c+1]=f[d+1],f[d+1]=e,c=d;return this.length},d.prototype.pop=function(){var a,b,c,d,e,f=this.buffer;for(b=f[0],a=f[1],this.length-=2,f[0]=f[this.length],f[1]=f[this.length+1],e=0;(d=2*e+2,!(d>=this.length))&&(d+2f[d]&&(d+=2),f[d]>f[e]);)c=f[e],f[e]=f[d],f[d]=c,c=f[e+1],f[e+1]=f[d+1],f[d+1]=c,e=d;return{index:a,value:b,length:this.length}};var v,w=2,x=[];for(v=0;288>v;v++)switch(m){case 143>=v:x.push([v+48,8]);break;case 255>=v:x.push([v-144+400,9]);break;case 279>=v:x.push([v-256+0,7]);break;case 287>=v:x.push([v-280+192,8]);break;default:throw\"invalid literal: \"+v}e.prototype.h=function(){var a,c,d,e,f=this.input;switch(this.e){case 0:for(d=0,e=f.length;e>d;){c=o?f.subarray(d,d+65535):f.slice(d,d+65535),d+=c.length;var h=c,j=d===e,n=l,p=l,q=l,r=l,s=l,t=this.b,u=this.c;if(o){for(t=new Uint8Array(this.b.buffer);t.length<=u+h.length+5;)t=new Uint8Array(t.length<<1);t.set(this.b)}if(n=j?1:0,t[u++]=0|n,p=h.length,q=~p+65536&65535,t[u++]=255&p,t[u++]=p>>>8&255,t[u++]=255&q,t[u++]=q>>>8&255,o)t.set(h,u),u+=h.length,t=t.subarray(0,u);else{for(r=0,s=h.length;s>r;++r)t[u++]=h[r];t.length=u}this.c=u,this.b=t}break;case 1:var v=new b(o?new Uint8Array(this.b.buffer):this.b,this.c);v.a(1,1,m),v.a(1,2,m);var y,z,A,B=g(this,f);for(y=0,z=B.length;z>y;y++)if(A=B[y],b.prototype.a.apply(v,x[A]),A>256)v.a(B[++y],B[++y],m),v.a(B[++y],5),v.a(B[++y],B[++y],m);else if(256===A)break;this.b=v.finish(),this.c=this.b.length;break;case w:var C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R=new b(o?new Uint8Array(this.b.buffer):this.b,this.c),S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],T=Array(19);for(C=w,R.a(1,1,m),R.a(C,2,m),D=g(this,f),H=i(this.j,15),I=k(H),J=i(this.i,7),K=k(J),E=286;E>257&&0===H[E-1];E--);for(F=30;F>1&&0===J[F-1];F--);var U,V,W,X,Y,Z,$=E,_=F,ab=new(o?Uint32Array:Array)($+_),bb=new(o?Uint32Array:Array)(316),cb=new(o?Uint8Array:Array)(19);for(U=V=0;$>U;U++)ab[V++]=H[U];for(U=0;_>U;U++)ab[V++]=J[U];if(!o)for(U=0,X=cb.length;X>U;++U)cb[U]=0;for(U=Y=0,X=ab.length;X>U;U+=V){for(V=1;X>U+V&&ab[U+V]===ab[U];++V);if(W=V,0===ab[U])if(3>W)for(;00;)Z=138>W?W:138,Z>W-3&&W>Z&&(Z=W-3),10>=Z?(bb[Y++]=17,bb[Y++]=Z-3,cb[17]++):(bb[Y++]=18,bb[Y++]=Z-11,cb[18]++),W-=Z;else if(bb[Y++]=ab[U],cb[ab[U]]++,W--,3>W)for(;00;)Z=6>W?W:6,Z>W-3&&W>Z&&(Z=W-3),bb[Y++]=16,bb[Y++]=Z-3,cb[16]++,W-=Z}for(a=o?bb.subarray(0,Y):bb.slice(0,Y),L=i(cb,7),P=0;19>P;P++)T[P]=L[S[P]];for(G=19;G>4&&0===T[G-1];G--);for(M=k(L),R.a(E-257,5,m),R.a(F-1,5,m),R.a(G-4,4,m),P=0;G>P;P++)R.a(T[P],3,m);for(P=0,Q=a.length;Q>P;P++)if(N=a[P],R.a(M[N],L[N],m),N>=16){switch(P++,N){case 16:O=2;break;case 17:O=3;break;case 18:O=7;break;default:throw\"invalid code: \"+N}R.a(a[P],O,m)}var db,eb,fb,gb,hb,ib,jb,kb,lb=[I,H],mb=[K,J];for(hb=lb[0],ib=lb[1],jb=mb[0],kb=mb[1],db=0,eb=D.length;eb>db;++db)if(fb=D[db],R.a(hb[fb],ib[fb],m),fb>256)R.a(D[++db],D[++db],m),gb=D[++db],R.a(jb[gb],kb[gb],m),R.a(D[++db],D[++db],m);else if(256===fb)break;this.b=R.finish(),this.c=this.b.length;break;default:throw\"invalid compression type\"}return this.b};var y=function(){function a(a){switch(m){case 3===a:return[257,a-3,0];case 4===a:return[258,a-4,0];case 5===a:return[259,a-5,0];case 6===a:return[260,a-6,0];case 7===a:return[261,a-7,0];case 8===a:return[262,a-8,0];case 9===a:return[263,a-9,0];case 10===a:return[264,a-10,0];case 12>=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:throw\"invalid length: \"+a}}var b,c,d=[];for(b=3;258>=b;b++)c=a(b),d[b]=c[2]<<24|c[1]<<16|c[0];return d}(),z=o?new Uint32Array(y):y;a(\"Zlib.RawDeflate\",e),a(\"Zlib.RawDeflate.prototype.compress\",e.prototype.h);var A,B,C,D,E={NONE:0,FIXED:1,DYNAMIC:w};if(Object.keys)A=Object.keys(E);else for(B in A=[],C=0,E)A[C++]=B;for(C=0,D=A.length;D>C;++C)B=A[C],a(\"Zlib.RawDeflate.CompressionType.\"+B,E[B])}).call(this)},{}],20:[function(){/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */\n(function(){\"use strict\";function a(a,b){var c=a.split(\".\"),d=g;!(c[0]in d)&&d.execScript&&d.execScript(\"var \"+c[0]);for(var e;c.length&&(e=c.shift());)c.length||void 0===b?d=d[e]?d[e]:d[e]={}:d[e]=b}function b(a){var b,c,d,e,f,g,i,j,k,l,m=a.length,n=0,o=Number.POSITIVE_INFINITY;for(j=0;m>j;++j)a[j]>n&&(n=a[j]),a[j]=d;){for(j=0;m>j;++j)if(a[j]===d){for(g=0,i=e,k=0;d>k;++k)g=g<<1|1&i,i>>=1;for(l=d<<16|j,k=g;b>k;k+=f)c[k]=l;++e}++d,e<<=1,f<<=1}return[c,n,o]}function c(a,b){switch(this.g=[],this.h=32768,this.c=this.f=this.d=this.k=0,this.input=h?new Uint8Array(a):a,this.l=!1,this.i=j,this.q=!1,(b||!(b={}))&&(b.index&&(this.d=b.index),b.bufferSize&&(this.h=b.bufferSize),b.bufferType&&(this.i=b.bufferType),b.resize&&(this.q=b.resize)),this.i){case i:this.a=32768,this.b=new(h?Uint8Array:Array)(32768+this.h+258);break;case j:this.a=0,this.b=new(h?Uint8Array:Array)(this.h),this.e=this.v,this.m=this.s,this.j=this.t;break;default:throw Error(\"invalid inflate mode\")}}function d(a,b){for(var c,d=a.f,e=a.c,f=a.input,g=a.d,h=f.length;b>e;){if(g>=h)throw Error(\"input buffer is broken\");d|=f[g++]<>>b,a.c=e-b,a.d=g,c}function e(a,b){for(var c,d,e=a.f,f=a.c,g=a.input,h=a.d,i=g.length,j=b[0],k=b[1];k>f&&!(h>=i);)e|=g[h++]<>>16,a.f=e>>d,a.c=f-d,a.d=h,65535&c}function f(a){function c(a,b,c){var f,g,h,i=this.p;for(h=0;a>h;)switch(f=e(this,b)){case 16:for(g=3+d(this,2);g--;)c[h++]=i;break;case 17:for(g=3+d(this,3);g--;)c[h++]=0;i=0;break;case 18:for(g=11+d(this,7);g--;)c[h++]=0;i=0;break;default:i=c[h++]=f}return this.p=i,c}var f,g,i,j,k=d(a,5)+257,l=d(a,5)+1,m=d(a,4)+4,o=new(h?Uint8Array:Array)(n.length);for(j=0;m>j;++j)o[n[j]]=d(a,3);if(!h)for(j=m,m=o.length;m>j;++j)o[n[j]]=0;f=b(o),g=new(h?Uint8Array:Array)(k),i=new(h?Uint8Array:Array)(l),a.p=0,a.j(b(c.call(a,k,f,g)),b(c.call(a,l,f,i)))}var g=this,h=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Uint32Array&&\"undefined\"!=typeof DataView,i=0,j=1;c.prototype.u=function(){for(;!this.l;){var a=d(this,3);switch(1&a&&(this.l=!0),a>>>=1){case 0:var b=this.input,c=this.d,e=this.b,g=this.a,k=b.length,l=void 0,m=void 0,n=e.length,o=void 0;if(this.c=this.f=0,c+1>=k)throw Error(\"invalid uncompressed block header: LEN\");if(l=b[c++]|b[c++]<<8,c+1>=k)throw Error(\"invalid uncompressed block header: NLEN\");if(m=b[c++]|b[c++]<<8,l===~m)throw Error(\"invalid uncompressed block header: length verify\");if(c+l>b.length)throw Error(\"input buffer is broken\");switch(this.i){case i:for(;g+l>e.length;){if(o=n-g,l-=o,h)e.set(b.subarray(c,c+o),g),g+=o,c+=o;else for(;o--;)e[g++]=b[c++];this.a=g,e=this.e(),g=this.a}break;case j:for(;g+l>e.length;)e=this.e({o:2});break;default:throw Error(\"invalid inflate mode\")}if(h)e.set(b.subarray(c,c+l),g),g+=l,c+=l;else for(;l--;)e[g++]=b[c++];this.d=c,this.a=g,this.b=e;break;case 1:this.j(z,B);break;case 2:f(this);break;default:throw Error(\"unknown BTYPE: \"+a)}}return this.m()};var k,l,m=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],n=h?new Uint16Array(m):m,o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],p=h?new Uint16Array(o):o,q=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],r=h?new Uint8Array(q):q,s=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],t=h?new Uint16Array(s):s,u=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],v=h?new Uint8Array(u):u,w=new(h?Uint8Array:Array)(288);for(k=0,l=w.length;l>k;++k)w[k]=143>=k?8:255>=k?9:279>=k?7:8;var x,y,z=b(w),A=new(h?Uint8Array:Array)(30);for(x=0,y=A.length;y>x;++x)A[x]=5;var B=b(A);c.prototype.j=function(a,b){var c=this.b,f=this.a;this.n=a;for(var g,h,i,j,k=c.length-258;256!==(g=e(this,a));)if(256>g)f>=k&&(this.a=f,c=this.e(),f=this.a),c[f++]=g;else for(h=g-257,j=p[h],0=k&&(this.a=f,c=this.e(),f=this.a);j--;)c[f]=c[f++-i];for(;8<=this.c;)this.c-=8,this.d--;this.a=f},c.prototype.t=function(a,b){var c=this.b,f=this.a;this.n=a;for(var g,h,i,j,k=c.length;256!==(g=e(this,a));)if(256>g)f>=k&&(c=this.e(),k=c.length),c[f++]=g;else for(h=g-257,j=p[h],0k&&(c=this.e(),k=c.length);j--;)c[f]=c[f++-i];for(;8<=this.c;)this.c-=8,this.d--;this.a=f},c.prototype.e=function(){var a,b,c=new(h?Uint8Array:Array)(this.a-32768),d=this.a-32768,e=this.b;if(h)c.set(e.subarray(32768,c.length));else for(a=0,b=c.length;b>a;++a)c[a]=e[a+32768];if(this.g.push(c),this.k+=c.length,h)e.set(e.subarray(d,d+32768));else for(a=0;32768>a;++a)e[a]=e[d+a];return this.a=32768,e},c.prototype.v=function(a){var b,c,d,e,f=this.input.length/this.d+1|0,g=this.input,i=this.b;return a&&(\"number\"==typeof a.o&&(f=a.o),\"number\"==typeof a.r&&(f+=a.r)),2>f?(c=(g.length-this.d)/this.n[2],e=258*(c/2)|0,d=eb;++b)for(a=i[b],d=0,e=a.length;e>d;++d)j[f++]=a[d];for(b=32768,c=this.a;c>b;++b)j[f++]=g[b];return this.g=[],this.buffer=j},c.prototype.s=function(){var a,b=this.a;return h?this.q?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b),this.buffer=a},a(\"Zlib.RawInflate\",c),a(\"Zlib.RawInflate.prototype.decompress\",c.prototype.u);var C,D,E,F,G={ADAPTIVE:j,BLOCK:i};if(Object.keys)C=Object.keys(G);else for(D in C=[],E=0,G)C[E++]=D;for(E=0,F=C.length;F>E;++E)D=C[E],a(\"Zlib.RawInflate.BufferType.\"+D,G[D])}).call(this)},{}]},{},[7])(7)});","// Spectrum Colorpicker v1.1.2\n// https://github.com/bgrins/spectrum\n// Author: Brian Grinstead\n// License: MIT\n\n(function (window, $, undefined) {\n var defaultOpts = {\n\n // Callbacks\n beforeShow: noop,\n move: noop,\n change: noop,\n show: noop,\n hide: noop,\n\n // Options\n color: false,\n flat: false,\n showInput: false,\n showButtons: true,\n clickoutFiresChange: false,\n showInitial: false,\n showPalette: false,\n showPaletteOnly: false,\n showSelectionPalette: true,\n localStorageKey: false,\n appendTo: \"body\",\n maxSelectionSize: 7,\n cancelText: \"cancel\",\n chooseText: \"choose\",\n preferredFormat: false,\n className: \"\",\n showAlpha: false,\n theme: \"sp-light\",\n palette: ['fff', '000'],\n selectionPalette: [],\n disabled: false\n },\n spectrums = [],\n IE = !!/msie/i.exec( window.navigator.userAgent ),\n rgbaSupport = (function() {\n function contains( str, substr ) {\n return !!~('' + str).indexOf(substr);\n }\n\n var elem = document.createElement('div');\n var style = elem.style;\n style.cssText = 'background-color:rgba(0,0,0,.5)';\n return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');\n })(),\n replaceInput = [\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \"\n ].join(''),\n markup = (function () {\n\n // IE does not support gradients with multiple stops, so we need to simulate\n // that for the rainbow slider with 8 divs that each have a single gradient\n var gradientFix = \"\";\n if (IE) {\n for (var i = 1; i <= 6; i++) {\n gradientFix += \"
        \";\n }\n }\n\n return [\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n gradientFix,\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"\",\n \"
        \",\n \"
        \",\n \"
        \",\n \"\",\n \"\",\n \"
        \",\n \"
        \",\n \"
        \"\n ].join(\"\");\n })();\n\n function paletteTemplate (p, color, className) {\n var html = [];\n for (var i = 0; i < p.length; i++) {\n var tiny = tinycolor(p[i]);\n var c = tiny.toHsl().l < 0.5 ? \"sp-thumb-el sp-thumb-dark\" : \"sp-thumb-el sp-thumb-light\";\n c += (tinycolor.equals(color, p[i])) ? \" sp-thumb-active\" : \"\";\n\n var swatchStyle = rgbaSupport ? (\"background-color:\" + tiny.toRgbString()) : \"filter:\" + tiny.toFilter();\n html.push('');\n }\n return \"
        \" + html.join('') + \"
        \";\n }\n\n function hideAll() {\n for (var i = 0; i < spectrums.length; i++) {\n if (spectrums[i]) {\n spectrums[i].hide();\n }\n }\n }\n\n function instanceOptions(o, callbackContext) {\n var opts = $.extend({}, defaultOpts, o);\n opts.callbacks = {\n 'move': bind(opts.move, callbackContext),\n 'change': bind(opts.change, callbackContext),\n 'show': bind(opts.show, callbackContext),\n 'hide': bind(opts.hide, callbackContext),\n 'beforeShow': bind(opts.beforeShow, callbackContext)\n };\n\n return opts;\n }\n\n function spectrum(element, o) {\n\n var opts = instanceOptions(o, element),\n flat = opts.flat,\n showSelectionPalette = opts.showSelectionPalette,\n localStorageKey = opts.localStorageKey,\n theme = opts.theme,\n callbacks = opts.callbacks,\n resize = throttle(reflow, 10),\n visible = false,\n dragWidth = 0,\n dragHeight = 0,\n dragHelperHeight = 0,\n slideHeight = 0,\n slideWidth = 0,\n alphaWidth = 0,\n alphaSlideHelperWidth = 0,\n slideHelperHeight = 0,\n currentHue = 0,\n currentSaturation = 0,\n currentValue = 0,\n currentAlpha = 1,\n palette = opts.palette.slice(0),\n paletteArray = $.isArray(palette[0]) ? palette : [palette],\n selectionPalette = opts.selectionPalette.slice(0),\n maxSelectionSize = opts.maxSelectionSize,\n draggingClass = \"sp-dragging\",\n shiftMovementDirection = null;\n\n var doc = element.ownerDocument,\n body = doc.body,\n boundElement = $(element),\n disabled = false,\n container = $(markup, doc).addClass(theme),\n dragger = container.find(\".sp-color\"),\n dragHelper = container.find(\".sp-dragger\"),\n slider = container.find(\".sp-hue\"),\n slideHelper = container.find(\".sp-slider\"),\n alphaSliderInner = container.find(\".sp-alpha-inner\"),\n alphaSlider = container.find(\".sp-alpha\"),\n alphaSlideHelper = container.find(\".sp-alpha-handle\"),\n textInput = container.find(\".sp-input\"),\n paletteContainer = container.find(\".sp-palette\"),\n initialColorContainer = container.find(\".sp-initial\"),\n cancelButton = container.find(\".sp-cancel\"),\n chooseButton = container.find(\".sp-choose\"),\n isInput = boundElement.is(\"input\"),\n shouldReplace = isInput && !flat,\n replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className) : $([]),\n offsetElement = (shouldReplace) ? replacer : boundElement,\n previewElement = replacer.find(\".sp-preview-inner\"),\n initialColor = opts.color || (isInput && boundElement.val()),\n colorOnShow = false,\n preferredFormat = opts.preferredFormat,\n currentPreferredFormat = preferredFormat,\n clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange;\n\n\n function applyOptions() {\n\n if (opts.showPaletteOnly) {\n opts.showPalette = true;\n }\n\n container.toggleClass(\"sp-flat\", flat);\n container.toggleClass(\"sp-input-disabled\", !opts.showInput);\n container.toggleClass(\"sp-alpha-enabled\", opts.showAlpha);\n container.toggleClass(\"sp-buttons-disabled\", !opts.showButtons);\n container.toggleClass(\"sp-palette-disabled\", !opts.showPalette);\n container.toggleClass(\"sp-palette-only\", opts.showPaletteOnly);\n container.toggleClass(\"sp-initial-disabled\", !opts.showInitial);\n container.addClass(opts.className);\n\n reflow();\n }\n\n function initialize() {\n\n if (IE) {\n container.find(\"*:not(input)\").attr(\"unselectable\", \"on\");\n }\n\n applyOptions();\n\n if (shouldReplace) {\n boundElement.after(replacer).hide();\n }\n\n if (flat) {\n boundElement.after(container).hide();\n }\n else {\n\n var appendTo = opts.appendTo === \"parent\" ? boundElement.parent() : $(opts.appendTo);\n if (appendTo.length !== 1) {\n appendTo = $(\"body\");\n }\n\n appendTo.append(container);\n }\n\n if (localStorageKey && window.localStorage) {\n\n // Migrate old palettes over to new format. May want to remove this eventually.\n try {\n var oldPalette = window.localStorage[localStorageKey].split(\",#\");\n if (oldPalette.length > 1) {\n delete window.localStorage[localStorageKey];\n $.each(oldPalette, function(i, c) {\n addColorToSelectionPalette(c);\n });\n }\n }\n catch(e) { }\n\n try {\n selectionPalette = window.localStorage[localStorageKey].split(\";\");\n }\n catch (e) { }\n }\n\n offsetElement.bind(\"click.spectrum touchstart.spectrum\", function (e) {\n if (!disabled) {\n toggle();\n }\n\n e.stopPropagation();\n\n if (!$(e.target).is(\"input\")) {\n e.preventDefault();\n }\n });\n\n if(boundElement.is(\":disabled\") || (opts.disabled === true)) {\n disable();\n }\n\n // Prevent clicks from bubbling up to document. This would cause it to be hidden.\n container.click(stopPropagation);\n\n // Handle user typed input\n textInput.change(setFromTextInput);\n textInput.bind(\"paste\", function () {\n setTimeout(setFromTextInput, 1);\n });\n textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });\n\n cancelButton.text(opts.cancelText);\n cancelButton.bind(\"click.spectrum\", function (e) {\n e.stopPropagation();\n e.preventDefault();\n hide(\"cancel\");\n });\n\n chooseButton.text(opts.chooseText);\n chooseButton.bind(\"click.spectrum\", function (e) {\n e.stopPropagation();\n e.preventDefault();\n\n if (isValid()) {\n updateOriginalInput(true);\n hide();\n }\n });\n\n draggable(alphaSlider, function (dragX, dragY, e) {\n currentAlpha = (dragX / alphaWidth);\n if (e.shiftKey) {\n currentAlpha = Math.round(currentAlpha * 10) / 10;\n }\n\n move();\n });\n\n draggable(slider, function (dragX, dragY) {\n currentHue = parseFloat(dragY / slideHeight);\n move();\n }, dragStart, dragStop);\n\n draggable(dragger, function (dragX, dragY, e) {\n\n // shift+drag should snap the movement to either the x or y axis.\n if (!e.shiftKey) {\n shiftMovementDirection = null;\n }\n else if (!shiftMovementDirection) {\n var oldDragX = currentSaturation * dragWidth;\n var oldDragY = dragHeight - (currentValue * dragHeight);\n var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);\n\n shiftMovementDirection = furtherFromX ? \"x\" : \"y\";\n }\n\n var setSaturation = !shiftMovementDirection || shiftMovementDirection === \"x\";\n var setValue = !shiftMovementDirection || shiftMovementDirection === \"y\";\n\n if (setSaturation) {\n currentSaturation = parseFloat(dragX / dragWidth);\n }\n if (setValue) {\n currentValue = parseFloat((dragHeight - dragY) / dragHeight);\n }\n\n move();\n\n }, dragStart, dragStop);\n\n if (!!initialColor) {\n set(initialColor);\n\n // In case color was black - update the preview UI and set the format\n // since the set function will not run (default color is black).\n updateUI();\n currentPreferredFormat = preferredFormat || tinycolor(initialColor).format;\n\n addColorToSelectionPalette(initialColor);\n }\n else {\n updateUI();\n }\n\n if (flat) {\n show();\n }\n\n function palletElementClick(e) {\n if (e.data && e.data.ignore) {\n set($(this).data(\"color\"));\n move();\n }\n else {\n set($(this).data(\"color\"));\n updateOriginalInput(true);\n move();\n hide();\n }\n\n return false;\n }\n\n var paletteEvent = IE ? \"mousedown.spectrum\" : \"click.spectrum touchstart.spectrum\";\n paletteContainer.delegate(\".sp-thumb-el\", paletteEvent, palletElementClick);\n initialColorContainer.delegate(\".sp-thumb-el:nth-child(1)\", paletteEvent, { ignore: true }, palletElementClick);\n }\n\n function addColorToSelectionPalette(color) {\n if (showSelectionPalette) {\n var colorRgb = tinycolor(color).toRgbString();\n if ($.inArray(colorRgb, selectionPalette) === -1) {\n selectionPalette.push(colorRgb);\n while(selectionPalette.length > maxSelectionSize) {\n selectionPalette.shift();\n }\n }\n\n if (localStorageKey && window.localStorage) {\n try {\n window.localStorage[localStorageKey] = selectionPalette.join(\";\");\n }\n catch(e) { }\n }\n }\n }\n\n function getUniqueSelectionPalette() {\n var unique = [];\n var p = selectionPalette;\n var paletteLookup = {};\n var rgb;\n\n if (opts.showPalette) {\n\n for (var i = 0; i < paletteArray.length; i++) {\n for (var j = 0; j < paletteArray[i].length; j++) {\n rgb = tinycolor(paletteArray[i][j]).toRgbString();\n paletteLookup[rgb] = true;\n }\n }\n\n for (i = 0; i < p.length; i++) {\n rgb = tinycolor(p[i]).toRgbString();\n\n if (!paletteLookup.hasOwnProperty(rgb)) {\n unique.push(p[i]);\n paletteLookup[rgb] = true;\n }\n }\n }\n\n return unique.reverse().slice(0, opts.maxSelectionSize);\n }\n\n function drawPalette() {\n\n var currentColor = get();\n\n var html = $.map(paletteArray, function (palette, i) {\n return paletteTemplate(palette, currentColor, \"sp-palette-row sp-palette-row-\" + i);\n });\n\n if (selectionPalette) {\n html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, \"sp-palette-row sp-palette-row-selection\"));\n }\n\n paletteContainer.html(html.join(\"\"));\n }\n\n function drawInitial() {\n if (opts.showInitial) {\n var initial = colorOnShow;\n var current = get();\n initialColorContainer.html(paletteTemplate([initial, current], current, \"sp-palette-row-initial\"));\n }\n }\n\n function dragStart() {\n if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {\n reflow();\n }\n container.addClass(draggingClass);\n shiftMovementDirection = null;\n }\n\n function dragStop() {\n container.removeClass(draggingClass);\n }\n\n function setFromTextInput() {\n var tiny = tinycolor(textInput.val());\n if (tiny.ok) {\n set(tiny);\n }\n else {\n textInput.addClass(\"sp-validation-error\");\n }\n }\n\n function toggle() {\n if (visible) {\n hide();\n }\n else {\n show();\n }\n }\n\n function show() {\n var event = $.Event('beforeShow.spectrum');\n\n if (visible) {\n reflow();\n return;\n }\n\n colorOnShow = get();\n boundElement.trigger(event, [ colorOnShow ]);\n\n if (callbacks.beforeShow(colorOnShow) === false || event.isDefaultPrevented()) {\n return;\n }\n\n // if color has changed\n set(colorOnShow);\n\n hideAll();\n visible = true;\n\n $(doc).bind(\"mousedown.spectrum\", onMousedown);\n\n if (!flat) {\n // Piskel-specific : change the color as soon as the user does a mouseup\n $(doc).bind(\"mouseup.spectrum\", updateColor);\n }\n\n $(window).bind(\"resize.spectrum\", resize);\n replacer.addClass(\"sp-active\");\n container.removeClass(\"sp-hidden\");\n\n if (opts.showPalette) {\n drawPalette();\n }\n reflow();\n updateUI();\n\n drawInitial();\n callbacks.show(colorOnShow);\n boundElement.trigger('show.spectrum', [ colorOnShow ]);\n }\n\n function onMousedown (e) {\n var target = $(e.target);\n var parents = target.parents();\n var isClickOutsideWidget = !parents.is(container) && !target.is(container);\n\n if (isClickOutsideWidget) {\n hide(e);\n }\n }\n\n // Piskel-specific (code extracted to method)\n function updateColor(e) {\n var colorHasChanged = !tinycolor.equals(get(), colorOnShow);\n\n if (colorHasChanged) {\n if (clickoutFiresChange && e !== \"cancel\") {\n updateOriginalInput(true);\n }\n else {\n revert();\n }\n }\n }\n\n function hide(e) {\n\n // Return on right click\n if (e && e.type == \"click\" && e.button == 2) { return; }\n\n // Return if hiding is unnecessary\n if (!visible || flat) { return; }\n visible = false;\n\n $(doc).unbind(\"mousedown.spectrum\", onMousedown);\n\n // Piskel-specific\n $(doc).unbind(\"mouseup.spectrum\", updateColor);\n\n $(window).unbind(\"resize.spectrum\", resize);\n\n replacer.removeClass(\"sp-active\");\n container.addClass(\"sp-hidden\");\n\n updateColor(e);\n\n // Piskel-specific\n addColorToSelectionPalette(get());\n\n callbacks.hide(get());\n boundElement.trigger('hide.spectrum', [ get() ]);\n }\n\n function revert() {\n set(colorOnShow, true);\n }\n\n function set(color, ignoreFormatChange) {\n if (tinycolor.equals(color, get())) {\n return;\n }\n\n var newColor = tinycolor(color);\n var newHsv = newColor.toHsv();\n\n currentHue = (newHsv.h % 360) / 360;\n currentSaturation = newHsv.s;\n currentValue = newHsv.v;\n currentAlpha = newHsv.a;\n\n updateUI();\n\n if (newColor.ok && !ignoreFormatChange) {\n currentPreferredFormat = preferredFormat || newColor.format;\n }\n }\n\n function get(opts) {\n opts = opts || { };\n return tinycolor.fromRatio({\n h: currentHue,\n s: currentSaturation,\n v: currentValue,\n a: Math.round(currentAlpha * 100) / 100\n }, { format: opts.format || currentPreferredFormat });\n }\n\n function isValid() {\n return !textInput.hasClass(\"sp-validation-error\");\n }\n\n function move() {\n updateUI();\n\n callbacks.move(get());\n boundElement.trigger('move.spectrum', [ get() ]);\n }\n\n function updateUI() {\n\n textInput.removeClass(\"sp-validation-error\");\n\n updateHelperLocations();\n\n // Update dragger background color (gradients take care of saturation and value).\n var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });\n dragger.css(\"background-color\", flatColor.toHexString());\n\n // Get a format that alpha will be included in (hex and names ignore alpha)\n var format = currentPreferredFormat;\n if (currentAlpha < 1) {\n if (format === \"hex\" || format === \"hex3\" || format === \"hex6\" || format === \"name\") {\n format = \"rgb\";\n }\n }\n\n var realColor = get({ format: format }),\n realHex = realColor.toHexString(),\n realRgb = realColor.toRgbString();\n\n // Update the replaced elements background color (with actual selected color)\n if (rgbaSupport || realColor.alpha === 1) {\n previewElement.css(\"background-color\", realRgb);\n }\n else {\n previewElement.css(\"background-color\", \"transparent\");\n previewElement.css(\"filter\", realColor.toFilter());\n }\n\n if (opts.showAlpha) {\n var rgb = realColor.toRgb();\n rgb.a = 0;\n var realAlpha = tinycolor(rgb).toRgbString();\n var gradient = \"linear-gradient(left, \" + realAlpha + \", \" + realHex + \")\";\n\n if (IE) {\n alphaSliderInner.css(\"filter\", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));\n }\n else {\n alphaSliderInner.css(\"background\", \"-webkit-\" + gradient);\n alphaSliderInner.css(\"background\", \"-moz-\" + gradient);\n alphaSliderInner.css(\"background\", \"-ms-\" + gradient);\n alphaSliderInner.css(\"background\", gradient);\n }\n }\n\n // Update the text entry input as it changes happen\n if (opts.showInput) {\n var displayFormat = pskl.UserSettings.get(pskl.UserSettings.COLOR_FORMAT);\n textInput.val(realColor.toString(displayFormat));\n }\n\n if (opts.showPalette) {\n drawPalette();\n }\n\n drawInitial();\n }\n\n function updateHelperLocations() {\n var s = currentSaturation;\n var v = currentValue;\n\n // Where to show the little circle in that displays your current selected color\n var dragX = s * dragWidth;\n var dragY = (dragHeight) - (v * dragHeight);\n dragX = Math.max(\n -dragHelperHeight/2,\n Math.min(dragWidth - dragHelperHeight/2, dragX - dragHelperHeight/2)\n );\n dragY = Math.max(\n -dragHelperHeight/2,\n Math.min(dragHeight - dragHelperHeight/2, dragY - dragHelperHeight/2)\n );\n dragHelper.css({\n \"top\": dragY,\n \"left\": dragX\n });\n\n var alphaX = currentAlpha * alphaWidth;\n alphaSlideHelper.css({\n \"left\": alphaX - (alphaSlideHelperWidth / 2)\n });\n\n // Where to show the bar that displays your current selected hue\n var slideY = (currentHue) * slideHeight;\n slideHelper.css({\n \"top\": slideY - (slideHelperHeight/2)\n });\n }\n\n function updateOriginalInput(fireCallback) {\n var color = get();\n\n if (isInput) {\n boundElement.val(color.toString(currentPreferredFormat));\n }\n\n var hasChanged = !tinycolor.equals(color, colorOnShow);\n colorOnShow = color;\n\n // Update the selection palette with the current color\n\n // Piskel-specific : commented-out, palette update is done on hide\n // addColorToSelectionPalette(color);\n\n if (fireCallback && hasChanged) {\n callbacks.change(color);\n boundElement.trigger('change', [ color ]);\n }\n }\n\n function reflow() {\n dragWidth = dragger.width();\n dragHeight = dragger.height();\n dragHelperHeight = dragHelper.height() + 4;\n slideWidth = slider.width();\n slideHeight = slider.height();\n slideHelperHeight = slideHelper.height() + 4;\n alphaWidth = alphaSlider.width();\n alphaSlideHelperWidth = alphaSlideHelper.width();\n\n if (!flat) {\n container.css(\"position\", \"absolute\");\n container.offset(getOffset(container, offsetElement));\n }\n\n updateHelperLocations();\n }\n\n function destroy() {\n boundElement.show();\n offsetElement.unbind(\"click.spectrum touchstart.spectrum\");\n container.remove();\n replacer.remove();\n spectrums[spect.id] = null;\n }\n\n function option(optionName, optionValue) {\n if (optionName === undefined) {\n return $.extend({}, opts);\n }\n if (optionValue === undefined) {\n return opts[optionName];\n }\n\n opts[optionName] = optionValue;\n applyOptions();\n }\n\n function enable() {\n disabled = false;\n boundElement.attr(\"disabled\", false);\n offsetElement.removeClass(\"sp-disabled\");\n }\n\n function disable() {\n hide();\n disabled = true;\n boundElement.attr(\"disabled\", true);\n offsetElement.addClass(\"sp-disabled\");\n }\n\n initialize();\n\n var spect = {\n show: show,\n hide: hide,\n toggle: toggle,\n reflow: reflow,\n option: option,\n enable: enable,\n disable: disable,\n set: function (c) {\n set(c);\n updateOriginalInput();\n },\n get: get,\n destroy: destroy,\n container: container\n };\n\n spect.id = spectrums.push(spect) - 1;\n\n return spect;\n }\n\n /**\n * checkOffset - get the offset below/above and left/right element depending on screen position\n * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js\n */\n function getOffset(picker, input) {\n var extraY = 0;\n var dpWidth = picker.outerWidth();\n var dpHeight = picker.outerHeight();\n var inputHeight = input.outerHeight();\n var doc = picker[0].ownerDocument;\n var docElem = doc.documentElement;\n var viewWidth = docElem.clientWidth + $(doc).scrollLeft();\n var viewHeight = docElem.clientHeight + $(doc).scrollTop();\n var offset = input.offset();\n offset.top += inputHeight;\n\n if (Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth))) {\n offset.left -= Math.abs(offset.left + dpWidth - viewWidth);\n picker.attr('data-x-position','right');\n } else {\n offset.left -= 0;\n picker.attr('data-x-position','left');\n }\n\n if (Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight))) {\n offset.top -= Math.abs(dpHeight + inputHeight - extraY);\n picker.attr('data-y-position','top');\n } else {\n offset.top -= extraY;\n picker.attr('data-y-position','bottom');\n }\n\n return offset;\n }\n\n /**\n * noop - do nothing\n */\n function noop() {\n\n }\n\n /**\n * stopPropagation - makes the code only doing this a little easier to read in line\n */\n function stopPropagation(e) {\n e.stopPropagation();\n }\n\n /**\n * Create a function bound to a given object\n * Thanks to underscore.js\n */\n function bind(func, obj) {\n var slice = Array.prototype.slice;\n var args = slice.call(arguments, 2);\n return function () {\n return func.apply(obj, args.concat(slice.call(arguments)));\n };\n }\n\n /**\n * Lightweight drag helper. Handles containment within the element, so that\n * when dragging, the x is within [0,element.width] and y is within [0,element.height]\n */\n function draggable(element, onmove, onstart, onstop) {\n onmove = onmove || function () { };\n onstart = onstart || function () { };\n onstop = onstop || function () { };\n var doc = element.ownerDocument || document;\n var dragging = false;\n var offset = {};\n var maxHeight = 0;\n var maxWidth = 0;\n var hasTouch = ('ontouchstart' in window);\n\n var duringDragEvents = {};\n duringDragEvents[\"selectstart\"] = prevent;\n duringDragEvents[\"dragstart\"] = prevent;\n duringDragEvents[\"touchmove mousemove\"] = move;\n duringDragEvents[\"touchend mouseup\"] = stop;\n\n function prevent(e) {\n if (e.stopPropagation) {\n e.stopPropagation();\n }\n if (e.preventDefault) {\n e.preventDefault();\n }\n e.returnValue = false;\n }\n\n function move(e) {\n if (dragging) {\n // Mouseup happened outside of window\n if (IE && document.documentMode < 9 && !e.button) {\n return stop();\n }\n\n var touches = e.originalEvent.touches;\n var pageX = touches ? touches[0].pageX : e.pageX;\n var pageY = touches ? touches[0].pageY : e.pageY;\n\n var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));\n var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));\n\n if (hasTouch) {\n // Stop scrolling in iOS\n prevent(e);\n }\n\n onmove.apply(element, [dragX, dragY, e]);\n }\n }\n function start(e) {\n var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);\n var touches = e.originalEvent.touches;\n\n if (!rightclick && !dragging) {\n if (onstart.apply(element, arguments) !== false) {\n dragging = true;\n maxHeight = $(element).height();\n maxWidth = $(element).width();\n offset = $(element).offset();\n\n $(doc).bind(duringDragEvents);\n $(doc.body).addClass(\"sp-dragging\");\n\n if (!hasTouch) {\n move(e);\n }\n\n prevent(e);\n }\n }\n }\n function stop() {\n if (dragging) {\n $(doc).unbind(duringDragEvents);\n $(doc.body).removeClass(\"sp-dragging\");\n onstop.apply(element, arguments);\n }\n dragging = false;\n }\n\n $(element).bind(\"touchstart mousedown\", start);\n }\n\n function throttle(func, wait, debounce) {\n var timeout;\n return function () {\n var context = this, args = arguments;\n var throttler = function () {\n timeout = null;\n func.apply(context, args);\n };\n if (debounce) clearTimeout(timeout);\n if (debounce || !timeout) timeout = setTimeout(throttler, wait);\n };\n }\n\n\n function log(){/* jshint -W021 */if(window.console){if(Function.prototype.bind)log=Function.prototype.bind.call(console.log,console);else log=function(){Function.prototype.apply.call(console.log,console,arguments);};log.apply(this,arguments);}}\n\n /**\n * Define a jQuery plugin\n */\n var dataID = \"spectrum.id\";\n $.fn.spectrum = function (opts, extra) {\n\n if (typeof opts == \"string\") {\n\n var returnValue = this;\n var args = Array.prototype.slice.call( arguments, 1 );\n\n this.each(function () {\n var spect = spectrums[$(this).data(dataID)];\n if (spect) {\n\n var method = spect[opts];\n if (!method) {\n throw new Error( \"Spectrum: no such method: '\" + opts + \"'\" );\n }\n\n if (opts == \"get\") {\n returnValue = spect.get();\n }\n else if (opts == \"container\") {\n returnValue = spect.container;\n }\n else if (opts == \"option\") {\n returnValue = spect.option.apply(spect, args);\n }\n else if (opts == \"destroy\") {\n spect.destroy();\n $(this).removeData(dataID);\n }\n else {\n method.apply(spect, args);\n }\n }\n });\n\n return returnValue;\n }\n\n // Initializing a new instance of spectrum\n return this.spectrum(\"destroy\").each(function () {\n var spect = spectrum(this, opts);\n $(this).data(dataID, spect.id);\n });\n };\n\n $.fn.spectrum.load = true;\n $.fn.spectrum.loadOpts = {};\n $.fn.spectrum.draggable = draggable;\n $.fn.spectrum.defaults = defaultOpts;\n\n $.spectrum = { };\n $.spectrum.localization = { };\n $.spectrum.palettes = { };\n\n $.fn.spectrum.processNativeColorInputs = function () {\n var colorInput = $(\"\")[0];\n var supportsColor = colorInput.type === \"color\" && colorInput.value != \"!\";\n\n if (!supportsColor) {\n $(\"input[type=color]\").spectrum({\n preferredFormat: \"hex6\"\n });\n }\n };\n\n // TinyColor v0.9.16\n // https://github.com/bgrins/TinyColor\n // 2013-08-10, Brian Grinstead, MIT License\n\n (function() {\n\n var trimLeft = /^[\\s,#]+/,\n trimRight = /\\s+$/,\n tinyCounter = 0,\n math = Math,\n mathRound = math.round,\n mathMin = math.min,\n mathMax = math.max,\n mathRandom = math.random;\n\n function tinycolor (color, opts) {\n\n color = (color) ? color : '';\n opts = opts || { };\n\n // If input is already a tinycolor, return itself\n if (typeof color == \"object\" && color.hasOwnProperty(\"_tc_id\")) {\n return color;\n }\n\n var rgb = inputToRGB(color);\n var r = rgb.r,\n g = rgb.g,\n b = rgb.b,\n a = rgb.a,\n roundA = mathRound(100*a) / 100,\n format = opts.format || rgb.format;\n\n // Don't let the range of [0,255] come back in [0,1].\n // Potentially lose a little bit of precision here, but will fix issues where\n // .5 gets interpreted as half of the total, instead of half of 1\n // If it was supposed to be 128, this was already taken care of by `inputToRgb`\n if (r < 1) { r = mathRound(r); }\n if (g < 1) { g = mathRound(g); }\n if (b < 1) { b = mathRound(b); }\n\n return {\n ok: rgb.ok,\n format: format,\n _tc_id: tinyCounter++,\n alpha: a,\n getAlpha: function() {\n return a;\n },\n setAlpha: function(value) {\n a = boundAlpha(value);\n roundA = mathRound(100*a) / 100;\n },\n toHsv: function() {\n var hsv = rgbToHsv(r, g, b);\n return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: a };\n },\n toHsvString: function() {\n var hsv = rgbToHsv(r, g, b);\n var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);\n return (a == 1) ?\n \"hsv(\" + h + \", \" + s + \"%, \" + v + \"%)\" :\n \"hsva(\" + h + \", \" + s + \"%, \" + v + \"%, \"+ roundA + \")\";\n },\n toHsl: function() {\n var hsl = rgbToHsl(r, g, b);\n return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: a };\n },\n toHslString: function() {\n var hsl = rgbToHsl(r, g, b);\n var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);\n return (a == 1) ?\n \"hsl(\" + h + \", \" + s + \"%, \" + l + \"%)\" :\n \"hsla(\" + h + \", \" + s + \"%, \" + l + \"%, \"+ roundA + \")\";\n },\n toHex: function(allow3Char) {\n return rgbToHex(r, g, b, allow3Char);\n },\n toHexString: function(allow3Char) {\n return '#' + rgbToHex(r, g, b, allow3Char);\n },\n toRgb: function() {\n return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a };\n },\n toRgbString: function() {\n return (a == 1) ?\n \"rgb(\" + mathRound(r) + \", \" + mathRound(g) + \", \" + mathRound(b) + \")\" :\n \"rgba(\" + mathRound(r) + \", \" + mathRound(g) + \", \" + mathRound(b) + \", \" + roundA + \")\";\n },\n toPercentageRgb: function() {\n return { r: mathRound(bound01(r, 255) * 100) + \"%\", g: mathRound(bound01(g, 255) * 100) + \"%\", b: mathRound(bound01(b, 255) * 100) + \"%\", a: a };\n },\n toPercentageRgbString: function() {\n return (a == 1) ?\n \"rgb(\" + mathRound(bound01(r, 255) * 100) + \"%, \" + mathRound(bound01(g, 255) * 100) + \"%, \" + mathRound(bound01(b, 255) * 100) + \"%)\" :\n \"rgba(\" + mathRound(bound01(r, 255) * 100) + \"%, \" + mathRound(bound01(g, 255) * 100) + \"%, \" + mathRound(bound01(b, 255) * 100) + \"%, \" + roundA + \")\";\n },\n toName: function() {\n if (a === 0) {\n return \"transparent\";\n }\n\n return hexNames[rgbToHex(r, g, b, true)] || false;\n },\n toFilter: function(secondColor) {\n var hex = rgbToHex(r, g, b);\n var secondHex = hex;\n var alphaHex = Math.round(parseFloat(a) * 255).toString(16);\n var secondAlphaHex = alphaHex;\n var gradientType = opts && opts.gradientType ? \"GradientType = 1, \" : \"\";\n\n if (secondColor) {\n var s = tinycolor(secondColor);\n secondHex = s.toHex();\n secondAlphaHex = Math.round(parseFloat(s.alpha) * 255).toString(16);\n }\n\n return \"progid:DXImageTransform.Microsoft.gradient(\"+gradientType+\"startColorstr=#\" + pad2(alphaHex) + hex + \",endColorstr=#\" + pad2(secondAlphaHex) + secondHex + \")\";\n },\n toString: function(format) {\n var formatSet = !!format;\n format = format || this.format;\n\n var formattedString = false;\n var hasAlphaAndFormatNotSet = !formatSet && a < 1 && a > 0;\n var formatWithAlpha = hasAlphaAndFormatNotSet && (format === \"hex\" || format === \"hex6\" || format === \"hex3\" || format === \"name\");\n\n if (format === \"rgb\") {\n formattedString = this.toRgbString();\n }\n if (format === \"prgb\") {\n formattedString = this.toPercentageRgbString();\n }\n if (format === \"hex\" || format === \"hex6\") {\n formattedString = this.toHexString();\n }\n if (format === \"hex3\") {\n formattedString = this.toHexString(true);\n }\n if (format === \"name\") {\n formattedString = this.toName();\n }\n if (format === \"hsl\") {\n formattedString = this.toHslString();\n }\n if (format === \"hsv\") {\n formattedString = this.toHsvString();\n }\n\n if (formatWithAlpha) {\n return this.toRgbString();\n }\n\n return formattedString || this.toHexString();\n }\n };\n }\n\n // If input is an object, force 1 into \"1.0\" to handle ratios properly\n // String input requires \"1.0\" as input, so 1 will be treated as 1\n tinycolor.fromRatio = function(color, opts) {\n if (typeof color == \"object\") {\n var newColor = {};\n for (var i in color) {\n if (color.hasOwnProperty(i)) {\n if (i === \"a\") {\n newColor[i] = color[i];\n }\n else {\n newColor[i] = convertToPercentage(color[i]);\n }\n }\n }\n color = newColor;\n }\n\n return tinycolor(color, opts);\n };\n\n // Given a string or object, convert that input to RGB\n // Possible string inputs:\n //\n // \"red\"\n // \"#f00\" or \"f00\"\n // \"#ff0000\" or \"ff0000\"\n // \"rgb 255 0 0\" or \"rgb (255, 0, 0)\"\n // \"rgb 1.0 0 0\" or \"rgb (1, 0, 0)\"\n // \"rgba (255, 0, 0, 1)\" or \"rgba 255, 0, 0, 1\"\n // \"rgba (1.0, 0, 0, 1)\" or \"rgba 1.0, 0, 0, 1\"\n // \"hsl(0, 100%, 50%)\" or \"hsl 0 100% 50%\"\n // \"hsla(0, 100%, 50%, 1)\" or \"hsla 0 100% 50%, 1\"\n // \"hsv(0, 100%, 100%)\" or \"hsv 0 100% 100%\"\n //\n function inputToRGB(color) {\n\n var rgb = { r: 0, g: 0, b: 0 };\n var a = 1;\n var ok = false;\n var format = false;\n\n if (typeof color == \"string\") {\n color = stringInputToObject(color);\n }\n\n if (typeof color == \"object\") {\n if (color.hasOwnProperty(\"r\") && color.hasOwnProperty(\"g\") && color.hasOwnProperty(\"b\")) {\n rgb = rgbToRgb(color.r, color.g, color.b);\n ok = true;\n format = String(color.r).substr(-1) === \"%\" ? \"prgb\" : \"rgb\";\n }\n else if (color.hasOwnProperty(\"h\") && color.hasOwnProperty(\"s\") && color.hasOwnProperty(\"v\")) {\n color.s = convertToPercentage(color.s);\n color.v = convertToPercentage(color.v);\n rgb = hsvToRgb(color.h, color.s, color.v);\n ok = true;\n format = \"hsv\";\n }\n else if (color.hasOwnProperty(\"h\") && color.hasOwnProperty(\"s\") && color.hasOwnProperty(\"l\")) {\n color.s = convertToPercentage(color.s);\n color.l = convertToPercentage(color.l);\n rgb = hslToRgb(color.h, color.s, color.l);\n ok = true;\n format = \"hsl\";\n }\n\n if (color.hasOwnProperty(\"a\")) {\n a = color.a;\n }\n }\n\n a = boundAlpha(a);\n\n return {\n ok: ok,\n format: color.format || format,\n r: mathMin(255, mathMax(rgb.r, 0)),\n g: mathMin(255, mathMax(rgb.g, 0)),\n b: mathMin(255, mathMax(rgb.b, 0)),\n a: a\n };\n }\n\n\n // Conversion Functions\n // --------------------\n\n // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:\n // \n\n // `rgbToRgb`\n // Handle bounds / percentage checking to conform to CSS color spec\n // \n // *Assumes:* r, g, b in [0, 255] or [0, 1]\n // *Returns:* { r, g, b } in [0, 255]\n function rgbToRgb(r, g, b){\n return {\n r: bound01(r, 255) * 255,\n g: bound01(g, 255) * 255,\n b: bound01(b, 255) * 255\n };\n }\n\n // `rgbToHsl`\n // Converts an RGB color value to HSL.\n // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]\n // *Returns:* { h, s, l } in [0,1]\n function rgbToHsl(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, l = (max + min) / 2;\n\n if(max == min) {\n h = s = 0; // achromatic\n }\n else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n\n h /= 6;\n }\n\n return { h: h, s: s, l: l };\n }\n\n // `hslToRgb`\n // Converts an HSL color value to RGB.\n // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]\n // *Returns:* { r, g, b } in the set [0, 255]\n function hslToRgb(h, s, l) {\n var r, g, b;\n\n h = bound01(h, 360);\n s = bound01(s, 100);\n l = bound01(l, 100);\n\n function hue2rgb(p, q, t) {\n if(t < 0) t += 1;\n if(t > 1) t -= 1;\n if(t < 1/6) return p + (q - p) * 6 * t;\n if(t < 1/2) return q;\n if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;\n return p;\n }\n\n if(s === 0) {\n r = g = b = l; // achromatic\n }\n else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1/3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1/3);\n }\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n }\n\n // `rgbToHsv`\n // Converts an RGB color value to HSV\n // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]\n // *Returns:* { h, s, v } in [0,1]\n function rgbToHsv(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, v = max;\n\n var d = max - min;\n s = max === 0 ? 0 : d / max;\n\n if(max == min) {\n h = 0; // achromatic\n }\n else {\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n h /= 6;\n }\n return { h: h, s: s, v: v };\n }\n\n // `hsvToRgb`\n // Converts an HSV color value to RGB.\n // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]\n // *Returns:* { r, g, b } in the set [0, 255]\n function hsvToRgb(h, s, v) {\n\n h = bound01(h, 360) * 6;\n s = bound01(s, 100);\n v = bound01(v, 100);\n\n var i = math.floor(h),\n f = h - i,\n p = v * (1 - s),\n q = v * (1 - f * s),\n t = v * (1 - (1 - f) * s),\n mod = i % 6,\n r = [v, q, p, p, t, v][mod],\n g = [t, v, v, q, p, p][mod],\n b = [p, p, t, v, v, q][mod];\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n }\n\n // `rgbToHex`\n // Converts an RGB color to hex\n // Assumes r, g, and b are contained in the set [0, 255]\n // Returns a 3 or 6 character hex\n function rgbToHex(r, g, b, allow3Char) {\n\n var hex = [\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16))\n ];\n\n // Return a 3 character hex if possible\n if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);\n }\n\n return hex.join(\"\");\n }\n\n // `equals`\n // Can be called with any tinycolor input\n tinycolor.equals = function (color1, color2) {\n if (!color1 || !color2) { return false; }\n return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();\n };\n tinycolor.random = function() {\n return tinycolor.fromRatio({\n r: mathRandom(),\n g: mathRandom(),\n b: mathRandom()\n });\n };\n\n\n // Modification Functions\n // ----------------------\n // Thanks to less.js for some of the basics here\n // \n\n tinycolor.desaturate = function (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s -= amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n };\n tinycolor.saturate = function (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s += amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n };\n tinycolor.greyscale = function(color) {\n return tinycolor.desaturate(color, 100);\n };\n tinycolor.lighten = function(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l += amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n };\n tinycolor.darken = function (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l -= amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n };\n tinycolor.complement = function(color) {\n var hsl = tinycolor(color).toHsl();\n hsl.h = (hsl.h + 180) % 360;\n return tinycolor(hsl);\n };\n\n\n // Combination Functions\n // ---------------------\n // Thanks to jQuery xColor for some of the ideas behind these\n // \n\n tinycolor.triad = function(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })\n ];\n };\n tinycolor.tetrad = function(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })\n ];\n };\n tinycolor.splitcomplement = function(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),\n tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})\n ];\n };\n tinycolor.analogous = function(color, results, slices) {\n results = results || 6;\n slices = slices || 30;\n\n var hsl = tinycolor(color).toHsl();\n var part = 360 / slices;\n var ret = [tinycolor(color)];\n\n for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {\n hsl.h = (hsl.h + part) % 360;\n ret.push(tinycolor(hsl));\n }\n return ret;\n };\n tinycolor.monochromatic = function(color, results) {\n results = results || 6;\n var hsv = tinycolor(color).toHsv();\n var h = hsv.h, s = hsv.s, v = hsv.v;\n var ret = [];\n var modification = 1 / results;\n\n while (results--) {\n ret.push(tinycolor({ h: h, s: s, v: v}));\n v = (v + modification) % 1;\n }\n\n return ret;\n };\n\n\n // Readability Functions\n // ---------------------\n // \n\n // `readability`\n // Analyze the 2 colors and returns an object with the following properties:\n // `brightness`: difference in brightness between the two colors\n // `color`: difference in color/hue between the two colors\n tinycolor.readability = function(color1, color2) {\n var a = tinycolor(color1).toRgb();\n var b = tinycolor(color2).toRgb();\n var brightnessA = (a.r * 299 + a.g * 587 + a.b * 114) / 1000;\n var brightnessB = (b.r * 299 + b.g * 587 + b.b * 114) / 1000;\n var colorDiff = (\n Math.max(a.r, b.r) - Math.min(a.r, b.r) +\n Math.max(a.g, b.g) - Math.min(a.g, b.g) +\n Math.max(a.b, b.b) - Math.min(a.b, b.b)\n );\n\n return {\n brightness: Math.abs(brightnessA - brightnessB),\n color: colorDiff\n };\n };\n\n // `readable`\n // http://www.w3.org/TR/AERT#color-contrast\n // Ensure that foreground and background color combinations provide sufficient contrast.\n // *Example*\n // tinycolor.readable(\"#000\", \"#111\") => false\n tinycolor.readable = function(color1, color2) {\n var readability = tinycolor.readability(color1, color2);\n return readability.brightness > 125 && readability.color > 500;\n };\n\n // `mostReadable`\n // Given a base color and a list of possible foreground or background\n // colors for that base, returns the most readable color.\n // *Example*\n // tinycolor.mostReadable(\"#123\", [\"#fff\", \"#000\"]) => \"#000\"\n tinycolor.mostReadable = function(baseColor, colorList) {\n var bestColor = null;\n var bestScore = 0;\n var bestIsReadable = false;\n for (var i=0; i < colorList.length; i++) {\n\n // We normalize both around the \"acceptable\" breaking point,\n // but rank brightness constrast higher than hue.\n\n var readability = tinycolor.readability(baseColor, colorList[i]);\n var readable = readability.brightness > 125 && readability.color > 500;\n var score = 3 * (readability.brightness / 125) + (readability.color / 500);\n\n if ((readable && ! bestIsReadable) ||\n (readable && bestIsReadable && score > bestScore) ||\n ((! readable) && (! bestIsReadable) && score > bestScore)) {\n bestIsReadable = readable;\n bestScore = score;\n bestColor = tinycolor(colorList[i]);\n }\n }\n return bestColor;\n };\n\n\n // Big List of Colors\n // ------------------\n // \n var names = tinycolor.names = {\n aliceblue: \"f0f8ff\",\n antiquewhite: \"faebd7\",\n aqua: \"0ff\",\n aquamarine: \"7fffd4\",\n azure: \"f0ffff\",\n beige: \"f5f5dc\",\n bisque: \"ffe4c4\",\n black: \"000\",\n blanchedalmond: \"ffebcd\",\n blue: \"00f\",\n blueviolet: \"8a2be2\",\n brown: \"a52a2a\",\n burlywood: \"deb887\",\n burntsienna: \"ea7e5d\",\n cadetblue: \"5f9ea0\",\n chartreuse: \"7fff00\",\n chocolate: \"d2691e\",\n coral: \"ff7f50\",\n cornflowerblue: \"6495ed\",\n cornsilk: \"fff8dc\",\n crimson: \"dc143c\",\n cyan: \"0ff\",\n darkblue: \"00008b\",\n darkcyan: \"008b8b\",\n darkgoldenrod: \"b8860b\",\n darkgray: \"a9a9a9\",\n darkgreen: \"006400\",\n darkgrey: \"a9a9a9\",\n darkkhaki: \"bdb76b\",\n darkmagenta: \"8b008b\",\n darkolivegreen: \"556b2f\",\n darkorange: \"ff8c00\",\n darkorchid: \"9932cc\",\n darkred: \"8b0000\",\n darksalmon: \"e9967a\",\n darkseagreen: \"8fbc8f\",\n darkslateblue: \"483d8b\",\n darkslategray: \"2f4f4f\",\n darkslategrey: \"2f4f4f\",\n darkturquoise: \"00ced1\",\n darkviolet: \"9400d3\",\n deeppink: \"ff1493\",\n deepskyblue: \"00bfff\",\n dimgray: \"696969\",\n dimgrey: \"696969\",\n dodgerblue: \"1e90ff\",\n firebrick: \"b22222\",\n floralwhite: \"fffaf0\",\n forestgreen: \"228b22\",\n fuchsia: \"f0f\",\n gainsboro: \"dcdcdc\",\n ghostwhite: \"f8f8ff\",\n gold: \"ffd700\",\n goldenrod: \"daa520\",\n gray: \"808080\",\n green: \"008000\",\n greenyellow: \"adff2f\",\n grey: \"808080\",\n honeydew: \"f0fff0\",\n hotpink: \"ff69b4\",\n indianred: \"cd5c5c\",\n indigo: \"4b0082\",\n ivory: \"fffff0\",\n khaki: \"f0e68c\",\n lavender: \"e6e6fa\",\n lavenderblush: \"fff0f5\",\n lawngreen: \"7cfc00\",\n lemonchiffon: \"fffacd\",\n lightblue: \"add8e6\",\n lightcoral: \"f08080\",\n lightcyan: \"e0ffff\",\n lightgoldenrodyellow: \"fafad2\",\n lightgray: \"d3d3d3\",\n lightgreen: \"90ee90\",\n lightgrey: \"d3d3d3\",\n lightpink: \"ffb6c1\",\n lightsalmon: \"ffa07a\",\n lightseagreen: \"20b2aa\",\n lightskyblue: \"87cefa\",\n lightslategray: \"789\",\n lightslategrey: \"789\",\n lightsteelblue: \"b0c4de\",\n lightyellow: \"ffffe0\",\n lime: \"0f0\",\n limegreen: \"32cd32\",\n linen: \"faf0e6\",\n magenta: \"f0f\",\n maroon: \"800000\",\n mediumaquamarine: \"66cdaa\",\n mediumblue: \"0000cd\",\n mediumorchid: \"ba55d3\",\n mediumpurple: \"9370db\",\n mediumseagreen: \"3cb371\",\n mediumslateblue: \"7b68ee\",\n mediumspringgreen: \"00fa9a\",\n mediumturquoise: \"48d1cc\",\n mediumvioletred: \"c71585\",\n midnightblue: \"191970\",\n mintcream: \"f5fffa\",\n mistyrose: \"ffe4e1\",\n moccasin: \"ffe4b5\",\n navajowhite: \"ffdead\",\n navy: \"000080\",\n oldlace: \"fdf5e6\",\n olive: \"808000\",\n olivedrab: \"6b8e23\",\n orange: \"ffa500\",\n orangered: \"ff4500\",\n orchid: \"da70d6\",\n palegoldenrod: \"eee8aa\",\n palegreen: \"98fb98\",\n paleturquoise: \"afeeee\",\n palevioletred: \"db7093\",\n papayawhip: \"ffefd5\",\n peachpuff: \"ffdab9\",\n peru: \"cd853f\",\n pink: \"ffc0cb\",\n plum: \"dda0dd\",\n powderblue: \"b0e0e6\",\n purple: \"800080\",\n red: \"f00\",\n rosybrown: \"bc8f8f\",\n royalblue: \"4169e1\",\n saddlebrown: \"8b4513\",\n salmon: \"fa8072\",\n sandybrown: \"f4a460\",\n seagreen: \"2e8b57\",\n seashell: \"fff5ee\",\n sienna: \"a0522d\",\n silver: \"c0c0c0\",\n skyblue: \"87ceeb\",\n slateblue: \"6a5acd\",\n slategray: \"708090\",\n slategrey: \"708090\",\n snow: \"fffafa\",\n springgreen: \"00ff7f\",\n steelblue: \"4682b4\",\n tan: \"d2b48c\",\n teal: \"008080\",\n thistle: \"d8bfd8\",\n tomato: \"ff6347\",\n turquoise: \"40e0d0\",\n violet: \"ee82ee\",\n wheat: \"f5deb3\",\n white: \"fff\",\n whitesmoke: \"f5f5f5\",\n yellow: \"ff0\",\n yellowgreen: \"9acd32\"\n };\n\n // Make it easy to access colors via `hexNames[hex]`\n var hexNames = tinycolor.hexNames = flip(names);\n\n\n // Utilities\n // ---------\n\n // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`\n function flip(o) {\n var flipped = { };\n for (var i in o) {\n if (o.hasOwnProperty(i)) {\n flipped[o[i]] = i;\n }\n }\n return flipped;\n }\n\n // Return a valid alpha value [0,1] with all invalid values being set to 1\n function boundAlpha(a) {\n a = parseFloat(a);\n\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n\n return a;\n }\n\n // Take input from [0, n] and return it as [0, 1]\n function bound01(n, max) {\n if (isOnePointZero(n)) { n = \"100%\"; }\n\n var processPercent = isPercentage(n);\n n = mathMin(max, mathMax(0, parseFloat(n)));\n\n // Automatically convert percentage into number\n if (processPercent) {\n n = parseInt(n * max, 10) / 100;\n }\n\n // Handle floating point rounding errors\n if ((math.abs(n - max) < 0.000001)) {\n return 1;\n }\n\n // Convert into [0, 1] range if it isn't already\n return (n % max) / parseFloat(max);\n }\n\n // Force a number between 0 and 1\n function clamp01(val) {\n return mathMin(1, mathMax(0, val));\n }\n\n // Parse an integer into hex\n function parseHex(val) {\n return parseInt(val, 16);\n }\n\n // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1\n // \n function isOnePointZero(n) {\n return typeof n == \"string\" && n.indexOf('.') != -1 && parseFloat(n) === 1;\n }\n\n // Check to see if string passed in is a percentage\n function isPercentage(n) {\n return typeof n === \"string\" && n.indexOf('%') != -1;\n }\n\n // Force a hex value to have 2 characters\n function pad2(c) {\n return c.length == 1 ? '0' + c : '' + c;\n }\n\n // Replace a decimal with it's percentage value\n function convertToPercentage(n) {\n if (n <= 1) {\n n = (n * 100) + \"%\";\n }\n\n return n;\n }\n\n var matchers = (function() {\n\n // \n var CSS_INTEGER = \"[-\\\\+]?\\\\d+%?\";\n\n // \n var CSS_NUMBER = \"[-\\\\+]?\\\\d*\\\\.\\\\d+%?\";\n\n // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.\n var CSS_UNIT = \"(?:\" + CSS_NUMBER + \")|(?:\" + CSS_INTEGER + \")\";\n\n // Actual matching.\n // Parentheses and commas are optional, but not required.\n // Whitespace can take the place of commas or opening paren\n var PERMISSIVE_MATCH3 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n var PERMISSIVE_MATCH4 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n\n return {\n rgb: new RegExp(\"rgb\" + PERMISSIVE_MATCH3),\n rgba: new RegExp(\"rgba\" + PERMISSIVE_MATCH4),\n hsl: new RegExp(\"hsl\" + PERMISSIVE_MATCH3),\n hsla: new RegExp(\"hsla\" + PERMISSIVE_MATCH4),\n hsv: new RegExp(\"hsv\" + PERMISSIVE_MATCH3),\n hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/\n };\n })();\n\n // `stringInputToObject`\n // Permissive string parsing. Take in a number of formats, and output an object\n // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`\n function stringInputToObject(color) {\n\n color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();\n var named = false;\n if (names[color]) {\n color = names[color];\n named = true;\n }\n else if (color == 'transparent') {\n return { r: 0, g: 0, b: 0, a: 0, format: \"name\" };\n }\n\n // Try to match string input using regular expressions.\n // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]\n // Just return an object and let the conversion functions handle that.\n // This way the result will be the same whether the tinycolor is initialized with string or object.\n var match;\n if ((match = matchers.rgb.exec(color))) {\n return { r: match[1], g: match[2], b: match[3] };\n }\n if ((match = matchers.rgba.exec(color))) {\n return { r: match[1], g: match[2], b: match[3], a: match[4] };\n }\n if ((match = matchers.hsl.exec(color))) {\n return { h: match[1], s: match[2], l: match[3] };\n }\n if ((match = matchers.hsla.exec(color))) {\n return { h: match[1], s: match[2], l: match[3], a: match[4] };\n }\n if ((match = matchers.hsv.exec(color))) {\n return { h: match[1], s: match[2], v: match[3] };\n }\n if ((match = matchers.hex6.exec(color))) {\n return {\n r: parseHex(match[1]),\n g: parseHex(match[2]),\n b: parseHex(match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n if ((match = matchers.hex3.exec(color))) {\n return {\n r: parseHex(match[1] + '' + match[1]),\n g: parseHex(match[2] + '' + match[2]),\n b: parseHex(match[3] + '' + match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n\n return false;\n }\n\n // Expose tinycolor to window, does not need to run in non-browser context.\n window.tinycolor = tinycolor;\n\n })();\n var tinycolor = window.tinycolor;\n\n $(function () {\n if ($.fn.spectrum.load) {\n $.fn.spectrum.processNativeColorInputs();\n }\n });\n\n})(window, jQuery);\n","// vim:ts=4:sts=4:sw=4:\n/*!\n *\n * Copyright 2009-2012 Kris Kowal under the terms of the MIT\n * license found at http://github.com/kriskowal/q/raw/master/LICENSE\n *\n * With parts by Tyler Close\n * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found\n * at http://www.opensource.org/licenses/mit-license.html\n * Forked at ref_send.js version: 2009-05-11\n *\n * With parts by Mark Miller\n * Copyright (C) 2011 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n(function (definition) {\n \"use strict\";\n\n // This file will function properly as a \n\n Image tag attributes:\n\n data-animated-src - If this url is specified, it's loaded into the player instead of src.\n This allows a preview frame to be shown until animated gif data is streamed into the canvas\n\n Constructor options args\n\n gif Required. The DOM element of an img tag.\n\n Instance methods\n\n // loading\n load( callback ) Loads the gif into a canvas element and then calls callback if one is passed\n\n For additional customization (viewport inside iframe) these params may be passed:\n c_w, c_h - width and height of canvas\n vp_t, vp_l, vp_ w, vp_h - top, left, width and height of the viewport\n\n A bonus: few articles to understand what is going on\n http://enthusiasms.org/post/16976438906\n http://www.matthewflickinger.com/lab/whatsinagif/bits_and_bytes.asp\n http://humpy77.deviantart.com/journal/Frame-Delay-Times-for-Animated-GIFs-214150546\n\n*/\n\n( function( window ) { 'use strict';\n\n// Generic functions\nvar bitsToNum = function (ba) {\n return ba.reduce(function (s, n) {\n return s * 2 + n;\n }, 0);\n};\n\nvar byteToBitArr = function (bite) {\n var a = [];\n for (var i = 7; i >= 0; i--) {\n a.push( !! (bite & (1 << i)));\n }\n return a;\n};\n\n// Stream\n/**\n * @constructor\n */\n// Make compiler happy.\nvar Stream = function (data) {\n this.data = data;\n this.len = this.data.length;\n this.pos = 0;\n\n this.readByte = function () {\n if (this.pos >= this.data.length) {\n throw new Error('Attempted to read past end of stream.');\n }\n return data.charCodeAt(this.pos++) & 0xFF;\n };\n\n this.readBytes = function (n) {\n var bytes = [];\n for (var i = 0; i < n; i++) {\n bytes.push(this.readByte());\n }\n return bytes;\n };\n\n this.read = function (n) {\n var s = '';\n for (var i = 0; i < n; i++) {\n s += String.fromCharCode(this.readByte());\n }\n return s;\n };\n\n this.readUnsigned = function () { // Little-endian.\n var a = this.readBytes(2);\n return (a[1] << 8) + a[0];\n };\n};\n\nvar lzwDecode = function (minCodeSize, data) {\n // TODO: Now that the GIF parser is a bit different, maybe this should get an array of bytes instead of a String?\n var pos = 0; // Maybe this streaming thing should be merged with the Stream?\n var readCode = function (size) {\n var code = 0;\n for (var i = 0; i < size; i++) {\n if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) {\n code |= 1 << i;\n }\n pos++;\n }\n return code;\n };\n\n var output = [];\n\n var clearCode = 1 << minCodeSize;\n var eoiCode = clearCode + 1;\n\n var codeSize = minCodeSize + 1;\n\n var dict = [];\n\n var clear = function () {\n dict = [];\n codeSize = minCodeSize + 1;\n for (var i = 0; i < clearCode; i++) {\n dict[i] = [i];\n }\n dict[clearCode] = [];\n dict[eoiCode] = null;\n\n };\n\n var code;\n var last;\n\n while (true) {\n last = code;\n code = readCode(codeSize);\n\n if (code === clearCode) {\n clear();\n continue;\n }\n if (code === eoiCode) break;\n\n if (code < dict.length) {\n if (last !== clearCode) {\n dict.push(dict[last].concat(dict[code][0]));\n }\n }\n else {\n if (code !== dict.length) throw new Error('Invalid LZW code.');\n dict.push(dict[last].concat(dict[last][0]));\n }\n output.push.apply(output, dict[code]);\n\n if (dict.length === (1 << codeSize) && codeSize < 12) {\n // If we're at the last code and codeSize is 12, the next code will be a clearCode, and it'll be 12 bits long.\n codeSize++;\n }\n }\n\n // I don't know if this is technically an error, but some GIFs do it.\n //if (Math.ceil(pos / 8) !== data.length) throw new Error('Extraneous LZW bytes.');\n return output;\n};\n\n\n// The actual parsing; returns an object with properties.\nvar parseGIF = function (st, handler) {\n handler || (handler = {});\n\n // LZW (GIF-specific)\n var parseCT = function (entries) { // Each entry is 3 bytes, for RGB.\n var ct = [];\n for (var i = 0; i < entries; i++) {\n ct.push(st.readBytes(3));\n }\n return ct;\n };\n\n var readSubBlocks = function () {\n var size, data;\n data = '';\n do {\n size = st.readByte();\n data += st.read(size);\n } while (size !== 0);\n return data;\n };\n\n var parseHeader = function () {\n var hdr = {};\n hdr.sig = st.read(3);\n hdr.ver = st.read(3);\n if (hdr.sig !== 'GIF') {\n handler.onError(); // XXX: This should probably be handled more nicely.\n throw new Error('Not a GIF file.');\n }\n hdr.width = st.readUnsigned();\n hdr.height = st.readUnsigned();\n\n var bits = byteToBitArr(st.readByte());\n hdr.gctFlag = bits.shift();\n hdr.colorRes = bitsToNum(bits.splice(0, 3));\n hdr.sorted = bits.shift();\n hdr.gctSize = bitsToNum(bits.splice(0, 3));\n\n hdr.bgColor = st.readByte();\n hdr.pixelAspectRatio = st.readByte(); // if not 0, aspectRatio = (pixelAspectRatio + 15) / 64\n if (hdr.gctFlag) {\n hdr.gct = parseCT(1 << (hdr.gctSize + 1));\n }\n handler.hdr && handler.hdr(hdr);\n };\n\n var parseExt = function (block) {\n var parseGCExt = function (block) {\n var blockSize = st.readByte(); // Always 4\n var bits = byteToBitArr(st.readByte());\n block.reserved = bits.splice(0, 3); // Reserved; should be 000.\n block.disposalMethod = bitsToNum(bits.splice(0, 3));\n block.userInput = bits.shift();\n block.transparencyGiven = bits.shift();\n\n block.delayTime = st.readUnsigned();\n\n block.transparencyIndex = st.readByte();\n\n block.terminator = st.readByte();\n\n handler.gce && handler.gce(block);\n };\n\n var parseComExt = function (block) {\n block.comment = readSubBlocks();\n handler.com && handler.com(block);\n };\n\n var parsePTExt = function (block) {\n // No one *ever* uses this. If you use it, deal with parsing it yourself.\n var blockSize = st.readByte(); // Always 12\n block.ptHeader = st.readBytes(12);\n block.ptData = readSubBlocks();\n handler.pte && handler.pte(block);\n };\n\n var parseAppExt = function (block) {\n var parseNetscapeExt = function (block) {\n var blockSize = st.readByte(); // Always 3\n block.unknown = st.readByte(); // ??? Always 1? What is this?\n block.iterations = st.readUnsigned();\n block.terminator = st.readByte();\n handler.app && handler.app.NETSCAPE && handler.app.NETSCAPE(block);\n };\n\n var parseUnknownAppExt = function (block) {\n block.appData = readSubBlocks();\n // FIXME: This won't work if a handler wants to match on any identifier.\n handler.app && handler.app[block.identifier] && handler.app[block.identifier](block);\n };\n\n var blockSize = st.readByte(); // Always 11\n block.identifier = st.read(8);\n block.authCode = st.read(3);\n switch (block.identifier) {\n case 'NETSCAPE':\n parseNetscapeExt(block);\n break;\n default:\n parseUnknownAppExt(block);\n break;\n }\n };\n\n var parseUnknownExt = function (block) {\n block.data = readSubBlocks();\n handler.unknown && handler.unknown(block);\n };\n\n block.label = st.readByte();\n switch (block.label) {\n case 0xF9:\n block.extType = 'gce';\n parseGCExt(block);\n break;\n case 0xFE:\n block.extType = 'com';\n parseComExt(block);\n break;\n case 0x01:\n block.extType = 'pte';\n parsePTExt(block);\n break;\n case 0xFF:\n block.extType = 'app';\n parseAppExt(block);\n break;\n default:\n block.extType = 'unknown';\n parseUnknownExt(block);\n break;\n }\n };\n\n var parseImg = function (img) {\n var deinterlace = function (pixels, width) {\n // Of course this defeats the purpose of interlacing. And it's *probably*\n // the least efficient way it's ever been implemented. But nevertheless...\n var newPixels = new Array(pixels.length);\n var rows = pixels.length / width;\n var cpRow = function (toRow, fromRow) {\n var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);\n newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));\n };\n\n // See appendix E.\n var offsets = [0, 4, 2, 1];\n var steps = [8, 8, 4, 2];\n\n var fromRow = 0;\n for (var pass = 0; pass < 4; pass++) {\n for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {\n cpRow(toRow, fromRow)\n fromRow++;\n }\n }\n\n return newPixels;\n };\n\n img.leftPos = st.readUnsigned();\n img.topPos = st.readUnsigned();\n img.width = st.readUnsigned();\n img.height = st.readUnsigned();\n\n var bits = byteToBitArr(st.readByte());\n img.lctFlag = bits.shift();\n img.interlaced = bits.shift();\n img.sorted = bits.shift();\n img.reserved = bits.splice(0, 2);\n img.lctSize = bitsToNum(bits.splice(0, 3));\n\n if (img.lctFlag) {\n img.lct = parseCT(1 << (img.lctSize + 1));\n }\n\n img.lzwMinCodeSize = st.readByte();\n\n var lzwData = readSubBlocks();\n\n img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData);\n\n if (img.interlaced) { // Move\n img.pixels = deinterlace(img.pixels, img.width);\n }\n\n handler.img && handler.img(img);\n };\n\n var parseBlock = function () {\n var block = {};\n block.sentinel = st.readByte();\n\n switch (String.fromCharCode(block.sentinel)) { // For ease of matching\n case '!':\n block.type = 'ext';\n parseExt(block);\n break;\n case ',':\n block.type = 'img';\n parseImg(block);\n break;\n case ';':\n block.type = 'eof';\n handler.eof && handler.eof(block);\n break;\n default:\n return handler.onError(new Error('Unknown block: 0x' + block.sentinel.toString(16))); // TODO: Pad this with a 0.\n }\n\n if (block.type !== 'eof') {\n setTimeout(parseBlock, 0);\n }\n };\n\n var parse = function () {\n parseHeader();\n setTimeout(parseBlock, 0);\n };\n\n parse();\n};\n\n\nvar SuperGif = function ( opts ) {\n var options = {\n //viewport position\n vp_l: 0,\n vp_t: 0,\n vp_w: null,\n vp_h: null,\n //canvas sizes\n c_w: null,\n c_h: null\n };\n for (var i in opts ) { options[i] = opts[i] }\n if (options.vp_w && options.vp_h) options.is_vp = true;\n\n var stream;\n var hdr;\n\n var loadError = null;\n var loading = false;\n\n var transparency = null;\n var delay = null;\n var disposalMethod = null;\n var disposalRestoreFromIdx = 0;\n var lastDisposalMethod = null;\n var frame = null;\n var lastImg = null;\n\n var frames = [];\n\n var gif = options.gif;\n\n var clear = function () {\n transparency = null;\n delay = null;\n lastDisposalMethod = disposalMethod;\n disposalMethod = null;\n frame = null;\n };\n\n // XXX: There's probably a better way to handle catching exceptions when\n // callbacks are involved.\n var doParse = function () {\n try {\n parseGIF(stream, handler);\n }\n catch (err) {\n doLoadError('parse');\n }\n };\n\n var setSizes = function(w, h) {\n tmpCanvas.width = w;\n tmpCanvas.height = h;\n tmpCanvas.getContext('2d').setTransform(1, 0, 0, 1, 0, 0);\n }\n\n var doLoadError = function (originOfError) {\n\n\n loadError = originOfError;\n hdr = {\n width: gif.width,\n height: gif.height\n }; // Fake header.\n frames = [];\n };\n\n var doHdr = function (_hdr) {\n hdr = _hdr;\n setSizes(hdr.width, hdr.height)\n };\n\n var doGCE = function (gce) {\n pushFrame();\n clear();\n transparency = gce.transparencyGiven ? gce.transparencyIndex : null;\n delay = gce.delayTime;\n disposalMethod = gce.disposalMethod;\n // We don't have much to do with the rest of GCE.\n };\n\n var pushFrame = function () {\n if (!frame) return;\n frames.push({\n data: frame.getImageData(0, 0, hdr.width, hdr.height),\n delay: delay\n });\n };\n\n // flag for drawing initial frame\n var isInitFrameDrawn = false;\n\n var doImg = function (img) {\n if (!frame) frame = tmpCanvas.getContext('2d');\n\n var currIdx = frames.length;\n\n //ct = color table, gct = global color table\n var ct = img.lctFlag ? img.lct : hdr.gct; // TODO: What if neither exists?\n\n /*\n Disposal method indicates the way in which the graphic is to\n be treated after being displayed.\n\n Values : 0 - No disposal specified. The decoder is\n not required to take any action.\n 1 - Do not dispose. The graphic is to be left\n in place.\n 2 - Restore to background color. The area used by the\n graphic must be restored to the background color.\n 3 - Restore to previous. The decoder is required to\n restore the area overwritten by the graphic with\n what was there prior to rendering the graphic.\n\n Importantly, \"previous\" means the frame state\n after the last disposal of method 0, 1, or 2.\n */\n if (currIdx > 0) {\n if (lastDisposalMethod === 3) {\n // Restore to previous\n frame.putImageData(frames[disposalRestoreFromIdx].data, 0, 0);\n } else {\n disposalRestoreFromIdx = currIdx - 1;\n }\n\n if (lastDisposalMethod === 2) {\n // Restore to background color\n // Browser implementations historically restore to transparent; we do the same.\n // http://www.wizards-toolkit.org/discourse-server/viewtopic.php?f=1&t=21172#p86079\n frame.clearRect(lastImg.leftPos, lastImg.topPos, lastImg.width, lastImg.height);\n }\n }\n // else, Undefined/Do not dispose.\n // frame contains final pixel data from the last frame; do nothing\n\n //Get existing pixels for img region after applying disposal method\n var imgData = frame.getImageData(img.leftPos, img.topPos, img.width, img.height);\n //apply color table colors\n var cdd = imgData.data;\n img.pixels.forEach(function (pixel, i) {\n // imgData.data === [R,G,B,A,R,G,B,A,...]\n if (pixel !== transparency) {\n cdd[i * 4 + 0] = ct[pixel][0];\n cdd[i * 4 + 1] = ct[pixel][1];\n cdd[i * 4 + 2] = ct[pixel][2];\n cdd[i * 4 + 3] = 255; // Opaque.\n }\n });\n\n frame.putImageData(imgData, img.leftPos, img.topPos);\n\n lastImg = img;\n };\n\n var doNothing = function () {};\n /**\n * @param{boolean=} draw Whether to draw progress bar or not; this is not idempotent because of translucency.\n * Note that this means that the text will be unsynchronized with the progress bar on non-frames;\n * but those are typically so small (GCE etc.) that it doesn't really matter. TODO: Do this properly.\n */\n var handler = {\n hdr: doHdr,\n gce: doGCE,\n // I guess that's all for now.\n // app: {\n // // TODO: Is there much point in actually supporting iterations?\n // NETSCAPE: withProgress(doNothing)\n // },\n img: doImg,\n eof: function (block) {\n pushFrame();\n loading = false;\n if (load_callback) {\n load_callback();\n }\n },\n\n onError : function (error) {\n if (error_callback) {\n error_callback();\n }\n }\n };\n\n var load_callback = false;\n var step_callback = false;\n var error_callback = false;\n var tmpCanvas = document.createElement('canvas');\n\n return {\n\n load: function (callback) {\n\n load_callback = callback.success;\n step_callback = callback.step;\n error_callback = callback.error;\n\n loading = true;\n\n if (gif.src.indexOf('data:') !== -1) {\n var data = gif.src.substring(gif.src.indexOf(',')+1);\n stream = new Stream(window.atob(data));\n doParse();\n } else {\n var h = new XMLHttpRequest();\n h.overrideMimeType('text/plain; charset=x-user-defined');\n h.onload = function(e) {\n stream = new Stream(h.responseText);\n setTimeout(doParse, 0);\n };\n h.onerror = function() { doLoadError('xhr'); };\n h.open('GET', gif.getAttribute('data-animated-src') || gif.src, true);\n h.send();\n }\n },\n\n getFrames : function () {\n return frames;\n }\n };\n};\n\n\nwindow.SuperGif = SuperGif;\n\n})( window );","/*!\n\nJSZip - A Javascript class for generating and reading zip files\n\n\n(c) 2009-2014 Stuart Knightley \nDual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.\n\nJSZip uses the library zlib.js released under the following license :\nzlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License\n*/\n!function(a){\"object\"==typeof exports?module.exports=a():\"function\"==typeof define&&define.amd?define(a):\"undefined\"!=typeof window?window.JSZip=a():\"undefined\"!=typeof global?global.JSZip=a():\"undefined\"!=typeof self&&(self.JSZip=a())}(function(){return function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i=\"function\"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);throw new Error(\"Cannot find module '\"+g+\"'\")}var j=c[g]={exports:{}};b[g][0].call(j.exports,function(a){var c=b[g][1][a];return e(c?c:a)},j,j.exports,a,b,c,d)}return c[g].exports}for(var f=\"function\"==typeof require&&require,g=0;g>2,g=(3&b)<<4|c>>4,h=(15&c)<<2|e>>6,i=63&e,isNaN(c)?h=i=64:isNaN(e)&&(i=64),j=j+d.charAt(f)+d.charAt(g)+d.charAt(h)+d.charAt(i);return j},c.decode=function(a){var b,c,e,f,g,h,i,j=\"\",k=0;for(a=a.replace(/[^A-Za-z0-9\\+\\/\\=]/g,\"\");k>4,c=(15&g)<<4|h>>2,e=(3&h)<<6|i,j+=String.fromCharCode(b),64!=h&&(j+=String.fromCharCode(c)),64!=i&&(j+=String.fromCharCode(e));return j}},{}],2:[function(a,b){\"use strict\";function c(){this.compressedSize=0,this.uncompressedSize=0,this.crc32=0,this.compressionMethod=null,this.compressedContent=null}c.prototype={getContent:function(){return null},getCompressedContent:function(){return null}},b.exports=c},{}],3:[function(a,b,c){\"use strict\";c.STORE={magic:\"\\x00\\x00\",compress:function(a){return a},uncompress:function(a){return a},compressInputType:null,uncompressInputType:null},c.DEFLATE=a(\"./flate\")},{\"./flate\":6}],4:[function(a,b){\"use strict\";function c(){this.data=null,this.length=0,this.index=0}var d=a(\"./utils\");c.prototype={checkOffset:function(a){this.checkIndex(this.index+a)},checkIndex:function(a){if(this.lengtha)throw new Error(\"End of data reached (data length = \"+this.length+\", asked index = \"+a+\"). Corrupted zip ?\")},setIndex:function(a){this.checkIndex(a),this.index=a},skip:function(a){this.setIndex(this.index+a)},byteAt:function(){},readInt:function(a){var b,c=0;for(this.checkOffset(a),b=this.index+a-1;b>=this.index;b--)c=(c<<8)+this.byteAt(b);return this.index+=a,c},readString:function(a){return d.transformTo(\"string\",this.readData(a))},readData:function(){},lastIndexOfSignature:function(){},readDate:function(){var a=this.readInt(4);return new Date((a>>25&127)+1980,(a>>21&15)-1,a>>16&31,a>>11&31,a>>5&63,(31&a)<<1)}},b.exports=c},{\"./utils\":14}],5:[function(a,b,c){\"use strict\";c.base64=!1,c.binary=!1,c.dir=!1,c.date=null,c.compression=null},{}],6:[function(a,b,c){\"use strict\";var d=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Uint32Array,e=a(\"zlibjs/bin/rawdeflate.min\").Zlib,f=a(\"zlibjs/bin/rawinflate.min\").Zlib;c.uncompressInputType=d?\"uint8array\":\"array\",c.compressInputType=d?\"uint8array\":\"array\",c.magic=\"\\b\\x00\",c.compress=function(a){var b=new e.RawDeflate(a);return b.compress()},c.uncompress=function(a){var b=new f.RawInflate(a);return b.decompress()}},{\"zlibjs/bin/rawdeflate.min\":19,\"zlibjs/bin/rawinflate.min\":20}],7:[function(a,b){\"use strict\";function c(a,b){return this instanceof c?(this.files={},this.root=\"\",a&&this.load(a,b),void(this.clone=function(){var a=new c;for(var b in this)\"function\"!=typeof this[b]&&(a[b]=this[b]);return a})):new c(a,b)}c.prototype=a(\"./object\"),c.prototype.load=a(\"./load\"),c.support=a(\"./support\"),c.defaults=a(\"./defaults\"),c.utils=a(\"./utils\"),c.base64=a(\"./base64\"),c.compressions=a(\"./compressions\"),b.exports=c},{\"./base64\":1,\"./compressions\":3,\"./defaults\":5,\"./load\":8,\"./object\":9,\"./support\":12,\"./utils\":14}],8:[function(a,b){\"use strict\";var c=a(\"./base64\"),d=a(\"./zipEntries\");b.exports=function(a,b){var e,f,g,h;for(b=b||{},b.base64&&(a=c.decode(a)),f=new d(a,b),e=f.files,g=0;gc;c++)d+=String.fromCharCode(255&a),a>>>=8;return d},r=function(){var a,b,c={};for(a=0;a0?a.substring(0,b):\"\"},v=function(a){return\"/\"!=a.slice(-1)&&(a+=\"/\"),this.files[a]||t.call(this,a,null,{dir:!0}),this.files[a]},w=function(a,b){var c,d=new k;return a._data instanceof k?(d.uncompressedSize=a._data.uncompressedSize,d.crc32=a._data.crc32,0===d.uncompressedSize||a.options.dir?(b=j.STORE,d.compressedContent=\"\",d.crc32=0):a._data.compressionMethod===b.magic?d.compressedContent=a._data.getCompressedContent():(c=a._data.getContent(),d.compressedContent=b.compress(f.transformTo(b.compressInputType,c)))):(c=n(a),(!c||0===c.length||a.options.dir)&&(b=j.STORE,c=\"\"),d.uncompressedSize=c.length,d.crc32=this.crc32(c),d.compressedContent=b.compress(f.transformTo(b.compressInputType,c))),d.compressedSize=d.compressedContent.length,d.compressionMethod=b.magic,d},x=function(a,b,c,d){var e,f,h=(c.compressedContent,this.utf8encode(b.name)),i=h!==b.name,j=b.options,k=\"\",l=\"\";e=j.date.getHours(),e<<=6,e|=j.date.getMinutes(),e<<=5,e|=j.date.getSeconds()/2,f=j.date.getFullYear()-1980,f<<=4,f|=j.date.getMonth()+1,f<<=5,f|=j.date.getDate(),i&&(l=q(1,1)+q(this.crc32(h),4)+h,k+=\"up\"+q(l.length,2)+l);var m=\"\";m+=\"\\n\\x00\",m+=i?\"\\x00\\b\":\"\\x00\\x00\",m+=c.compressionMethod,m+=q(e,2),m+=q(f,2),m+=q(c.crc32,4),m+=q(c.compressedSize,4),m+=q(c.uncompressedSize,4),m+=q(h.length,2),m+=q(k.length,2);var n=g.LOCAL_FILE_HEADER+m+h+k,o=g.CENTRAL_FILE_HEADER+\"\u0014\\x00\"+m+\"\\x00\\x00\\x00\\x00\\x00\\x00\"+(b.options.dir===!0?\"\u0010\\x00\\x00\\x00\":\"\\x00\\x00\\x00\\x00\")+q(d,4)+h+k;return{fileRecord:n,dirRecord:o,compressedObject:c}},y=function(){this.data=[]};y.prototype={append:function(a){a=f.transformTo(\"string\",a),this.data.push(a)},finalize:function(){return this.data.join(\"\")}};var z=function(a){this.data=new Uint8Array(a),this.index=0};z.prototype={append:function(a){0!==a.length&&(a=f.transformTo(\"uint8array\",a),this.data.set(a,this.index),this.index+=a.length)},finalize:function(){return this.data}};var A={load:function(){throw new Error(\"Load method is not defined. Is the file jszip-load.js included ?\")},filter:function(a){var b,c,d,e,f=[];for(b in this.files)this.files.hasOwnProperty(b)&&(d=this.files[b],e=new p(d.name,d._data,r(d.options)),c=b.slice(this.root.length,b.length),b.slice(0,this.root.length)===this.root&&a(c,e)&&f.push(e));return f},file:function(a,b,c){if(1===arguments.length){if(f.isRegExp(a)){var d=a;return this.filter(function(a,b){return!b.options.dir&&d.test(a)})}return this.filter(function(b,c){return!c.options.dir&&b===a})[0]||null}return a=this.root+a,t.call(this,a,b,c),this},folder:function(a){if(!a)return this;if(f.isRegExp(a))return this.filter(function(b,c){return c.options.dir&&a.test(b)});var b=this.root+a,c=v.call(this,b),d=this.clone();return d.root=c.name,d},remove:function(a){a=this.root+a;var b=this.files[a];if(b||(\"/\"!=a.slice(-1)&&(a+=\"/\"),b=this.files[a]),b)if(b.options.dir)for(var c=this.filter(function(b,c){return c.name.slice(0,a.length)===a}),d=0;di;i++)h=c?a[i]:a.charCodeAt(i),g=255&(b^h),e=d[g],b=b>>>8^e;return-1^b},utf8encode:function(a){if(c){var b=c.encode(a);return f.transformTo(\"string\",b)}if(e.nodebuffer)return f.transformTo(\"string\",l(a,\"utf-8\"));for(var d=[],g=0,h=0;hi?d[g++]=String.fromCharCode(i):i>127&&2048>i?(d[g++]=String.fromCharCode(i>>6|192),d[g++]=String.fromCharCode(63&i|128)):(d[g++]=String.fromCharCode(i>>12|224),d[g++]=String.fromCharCode(i>>6&63|128),d[g++]=String.fromCharCode(63&i|128))}return d.join(\"\")},utf8decode:function(a){var b=[],c=0,g=f.getTypeOf(a),h=\"string\"!==g,i=0,j=0,k=0,l=0;if(d)return d.decode(f.transformTo(\"uint8array\",a));if(e.nodebuffer)return f.transformTo(\"nodebuffer\",a).toString(\"utf-8\");for(;ij?(b[c++]=String.fromCharCode(j),i++):j>191&&224>j?(k=h?a[i+1]:a.charCodeAt(i+1),b[c++]=String.fromCharCode((31&j)<<6|63&k),i+=2):(k=h?a[i+1]:a.charCodeAt(i+1),l=h?a[i+2]:a.charCodeAt(i+2),b[c++]=String.fromCharCode((15&j)<<12|(63&k)<<6|63&l),i+=3);return b.join(\"\")}};b.exports=A},{\"./base64\":1,\"./compressedObject\":2,\"./compressions\":3,\"./defaults\":5,\"./nodeBuffer\":17,\"./signature\":10,\"./support\":12,\"./utils\":14}],10:[function(a,b,c){\"use strict\";c.LOCAL_FILE_HEADER=\"PK\u0003\u0004\",c.CENTRAL_FILE_HEADER=\"PK\u0001\u0002\",c.CENTRAL_DIRECTORY_END=\"PK\u0005\u0006\",c.ZIP64_CENTRAL_DIRECTORY_LOCATOR=\"PK\u0006\u0007\",c.ZIP64_CENTRAL_DIRECTORY_END=\"PK\u0006\u0006\",c.DATA_DESCRIPTOR=\"PK\u0007\\b\"},{}],11:[function(a,b){\"use strict\";function c(a,b){this.data=a,b||(this.data=e.string2binary(this.data)),this.length=this.data.length,this.index=0}var d=a(\"./dataReader\"),e=a(\"./utils\");c.prototype=new d,c.prototype.byteAt=function(a){return this.data.charCodeAt(a)},c.prototype.lastIndexOfSignature=function(a){return this.data.lastIndexOf(a)},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.slice(this.index,this.index+a);return this.index+=a,b},b.exports=c},{\"./dataReader\":4,\"./utils\":14}],12:[function(a,b,c){var d=a(\"__browserify_process\");if(c.base64=!0,c.array=!0,c.string=!0,c.arraybuffer=\"undefined\"!=typeof ArrayBuffer&&\"undefined\"!=typeof Uint8Array,c.nodebuffer=!d.browser,c.uint8array=\"undefined\"!=typeof Uint8Array,\"undefined\"==typeof ArrayBuffer)c.blob=!1;else{var e=new ArrayBuffer(0);try{c.blob=0===new Blob([e],{type:\"application/zip\"}).size}catch(f){try{var g=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder||window.MSBlobBuilder,h=new g;h.append(e),c.blob=0===h.getBlob(\"application/zip\").size}catch(f){c.blob=!1}}}},{__browserify_process:18}],13:[function(a,b){\"use strict\";function c(a){a&&(this.data=a,this.length=this.data.length,this.index=0)}var d=a(\"./dataReader\");c.prototype=new d,c.prototype.byteAt=function(a){return this.data[a]},c.prototype.lastIndexOfSignature=function(a){for(var b=a.charCodeAt(0),c=a.charCodeAt(1),d=a.charCodeAt(2),e=a.charCodeAt(3),f=this.length-4;f>=0;--f)if(this.data[f]===b&&this.data[f+1]===c&&this.data[f+2]===d&&this.data[f+3]===e)return f;return-1},c.prototype.readData=function(a){this.checkOffset(a);var b=this.data.subarray(this.index,this.index+a);return this.index+=a,b},b.exports=c},{\"./dataReader\":4}],14:[function(a,b,c){\"use strict\";function d(a){return a}function e(a,b){for(var c=0;cg&&b>1;)try{d.push(\"array\"===f||\"nodebuffer\"===f?String.fromCharCode.apply(null,a.slice(g,Math.min(g+b,e))):String.fromCharCode.apply(null,a.subarray(g,Math.min(g+b,e)))),g+=b}catch(i){b=Math.floor(b/2)}return d.join(\"\")}function g(a,b){for(var c=0;cb?\"0\":\"\")+b.toString(16).toUpperCase();return d},c.findCompression=function(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b].magic===a)return i[b];return null},c.isRegExp=function(a){return\"[object RegExp]\"===Object.prototype.toString.call(a)}},{\"./compressions\":3,\"./nodeBuffer\":17,\"./support\":12}],15:[function(a,b){\"use strict\";function c(a,b){this.files=[],this.loadOptions=b,a&&this.load(a)}var d=a(\"./stringReader\"),e=a(\"./nodeBufferReader\"),f=a(\"./uint8ArrayReader\"),g=a(\"./utils\"),h=a(\"./signature\"),i=a(\"./zipEntry\"),j=a(\"./support\");c.prototype={checkSignature:function(a){var b=this.reader.readString(4);if(b!==a)throw new Error(\"Corrupted zip or bug : unexpected signature (\"+g.pretty(b)+\", expected \"+g.pretty(a)+\")\")},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2),this.zipComment=this.reader.readString(this.zipCommentLength)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.versionMadeBy=this.reader.readString(2),this.versionNeeded=this.reader.readInt(2),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var a,b,c,d=this.zip64EndOfCentralSize-44,e=0;d>e;)a=this.reader.readInt(2),b=this.reader.readInt(4),c=this.reader.readString(b),this.zip64ExtensibleData[a]={id:a,length:b,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error(\"Multi-volumes zip are not supported\")},readLocalFiles:function(){var a,b;for(a=0;a0)){var d=c.shift();d()}},!0),function(a){c.push(a),window.postMessage(\"process-tick\",\"*\")}}return function(a){setTimeout(a,0)}}(),c.title=\"browser\",c.browser=!0,c.env={},c.argv=[],c.binding=function(){throw new Error(\"process.binding is not supported\")},c.cwd=function(){return\"/\"},c.chdir=function(){throw new Error(\"process.chdir is not supported\")}},{}],19:[function(){/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */\n(function(){\"use strict\";function a(a,b){var c=a.split(\".\"),d=n;!(c[0]in d)&&d.execScript&&d.execScript(\"var \"+c[0]);for(var e;c.length&&(e=c.shift());)c.length||b===l?d=d[e]?d[e]:d[e]={}:d[e]=b}function b(a,b){if(this.index=\"number\"==typeof b?b:0,this.d=0,this.buffer=a instanceof(o?Uint8Array:Array)?a:new(o?Uint8Array:Array)(32768),2*this.buffer.length<=this.index)throw Error(\"invalid index\");this.buffer.length<=this.index&&c(this)}function c(a){var b,c=a.buffer,d=c.length,e=new(o?Uint8Array:Array)(d<<1);if(o)e.set(c);else for(b=0;d>b;++b)e[b]=c[b];return a.buffer=e}function d(a){this.buffer=new(o?Uint16Array:Array)(2*a),this.length=0}function e(a,b){this.e=w,this.f=0,this.input=o&&a instanceof Array?new Uint8Array(a):a,this.c=0,b&&(b.lazy&&(this.f=b.lazy),\"number\"==typeof b.compressionType&&(this.e=b.compressionType),b.outputBuffer&&(this.b=o&&b.outputBuffer instanceof Array?new Uint8Array(b.outputBuffer):b.outputBuffer),\"number\"==typeof b.outputIndex&&(this.c=b.outputIndex)),this.b||(this.b=new(o?Uint8Array:Array)(32768))}function f(a,b){this.length=a,this.g=b}function g(a,b){function c(a,b){var c,d=a.g,e=[],f=0;c=z[a.length],e[f++]=65535&c,e[f++]=c>>16&255,e[f++]=c>>24;var g;switch(m){case 1===d:g=[0,d-1,0];break;case 2===d:g=[1,d-2,0];break;case 3===d:g=[2,d-3,0];break;case 4===d:g=[3,d-4,0];break;case 6>=d:g=[4,d-5,1];break;case 8>=d:g=[5,d-7,1];break;case 12>=d:g=[6,d-9,2];break;case 16>=d:g=[7,d-13,2];break;case 24>=d:g=[8,d-17,3];break;case 32>=d:g=[9,d-25,3];break;case 48>=d:g=[10,d-33,4];break;case 64>=d:g=[11,d-49,4];break;case 96>=d:g=[12,d-65,5];break;case 128>=d:g=[13,d-97,5];break;case 192>=d:g=[14,d-129,6];break;case 256>=d:g=[15,d-193,6];break;case 384>=d:g=[16,d-257,7];break;case 512>=d:g=[17,d-385,7];break;case 768>=d:g=[18,d-513,8];break;case 1024>=d:g=[19,d-769,8];break;case 1536>=d:g=[20,d-1025,9];break;case 2048>=d:g=[21,d-1537,9];break;case 3072>=d:g=[22,d-2049,10];break;case 4096>=d:g=[23,d-3073,10];break;case 6144>=d:g=[24,d-4097,11];break;case 8192>=d:g=[25,d-6145,11];break;case 12288>=d:g=[26,d-8193,12];break;case 16384>=d:g=[27,d-12289,12];break;case 24576>=d:g=[28,d-16385,13];break;case 32768>=d:g=[29,d-24577,13];break;default:throw\"invalid distance\"}c=g,e[f++]=c[0],e[f++]=c[1],e[f++]=c[2];var h,i;for(h=0,i=e.length;i>h;++h)r[s++]=e[h];u[e[0]]++,v[e[3]]++,t=a.length+b-1,n=null}var d,e,f,g,i,j,k,n,p,q={},r=o?new Uint16Array(2*b.length):[],s=0,t=0,u=new(o?Uint32Array:Array)(286),v=new(o?Uint32Array:Array)(30),w=a.f;if(!o){for(f=0;285>=f;)u[f++]=0;for(f=0;29>=f;)v[f++]=0}for(u[256]=1,d=0,e=b.length;e>d;++d){for(f=i=0,g=3;g>f&&d+f!==e;++f)i=i<<8|b[d+f];if(q[i]===l&&(q[i]=[]),j=q[i],!(0=e){for(n&&c(n,-1),f=0,g=e-d;g>f;++f)p=b[d+f],r[s++]=p,++u[p];break}0h;h++){if(d=c[j-h-1],g=3,k>3){for(i=k;i>3;i--)if(a[d+i-1]!==a[b+i-1])continue a;g=k}for(;258>g&&l>b+g&&a[d+g]===a[b+g];)++g;if(g>k&&(e=d,k=g),258===g)break}return new f(k,b-e)}function i(a,b){var c,e,f,g,h,i=a.length,k=new d(572),l=new(o?Uint8Array:Array)(i);if(!o)for(g=0;i>g;g++)l[g]=0;for(g=0;i>g;++g)0g;++g)c[g]=k.pop(),e[g]=c[g].value;for(f=j(e,e.length,b),g=0,h=c.length;h>g;++g)l[c[g].index]=f[g];return l}function j(a,b,c){function d(a){var c=n[a][p[a]];c===b?(d(a+1),d(a+1)):--l[c],++p[a]}var e,f,g,h,i,j=new(o?Uint16Array:Array)(c),k=new(o?Uint8Array:Array)(c),l=new(o?Uint8Array:Array)(b),m=Array(c),n=Array(c),p=Array(c),q=(1<f;++f)r>q?k[f]=0:(k[f]=1,q-=r),q<<=1,j[c-2-f]=(j[c-1-f]/2|0)+b;for(j[0]=k[0],m[0]=Array(j[0]),n[0]=Array(j[0]),f=1;c>f;++f)j[f]>2*j[f-1]+k[f]&&(j[f]=2*j[f-1]+k[f]),m[f]=Array(j[f]),n[f]=Array(j[f]);for(e=0;b>e;++e)l[e]=c;for(g=0;ge;++e)p[e]=0;for(1===k[c-1]&&(--l[0],++p[c-1]),f=c-2;f>=0;--f){for(h=e=0,i=p[f+1],g=0;ga[e]?(m[f][g]=h,n[f][g]=b,i+=2):(m[f][g]=a[e],n[f][g]=e,++e);p[f]=0,1===k[f]&&d(f)}return l}function k(a){var b,c,d,e,f=new(o?Uint16Array:Array)(a.length),g=[],h=[],i=0;for(b=0,c=a.length;c>b;b++)g[a[b]]=(0|g[a[b]])+1;for(b=1,c=16;c>=b;b++)h[b]=i,i+=0|g[b],i<<=1;for(b=0,c=a.length;c>b;b++)for(i=h[a[b]],h[a[b]]+=1,d=f[b]=0,e=a[b];e>d;d++)f[b]=f[b]<<1|1&i,i>>>=1;return f}var l=void 0,m=!0,n=this,o=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Uint32Array&&\"undefined\"!=typeof DataView;b.prototype.a=function(a,b,d){var e,f=this.buffer,g=this.index,h=this.d,i=f[g];if(d&&b>1&&(a=b>8?(u[255&a]<<24|u[a>>>8&255]<<16|u[a>>>16&255]<<8|u[a>>>24&255])>>32-b:u[a]>>8-b),8>b+h)i=i<e;++e)i=i<<1|a>>b-e-1&1,8===++h&&(h=0,f[g++]=u[i],i=0,g===f.length&&(f=c(this)));f[g]=i,this.buffer=f,this.d=h,this.index=g},b.prototype.finish=function(){var a,b=this.buffer,c=this.index;return 0p;++p){for(var r=p,s=r,t=7,r=r>>>1;r;r>>>=1)s<<=1,s|=1&r,--t;q[p]=(s<>>0}var u=q;d.prototype.getParent=function(a){return 2*((a-2)/4|0)},d.prototype.push=function(a,b){var c,d,e,f=this.buffer;for(c=this.length,f[this.length++]=b,f[this.length++]=a;c>0&&(d=this.getParent(c),f[c]>f[d]);)e=f[c],f[c]=f[d],f[d]=e,e=f[c+1],f[c+1]=f[d+1],f[d+1]=e,c=d;return this.length},d.prototype.pop=function(){var a,b,c,d,e,f=this.buffer;for(b=f[0],a=f[1],this.length-=2,f[0]=f[this.length],f[1]=f[this.length+1],e=0;(d=2*e+2,!(d>=this.length))&&(d+2f[d]&&(d+=2),f[d]>f[e]);)c=f[e],f[e]=f[d],f[d]=c,c=f[e+1],f[e+1]=f[d+1],f[d+1]=c,e=d;return{index:a,value:b,length:this.length}};var v,w=2,x=[];for(v=0;288>v;v++)switch(m){case 143>=v:x.push([v+48,8]);break;case 255>=v:x.push([v-144+400,9]);break;case 279>=v:x.push([v-256+0,7]);break;case 287>=v:x.push([v-280+192,8]);break;default:throw\"invalid literal: \"+v}e.prototype.h=function(){var a,c,d,e,f=this.input;switch(this.e){case 0:for(d=0,e=f.length;e>d;){c=o?f.subarray(d,d+65535):f.slice(d,d+65535),d+=c.length;var h=c,j=d===e,n=l,p=l,q=l,r=l,s=l,t=this.b,u=this.c;if(o){for(t=new Uint8Array(this.b.buffer);t.length<=u+h.length+5;)t=new Uint8Array(t.length<<1);t.set(this.b)}if(n=j?1:0,t[u++]=0|n,p=h.length,q=~p+65536&65535,t[u++]=255&p,t[u++]=p>>>8&255,t[u++]=255&q,t[u++]=q>>>8&255,o)t.set(h,u),u+=h.length,t=t.subarray(0,u);else{for(r=0,s=h.length;s>r;++r)t[u++]=h[r];t.length=u}this.c=u,this.b=t}break;case 1:var v=new b(o?new Uint8Array(this.b.buffer):this.b,this.c);v.a(1,1,m),v.a(1,2,m);var y,z,A,B=g(this,f);for(y=0,z=B.length;z>y;y++)if(A=B[y],b.prototype.a.apply(v,x[A]),A>256)v.a(B[++y],B[++y],m),v.a(B[++y],5),v.a(B[++y],B[++y],m);else if(256===A)break;this.b=v.finish(),this.c=this.b.length;break;case w:var C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R=new b(o?new Uint8Array(this.b.buffer):this.b,this.c),S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],T=Array(19);for(C=w,R.a(1,1,m),R.a(C,2,m),D=g(this,f),H=i(this.j,15),I=k(H),J=i(this.i,7),K=k(J),E=286;E>257&&0===H[E-1];E--);for(F=30;F>1&&0===J[F-1];F--);var U,V,W,X,Y,Z,$=E,_=F,ab=new(o?Uint32Array:Array)($+_),bb=new(o?Uint32Array:Array)(316),cb=new(o?Uint8Array:Array)(19);for(U=V=0;$>U;U++)ab[V++]=H[U];for(U=0;_>U;U++)ab[V++]=J[U];if(!o)for(U=0,X=cb.length;X>U;++U)cb[U]=0;for(U=Y=0,X=ab.length;X>U;U+=V){for(V=1;X>U+V&&ab[U+V]===ab[U];++V);if(W=V,0===ab[U])if(3>W)for(;00;)Z=138>W?W:138,Z>W-3&&W>Z&&(Z=W-3),10>=Z?(bb[Y++]=17,bb[Y++]=Z-3,cb[17]++):(bb[Y++]=18,bb[Y++]=Z-11,cb[18]++),W-=Z;else if(bb[Y++]=ab[U],cb[ab[U]]++,W--,3>W)for(;00;)Z=6>W?W:6,Z>W-3&&W>Z&&(Z=W-3),bb[Y++]=16,bb[Y++]=Z-3,cb[16]++,W-=Z}for(a=o?bb.subarray(0,Y):bb.slice(0,Y),L=i(cb,7),P=0;19>P;P++)T[P]=L[S[P]];for(G=19;G>4&&0===T[G-1];G--);for(M=k(L),R.a(E-257,5,m),R.a(F-1,5,m),R.a(G-4,4,m),P=0;G>P;P++)R.a(T[P],3,m);for(P=0,Q=a.length;Q>P;P++)if(N=a[P],R.a(M[N],L[N],m),N>=16){switch(P++,N){case 16:O=2;break;case 17:O=3;break;case 18:O=7;break;default:throw\"invalid code: \"+N}R.a(a[P],O,m)}var db,eb,fb,gb,hb,ib,jb,kb,lb=[I,H],mb=[K,J];for(hb=lb[0],ib=lb[1],jb=mb[0],kb=mb[1],db=0,eb=D.length;eb>db;++db)if(fb=D[db],R.a(hb[fb],ib[fb],m),fb>256)R.a(D[++db],D[++db],m),gb=D[++db],R.a(jb[gb],kb[gb],m),R.a(D[++db],D[++db],m);else if(256===fb)break;this.b=R.finish(),this.c=this.b.length;break;default:throw\"invalid compression type\"}return this.b};var y=function(){function a(a){switch(m){case 3===a:return[257,a-3,0];case 4===a:return[258,a-4,0];case 5===a:return[259,a-5,0];case 6===a:return[260,a-6,0];case 7===a:return[261,a-7,0];case 8===a:return[262,a-8,0];case 9===a:return[263,a-9,0];case 10===a:return[264,a-10,0];case 12>=a:return[265,a-11,1];case 14>=a:return[266,a-13,1];case 16>=a:return[267,a-15,1];case 18>=a:return[268,a-17,1];case 22>=a:return[269,a-19,2];case 26>=a:return[270,a-23,2];case 30>=a:return[271,a-27,2];case 34>=a:return[272,a-31,2];case 42>=a:return[273,a-35,3];case 50>=a:return[274,a-43,3];case 58>=a:return[275,a-51,3];case 66>=a:return[276,a-59,3];case 82>=a:return[277,a-67,4];case 98>=a:return[278,a-83,4];case 114>=a:return[279,a-99,4];case 130>=a:return[280,a-115,4];case 162>=a:return[281,a-131,5];case 194>=a:return[282,a-163,5];case 226>=a:return[283,a-195,5];case 257>=a:return[284,a-227,5];case 258===a:return[285,a-258,0];default:throw\"invalid length: \"+a}}var b,c,d=[];for(b=3;258>=b;b++)c=a(b),d[b]=c[2]<<24|c[1]<<16|c[0];return d}(),z=o?new Uint32Array(y):y;a(\"Zlib.RawDeflate\",e),a(\"Zlib.RawDeflate.prototype.compress\",e.prototype.h);var A,B,C,D,E={NONE:0,FIXED:1,DYNAMIC:w};if(Object.keys)A=Object.keys(E);else for(B in A=[],C=0,E)A[C++]=B;for(C=0,D=A.length;D>C;++C)B=A[C],a(\"Zlib.RawDeflate.CompressionType.\"+B,E[B])}).call(this)},{}],20:[function(){/** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */\n(function(){\"use strict\";function a(a,b){var c=a.split(\".\"),d=g;!(c[0]in d)&&d.execScript&&d.execScript(\"var \"+c[0]);for(var e;c.length&&(e=c.shift());)c.length||void 0===b?d=d[e]?d[e]:d[e]={}:d[e]=b}function b(a){var b,c,d,e,f,g,i,j,k,l,m=a.length,n=0,o=Number.POSITIVE_INFINITY;for(j=0;m>j;++j)a[j]>n&&(n=a[j]),a[j]=d;){for(j=0;m>j;++j)if(a[j]===d){for(g=0,i=e,k=0;d>k;++k)g=g<<1|1&i,i>>=1;for(l=d<<16|j,k=g;b>k;k+=f)c[k]=l;++e}++d,e<<=1,f<<=1}return[c,n,o]}function c(a,b){switch(this.g=[],this.h=32768,this.c=this.f=this.d=this.k=0,this.input=h?new Uint8Array(a):a,this.l=!1,this.i=j,this.q=!1,(b||!(b={}))&&(b.index&&(this.d=b.index),b.bufferSize&&(this.h=b.bufferSize),b.bufferType&&(this.i=b.bufferType),b.resize&&(this.q=b.resize)),this.i){case i:this.a=32768,this.b=new(h?Uint8Array:Array)(32768+this.h+258);break;case j:this.a=0,this.b=new(h?Uint8Array:Array)(this.h),this.e=this.v,this.m=this.s,this.j=this.t;break;default:throw Error(\"invalid inflate mode\")}}function d(a,b){for(var c,d=a.f,e=a.c,f=a.input,g=a.d,h=f.length;b>e;){if(g>=h)throw Error(\"input buffer is broken\");d|=f[g++]<>>b,a.c=e-b,a.d=g,c}function e(a,b){for(var c,d,e=a.f,f=a.c,g=a.input,h=a.d,i=g.length,j=b[0],k=b[1];k>f&&!(h>=i);)e|=g[h++]<>>16,a.f=e>>d,a.c=f-d,a.d=h,65535&c}function f(a){function c(a,b,c){var f,g,h,i=this.p;for(h=0;a>h;)switch(f=e(this,b)){case 16:for(g=3+d(this,2);g--;)c[h++]=i;break;case 17:for(g=3+d(this,3);g--;)c[h++]=0;i=0;break;case 18:for(g=11+d(this,7);g--;)c[h++]=0;i=0;break;default:i=c[h++]=f}return this.p=i,c}var f,g,i,j,k=d(a,5)+257,l=d(a,5)+1,m=d(a,4)+4,o=new(h?Uint8Array:Array)(n.length);for(j=0;m>j;++j)o[n[j]]=d(a,3);if(!h)for(j=m,m=o.length;m>j;++j)o[n[j]]=0;f=b(o),g=new(h?Uint8Array:Array)(k),i=new(h?Uint8Array:Array)(l),a.p=0,a.j(b(c.call(a,k,f,g)),b(c.call(a,l,f,i)))}var g=this,h=\"undefined\"!=typeof Uint8Array&&\"undefined\"!=typeof Uint16Array&&\"undefined\"!=typeof Uint32Array&&\"undefined\"!=typeof DataView,i=0,j=1;c.prototype.u=function(){for(;!this.l;){var a=d(this,3);switch(1&a&&(this.l=!0),a>>>=1){case 0:var b=this.input,c=this.d,e=this.b,g=this.a,k=b.length,l=void 0,m=void 0,n=e.length,o=void 0;if(this.c=this.f=0,c+1>=k)throw Error(\"invalid uncompressed block header: LEN\");if(l=b[c++]|b[c++]<<8,c+1>=k)throw Error(\"invalid uncompressed block header: NLEN\");if(m=b[c++]|b[c++]<<8,l===~m)throw Error(\"invalid uncompressed block header: length verify\");if(c+l>b.length)throw Error(\"input buffer is broken\");switch(this.i){case i:for(;g+l>e.length;){if(o=n-g,l-=o,h)e.set(b.subarray(c,c+o),g),g+=o,c+=o;else for(;o--;)e[g++]=b[c++];this.a=g,e=this.e(),g=this.a}break;case j:for(;g+l>e.length;)e=this.e({o:2});break;default:throw Error(\"invalid inflate mode\")}if(h)e.set(b.subarray(c,c+l),g),g+=l,c+=l;else for(;l--;)e[g++]=b[c++];this.d=c,this.a=g,this.b=e;break;case 1:this.j(z,B);break;case 2:f(this);break;default:throw Error(\"unknown BTYPE: \"+a)}}return this.m()};var k,l,m=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],n=h?new Uint16Array(m):m,o=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,258,258],p=h?new Uint16Array(o):o,q=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0],r=h?new Uint8Array(q):q,s=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577],t=h?new Uint16Array(s):s,u=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],v=h?new Uint8Array(u):u,w=new(h?Uint8Array:Array)(288);for(k=0,l=w.length;l>k;++k)w[k]=143>=k?8:255>=k?9:279>=k?7:8;var x,y,z=b(w),A=new(h?Uint8Array:Array)(30);for(x=0,y=A.length;y>x;++x)A[x]=5;var B=b(A);c.prototype.j=function(a,b){var c=this.b,f=this.a;this.n=a;for(var g,h,i,j,k=c.length-258;256!==(g=e(this,a));)if(256>g)f>=k&&(this.a=f,c=this.e(),f=this.a),c[f++]=g;else for(h=g-257,j=p[h],0=k&&(this.a=f,c=this.e(),f=this.a);j--;)c[f]=c[f++-i];for(;8<=this.c;)this.c-=8,this.d--;this.a=f},c.prototype.t=function(a,b){var c=this.b,f=this.a;this.n=a;for(var g,h,i,j,k=c.length;256!==(g=e(this,a));)if(256>g)f>=k&&(c=this.e(),k=c.length),c[f++]=g;else for(h=g-257,j=p[h],0k&&(c=this.e(),k=c.length);j--;)c[f]=c[f++-i];for(;8<=this.c;)this.c-=8,this.d--;this.a=f},c.prototype.e=function(){var a,b,c=new(h?Uint8Array:Array)(this.a-32768),d=this.a-32768,e=this.b;if(h)c.set(e.subarray(32768,c.length));else for(a=0,b=c.length;b>a;++a)c[a]=e[a+32768];if(this.g.push(c),this.k+=c.length,h)e.set(e.subarray(d,d+32768));else for(a=0;32768>a;++a)e[a]=e[d+a];return this.a=32768,e},c.prototype.v=function(a){var b,c,d,e,f=this.input.length/this.d+1|0,g=this.input,i=this.b;return a&&(\"number\"==typeof a.o&&(f=a.o),\"number\"==typeof a.r&&(f+=a.r)),2>f?(c=(g.length-this.d)/this.n[2],e=258*(c/2)|0,d=eb;++b)for(a=i[b],d=0,e=a.length;e>d;++d)j[f++]=a[d];for(b=32768,c=this.a;c>b;++b)j[f++]=g[b];return this.g=[],this.buffer=j},c.prototype.s=function(){var a,b=this.a;return h?this.q?(a=new Uint8Array(b),a.set(this.b.subarray(0,b))):a=this.b.subarray(0,b):(this.b.length>b&&(this.b.length=b),a=this.b),this.buffer=a},a(\"Zlib.RawInflate\",c),a(\"Zlib.RawInflate.prototype.decompress\",c.prototype.u);var C,D,E,F,G={ADAPTIVE:j,BLOCK:i};if(Object.keys)C=Object.keys(G);else for(D in C=[],E=0,G)C[E++]=D;for(E=0,F=C.length;F>E;++E)D=C[E],a(\"Zlib.RawInflate.BufferType.\"+D,G[D])}).call(this)},{}]},{},[7])(7)});","// Spectrum Colorpicker v1.1.2\n// https://github.com/bgrins/spectrum\n// Author: Brian Grinstead\n// License: MIT\n\n(function (window, $, undefined) {\n var defaultOpts = {\n\n // Callbacks\n beforeShow: noop,\n move: noop,\n change: noop,\n show: noop,\n hide: noop,\n\n // Options\n color: false,\n flat: false,\n showInput: false,\n showButtons: true,\n clickoutFiresChange: false,\n showInitial: false,\n showPalette: false,\n showPaletteOnly: false,\n showSelectionPalette: true,\n localStorageKey: false,\n appendTo: \"body\",\n maxSelectionSize: 7,\n cancelText: \"cancel\",\n chooseText: \"choose\",\n preferredFormat: false,\n className: \"\",\n showAlpha: false,\n theme: \"sp-light\",\n palette: ['fff', '000'],\n selectionPalette: [],\n disabled: false\n },\n spectrums = [],\n IE = !!/msie/i.exec( window.navigator.userAgent ),\n rgbaSupport = (function() {\n function contains( str, substr ) {\n return !!~('' + str).indexOf(substr);\n }\n\n var elem = document.createElement('div');\n var style = elem.style;\n style.cssText = 'background-color:rgba(0,0,0,.5)';\n return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');\n })(),\n replaceInput = [\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \"\n ].join(''),\n markup = (function () {\n\n // IE does not support gradients with multiple stops, so we need to simulate\n // that for the rainbow slider with 8 divs that each have a single gradient\n var gradientFix = \"\";\n if (IE) {\n for (var i = 1; i <= 6; i++) {\n gradientFix += \"
        \";\n }\n }\n\n return [\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n gradientFix,\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"
        \",\n \"\",\n \"
        \",\n \"
        \",\n \"
        \",\n \"\",\n \"\",\n \"
        \",\n \"
        \",\n \"
        \"\n ].join(\"\");\n })();\n\n function paletteTemplate (p, color, className) {\n var html = [];\n for (var i = 0; i < p.length; i++) {\n var tiny = tinycolor(p[i]);\n var c = tiny.toHsl().l < 0.5 ? \"sp-thumb-el sp-thumb-dark\" : \"sp-thumb-el sp-thumb-light\";\n c += (tinycolor.equals(color, p[i])) ? \" sp-thumb-active\" : \"\";\n\n var swatchStyle = rgbaSupport ? (\"background-color:\" + tiny.toRgbString()) : \"filter:\" + tiny.toFilter();\n html.push('');\n }\n return \"
        \" + html.join('') + \"
        \";\n }\n\n function hideAll() {\n for (var i = 0; i < spectrums.length; i++) {\n if (spectrums[i]) {\n spectrums[i].hide();\n }\n }\n }\n\n function instanceOptions(o, callbackContext) {\n var opts = $.extend({}, defaultOpts, o);\n opts.callbacks = {\n 'move': bind(opts.move, callbackContext),\n 'change': bind(opts.change, callbackContext),\n 'show': bind(opts.show, callbackContext),\n 'hide': bind(opts.hide, callbackContext),\n 'beforeShow': bind(opts.beforeShow, callbackContext)\n };\n\n return opts;\n }\n\n function spectrum(element, o) {\n\n var opts = instanceOptions(o, element),\n flat = opts.flat,\n showSelectionPalette = opts.showSelectionPalette,\n localStorageKey = opts.localStorageKey,\n theme = opts.theme,\n callbacks = opts.callbacks,\n resize = throttle(reflow, 10),\n visible = false,\n dragWidth = 0,\n dragHeight = 0,\n dragHelperHeight = 0,\n slideHeight = 0,\n slideWidth = 0,\n alphaWidth = 0,\n alphaSlideHelperWidth = 0,\n slideHelperHeight = 0,\n currentHue = 0,\n currentSaturation = 0,\n currentValue = 0,\n currentAlpha = 1,\n palette = opts.palette.slice(0),\n paletteArray = $.isArray(palette[0]) ? palette : [palette],\n selectionPalette = opts.selectionPalette.slice(0),\n maxSelectionSize = opts.maxSelectionSize,\n draggingClass = \"sp-dragging\",\n shiftMovementDirection = null;\n\n var doc = element.ownerDocument,\n body = doc.body,\n boundElement = $(element),\n disabled = false,\n container = $(markup, doc).addClass(theme),\n dragger = container.find(\".sp-color\"),\n dragHelper = container.find(\".sp-dragger\"),\n slider = container.find(\".sp-hue\"),\n slideHelper = container.find(\".sp-slider\"),\n alphaSliderInner = container.find(\".sp-alpha-inner\"),\n alphaSlider = container.find(\".sp-alpha\"),\n alphaSlideHelper = container.find(\".sp-alpha-handle\"),\n textInput = container.find(\".sp-input\"),\n paletteContainer = container.find(\".sp-palette\"),\n initialColorContainer = container.find(\".sp-initial\"),\n cancelButton = container.find(\".sp-cancel\"),\n chooseButton = container.find(\".sp-choose\"),\n isInput = boundElement.is(\"input\"),\n shouldReplace = isInput && !flat,\n replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className) : $([]),\n offsetElement = (shouldReplace) ? replacer : boundElement,\n previewElement = replacer.find(\".sp-preview-inner\"),\n initialColor = opts.color || (isInput && boundElement.val()),\n colorOnShow = false,\n preferredFormat = opts.preferredFormat,\n currentPreferredFormat = preferredFormat,\n clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange;\n\n\n function applyOptions() {\n\n if (opts.showPaletteOnly) {\n opts.showPalette = true;\n }\n\n container.toggleClass(\"sp-flat\", flat);\n container.toggleClass(\"sp-input-disabled\", !opts.showInput);\n container.toggleClass(\"sp-alpha-enabled\", opts.showAlpha);\n container.toggleClass(\"sp-buttons-disabled\", !opts.showButtons);\n container.toggleClass(\"sp-palette-disabled\", !opts.showPalette);\n container.toggleClass(\"sp-palette-only\", opts.showPaletteOnly);\n container.toggleClass(\"sp-initial-disabled\", !opts.showInitial);\n container.addClass(opts.className);\n\n reflow();\n }\n\n function initialize() {\n\n if (IE) {\n container.find(\"*:not(input)\").attr(\"unselectable\", \"on\");\n }\n\n applyOptions();\n\n if (shouldReplace) {\n boundElement.after(replacer).hide();\n }\n\n if (flat) {\n boundElement.after(container).hide();\n }\n else {\n\n var appendTo = opts.appendTo === \"parent\" ? boundElement.parent() : $(opts.appendTo);\n if (appendTo.length !== 1) {\n appendTo = $(\"body\");\n }\n\n appendTo.append(container);\n }\n\n if (localStorageKey && window.localStorage) {\n\n // Migrate old palettes over to new format. May want to remove this eventually.\n try {\n var oldPalette = window.localStorage[localStorageKey].split(\",#\");\n if (oldPalette.length > 1) {\n delete window.localStorage[localStorageKey];\n $.each(oldPalette, function(i, c) {\n addColorToSelectionPalette(c);\n });\n }\n }\n catch(e) { }\n\n try {\n selectionPalette = window.localStorage[localStorageKey].split(\";\");\n }\n catch (e) { }\n }\n\n offsetElement.bind(\"click.spectrum touchstart.spectrum\", function (e) {\n if (!disabled) {\n toggle();\n }\n\n e.stopPropagation();\n\n if (!$(e.target).is(\"input\")) {\n e.preventDefault();\n }\n });\n\n if(boundElement.is(\":disabled\") || (opts.disabled === true)) {\n disable();\n }\n\n // Prevent clicks from bubbling up to document. This would cause it to be hidden.\n container.click(stopPropagation);\n\n // Handle user typed input\n textInput.change(setFromTextInput);\n textInput.bind(\"paste\", function () {\n setTimeout(setFromTextInput, 1);\n });\n textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } });\n\n cancelButton.text(opts.cancelText);\n cancelButton.bind(\"click.spectrum\", function (e) {\n e.stopPropagation();\n e.preventDefault();\n hide(\"cancel\");\n });\n\n chooseButton.text(opts.chooseText);\n chooseButton.bind(\"click.spectrum\", function (e) {\n e.stopPropagation();\n e.preventDefault();\n\n if (isValid()) {\n updateOriginalInput(true);\n hide();\n }\n });\n\n draggable(alphaSlider, function (dragX, dragY, e) {\n currentAlpha = (dragX / alphaWidth);\n if (e.shiftKey) {\n currentAlpha = Math.round(currentAlpha * 10) / 10;\n }\n\n move();\n });\n\n draggable(slider, function (dragX, dragY) {\n currentHue = parseFloat(dragY / slideHeight);\n move();\n }, dragStart, dragStop);\n\n draggable(dragger, function (dragX, dragY, e) {\n\n // shift+drag should snap the movement to either the x or y axis.\n if (!e.shiftKey) {\n shiftMovementDirection = null;\n }\n else if (!shiftMovementDirection) {\n var oldDragX = currentSaturation * dragWidth;\n var oldDragY = dragHeight - (currentValue * dragHeight);\n var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY);\n\n shiftMovementDirection = furtherFromX ? \"x\" : \"y\";\n }\n\n var setSaturation = !shiftMovementDirection || shiftMovementDirection === \"x\";\n var setValue = !shiftMovementDirection || shiftMovementDirection === \"y\";\n\n if (setSaturation) {\n currentSaturation = parseFloat(dragX / dragWidth);\n }\n if (setValue) {\n currentValue = parseFloat((dragHeight - dragY) / dragHeight);\n }\n\n move();\n\n }, dragStart, dragStop);\n\n if (!!initialColor) {\n set(initialColor);\n\n // In case color was black - update the preview UI and set the format\n // since the set function will not run (default color is black).\n updateUI();\n currentPreferredFormat = preferredFormat || tinycolor(initialColor).format;\n\n addColorToSelectionPalette(initialColor);\n }\n else {\n updateUI();\n }\n\n if (flat) {\n show();\n }\n\n function palletElementClick(e) {\n if (e.data && e.data.ignore) {\n set($(this).data(\"color\"));\n move();\n }\n else {\n set($(this).data(\"color\"));\n updateOriginalInput(true);\n move();\n hide();\n }\n\n return false;\n }\n\n var paletteEvent = IE ? \"mousedown.spectrum\" : \"click.spectrum touchstart.spectrum\";\n paletteContainer.delegate(\".sp-thumb-el\", paletteEvent, palletElementClick);\n initialColorContainer.delegate(\".sp-thumb-el:nth-child(1)\", paletteEvent, { ignore: true }, palletElementClick);\n }\n\n function addColorToSelectionPalette(color) {\n if (showSelectionPalette) {\n var colorRgb = tinycolor(color).toRgbString();\n if ($.inArray(colorRgb, selectionPalette) === -1) {\n selectionPalette.push(colorRgb);\n while(selectionPalette.length > maxSelectionSize) {\n selectionPalette.shift();\n }\n }\n\n if (localStorageKey && window.localStorage) {\n try {\n window.localStorage[localStorageKey] = selectionPalette.join(\";\");\n }\n catch(e) { }\n }\n }\n }\n\n function getUniqueSelectionPalette() {\n var unique = [];\n var p = selectionPalette;\n var paletteLookup = {};\n var rgb;\n\n if (opts.showPalette) {\n\n for (var i = 0; i < paletteArray.length; i++) {\n for (var j = 0; j < paletteArray[i].length; j++) {\n rgb = tinycolor(paletteArray[i][j]).toRgbString();\n paletteLookup[rgb] = true;\n }\n }\n\n for (i = 0; i < p.length; i++) {\n rgb = tinycolor(p[i]).toRgbString();\n\n if (!paletteLookup.hasOwnProperty(rgb)) {\n unique.push(p[i]);\n paletteLookup[rgb] = true;\n }\n }\n }\n\n return unique.reverse().slice(0, opts.maxSelectionSize);\n }\n\n function drawPalette() {\n\n var currentColor = get();\n\n var html = $.map(paletteArray, function (palette, i) {\n return paletteTemplate(palette, currentColor, \"sp-palette-row sp-palette-row-\" + i);\n });\n\n if (selectionPalette) {\n html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, \"sp-palette-row sp-palette-row-selection\"));\n }\n\n paletteContainer.html(html.join(\"\"));\n }\n\n function drawInitial() {\n if (opts.showInitial) {\n var initial = colorOnShow;\n var current = get();\n initialColorContainer.html(paletteTemplate([initial, current], current, \"sp-palette-row-initial\"));\n }\n }\n\n function dragStart() {\n if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) {\n reflow();\n }\n container.addClass(draggingClass);\n shiftMovementDirection = null;\n }\n\n function dragStop() {\n container.removeClass(draggingClass);\n }\n\n function setFromTextInput() {\n var tiny = tinycolor(textInput.val());\n if (tiny.ok) {\n set(tiny);\n }\n else {\n textInput.addClass(\"sp-validation-error\");\n }\n }\n\n function toggle() {\n if (visible) {\n hide();\n }\n else {\n show();\n }\n }\n\n function show() {\n var event = $.Event('beforeShow.spectrum');\n\n if (visible) {\n reflow();\n return;\n }\n\n colorOnShow = get();\n boundElement.trigger(event, [ colorOnShow ]);\n\n if (callbacks.beforeShow(colorOnShow) === false || event.isDefaultPrevented()) {\n return;\n }\n\n // if color has changed\n set(colorOnShow);\n\n hideAll();\n visible = true;\n\n $(doc).bind(\"mousedown.spectrum\", onMousedown);\n\n if (!flat) {\n // Piskel-specific : change the color as soon as the user does a mouseup\n $(doc).bind(\"mouseup.spectrum\", updateColor);\n }\n\n $(window).bind(\"resize.spectrum\", resize);\n replacer.addClass(\"sp-active\");\n container.removeClass(\"sp-hidden\");\n\n if (opts.showPalette) {\n drawPalette();\n }\n reflow();\n updateUI();\n\n drawInitial();\n callbacks.show(colorOnShow);\n boundElement.trigger('show.spectrum', [ colorOnShow ]);\n }\n\n function onMousedown (e) {\n var target = $(e.target);\n var parents = target.parents();\n var isClickOutsideWidget = !parents.is(container) && !target.is(container);\n\n if (isClickOutsideWidget) {\n hide(e);\n }\n }\n\n // Piskel-specific (code extracted to method)\n function updateColor(e) {\n var colorHasChanged = !tinycolor.equals(get(), colorOnShow);\n\n if (colorHasChanged) {\n if (clickoutFiresChange && e !== \"cancel\") {\n updateOriginalInput(true);\n }\n else {\n revert();\n }\n }\n }\n\n function hide(e) {\n\n // Return on right click\n if (e && e.type == \"click\" && e.button == 2) { return; }\n\n // Return if hiding is unnecessary\n if (!visible || flat) { return; }\n visible = false;\n\n $(doc).unbind(\"mousedown.spectrum\", onMousedown);\n\n // Piskel-specific\n $(doc).unbind(\"mouseup.spectrum\", updateColor);\n\n $(window).unbind(\"resize.spectrum\", resize);\n\n replacer.removeClass(\"sp-active\");\n container.addClass(\"sp-hidden\");\n\n updateColor(e);\n\n // Piskel-specific\n addColorToSelectionPalette(get());\n\n callbacks.hide(get());\n boundElement.trigger('hide.spectrum', [ get() ]);\n }\n\n function revert() {\n set(colorOnShow, true);\n }\n\n function set(color, ignoreFormatChange) {\n if (tinycolor.equals(color, get())) {\n return;\n }\n\n var newColor = tinycolor(color);\n var newHsv = newColor.toHsv();\n\n currentHue = (newHsv.h % 360) / 360;\n currentSaturation = newHsv.s;\n currentValue = newHsv.v;\n currentAlpha = newHsv.a;\n\n updateUI();\n\n if (newColor.ok && !ignoreFormatChange) {\n currentPreferredFormat = preferredFormat || newColor.format;\n }\n }\n\n function get(opts) {\n opts = opts || { };\n return tinycolor.fromRatio({\n h: currentHue,\n s: currentSaturation,\n v: currentValue,\n a: Math.round(currentAlpha * 100) / 100\n }, { format: opts.format || currentPreferredFormat });\n }\n\n function isValid() {\n return !textInput.hasClass(\"sp-validation-error\");\n }\n\n function move() {\n updateUI();\n\n callbacks.move(get());\n boundElement.trigger('move.spectrum', [ get() ]);\n }\n\n function updateUI() {\n\n textInput.removeClass(\"sp-validation-error\");\n\n updateHelperLocations();\n\n // Update dragger background color (gradients take care of saturation and value).\n var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 });\n dragger.css(\"background-color\", flatColor.toHexString());\n\n // Get a format that alpha will be included in (hex and names ignore alpha)\n var format = currentPreferredFormat;\n if (currentAlpha < 1) {\n if (format === \"hex\" || format === \"hex3\" || format === \"hex6\" || format === \"name\") {\n format = \"rgb\";\n }\n }\n\n var realColor = get({ format: format }),\n realHex = realColor.toHexString(),\n realRgb = realColor.toRgbString();\n\n // Update the replaced elements background color (with actual selected color)\n if (rgbaSupport || realColor.alpha === 1) {\n previewElement.css(\"background-color\", realRgb);\n }\n else {\n previewElement.css(\"background-color\", \"transparent\");\n previewElement.css(\"filter\", realColor.toFilter());\n }\n\n if (opts.showAlpha) {\n var rgb = realColor.toRgb();\n rgb.a = 0;\n var realAlpha = tinycolor(rgb).toRgbString();\n var gradient = \"linear-gradient(left, \" + realAlpha + \", \" + realHex + \")\";\n\n if (IE) {\n alphaSliderInner.css(\"filter\", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex));\n }\n else {\n alphaSliderInner.css(\"background\", \"-webkit-\" + gradient);\n alphaSliderInner.css(\"background\", \"-moz-\" + gradient);\n alphaSliderInner.css(\"background\", \"-ms-\" + gradient);\n alphaSliderInner.css(\"background\", gradient);\n }\n }\n\n // Update the text entry input as it changes happen\n if (opts.showInput) {\n var displayFormat = pskl.UserSettings.get(pskl.UserSettings.COLOR_FORMAT);\n textInput.val(realColor.toString(displayFormat));\n }\n\n if (opts.showPalette) {\n drawPalette();\n }\n\n drawInitial();\n }\n\n function updateHelperLocations() {\n var s = currentSaturation;\n var v = currentValue;\n\n // Where to show the little circle in that displays your current selected color\n var dragX = s * dragWidth;\n var dragY = (dragHeight) - (v * dragHeight);\n dragX = Math.max(\n -dragHelperHeight/2,\n Math.min(dragWidth - dragHelperHeight/2, dragX - dragHelperHeight/2)\n );\n dragY = Math.max(\n -dragHelperHeight/2,\n Math.min(dragHeight - dragHelperHeight/2, dragY - dragHelperHeight/2)\n );\n dragHelper.css({\n \"top\": dragY,\n \"left\": dragX\n });\n\n var alphaX = currentAlpha * alphaWidth;\n alphaSlideHelper.css({\n \"left\": alphaX - (alphaSlideHelperWidth / 2)\n });\n\n // Where to show the bar that displays your current selected hue\n var slideY = (currentHue) * slideHeight;\n slideHelper.css({\n \"top\": slideY - (slideHelperHeight/2)\n });\n }\n\n function updateOriginalInput(fireCallback) {\n var color = get();\n\n if (isInput) {\n boundElement.val(color.toString(currentPreferredFormat));\n }\n\n var hasChanged = !tinycolor.equals(color, colorOnShow);\n colorOnShow = color;\n\n // Update the selection palette with the current color\n\n // Piskel-specific : commented-out, palette update is done on hide\n // addColorToSelectionPalette(color);\n\n if (fireCallback && hasChanged) {\n callbacks.change(color);\n boundElement.trigger('change', [ color ]);\n }\n }\n\n function reflow() {\n dragWidth = dragger.width();\n dragHeight = dragger.height();\n dragHelperHeight = dragHelper.height() + 4;\n slideWidth = slider.width();\n slideHeight = slider.height();\n slideHelperHeight = slideHelper.height() + 4;\n alphaWidth = alphaSlider.width();\n alphaSlideHelperWidth = alphaSlideHelper.width();\n\n if (!flat) {\n container.css(\"position\", \"absolute\");\n container.offset(getOffset(container, offsetElement));\n }\n\n updateHelperLocations();\n }\n\n function destroy() {\n boundElement.show();\n offsetElement.unbind(\"click.spectrum touchstart.spectrum\");\n container.remove();\n replacer.remove();\n spectrums[spect.id] = null;\n }\n\n function option(optionName, optionValue) {\n if (optionName === undefined) {\n return $.extend({}, opts);\n }\n if (optionValue === undefined) {\n return opts[optionName];\n }\n\n opts[optionName] = optionValue;\n applyOptions();\n }\n\n function enable() {\n disabled = false;\n boundElement.attr(\"disabled\", false);\n offsetElement.removeClass(\"sp-disabled\");\n }\n\n function disable() {\n hide();\n disabled = true;\n boundElement.attr(\"disabled\", true);\n offsetElement.addClass(\"sp-disabled\");\n }\n\n initialize();\n\n var spect = {\n show: show,\n hide: hide,\n toggle: toggle,\n reflow: reflow,\n option: option,\n enable: enable,\n disable: disable,\n set: function (c) {\n set(c);\n updateOriginalInput();\n },\n get: get,\n destroy: destroy,\n container: container\n };\n\n spect.id = spectrums.push(spect) - 1;\n\n return spect;\n }\n\n /**\n * checkOffset - get the offset below/above and left/right element depending on screen position\n * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js\n */\n function getOffset(picker, input) {\n var extraY = 0;\n var dpWidth = picker.outerWidth();\n var dpHeight = picker.outerHeight();\n var inputHeight = input.outerHeight();\n var doc = picker[0].ownerDocument;\n var docElem = doc.documentElement;\n var viewWidth = docElem.clientWidth + $(doc).scrollLeft();\n var viewHeight = docElem.clientHeight + $(doc).scrollTop();\n var offset = input.offset();\n offset.top += inputHeight;\n\n if (Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth))) {\n offset.left -= Math.abs(offset.left + dpWidth - viewWidth);\n picker.attr('data-x-position','right');\n } else {\n offset.left -= 0;\n picker.attr('data-x-position','left');\n }\n\n if (Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight))) {\n offset.top -= Math.abs(dpHeight + inputHeight - extraY);\n picker.attr('data-y-position','top');\n } else {\n offset.top -= extraY;\n picker.attr('data-y-position','bottom');\n }\n\n return offset;\n }\n\n /**\n * noop - do nothing\n */\n function noop() {\n\n }\n\n /**\n * stopPropagation - makes the code only doing this a little easier to read in line\n */\n function stopPropagation(e) {\n e.stopPropagation();\n }\n\n /**\n * Create a function bound to a given object\n * Thanks to underscore.js\n */\n function bind(func, obj) {\n var slice = Array.prototype.slice;\n var args = slice.call(arguments, 2);\n return function () {\n return func.apply(obj, args.concat(slice.call(arguments)));\n };\n }\n\n /**\n * Lightweight drag helper. Handles containment within the element, so that\n * when dragging, the x is within [0,element.width] and y is within [0,element.height]\n */\n function draggable(element, onmove, onstart, onstop) {\n onmove = onmove || function () { };\n onstart = onstart || function () { };\n onstop = onstop || function () { };\n var doc = element.ownerDocument || document;\n var dragging = false;\n var offset = {};\n var maxHeight = 0;\n var maxWidth = 0;\n var hasTouch = ('ontouchstart' in window);\n\n var duringDragEvents = {};\n duringDragEvents[\"selectstart\"] = prevent;\n duringDragEvents[\"dragstart\"] = prevent;\n duringDragEvents[\"touchmove mousemove\"] = move;\n duringDragEvents[\"touchend mouseup\"] = stop;\n\n function prevent(e) {\n if (e.stopPropagation) {\n e.stopPropagation();\n }\n if (e.preventDefault) {\n e.preventDefault();\n }\n e.returnValue = false;\n }\n\n function move(e) {\n if (dragging) {\n // Mouseup happened outside of window\n if (IE && document.documentMode < 9 && !e.button) {\n return stop();\n }\n\n var touches = e.originalEvent.touches;\n var pageX = touches ? touches[0].pageX : e.pageX;\n var pageY = touches ? touches[0].pageY : e.pageY;\n\n var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth));\n var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight));\n\n if (hasTouch) {\n // Stop scrolling in iOS\n prevent(e);\n }\n\n onmove.apply(element, [dragX, dragY, e]);\n }\n }\n function start(e) {\n var rightclick = (e.which) ? (e.which == 3) : (e.button == 2);\n var touches = e.originalEvent.touches;\n\n if (!rightclick && !dragging) {\n if (onstart.apply(element, arguments) !== false) {\n dragging = true;\n maxHeight = $(element).height();\n maxWidth = $(element).width();\n offset = $(element).offset();\n\n $(doc).bind(duringDragEvents);\n $(doc.body).addClass(\"sp-dragging\");\n\n if (!hasTouch) {\n move(e);\n }\n\n prevent(e);\n }\n }\n }\n function stop() {\n if (dragging) {\n $(doc).unbind(duringDragEvents);\n $(doc.body).removeClass(\"sp-dragging\");\n onstop.apply(element, arguments);\n }\n dragging = false;\n }\n\n $(element).bind(\"touchstart mousedown\", start);\n }\n\n function throttle(func, wait, debounce) {\n var timeout;\n return function () {\n var context = this, args = arguments;\n var throttler = function () {\n timeout = null;\n func.apply(context, args);\n };\n if (debounce) clearTimeout(timeout);\n if (debounce || !timeout) timeout = setTimeout(throttler, wait);\n };\n }\n\n\n function log(){/* jshint -W021 */if(window.console){if(Function.prototype.bind)log=Function.prototype.bind.call(console.log,console);else log=function(){Function.prototype.apply.call(console.log,console,arguments);};log.apply(this,arguments);}}\n\n /**\n * Define a jQuery plugin\n */\n var dataID = \"spectrum.id\";\n $.fn.spectrum = function (opts, extra) {\n\n if (typeof opts == \"string\") {\n\n var returnValue = this;\n var args = Array.prototype.slice.call( arguments, 1 );\n\n this.each(function () {\n var spect = spectrums[$(this).data(dataID)];\n if (spect) {\n\n var method = spect[opts];\n if (!method) {\n throw new Error( \"Spectrum: no such method: '\" + opts + \"'\" );\n }\n\n if (opts == \"get\") {\n returnValue = spect.get();\n }\n else if (opts == \"container\") {\n returnValue = spect.container;\n }\n else if (opts == \"option\") {\n returnValue = spect.option.apply(spect, args);\n }\n else if (opts == \"destroy\") {\n spect.destroy();\n $(this).removeData(dataID);\n }\n else {\n method.apply(spect, args);\n }\n }\n });\n\n return returnValue;\n }\n\n // Initializing a new instance of spectrum\n return this.spectrum(\"destroy\").each(function () {\n var spect = spectrum(this, opts);\n $(this).data(dataID, spect.id);\n });\n };\n\n $.fn.spectrum.load = true;\n $.fn.spectrum.loadOpts = {};\n $.fn.spectrum.draggable = draggable;\n $.fn.spectrum.defaults = defaultOpts;\n\n $.spectrum = { };\n $.spectrum.localization = { };\n $.spectrum.palettes = { };\n\n $.fn.spectrum.processNativeColorInputs = function () {\n var colorInput = $(\"\")[0];\n var supportsColor = colorInput.type === \"color\" && colorInput.value != \"!\";\n\n if (!supportsColor) {\n $(\"input[type=color]\").spectrum({\n preferredFormat: \"hex6\"\n });\n }\n };\n\n // TinyColor v0.9.16\n // https://github.com/bgrins/TinyColor\n // 2013-08-10, Brian Grinstead, MIT License\n\n (function() {\n\n var trimLeft = /^[\\s,#]+/,\n trimRight = /\\s+$/,\n tinyCounter = 0,\n math = Math,\n mathRound = math.round,\n mathMin = math.min,\n mathMax = math.max,\n mathRandom = math.random;\n\n function tinycolor (color, opts) {\n\n color = (color) ? color : '';\n opts = opts || { };\n\n // If input is already a tinycolor, return itself\n if (typeof color == \"object\" && color.hasOwnProperty(\"_tc_id\")) {\n return color;\n }\n\n var rgb = inputToRGB(color);\n var r = rgb.r,\n g = rgb.g,\n b = rgb.b,\n a = rgb.a,\n roundA = mathRound(100*a) / 100,\n format = opts.format || rgb.format;\n\n // Don't let the range of [0,255] come back in [0,1].\n // Potentially lose a little bit of precision here, but will fix issues where\n // .5 gets interpreted as half of the total, instead of half of 1\n // If it was supposed to be 128, this was already taken care of by `inputToRgb`\n if (r < 1) { r = mathRound(r); }\n if (g < 1) { g = mathRound(g); }\n if (b < 1) { b = mathRound(b); }\n\n return {\n ok: rgb.ok,\n format: format,\n _tc_id: tinyCounter++,\n alpha: a,\n getAlpha: function() {\n return a;\n },\n setAlpha: function(value) {\n a = boundAlpha(value);\n roundA = mathRound(100*a) / 100;\n },\n toHsv: function() {\n var hsv = rgbToHsv(r, g, b);\n return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: a };\n },\n toHsvString: function() {\n var hsv = rgbToHsv(r, g, b);\n var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);\n return (a == 1) ?\n \"hsv(\" + h + \", \" + s + \"%, \" + v + \"%)\" :\n \"hsva(\" + h + \", \" + s + \"%, \" + v + \"%, \"+ roundA + \")\";\n },\n toHsl: function() {\n var hsl = rgbToHsl(r, g, b);\n return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: a };\n },\n toHslString: function() {\n var hsl = rgbToHsl(r, g, b);\n var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);\n return (a == 1) ?\n \"hsl(\" + h + \", \" + s + \"%, \" + l + \"%)\" :\n \"hsla(\" + h + \", \" + s + \"%, \" + l + \"%, \"+ roundA + \")\";\n },\n toHex: function(allow3Char) {\n return rgbToHex(r, g, b, allow3Char);\n },\n toHexString: function(allow3Char) {\n return '#' + rgbToHex(r, g, b, allow3Char);\n },\n toRgb: function() {\n return { r: mathRound(r), g: mathRound(g), b: mathRound(b), a: a };\n },\n toRgbString: function() {\n return (a == 1) ?\n \"rgb(\" + mathRound(r) + \", \" + mathRound(g) + \", \" + mathRound(b) + \")\" :\n \"rgba(\" + mathRound(r) + \", \" + mathRound(g) + \", \" + mathRound(b) + \", \" + roundA + \")\";\n },\n toPercentageRgb: function() {\n return { r: mathRound(bound01(r, 255) * 100) + \"%\", g: mathRound(bound01(g, 255) * 100) + \"%\", b: mathRound(bound01(b, 255) * 100) + \"%\", a: a };\n },\n toPercentageRgbString: function() {\n return (a == 1) ?\n \"rgb(\" + mathRound(bound01(r, 255) * 100) + \"%, \" + mathRound(bound01(g, 255) * 100) + \"%, \" + mathRound(bound01(b, 255) * 100) + \"%)\" :\n \"rgba(\" + mathRound(bound01(r, 255) * 100) + \"%, \" + mathRound(bound01(g, 255) * 100) + \"%, \" + mathRound(bound01(b, 255) * 100) + \"%, \" + roundA + \")\";\n },\n toName: function() {\n if (a === 0) {\n return \"transparent\";\n }\n\n return hexNames[rgbToHex(r, g, b, true)] || false;\n },\n toFilter: function(secondColor) {\n var hex = rgbToHex(r, g, b);\n var secondHex = hex;\n var alphaHex = Math.round(parseFloat(a) * 255).toString(16);\n var secondAlphaHex = alphaHex;\n var gradientType = opts && opts.gradientType ? \"GradientType = 1, \" : \"\";\n\n if (secondColor) {\n var s = tinycolor(secondColor);\n secondHex = s.toHex();\n secondAlphaHex = Math.round(parseFloat(s.alpha) * 255).toString(16);\n }\n\n return \"progid:DXImageTransform.Microsoft.gradient(\"+gradientType+\"startColorstr=#\" + pad2(alphaHex) + hex + \",endColorstr=#\" + pad2(secondAlphaHex) + secondHex + \")\";\n },\n toString: function(format) {\n var formatSet = !!format;\n format = format || this.format;\n\n var formattedString = false;\n var hasAlphaAndFormatNotSet = !formatSet && a < 1 && a > 0;\n var formatWithAlpha = hasAlphaAndFormatNotSet && (format === \"hex\" || format === \"hex6\" || format === \"hex3\" || format === \"name\");\n\n if (format === \"rgb\") {\n formattedString = this.toRgbString();\n }\n if (format === \"prgb\") {\n formattedString = this.toPercentageRgbString();\n }\n if (format === \"hex\" || format === \"hex6\") {\n formattedString = this.toHexString();\n }\n if (format === \"hex3\") {\n formattedString = this.toHexString(true);\n }\n if (format === \"name\") {\n formattedString = this.toName();\n }\n if (format === \"hsl\") {\n formattedString = this.toHslString();\n }\n if (format === \"hsv\") {\n formattedString = this.toHsvString();\n }\n\n if (formatWithAlpha) {\n return this.toRgbString();\n }\n\n return formattedString || this.toHexString();\n }\n };\n }\n\n // If input is an object, force 1 into \"1.0\" to handle ratios properly\n // String input requires \"1.0\" as input, so 1 will be treated as 1\n tinycolor.fromRatio = function(color, opts) {\n if (typeof color == \"object\") {\n var newColor = {};\n for (var i in color) {\n if (color.hasOwnProperty(i)) {\n if (i === \"a\") {\n newColor[i] = color[i];\n }\n else {\n newColor[i] = convertToPercentage(color[i]);\n }\n }\n }\n color = newColor;\n }\n\n return tinycolor(color, opts);\n };\n\n // Given a string or object, convert that input to RGB\n // Possible string inputs:\n //\n // \"red\"\n // \"#f00\" or \"f00\"\n // \"#ff0000\" or \"ff0000\"\n // \"rgb 255 0 0\" or \"rgb (255, 0, 0)\"\n // \"rgb 1.0 0 0\" or \"rgb (1, 0, 0)\"\n // \"rgba (255, 0, 0, 1)\" or \"rgba 255, 0, 0, 1\"\n // \"rgba (1.0, 0, 0, 1)\" or \"rgba 1.0, 0, 0, 1\"\n // \"hsl(0, 100%, 50%)\" or \"hsl 0 100% 50%\"\n // \"hsla(0, 100%, 50%, 1)\" or \"hsla 0 100% 50%, 1\"\n // \"hsv(0, 100%, 100%)\" or \"hsv 0 100% 100%\"\n //\n function inputToRGB(color) {\n\n var rgb = { r: 0, g: 0, b: 0 };\n var a = 1;\n var ok = false;\n var format = false;\n\n if (typeof color == \"string\") {\n color = stringInputToObject(color);\n }\n\n if (typeof color == \"object\") {\n if (color.hasOwnProperty(\"r\") && color.hasOwnProperty(\"g\") && color.hasOwnProperty(\"b\")) {\n rgb = rgbToRgb(color.r, color.g, color.b);\n ok = true;\n format = String(color.r).substr(-1) === \"%\" ? \"prgb\" : \"rgb\";\n }\n else if (color.hasOwnProperty(\"h\") && color.hasOwnProperty(\"s\") && color.hasOwnProperty(\"v\")) {\n color.s = convertToPercentage(color.s);\n color.v = convertToPercentage(color.v);\n rgb = hsvToRgb(color.h, color.s, color.v);\n ok = true;\n format = \"hsv\";\n }\n else if (color.hasOwnProperty(\"h\") && color.hasOwnProperty(\"s\") && color.hasOwnProperty(\"l\")) {\n color.s = convertToPercentage(color.s);\n color.l = convertToPercentage(color.l);\n rgb = hslToRgb(color.h, color.s, color.l);\n ok = true;\n format = \"hsl\";\n }\n\n if (color.hasOwnProperty(\"a\")) {\n a = color.a;\n }\n }\n\n a = boundAlpha(a);\n\n return {\n ok: ok,\n format: color.format || format,\n r: mathMin(255, mathMax(rgb.r, 0)),\n g: mathMin(255, mathMax(rgb.g, 0)),\n b: mathMin(255, mathMax(rgb.b, 0)),\n a: a\n };\n }\n\n\n // Conversion Functions\n // --------------------\n\n // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:\n // \n\n // `rgbToRgb`\n // Handle bounds / percentage checking to conform to CSS color spec\n // \n // *Assumes:* r, g, b in [0, 255] or [0, 1]\n // *Returns:* { r, g, b } in [0, 255]\n function rgbToRgb(r, g, b){\n return {\n r: bound01(r, 255) * 255,\n g: bound01(g, 255) * 255,\n b: bound01(b, 255) * 255\n };\n }\n\n // `rgbToHsl`\n // Converts an RGB color value to HSL.\n // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]\n // *Returns:* { h, s, l } in [0,1]\n function rgbToHsl(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, l = (max + min) / 2;\n\n if(max == min) {\n h = s = 0; // achromatic\n }\n else {\n var d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n\n h /= 6;\n }\n\n return { h: h, s: s, l: l };\n }\n\n // `hslToRgb`\n // Converts an HSL color value to RGB.\n // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]\n // *Returns:* { r, g, b } in the set [0, 255]\n function hslToRgb(h, s, l) {\n var r, g, b;\n\n h = bound01(h, 360);\n s = bound01(s, 100);\n l = bound01(l, 100);\n\n function hue2rgb(p, q, t) {\n if(t < 0) t += 1;\n if(t > 1) t -= 1;\n if(t < 1/6) return p + (q - p) * 6 * t;\n if(t < 1/2) return q;\n if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;\n return p;\n }\n\n if(s === 0) {\n r = g = b = l; // achromatic\n }\n else {\n var q = l < 0.5 ? l * (1 + s) : l + s - l * s;\n var p = 2 * l - q;\n r = hue2rgb(p, q, h + 1/3);\n g = hue2rgb(p, q, h);\n b = hue2rgb(p, q, h - 1/3);\n }\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n }\n\n // `rgbToHsv`\n // Converts an RGB color value to HSV\n // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]\n // *Returns:* { h, s, v } in [0,1]\n function rgbToHsv(r, g, b) {\n\n r = bound01(r, 255);\n g = bound01(g, 255);\n b = bound01(b, 255);\n\n var max = mathMax(r, g, b), min = mathMin(r, g, b);\n var h, s, v = max;\n\n var d = max - min;\n s = max === 0 ? 0 : d / max;\n\n if(max == min) {\n h = 0; // achromatic\n }\n else {\n switch(max) {\n case r: h = (g - b) / d + (g < b ? 6 : 0); break;\n case g: h = (b - r) / d + 2; break;\n case b: h = (r - g) / d + 4; break;\n }\n h /= 6;\n }\n return { h: h, s: s, v: v };\n }\n\n // `hsvToRgb`\n // Converts an HSV color value to RGB.\n // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]\n // *Returns:* { r, g, b } in the set [0, 255]\n function hsvToRgb(h, s, v) {\n\n h = bound01(h, 360) * 6;\n s = bound01(s, 100);\n v = bound01(v, 100);\n\n var i = math.floor(h),\n f = h - i,\n p = v * (1 - s),\n q = v * (1 - f * s),\n t = v * (1 - (1 - f) * s),\n mod = i % 6,\n r = [v, q, p, p, t, v][mod],\n g = [t, v, v, q, p, p][mod],\n b = [p, p, t, v, v, q][mod];\n\n return { r: r * 255, g: g * 255, b: b * 255 };\n }\n\n // `rgbToHex`\n // Converts an RGB color to hex\n // Assumes r, g, and b are contained in the set [0, 255]\n // Returns a 3 or 6 character hex\n function rgbToHex(r, g, b, allow3Char) {\n\n var hex = [\n pad2(mathRound(r).toString(16)),\n pad2(mathRound(g).toString(16)),\n pad2(mathRound(b).toString(16))\n ];\n\n // Return a 3 character hex if possible\n if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {\n return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);\n }\n\n return hex.join(\"\");\n }\n\n // `equals`\n // Can be called with any tinycolor input\n tinycolor.equals = function (color1, color2) {\n if (!color1 || !color2) { return false; }\n return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();\n };\n tinycolor.random = function() {\n return tinycolor.fromRatio({\n r: mathRandom(),\n g: mathRandom(),\n b: mathRandom()\n });\n };\n\n\n // Modification Functions\n // ----------------------\n // Thanks to less.js for some of the basics here\n // \n\n tinycolor.desaturate = function (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s -= amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n };\n tinycolor.saturate = function (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.s += amount / 100;\n hsl.s = clamp01(hsl.s);\n return tinycolor(hsl);\n };\n tinycolor.greyscale = function(color) {\n return tinycolor.desaturate(color, 100);\n };\n tinycolor.lighten = function(color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l += amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n };\n tinycolor.darken = function (color, amount) {\n amount = (amount === 0) ? 0 : (amount || 10);\n var hsl = tinycolor(color).toHsl();\n hsl.l -= amount / 100;\n hsl.l = clamp01(hsl.l);\n return tinycolor(hsl);\n };\n tinycolor.complement = function(color) {\n var hsl = tinycolor(color).toHsl();\n hsl.h = (hsl.h + 180) % 360;\n return tinycolor(hsl);\n };\n\n\n // Combination Functions\n // ---------------------\n // Thanks to jQuery xColor for some of the ideas behind these\n // \n\n tinycolor.triad = function(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })\n ];\n };\n tinycolor.tetrad = function(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),\n tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })\n ];\n };\n tinycolor.splitcomplement = function(color) {\n var hsl = tinycolor(color).toHsl();\n var h = hsl.h;\n return [\n tinycolor(color),\n tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),\n tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})\n ];\n };\n tinycolor.analogous = function(color, results, slices) {\n results = results || 6;\n slices = slices || 30;\n\n var hsl = tinycolor(color).toHsl();\n var part = 360 / slices;\n var ret = [tinycolor(color)];\n\n for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {\n hsl.h = (hsl.h + part) % 360;\n ret.push(tinycolor(hsl));\n }\n return ret;\n };\n tinycolor.monochromatic = function(color, results) {\n results = results || 6;\n var hsv = tinycolor(color).toHsv();\n var h = hsv.h, s = hsv.s, v = hsv.v;\n var ret = [];\n var modification = 1 / results;\n\n while (results--) {\n ret.push(tinycolor({ h: h, s: s, v: v}));\n v = (v + modification) % 1;\n }\n\n return ret;\n };\n\n\n // Readability Functions\n // ---------------------\n // \n\n // `readability`\n // Analyze the 2 colors and returns an object with the following properties:\n // `brightness`: difference in brightness between the two colors\n // `color`: difference in color/hue between the two colors\n tinycolor.readability = function(color1, color2) {\n var a = tinycolor(color1).toRgb();\n var b = tinycolor(color2).toRgb();\n var brightnessA = (a.r * 299 + a.g * 587 + a.b * 114) / 1000;\n var brightnessB = (b.r * 299 + b.g * 587 + b.b * 114) / 1000;\n var colorDiff = (\n Math.max(a.r, b.r) - Math.min(a.r, b.r) +\n Math.max(a.g, b.g) - Math.min(a.g, b.g) +\n Math.max(a.b, b.b) - Math.min(a.b, b.b)\n );\n\n return {\n brightness: Math.abs(brightnessA - brightnessB),\n color: colorDiff\n };\n };\n\n // `readable`\n // http://www.w3.org/TR/AERT#color-contrast\n // Ensure that foreground and background color combinations provide sufficient contrast.\n // *Example*\n // tinycolor.readable(\"#000\", \"#111\") => false\n tinycolor.readable = function(color1, color2) {\n var readability = tinycolor.readability(color1, color2);\n return readability.brightness > 125 && readability.color > 500;\n };\n\n // `mostReadable`\n // Given a base color and a list of possible foreground or background\n // colors for that base, returns the most readable color.\n // *Example*\n // tinycolor.mostReadable(\"#123\", [\"#fff\", \"#000\"]) => \"#000\"\n tinycolor.mostReadable = function(baseColor, colorList) {\n var bestColor = null;\n var bestScore = 0;\n var bestIsReadable = false;\n for (var i=0; i < colorList.length; i++) {\n\n // We normalize both around the \"acceptable\" breaking point,\n // but rank brightness constrast higher than hue.\n\n var readability = tinycolor.readability(baseColor, colorList[i]);\n var readable = readability.brightness > 125 && readability.color > 500;\n var score = 3 * (readability.brightness / 125) + (readability.color / 500);\n\n if ((readable && ! bestIsReadable) ||\n (readable && bestIsReadable && score > bestScore) ||\n ((! readable) && (! bestIsReadable) && score > bestScore)) {\n bestIsReadable = readable;\n bestScore = score;\n bestColor = tinycolor(colorList[i]);\n }\n }\n return bestColor;\n };\n\n\n // Big List of Colors\n // ------------------\n // \n var names = tinycolor.names = {\n aliceblue: \"f0f8ff\",\n antiquewhite: \"faebd7\",\n aqua: \"0ff\",\n aquamarine: \"7fffd4\",\n azure: \"f0ffff\",\n beige: \"f5f5dc\",\n bisque: \"ffe4c4\",\n black: \"000\",\n blanchedalmond: \"ffebcd\",\n blue: \"00f\",\n blueviolet: \"8a2be2\",\n brown: \"a52a2a\",\n burlywood: \"deb887\",\n burntsienna: \"ea7e5d\",\n cadetblue: \"5f9ea0\",\n chartreuse: \"7fff00\",\n chocolate: \"d2691e\",\n coral: \"ff7f50\",\n cornflowerblue: \"6495ed\",\n cornsilk: \"fff8dc\",\n crimson: \"dc143c\",\n cyan: \"0ff\",\n darkblue: \"00008b\",\n darkcyan: \"008b8b\",\n darkgoldenrod: \"b8860b\",\n darkgray: \"a9a9a9\",\n darkgreen: \"006400\",\n darkgrey: \"a9a9a9\",\n darkkhaki: \"bdb76b\",\n darkmagenta: \"8b008b\",\n darkolivegreen: \"556b2f\",\n darkorange: \"ff8c00\",\n darkorchid: \"9932cc\",\n darkred: \"8b0000\",\n darksalmon: \"e9967a\",\n darkseagreen: \"8fbc8f\",\n darkslateblue: \"483d8b\",\n darkslategray: \"2f4f4f\",\n darkslategrey: \"2f4f4f\",\n darkturquoise: \"00ced1\",\n darkviolet: \"9400d3\",\n deeppink: \"ff1493\",\n deepskyblue: \"00bfff\",\n dimgray: \"696969\",\n dimgrey: \"696969\",\n dodgerblue: \"1e90ff\",\n firebrick: \"b22222\",\n floralwhite: \"fffaf0\",\n forestgreen: \"228b22\",\n fuchsia: \"f0f\",\n gainsboro: \"dcdcdc\",\n ghostwhite: \"f8f8ff\",\n gold: \"ffd700\",\n goldenrod: \"daa520\",\n gray: \"808080\",\n green: \"008000\",\n greenyellow: \"adff2f\",\n grey: \"808080\",\n honeydew: \"f0fff0\",\n hotpink: \"ff69b4\",\n indianred: \"cd5c5c\",\n indigo: \"4b0082\",\n ivory: \"fffff0\",\n khaki: \"f0e68c\",\n lavender: \"e6e6fa\",\n lavenderblush: \"fff0f5\",\n lawngreen: \"7cfc00\",\n lemonchiffon: \"fffacd\",\n lightblue: \"add8e6\",\n lightcoral: \"f08080\",\n lightcyan: \"e0ffff\",\n lightgoldenrodyellow: \"fafad2\",\n lightgray: \"d3d3d3\",\n lightgreen: \"90ee90\",\n lightgrey: \"d3d3d3\",\n lightpink: \"ffb6c1\",\n lightsalmon: \"ffa07a\",\n lightseagreen: \"20b2aa\",\n lightskyblue: \"87cefa\",\n lightslategray: \"789\",\n lightslategrey: \"789\",\n lightsteelblue: \"b0c4de\",\n lightyellow: \"ffffe0\",\n lime: \"0f0\",\n limegreen: \"32cd32\",\n linen: \"faf0e6\",\n magenta: \"f0f\",\n maroon: \"800000\",\n mediumaquamarine: \"66cdaa\",\n mediumblue: \"0000cd\",\n mediumorchid: \"ba55d3\",\n mediumpurple: \"9370db\",\n mediumseagreen: \"3cb371\",\n mediumslateblue: \"7b68ee\",\n mediumspringgreen: \"00fa9a\",\n mediumturquoise: \"48d1cc\",\n mediumvioletred: \"c71585\",\n midnightblue: \"191970\",\n mintcream: \"f5fffa\",\n mistyrose: \"ffe4e1\",\n moccasin: \"ffe4b5\",\n navajowhite: \"ffdead\",\n navy: \"000080\",\n oldlace: \"fdf5e6\",\n olive: \"808000\",\n olivedrab: \"6b8e23\",\n orange: \"ffa500\",\n orangered: \"ff4500\",\n orchid: \"da70d6\",\n palegoldenrod: \"eee8aa\",\n palegreen: \"98fb98\",\n paleturquoise: \"afeeee\",\n palevioletred: \"db7093\",\n papayawhip: \"ffefd5\",\n peachpuff: \"ffdab9\",\n peru: \"cd853f\",\n pink: \"ffc0cb\",\n plum: \"dda0dd\",\n powderblue: \"b0e0e6\",\n purple: \"800080\",\n red: \"f00\",\n rosybrown: \"bc8f8f\",\n royalblue: \"4169e1\",\n saddlebrown: \"8b4513\",\n salmon: \"fa8072\",\n sandybrown: \"f4a460\",\n seagreen: \"2e8b57\",\n seashell: \"fff5ee\",\n sienna: \"a0522d\",\n silver: \"c0c0c0\",\n skyblue: \"87ceeb\",\n slateblue: \"6a5acd\",\n slategray: \"708090\",\n slategrey: \"708090\",\n snow: \"fffafa\",\n springgreen: \"00ff7f\",\n steelblue: \"4682b4\",\n tan: \"d2b48c\",\n teal: \"008080\",\n thistle: \"d8bfd8\",\n tomato: \"ff6347\",\n turquoise: \"40e0d0\",\n violet: \"ee82ee\",\n wheat: \"f5deb3\",\n white: \"fff\",\n whitesmoke: \"f5f5f5\",\n yellow: \"ff0\",\n yellowgreen: \"9acd32\"\n };\n\n // Make it easy to access colors via `hexNames[hex]`\n var hexNames = tinycolor.hexNames = flip(names);\n\n\n // Utilities\n // ---------\n\n // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`\n function flip(o) {\n var flipped = { };\n for (var i in o) {\n if (o.hasOwnProperty(i)) {\n flipped[o[i]] = i;\n }\n }\n return flipped;\n }\n\n // Return a valid alpha value [0,1] with all invalid values being set to 1\n function boundAlpha(a) {\n a = parseFloat(a);\n\n if (isNaN(a) || a < 0 || a > 1) {\n a = 1;\n }\n\n return a;\n }\n\n // Take input from [0, n] and return it as [0, 1]\n function bound01(n, max) {\n if (isOnePointZero(n)) { n = \"100%\"; }\n\n var processPercent = isPercentage(n);\n n = mathMin(max, mathMax(0, parseFloat(n)));\n\n // Automatically convert percentage into number\n if (processPercent) {\n n = parseInt(n * max, 10) / 100;\n }\n\n // Handle floating point rounding errors\n if ((math.abs(n - max) < 0.000001)) {\n return 1;\n }\n\n // Convert into [0, 1] range if it isn't already\n return (n % max) / parseFloat(max);\n }\n\n // Force a number between 0 and 1\n function clamp01(val) {\n return mathMin(1, mathMax(0, val));\n }\n\n // Parse an integer into hex\n function parseHex(val) {\n return parseInt(val, 16);\n }\n\n // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1\n // \n function isOnePointZero(n) {\n return typeof n == \"string\" && n.indexOf('.') != -1 && parseFloat(n) === 1;\n }\n\n // Check to see if string passed in is a percentage\n function isPercentage(n) {\n return typeof n === \"string\" && n.indexOf('%') != -1;\n }\n\n // Force a hex value to have 2 characters\n function pad2(c) {\n return c.length == 1 ? '0' + c : '' + c;\n }\n\n // Replace a decimal with it's percentage value\n function convertToPercentage(n) {\n if (n <= 1) {\n n = (n * 100) + \"%\";\n }\n\n return n;\n }\n\n var matchers = (function() {\n\n // \n var CSS_INTEGER = \"[-\\\\+]?\\\\d+%?\";\n\n // \n var CSS_NUMBER = \"[-\\\\+]?\\\\d*\\\\.\\\\d+%?\";\n\n // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.\n var CSS_UNIT = \"(?:\" + CSS_NUMBER + \")|(?:\" + CSS_INTEGER + \")\";\n\n // Actual matching.\n // Parentheses and commas are optional, but not required.\n // Whitespace can take the place of commas or opening paren\n var PERMISSIVE_MATCH3 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n var PERMISSIVE_MATCH4 = \"[\\\\s|\\\\(]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")[,|\\\\s]+(\" + CSS_UNIT + \")\\\\s*\\\\)?\";\n\n return {\n rgb: new RegExp(\"rgb\" + PERMISSIVE_MATCH3),\n rgba: new RegExp(\"rgba\" + PERMISSIVE_MATCH4),\n hsl: new RegExp(\"hsl\" + PERMISSIVE_MATCH3),\n hsla: new RegExp(\"hsla\" + PERMISSIVE_MATCH4),\n hsv: new RegExp(\"hsv\" + PERMISSIVE_MATCH3),\n hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,\n hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/\n };\n })();\n\n // `stringInputToObject`\n // Permissive string parsing. Take in a number of formats, and output an object\n // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`\n function stringInputToObject(color) {\n\n color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();\n var named = false;\n if (names[color]) {\n color = names[color];\n named = true;\n }\n else if (color == 'transparent') {\n return { r: 0, g: 0, b: 0, a: 0, format: \"name\" };\n }\n\n // Try to match string input using regular expressions.\n // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]\n // Just return an object and let the conversion functions handle that.\n // This way the result will be the same whether the tinycolor is initialized with string or object.\n var match;\n if ((match = matchers.rgb.exec(color))) {\n return { r: match[1], g: match[2], b: match[3] };\n }\n if ((match = matchers.rgba.exec(color))) {\n return { r: match[1], g: match[2], b: match[3], a: match[4] };\n }\n if ((match = matchers.hsl.exec(color))) {\n return { h: match[1], s: match[2], l: match[3] };\n }\n if ((match = matchers.hsla.exec(color))) {\n return { h: match[1], s: match[2], l: match[3], a: match[4] };\n }\n if ((match = matchers.hsv.exec(color))) {\n return { h: match[1], s: match[2], v: match[3] };\n }\n if ((match = matchers.hex6.exec(color))) {\n return {\n r: parseHex(match[1]),\n g: parseHex(match[2]),\n b: parseHex(match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n if ((match = matchers.hex3.exec(color))) {\n return {\n r: parseHex(match[1] + '' + match[1]),\n g: parseHex(match[2] + '' + match[2]),\n b: parseHex(match[3] + '' + match[3]),\n format: named ? \"name\" : \"hex\"\n };\n }\n\n return false;\n }\n\n // Expose tinycolor to window, does not need to run in non-browser context.\n window.tinycolor = tinycolor;\n\n })();\n var tinycolor = window.tinycolor;\n\n $(function () {\n if ($.fn.spectrum.load) {\n $.fn.spectrum.processNativeColorInputs();\n }\n });\n\n})(window, jQuery);\n","// vim:ts=4:sts=4:sw=4:\n/*!\n *\n * Copyright 2009-2012 Kris Kowal under the terms of the MIT\n * license found at http://github.com/kriskowal/q/raw/master/LICENSE\n *\n * With parts by Tyler Close\n * Copyright 2007-2009 Tyler Close under the terms of the MIT X license found\n * at http://www.opensource.org/licenses/mit-license.html\n * Forked at ref_send.js version: 2009-05-11\n *\n * With parts by Mark Miller\n * Copyright (C) 2011 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n */\n\n(function (definition) {\n \"use strict\";\n\n // This file will function properly as a + + + +
        +
        +
        +
        +
          +
          +
          +
          +
          + +
          + +
          +
          +
          +
          +
          + +
          +
          +
          +
          +
          +
          +
          + 1x +
          +
          +
          + Full +
          +
          +
          +
          +
          + +
          +
          +
          +
          +
          +
          + + +
          +
          +
          + +
          +

          + Layers +
          +

          +
          + + + + + + + + + + + +
          + +
            + + + + +
            + +
            +

            + Transform + +

            +
              +
              + +
              +

              Palettes

              +
              + + + +
              +
              + + + +
              + +
              +
              +
              + +
              +
              +
              +
              + +
              + +
              + +
              + +
              +
              + +
              +
              +
              +
              +
              +
              + + +
              +
              +
              +
              + +
              + + + + + + + + + + +
              + +
              + +
              + +
              + +
              + + +  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +{% endraw %} \ No newline at end of file diff --git a/vendor/piskel-prod/piskelapp-partials/piskel-web-partial-kids.html b/vendor/piskel-prod/piskelapp-partials/piskel-web-partial-kids.html new file mode 100644 index 0000000..0b6f6b8 --- /dev/null +++ b/vendor/piskel-prod/piskelapp-partials/piskel-web-partial-kids.html @@ -0,0 +1,1541 @@ +--- +layout: "editorLayout.html" +enableSafeMode: true +--- + + +
              +
              +
              +
              +
              +
              +
              +
              +
              +
              +
              +
              +
              + +
              +
              + +
              +
              +
              +
              +
              + + + + + +
              + + +
              +
              +
              +
              +
                +
                +
                +
                +
                + +
                + +
                +
                +
                +
                +
                + +
                +
                +
                +
                +
                +
                +
                + 1x +
                +
                +
                + Full +
                +
                +
                +
                +
                + +
                +
                +
                +
                +
                +
                + + +
                +
                +
                + +
                +

                + Layers +
                +

                +
                + + + + + + + + + + + +
                + +
                  + + + + +
                  + +
                  +

                  + Transform + +

                  +
                    +
                    + +
                    +

                    Palettes

                    +
                    + + + +
                    +
                    + + + +
                    + +
                    +
                    +
                    + +
                    +
                    +
                    +
                    + +
                    + +
                    + +
                    + +
                    +
                    + +
                    +
                    +
                    +
                    +
                    +
                    +
                    + +
                    +
                    +
                    +
                    + +
                    + + + + + + + + + + +
                    + +
                    + +
                    + +
                    + +
                    + + +  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vendor/piskel-prod/piskelapp-partials/piskel-web-partial.html b/vendor/piskel-prod/piskelapp-partials/piskel-web-partial.html new file mode 100644 index 0000000..b8a5869 --- /dev/null +++ b/vendor/piskel-prod/piskelapp-partials/piskel-web-partial.html @@ -0,0 +1,1540 @@ +--- +layout: "editorLayout.html" +--- + + +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    +
                    + +
                    +
                    + +
                    +
                    +
                    +
                    +
                    + + + + + +
                    + + +
                    +
                    +
                    +
                    +
                      +
                      +
                      +
                      +
                      + +
                      + +
                      +
                      +
                      +
                      +
                      + +
                      +
                      +
                      +
                      +
                      +
                      +
                      + 1x +
                      +
                      +
                      + Full +
                      +
                      +
                      +
                      +
                      + +
                      +
                      +
                      +
                      +
                      +
                      + + +
                      +
                      +
                      + +
                      +

                      + Layers +
                      +

                      +
                      + + + + + + + + + + + +
                      + +
                        + + + + +
                        + +
                        +

                        + Transform + +

                        +
                          +
                          + +
                          +

                          Palettes

                          +
                          + + + +
                          +
                          + + + +
                          + +
                          +
                          +
                          + +
                          +
                          +
                          +
                          + +
                          + +
                          + +
                          + +
                          +
                          + +
                          +
                          +
                          +
                          +
                          +
                          +
                          + +
                          +
                          +
                          +
                          + +
                          + + + + + + + + + + +
                          + +
                          + +
                          + +
                          + +
                          + + +  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0fdf571437c748816ca837d39e6b27f77abad6ea Mon Sep 17 00:00:00 2001 From: Ne9roni Date: Mon, 20 Apr 2026 00:04:52 +0800 Subject: [PATCH 2/4] docs: English-first command guide with zh-CN mirror; skill links to npm paths - Make docs/commands.md the primary English reference; add docs/commands.zh-CN.md. - Add README.zh-CN.md and cross-links from README.md; extend package files for docs. - Rewrite reference-plan-format.md in English; keep skill workflow in SKILL.md. - Point SKILL.md at offline paths under @ne9roni/piskel-cli (node_modules / npm root -g) for docs/commands.md and plan format, instead of relative repo or CDN URLs. Made-with: Cursor --- README.md | 4 +- README.zh-CN.md | 277 ++++++++++ docs/commands.md | 323 +++++------ docs/commands.zh-CN.md | 504 ++++++++++++++++++ package.json | 3 + skills/using-piskel-cli/SKILL.md | 62 ++- .../reference/reference-plan-format.md | 36 +- 7 files changed, 1014 insertions(+), 195 deletions(-) create mode 100644 README.zh-CN.md create mode 100644 docs/commands.zh-CN.md diff --git a/README.md b/README.md index 1080dd6..d75a7a9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # piskel-cli +> **中文文档:** [README.zh-CN.md](README.zh-CN.md) + > **Headless pixel art engine for scripts, pipelines, and AI agents.** > Create, edit, and export `.piskel` files from the terminal; use `serve` when you want the bundled **Piskel** web editor in a browser. @@ -201,7 +203,7 @@ piskel-cli run my-plan.json --json | **Run** | `run ` — execute multi-step plan files | | **Serve** | `serve []` — local HTTP + bundled Piskel web UI | -Full reference: [`docs/commands.md`](docs/commands.md) +Full reference: [`docs/commands.md`](docs/commands.md) · [中文版 `docs/commands.zh-CN.md`](docs/commands.zh-CN.md) --- diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..9d87487 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,277 @@ +# piskel-cli + +> **English:** [README.md](README.md) + +> **面向脚本、流水线与 AI 代理的无头像素引擎。** +> 在终端里创建、编辑、导出 `.piskel`;需要图形界面时使用 `serve` 打开自带的 **Piskel** 网页编辑器。 + +[![npm version](https://img.shields.io/npm/v/@ne9roni/piskel-cli)](https://www.npmjs.com/package/@ne9roni/piskel-cli) +[![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE) +[![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen)](https://nodejs.org) + +--- + +## 为什么选择 piskel-cli? + +[Piskel](https://www.piskelapp.com/) 是广受欢迎的浏览器像素编辑器。**piskel-cli** 将其 `.piskel` 格式带到命令行,让像素图能融入自动化流程: + +- **AI 代理** 可用一条提示生成精灵图与动画,无需图像模型 +- **构建流水线** 可在无人操作下生成并导出资源 +- **脚本** 可在数秒内批量编辑大量帧 +- **CI/CD** 可自动校验与重生成像素资源 + +所有操作均可脚本化、可组合,并返回结构化 JSON,便于与其他工具串联。 + +--- + +## AI 代理集成 + +**用 AI 画像素不必依赖图像生成模型。** 只要能写 JSON 的 LLM,就可以把需求写成计划文件,生成可用的精灵与动画。 + +### 安装 AI 技能 + +```bash +npx skills add Ne9roni/piskel-cli +``` + +会在代理环境中安装结构化提示([`skills/using-piskel-cli/SKILL.md`](skills/using-piskel-cli/SKILL.md)),其中包含完整工作流(英文)。 + +### 工作方式 + +用自然语言告诉 AI(Claude、GPT、Cursor 等)你的目标,例如: + +> *「画一个 16×16 红蘑菇,白点,导出 PNG」* + +代理编写 `plan.json` 并执行: + +```bash +piskel-cli run mushroom-plan.json --json +``` + +无需扩散模型,纯几何与命令。 + +--- + +## AI 生成示例 + +以下素材均由 AI 代理仅通过 piskel-cli 从一句话描述生成并导出,**未使用**图像模型。 + +### 精灵图(PNG) + +
                           
                          + + + + + + + + + + + + + + + + + + +
                          MushroomGemSwordHeart
                          mushroom spritegem spritesword spriteheart sprite
                          mushroom-plan.jsongem-plan.jsonsword-plan.jsonheart-plan.json
                          + +### 动画(GIF) + + + + + + + + + + + + + + + + + + + + +
                          Coin SpinFireGhostTwinkle Star
                          coin spin animationfire animationghost animationtwinkle star animation
                          coin-spin-plan.jsonfire-plan.jsonghost-plan.jsontwinkle-star-plan.json
                          + +每个示例都是 [`examples/`](examples/) 中的独立 JSON 计划,可自行运行: + +```bash +piskel-cli run examples/fire-plan.json --json +``` + +--- + +## 安装 + +```bash +# 全局安装(推荐) +npm install -g @ne9roni/piskel-cli + +# 验证 +piskel-cli --help +``` + +npm 发布包在 `vendor/piskel-prod` 下附带 **Piskel 生产构建**,因此 `npm install -g @ne9roni/piskel-cli` 即可使用 **`piskel-cli serve`**,无需再单独克隆或下载编辑器。 + +从源码本地运行: + +```bash +git clone https://github.com/Ne9roni/piskel-cli.git +cd piskel-cli +npm install && npm run build +node dist/src/cli.js --help +``` + +若克隆后没有 `vendor/piskel-prod`,需先执行一次 `npm run sync-piskel-vendor`(需要已构建的 [piskel](https://github.com/piskelapp/piskel) 仓库;见 [`vendor/README.md`](vendor/README.md))。 + +--- + +## 浏览器编辑器(`serve`) + +可选:在本机打开与 [piskelapp.com](https://www.piskelapp.com/) 相同的像素编辑器: + +```bash +piskel-cli serve +piskel-cli serve path/to/project.piskel +``` + +使用 `--no-open` 仅打印 URL;`--port` / `--host` 控制监听地址。按 Ctrl+C 结束进程。 + +--- + +## 快速开始 + +### 1. 创建工程 + +```bash +piskel-cli project create --width 16 --height 16 --name my-sprite --json +``` + +### 2. 绘制像素 + +```bash +piskel-cli draw rect output/my-sprite.piskel --x1 2 --y1 2 --x2 13 --y2 13 --color "#ff0000" --filled --json +piskel-cli draw pixel output/my-sprite.piskel --x 8 --y 8 --color "#ffffff" --json +``` + +### 3. 导出 + +```bash +piskel-cli export png output/my-sprite.piskel --json +piskel-cli export gif output/my-sprite.piskel --json +piskel-cli export frames output/my-sprite.piskel --json +``` + +### 或使用计划文件一次完成 + +```json +{ + "steps": [ + { "command": "project.create", "args": { "width": 16, "height": 16, "name": "hero" } }, + { "command": "draw.rect", "args": { "project": "output/output.piskel", "x1": 3, "y1": 0, "x2": 12, "y2": 15, "color": "#4fc3f7", "filled": true } }, + { "command": "export.gif", "args": { "project": "output/output.piskel" } } + ] +} +``` + +```bash +piskel-cli run my-plan.json --json +``` + +--- + +## 命令一览 + +| 分组 | 命令 | +|------|------| +| **Project** | `project create`, `project info` | +| **Layer** | `layer list`, `layer add`, `layer remove`, `layer rename`, `layer set-opacity`, `layer move` | +| **Frame** | `frame list`, `frame add`, `frame remove`, `frame duplicate`, `frame move` | +| **Draw** | `draw pixel`, `draw pixels`, `draw line`, `draw rect`, `draw circle` | +| **Fill / Erase** | `fill area`, `erase pixel`, `clear frame` | +| **Read** | `read pixel`, `read frame`, `read project`, `read palette`, `read bounds` | +| **Export** | `export png`, `export gif`, `export spritesheet`, `export frames` | +| **Run** | `run ` — 多步计划 | +| **Serve** | `serve []` — 本地 HTTP + 自带 Piskel 网页 UI | + +完整说明:[`docs/commands.md`](docs/commands.md)(英文)· [`docs/commands.zh-CN.md`](docs/commands.zh-CN.md)(中文) + +--- + +## JSON 协议 + +所有命令支持 `--json`,输出机器可读结果: + +```json +// 成功 +{ "ok": true, "data": { ... } } + +// 失败 +{ "ok": false, "error": { "code": "FRAME_INDEX_OUT_OF_RANGE", "message": "..." } } +``` + +错误码在各命令间保持一致,便于任意语言处理。 + +--- + +## 计划文件 + +`run` 按顺序执行 JSON 计划,适合 AI、构建脚本或多帧动画: + +```bash +piskel-cli run examples/twinkle-star-plan.json --json +``` + +更多示例见 [`examples/`](examples/);计划格式见 [`skills/using-piskel-cli/reference/reference-plan-format.md`](skills/using-piskel-cli/reference/reference-plan-format.md)(英文)。 + +--- + +## 架构 + +piskel-cli 为纯 **Node.js / TypeScript** 实现,运行时无浏览器依赖,直接读写 `.piskel` JSON: + +- **`src/probe/`** — 无头读写引擎 +- **`src/cli/`** — 命令解析与 JSON 协议 +- **`vendor/piskel-prod/`** — 上游 Piskel `dest/prod` 的随包副本(供 `serve`;通过 `npm run sync-piskel-vendor` 更新) +- **`tests/`** — Vitest 测试 + +--- + +## 开发 + +```bash +npm install +npm run build # 编译 TypeScript +npm test # 测试 +npm run test:watch # 监视模式 +``` + +### 自带 Piskel 编辑器(`serve`) + +在本地已 `npm install && npm run build` 的 [piskelapp/piskel](https://github.com/piskelapp/piskel) 克隆旁执行: + +```bash +npm run sync-piskel-vendor +# 或: PISKEL_ROOT=/path/to/piskel npm run sync-piskel-vendor +``` + +详见 [`vendor/README.md`](vendor/README.md)。 + +**发布:** `npm publish` 会执行 `prepublishOnly`,最后一步为 **`npm run assert-vendor`**;若缺少 `vendor/piskel-prod/index.html` 则发布失败,避免 registry 上的包无法使用 `serve`。发版前请先 `sync-piskel-vendor`。 + +测试位于 [`tests/`](tests/)。 + +--- + +## 许可证 + +[Apache-2.0](LICENSE) diff --git a/docs/commands.md b/docs/commands.md index aef3910..941dd03 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -1,65 +1,66 @@ -## Command Guide +# Command guide -这份文档是 `piskel-cli` 的唯一详细命令文档。 +This document is the detailed command reference for `piskel-cli`. -它同时包含两类内容: +It covers: -- 面向使用者的命令说明:每个命令是做什么的、怎么用 -- 面向集成方的规格说明:JSON 协议、默认输出规则、通用错误码 +- User-facing command descriptions: what each command does and how to use it +- Integration-oriented details: JSON protocol, default output rules, common error codes -## 通用说明 +> **Chinese:** [`commands.zh-CN.md`](./commands.zh-CN.md) -- 所有相对路径都按执行 CLI 时的当前工作目录解析 -- 所有命令都支持 `--json`,返回统一协议: - - 成功:`{ "ok": true, "data": ... }` - - 失败:`{ "ok": false, "error": { "code": "...", "message": "..." } }` -- 创建和导出类命令如果没指定输出位置,会默认写到当前工作目录下的 `output/` -- 修改类命令如果没指定 `--output`,默认原地修改输入的 `.piskel` +## General notes -## 默认输出规则 +- Relative paths are resolved from the current working directory when you invoke the CLI. +- Every command supports `--json` and returns a unified envelope: + - Success: `{ "ok": true, "data": ... }` + - Failure: `{ "ok": false, "error": { "code": "...", "message": "..." } }` +- Create and export commands default to `./output/` when no output path is given. +- Mutating commands default to in-place writes when `--output` is omitted (same path as the input `.piskel`). -- `project create`:默认输出到 `output/output.piskel` -- `export png`:默认输出到 `output/output.png` -- `export gif`:默认输出到 `output/output.gif` -- `export spritesheet`:默认输出图到 `output/output.png` -- `export frames`:默认输出目录为 `output/frames` +## Default output locations -## 通用错误码 +- `project create` → `output/output.piskel` +- `export png` → `output/output.png` +- `export gif` → `output/output.gif` +- `export spritesheet` → `output/output.png` (image) +- `export frames` → `output/frames/` +## Common error codes -| 错误码 | 含义 | -| --------------------------- | ------------------- | -| `USAGE_ERROR` | 命令或参数不合法 | -| `FILE_NOT_FOUND` | 输入文件不存在 | -| `INVALID_PISKEL_FILE` | `.piskel` 文件格式非法 | -| `UNSUPPORTED_MODEL_VERSION` | 不支持的 `modelVersion` | -| `FRAME_INDEX_OUT_OF_RANGE` | 帧索引越界 | -| `LAYER_INDEX_OUT_OF_RANGE` | 图层索引越界 | -| `INVALID_COLOR` | 颜色格式非法 | -| `INVALID_COORDINATES` | 坐标越界或无效 | -| `PROJECT_SYNC_ERROR` | 图层或帧不同步,不能导出或保存 | -| `WRITE_FAILED` | 文件写入失败 | -| `READ_FAILED` | 文件读取失败 | - +| Code | Meaning | +|------|---------| +| `USAGE_ERROR` | Invalid command or arguments | +| `FILE_NOT_FOUND` | Input file does not exist | +| `INVALID_PISKEL_FILE` | Invalid `.piskel` format | +| `UNSUPPORTED_MODEL_VERSION` | Unsupported `modelVersion` | +| `FRAME_INDEX_OUT_OF_RANGE` | Frame index out of range | +| `LAYER_INDEX_OUT_OF_RANGE` | Layer index out of range | +| `INVALID_COLOR` | Invalid color format | +| `INVALID_COORDINATES` | Coordinates out of bounds or invalid | +| `PROJECT_SYNC_ERROR` | Layer/frame sync error; cannot export or save | +| `WRITE_FAILED` | File write failed | +| `READ_FAILED` | File read failed | +| `VENDOR_MISSING` | Bundled web assets (`vendor/piskel-prod`) missing; `serve` cannot start | ## Project ### `project create` -作用: +Purpose: -- 创建一个新的 `.piskel` 工程文件 -- 默认会创建 1 个图层和 1 个空白帧 +- Create a new `.piskel` project file +- By default creates one layer and one empty frame -常用参数: +Common flags: -- `--width`:画布宽度 -- `--height`:画布高度 -- `--fps`:帧率,默认 `12` -- `--name`:项目名 -- `--output`:输出路径,默认 `output/output.piskel` +- `--width` — canvas width +- `--height` — canvas height +- `--fps` — frames per second (default `12`) +- `--name` — project name +- `--output` — output path (default `output/output.piskel`) -示例: +Examples: ```bash node dist/src/cli.js project create --width 16 --height 16 --json @@ -68,12 +69,12 @@ node dist/src/cli.js project create --width 32 --height 32 --name hero --output ### `project info` -作用: +Purpose: -- 读取 `.piskel` 的基础元信息 -- 适合脚本在修改前先看工程概况 +- Read basic metadata from a `.piskel` +- Useful for scripts to inspect a project before editing -示例: +Example: ```bash node dist/src/cli.js project info output/output.piskel --json @@ -83,12 +84,11 @@ node dist/src/cli.js project info output/output.piskel --json ### `layer list` -作用: +Purpose: -- 列出所有图层 -- 查看图层顺序、名称、不透明度和帧数 +- List all layers with order, name, opacity, and frame count -示例: +Example: ```bash node dist/src/cli.js layer list output/output.piskel --json @@ -96,12 +96,11 @@ node dist/src/cli.js layer list output/output.piskel --json ### `layer add` -作用: +Purpose: -- 添加一个新图层 -- 新图层会自动补齐与当前工程同步的帧数 +- Add a new layer; frame count is kept in sync with the project -示例: +Example: ```bash node dist/src/cli.js layer add output/output.piskel --name shadow --json @@ -109,12 +108,11 @@ node dist/src/cli.js layer add output/output.piskel --name shadow --json ### `layer remove` -作用: +Purpose: -- 删除指定图层 -- 不允许删除最后一个图层 +- Remove a layer; the last remaining layer cannot be removed -示例: +Examples: ```bash node dist/src/cli.js layer remove output/output.piskel --layer shadow --json @@ -123,11 +121,11 @@ node dist/src/cli.js layer remove output/output.piskel --layer 1 --json ### `layer rename` -作用: +Purpose: -- 重命名图层 +- Rename a layer -示例: +Example: ```bash node dist/src/cli.js layer rename output/output.piskel --layer shadow --name outline --json @@ -135,12 +133,11 @@ node dist/src/cli.js layer rename output/output.piskel --layer shadow --name out ### `layer set-opacity` -作用: +Purpose: -- 设置图层不透明度 -- 取值范围 `0..1` +- Set layer opacity in the range `0..1` -示例: +Example: ```bash node dist/src/cli.js layer set-opacity output/output.piskel --layer outline --opacity 0.5 --json @@ -148,12 +145,11 @@ node dist/src/cli.js layer set-opacity output/output.piskel --layer outline --op ### `layer move` -作用: +Purpose: -- 调整图层顺序 -- `--to` 是目标索引 +- Reorder layers; `--to` is the target index -示例: +Example: ```bash node dist/src/cli.js layer move output/output.piskel --layer outline --to 0 --json @@ -163,11 +159,11 @@ node dist/src/cli.js layer move output/output.piskel --layer outline --to 0 --js ### `frame list` -作用: +Purpose: -- 列出帧索引 +- List frame indices -示例: +Example: ```bash node dist/src/cli.js frame list output/output.piskel --json @@ -175,12 +171,11 @@ node dist/src/cli.js frame list output/output.piskel --json ### `frame add` -作用: +Purpose: -- 添加新帧 -- 默认追加到末尾 +- Add a frame (appended by default) -示例: +Examples: ```bash node dist/src/cli.js frame add output/output.piskel --json @@ -189,12 +184,11 @@ node dist/src/cli.js frame add output/output.piskel --index 1 --json ### `frame remove` -作用: +Purpose: -- 删除一帧 -- 不允许删除最后一帧 +- Remove a frame; the last remaining frame cannot be removed -示例: +Example: ```bash node dist/src/cli.js frame remove output/output.piskel --frame 1 --json @@ -202,11 +196,11 @@ node dist/src/cli.js frame remove output/output.piskel --frame 1 --json ### `frame duplicate` -作用: +Purpose: -- 复制指定帧 +- Duplicate a frame -示例: +Example: ```bash node dist/src/cli.js frame duplicate output/output.piskel --frame 0 --json @@ -214,11 +208,11 @@ node dist/src/cli.js frame duplicate output/output.piskel --frame 0 --json ### `frame move` -作用: +Purpose: -- 调整帧顺序 +- Reorder frames -示例: +Example: ```bash node dist/src/cli.js frame move output/output.piskel --frame 2 --to 0 --json @@ -228,11 +222,11 @@ node dist/src/cli.js frame move output/output.piskel --frame 2 --to 0 --json ### `draw pixel` -作用: +Purpose: -- 在指定图层、指定帧上画一个像素 +- Draw a single pixel on a layer/frame -示例: +Example: ```bash node dist/src/cli.js draw pixel output/output.piskel --x 1 --y 1 --color "#ff0000" --json @@ -240,12 +234,11 @@ node dist/src/cli.js draw pixel output/output.piskel --x 1 --y 1 --color "#ff000 ### `draw pixels` -作用: +Purpose: -- 批量绘制像素 -- 适合外部程序先生成一个像素数组,再一次性提交 +- Batch-draw pixels from a JSON file -示例: +Example: ```bash node dist/src/cli.js draw pixels output/output.piskel --input pixels.json --json @@ -253,11 +246,11 @@ node dist/src/cli.js draw pixels output/output.piskel --input pixels.json --json ### `draw line` -作用: +Purpose: -- 画一条线段 +- Draw a line segment -示例: +Example: ```bash node dist/src/cli.js draw line output/output.piskel --x1 0 --y1 0 --x2 7 --y2 7 --color "#00ff00" --json @@ -265,12 +258,11 @@ node dist/src/cli.js draw line output/output.piskel --x1 0 --y1 0 --x2 7 --y2 7 ### `draw rect` -作用: +Purpose: -- 画矩形 -- 加 `--filled` 时画实心矩形 +- Draw a rectangle; add `--filled` for a filled rectangle -示例: +Example: ```bash node dist/src/cli.js draw rect output/output.piskel --x1 1 --y1 1 --x2 4 --y2 4 --color "#ff0000" --filled --json @@ -278,11 +270,11 @@ node dist/src/cli.js draw rect output/output.piskel --x1 1 --y1 1 --x2 4 --y2 4 ### `draw circle` -作用: +Purpose: -- 画圆或椭圆轮廓 +- Draw a circle or ellipse outline -示例: +Example: ```bash node dist/src/cli.js draw circle output/output.piskel --x1 1 --y1 1 --x2 5 --y2 5 --color "#0000ff" --json @@ -290,11 +282,11 @@ node dist/src/cli.js draw circle output/output.piskel --x1 1 --y1 1 --x2 5 --y2 ### `fill area` -作用: +Purpose: -- 洪水填充连通区域 +- Flood-fill a connected region -示例: +Example: ```bash node dist/src/cli.js fill area output/output.piskel --x 3 --y 3 --color "#ffff00" --json @@ -302,11 +294,11 @@ node dist/src/cli.js fill area output/output.piskel --x 3 --y 3 --color "#ffff00 ### `erase pixel` -作用: +Purpose: -- 擦除单个像素 +- Erase a single pixel -示例: +Example: ```bash node dist/src/cli.js erase pixel output/output.piskel --x 1 --y 1 --json @@ -314,12 +306,11 @@ node dist/src/cli.js erase pixel output/output.piskel --x 1 --y 1 --json ### `clear frame` -作用: +Purpose: -- 清空整个帧 -- 如果带 `--layer`,则只清空该图层对应帧 +- Clear an entire frame; with `--layer`, only that layer’s frame cells are cleared -示例: +Example: ```bash node dist/src/cli.js clear frame output/output.piskel --json @@ -329,11 +320,11 @@ node dist/src/cli.js clear frame output/output.piskel --json ### `read pixel` -作用: +Purpose: -- 读取单个像素颜色 +- Read a single pixel color -示例: +Example: ```bash node dist/src/cli.js read pixel output/output.piskel --x 1 --y 1 --json @@ -341,12 +332,11 @@ node dist/src/cli.js read pixel output/output.piskel --x 1 --y 1 --json ### `read frame` -作用: +Purpose: -- 读取整帧二维像素网格 -- 常用于脚本或外部程序做结果检查或二次修补 +- Read the full 2D pixel grid for a frame -示例: +Example: ```bash node dist/src/cli.js read frame output/output.piskel --json @@ -354,11 +344,11 @@ node dist/src/cli.js read frame output/output.piskel --json ### `read project` -作用: +Purpose: -- 读取工程摘要 +- Read a project summary -示例: +Example: ```bash node dist/src/cli.js read project output/output.piskel --json @@ -366,11 +356,11 @@ node dist/src/cli.js read project output/output.piskel --json ### `read palette` -作用: +Purpose: -- 统计当前帧使用到的颜色集合 +- List colors used on the current frame -示例: +Example: ```bash node dist/src/cli.js read palette output/output.piskel --json @@ -378,12 +368,11 @@ node dist/src/cli.js read palette output/output.piskel --json ### `read bounds` -作用: +Purpose: -- 读取非透明像素的包围盒 -- 适合脚本或外部程序判断图形是否越界、是否居中 +- Bounding box of non-transparent pixels -示例: +Example: ```bash node dist/src/cli.js read bounds output/output.piskel --json @@ -393,12 +382,11 @@ node dist/src/cli.js read bounds output/output.piskel --json ### `export png` -作用: +Purpose: -- 导出单帧或整张 spritesheet 的 PNG -- 默认输出到 `output/output.png` +- Export a PNG (single frame or full spritesheet); default `output/output.png` -示例: +Examples: ```bash node dist/src/cli.js export png output/output.piskel --json @@ -407,12 +395,11 @@ node dist/src/cli.js export png output/output.piskel --frame 0 --json ### `export gif` -作用: +Purpose: -- 导出 GIF 动画 -- 默认输出到 `output/output.gif` +- Export an animated GIF; default `output/output.gif` -示例: +Example: ```bash node dist/src/cli.js export gif output/output.piskel --json @@ -420,12 +407,11 @@ node dist/src/cli.js export gif output/output.piskel --json ### `export spritesheet` -作用: +Purpose: -- 导出 spritesheet PNG -- 可选同时导出 metadata JSON +- Export a spritesheet PNG; optional metadata JSON -示例: +Example: ```bash node dist/src/cli.js export spritesheet output/output.piskel --columns 4 --metadata output/output.json --json @@ -433,29 +419,62 @@ node dist/src/cli.js export spritesheet output/output.piskel --columns 4 --metad ### `export frames` -作用: +Purpose: -- 把每一帧单独导出成 PNG 文件 -- 默认输出到 `output/frames` +- Export each frame as its own PNG under `output/frames` by default -示例: +Example: ```bash node dist/src/cli.js export frames output/output.piskel --json ``` +## Serve + +### `serve []` + +Purpose: + +- Start a local **HTTP static server** for the bundled **Piskel web editor** (`vendor/piskel-prod`, same build family as [piskelapp.com](https://www.piskelapp.com/)). +- Optionally open a `.piskel` file in the browser; with no path, opens a blank canvas. +- The process **keeps running** until **Ctrl+C**; meant for interactive local editing, not headless CI. + +Prerequisites: + +- `vendor/piskel-prod/index.html` must exist (included in published `npm install -g @ne9roni/piskel-cli`; if you clone source without it, run `npm run sync-piskel-vendor` — see [`vendor/README.md`](../vendor/README.md)). + +Flags: + +- **Positional (optional):** path to a `.piskel` file to load. +- `--port ` — listen port; **omit** to let the OS pick a free port. +- `--host ` — bind address (default `127.0.0.1`). +- `--no-open` — print the URL only; do **not** launch the default browser (useful on Linux/WSL without `xdg-open`). +- `--json` — after startup, print one JSON object (`ok`, `data.url`, `data.port`, …) to stdout; the process still keeps running. + +Notes: + +- When loading a project, the CLI exposes that file at a one-time URL under **`/__piskel/open/`** so arbitrary filesystem paths are not browsable. +- If the default browser launcher is missing (`xdg-open`), the CLI tries `wslview`, `gio`, then `sensible-browser`; if all fail, open the printed URL manually. + +Examples: + +```bash +node dist/src/cli.js serve +node dist/src/cli.js serve output/output.piskel +node dist/src/cli.js serve output/output.piskel --port 9000 --no-open +piskel-cli serve examples-output/sword/sword.piskel --json +``` + ## Run ### `run ` -作用: +Purpose: -- 顺序执行一个结构化计划文件 -- 适合脚本或外部程序一次性提交多步操作 +- Execute a structured multi-step plan file in order -示例: +Example: ```bash node dist/src/cli.js run examples/heart-plan.json --json ``` - diff --git a/docs/commands.zh-CN.md b/docs/commands.zh-CN.md new file mode 100644 index 0000000..0456b55 --- /dev/null +++ b/docs/commands.zh-CN.md @@ -0,0 +1,504 @@ +# 命令说明(中文) + +> 英文主文档:[commands.md](./commands.md) + +--- + +## Command Guide + +这份文档是 `piskel-cli` 的唯一详细命令文档。 + +它同时包含两类内容: + +- 面向使用者的命令说明:每个命令是做什么的、怎么用 +- 面向集成方的规格说明:JSON 协议、默认输出规则、通用错误码 + +## 通用说明 + +- 所有相对路径都按执行 CLI 时的当前工作目录解析 +- 所有命令都支持 `--json`,返回统一协议: + - 成功:`{ "ok": true, "data": ... }` + - 失败:`{ "ok": false, "error": { "code": "...", "message": "..." } }` +- 创建和导出类命令如果没指定输出位置,会默认写到当前工作目录下的 `output/` +- 修改类命令如果没指定 `--output`,默认原地修改输入的 `.piskel` + +## 默认输出规则 + +- `project create`:默认输出到 `output/output.piskel` +- `export png`:默认输出到 `output/output.png` +- `export gif`:默认输出到 `output/output.gif` +- `export spritesheet`:默认输出图到 `output/output.png` +- `export frames`:默认输出目录为 `output/frames` + +## 通用错误码 + + +| 错误码 | 含义 | +| --------------------------- | ------------------- | +| `USAGE_ERROR` | 命令或参数不合法 | +| `FILE_NOT_FOUND` | 输入文件不存在 | +| `INVALID_PISKEL_FILE` | `.piskel` 文件格式非法 | +| `UNSUPPORTED_MODEL_VERSION` | 不支持的 `modelVersion` | +| `FRAME_INDEX_OUT_OF_RANGE` | 帧索引越界 | +| `LAYER_INDEX_OUT_OF_RANGE` | 图层索引越界 | +| `INVALID_COLOR` | 颜色格式非法 | +| `INVALID_COORDINATES` | 坐标越界或无效 | +| `PROJECT_SYNC_ERROR` | 图层或帧不同步,不能导出或保存 | +| `WRITE_FAILED` | 文件写入失败 | +| `READ_FAILED` | 文件读取失败 | +| `VENDOR_MISSING` | 未找到配套网页资源(`vendor/piskel-prod`),无法启动 `serve` | + + +## Project + +### `project create` + +作用: + +- 创建一个新的 `.piskel` 工程文件 +- 默认会创建 1 个图层和 1 个空白帧 + +常用参数: + +- `--width`:画布宽度 +- `--height`:画布高度 +- `--fps`:帧率,默认 `12` +- `--name`:项目名 +- `--output`:输出路径,默认 `output/output.piskel` + +示例: + +```bash +node dist/src/cli.js project create --width 16 --height 16 --json +node dist/src/cli.js project create --width 32 --height 32 --name hero --output output/hero.piskel --json +``` + +### `project info` + +作用: + +- 读取 `.piskel` 的基础元信息 +- 适合脚本在修改前先看工程概况 + +示例: + +```bash +node dist/src/cli.js project info output/output.piskel --json +``` + +## Layer + +### `layer list` + +作用: + +- 列出所有图层 +- 查看图层顺序、名称、不透明度和帧数 + +示例: + +```bash +node dist/src/cli.js layer list output/output.piskel --json +``` + +### `layer add` + +作用: + +- 添加一个新图层 +- 新图层会自动补齐与当前工程同步的帧数 + +示例: + +```bash +node dist/src/cli.js layer add output/output.piskel --name shadow --json +``` + +### `layer remove` + +作用: + +- 删除指定图层 +- 不允许删除最后一个图层 + +示例: + +```bash +node dist/src/cli.js layer remove output/output.piskel --layer shadow --json +node dist/src/cli.js layer remove output/output.piskel --layer 1 --json +``` + +### `layer rename` + +作用: + +- 重命名图层 + +示例: + +```bash +node dist/src/cli.js layer rename output/output.piskel --layer shadow --name outline --json +``` + +### `layer set-opacity` + +作用: + +- 设置图层不透明度 +- 取值范围 `0..1` + +示例: + +```bash +node dist/src/cli.js layer set-opacity output/output.piskel --layer outline --opacity 0.5 --json +``` + +### `layer move` + +作用: + +- 调整图层顺序 +- `--to` 是目标索引 + +示例: + +```bash +node dist/src/cli.js layer move output/output.piskel --layer outline --to 0 --json +``` + +## Frame + +### `frame list` + +作用: + +- 列出帧索引 + +示例: + +```bash +node dist/src/cli.js frame list output/output.piskel --json +``` + +### `frame add` + +作用: + +- 添加新帧 +- 默认追加到末尾 + +示例: + +```bash +node dist/src/cli.js frame add output/output.piskel --json +node dist/src/cli.js frame add output/output.piskel --index 1 --json +``` + +### `frame remove` + +作用: + +- 删除一帧 +- 不允许删除最后一帧 + +示例: + +```bash +node dist/src/cli.js frame remove output/output.piskel --frame 1 --json +``` + +### `frame duplicate` + +作用: + +- 复制指定帧 + +示例: + +```bash +node dist/src/cli.js frame duplicate output/output.piskel --frame 0 --json +``` + +### `frame move` + +作用: + +- 调整帧顺序 + +示例: + +```bash +node dist/src/cli.js frame move output/output.piskel --frame 2 --to 0 --json +``` + +## Draw / Fill / Erase / Clear + +### `draw pixel` + +作用: + +- 在指定图层、指定帧上画一个像素 + +示例: + +```bash +node dist/src/cli.js draw pixel output/output.piskel --x 1 --y 1 --color "#ff0000" --json +``` + +### `draw pixels` + +作用: + +- 批量绘制像素 +- 适合外部程序先生成一个像素数组,再一次性提交 + +示例: + +```bash +node dist/src/cli.js draw pixels output/output.piskel --input pixels.json --json +``` + +### `draw line` + +作用: + +- 画一条线段 + +示例: + +```bash +node dist/src/cli.js draw line output/output.piskel --x1 0 --y1 0 --x2 7 --y2 7 --color "#00ff00" --json +``` + +### `draw rect` + +作用: + +- 画矩形 +- 加 `--filled` 时画实心矩形 + +示例: + +```bash +node dist/src/cli.js draw rect output/output.piskel --x1 1 --y1 1 --x2 4 --y2 4 --color "#ff0000" --filled --json +``` + +### `draw circle` + +作用: + +- 画圆或椭圆轮廓 + +示例: + +```bash +node dist/src/cli.js draw circle output/output.piskel --x1 1 --y1 1 --x2 5 --y2 5 --color "#0000ff" --json +``` + +### `fill area` + +作用: + +- 洪水填充连通区域 + +示例: + +```bash +node dist/src/cli.js fill area output/output.piskel --x 3 --y 3 --color "#ffff00" --json +``` + +### `erase pixel` + +作用: + +- 擦除单个像素 + +示例: + +```bash +node dist/src/cli.js erase pixel output/output.piskel --x 1 --y 1 --json +``` + +### `clear frame` + +作用: + +- 清空整个帧 +- 如果带 `--layer`,则只清空该图层对应帧 + +示例: + +```bash +node dist/src/cli.js clear frame output/output.piskel --json +``` + +## Read + +### `read pixel` + +作用: + +- 读取单个像素颜色 + +示例: + +```bash +node dist/src/cli.js read pixel output/output.piskel --x 1 --y 1 --json +``` + +### `read frame` + +作用: + +- 读取整帧二维像素网格 +- 常用于脚本或外部程序做结果检查或二次修补 + +示例: + +```bash +node dist/src/cli.js read frame output/output.piskel --json +``` + +### `read project` + +作用: + +- 读取工程摘要 + +示例: + +```bash +node dist/src/cli.js read project output/output.piskel --json +``` + +### `read palette` + +作用: + +- 统计当前帧使用到的颜色集合 + +示例: + +```bash +node dist/src/cli.js read palette output/output.piskel --json +``` + +### `read bounds` + +作用: + +- 读取非透明像素的包围盒 +- 适合脚本或外部程序判断图形是否越界、是否居中 + +示例: + +```bash +node dist/src/cli.js read bounds output/output.piskel --json +``` + +## Export + +### `export png` + +作用: + +- 导出单帧或整张 spritesheet 的 PNG +- 默认输出到 `output/output.png` + +示例: + +```bash +node dist/src/cli.js export png output/output.piskel --json +node dist/src/cli.js export png output/output.piskel --frame 0 --json +``` + +### `export gif` + +作用: + +- 导出 GIF 动画 +- 默认输出到 `output/output.gif` + +示例: + +```bash +node dist/src/cli.js export gif output/output.piskel --json +``` + +### `export spritesheet` + +作用: + +- 导出 spritesheet PNG +- 可选同时导出 metadata JSON + +示例: + +```bash +node dist/src/cli.js export spritesheet output/output.piskel --columns 4 --metadata output/output.json --json +``` + +### `export frames` + +作用: + +- 把每一帧单独导出成 PNG 文件 +- 默认输出到 `output/frames` + +示例: + +```bash +node dist/src/cli.js export frames output/output.piskel --json +``` + +## Serve + +### `serve []` + +作用: + +- 在本机启动一个 **HTTP 静态服务**,托管仓库自带的 **Piskel 网页编辑器**(`vendor/piskel-prod`,与 [piskelapp.com](https://www.piskelapp.com/) 同源构建)。 +- 可选在浏览器中 **打开指定的 `.piskel` 工程**;不传文件则打开空白画布。 +- 进程会 **一直运行** 直到你按 **Ctrl+C**;适合本地人工编辑,不适合无头 CI 流水线。 + +前提: + +- 已存在 `vendor/piskel-prod/index.html`(`npm install -g @ne9roni/piskel-cli` 的发布包会带上;若从源码克隆且目录缺失,需先执行 `npm run sync-piskel-vendor`,见仓库 `vendor/README.md`)。 + +参数: + +- **位置参数**(可选):要加载的 `.piskel` 文件路径。 +- `--port `:监听端口;**省略则由系统分配空闲端口**。 +- `--host <地址>`:监听地址,默认 `127.0.0.1`。 +- `--no-open`:只打印 URL,**不**尝试用系统默认浏览器打开(在无 `xdg-open` 的 Linux/WSL 上可配合使用)。 +- `--json`:启动成功后向 stdout 输出一条 JSON(`ok`、`data.url`、`data.port` 等),随后进程仍保持运行。 + +说明: + +- 打开带工程文件的页面时,CLI 会通过一次性路径 **`/__piskel/open/`** 暴露该文件,避免任意路径被访问。 +- 若自动打开浏览器失败(例如缺少 `xdg-open`),会依次尝试 `wslview`、`gio`、`sensible-browser`;全部失败时提示你手动打开终端里打印的 URL。 + +示例: + +```bash +node dist/src/cli.js serve +node dist/src/cli.js serve output/output.piskel +node dist/src/cli.js serve output/output.piskel --port 9000 --no-open +piskel-cli serve examples-output/sword/sword.piskel --json +``` + +## Run + +### `run ` + +作用: + +- 顺序执行一个结构化计划文件 +- 适合脚本或外部程序一次性提交多步操作 + +示例: + +```bash +node dist/src/cli.js run examples/heart-plan.json --json +``` + diff --git a/package.json b/package.json index c1ddc84..2108f13 100644 --- a/package.json +++ b/package.json @@ -30,8 +30,11 @@ "files": [ "dist/src", "vendor/piskel-prod", + "vendor/README.md", "skills", "README.md", + "README.zh-CN.md", + "docs", "LICENSE", "package.json" ], diff --git a/skills/using-piskel-cli/SKILL.md b/skills/using-piskel-cli/SKILL.md index e48d844..cef9e02 100644 --- a/skills/using-piskel-cli/SKILL.md +++ b/skills/using-piskel-cli/SKILL.md @@ -3,40 +3,54 @@ name: using-piskel-cli description: Use when an AI agent needs to create, edit, inspect, or export pixel art, sprites, animations, or .piskel files with piskel-cli in a tool-driven workflow. Workflow step 2 (align + explicit user go-ahead) is mandatory before any mutating or export commands; do not skip it. --- -# 使用 piskel-cli +# Using piskel-cli -用下面 **Workflow** 按顺序做即可;未写的细节以 `piskel-cli --help` 为准。 +Follow the **Workflow** below in order; anything not spelled out here defaults to `piskel-cli --help`. -## 核心原则 +For **every subcommand, flags, defaults, JSON protocol, error codes, and `serve`**, read the files shipped inside the installed npm package **`@ne9roni/piskel-cli`** (works offline after `npm install`; no CDN required): -- **Workflow 第 2 步是硬性门禁**:凡会**新建/改 `.piskel`、改像素、改帧或图层、导出 png/gif/逐帧图**(含通过 `run`、`plan.json`、脚本写像素 JSON 再调 CLI 等间接路径),**一律**须在 Workflow **第 2 步**完成「复述目标 + 列清默认值与须拍板项 + **用户侧明确拍板**」之后才能执行。拍板包括:**用户明确回复确认**你列出的方案,**或**用户**同一条消息**内已写清全部须拍板项(至少含画布宽高)并授权生成/导出。未完成第 2 步即执行上述操作,视为违反本技能。 -- **禁止未对齐就生成图**:不得用「用户说生成/帮我画」、语气像授权、或**代理自行补全画布宽高**等理由跳过对齐。**画布宽高**须在对话中**敲定**:要么用户**直接写出**宽高,要么你先列出方案且用户**明确回复确认**采纳(含宽高);**不得**在未完成上述任一路径时,用「常见尺寸」「先出一版」代替。**同一条消息**内授权生成时,该消息须**至少写明画布宽高**(及其它须拍板项),不得仅靠代理推断。 -- **先对齐需求,再执行生成**:任何会新建或修改 `.piskel`、绘制像素、增删帧/图层、或导出 png/gif/逐帧图的操作,都必须在**已与用户对齐且用户已确认**(见 Workflow 第 2 步)之后才能做;禁止为了「省事」跳过对齐。 -- **对齐内容**:至少复述用户目标、说明拟采用的 CLI 默认值,并列出须拍板项(**至少含画布宽高**与画什么;另有动画、透明底、导出路径等时一并列清)。**仅当**用户**明确回复确认**采纳你列出的方案,**或**用户**同一条消息**里已**写清全部须拍板项**(**至少含画布宽高**)并明确要求生成/导出时,方可进入 Workflow 第 3 步。 -- **不替用户擅自定案**:不得以「常见尺寸」「先跑一版」代替用户对关键参数的认可;脚本、`plan.json`、`run`、预生成像素 JSON 等凡导致改图的,均受同一规则约束。 -- **迭代边界**:在同一已确认的工程上做小改,可在该确认范围内继续;**新工程**或**画布尺寸 / 帧率 / 导出约定**等发生变化时,须重新对齐后再执行。 +- **Project / local dependency:** + `node_modules/@ne9roni/piskel-cli/docs/commands.md` (English) · `node_modules/@ne9roni/piskel-cli/docs/commands.zh-CN.md` (Chinese) +- **Global install** (`npm install -g @ne9roni/piskel-cli`): + `$(npm root -g)/@ne9roni/piskel-cli/docs/commands.md` — run `npm root -g` if you need the absolute prefix. + +## Core rules + +- **Step 2 is a hard gate:** Any action that **creates or edits a `.piskel`, changes pixels, frames, or layers, or exports PNG/GIF/frame sequences** (including via `run`, `plan.json`, scripts that write pixel JSON then invoke the CLI, etc.) **must** only run **after** step 2: restate the goal, list defaults and items that need user sign-off, and obtain **explicit user approval**. Approval means: the user **clearly confirms** your proposed plan, **or** a **single user message** already contains **all** required decisions (at least canvas width and height) and authorizes generation/export. Skipping step 2 before those actions violates this skill. +- **No drawing without alignment:** Do not skip alignment because the user said “generate” / “draw for me,” because it “sounds like permission,” or by **inferring canvas width and height yourself.** Width and height must be **settled in the conversation**: either the user **states** them, or you propose values and the user **explicitly confirms** (including dimensions). Do not substitute “common sizes” or “a first draft” before that. If approval is in **one message**, that message must **at least** state canvas width and height (and other required items); the agent must not rely on silent inference alone. +- **Align first, then mutate:** Any operation that creates or modifies `.piskel`, draws pixels, adds/removes frames or layers, or exports PNG/GIF/frames may run only **after** alignment and confirmation per step 2. +- **What to align:** At minimum, restate the user’s goal, state the CLI defaults you will use, and list what needs sign-off (**at least canvas width and height** and **what to draw**; also animation, transparency, export paths when relevant). Enter step 3 only when the user **explicitly confirms** your list, or a **single message** already contains **all** required items (**including width and height**) and asks for generation/export. +- **Do not decide critical parameters for the user:** Do not replace user sign-off with “usual sizes” or “let me try a run”; scripts, `plan.json`, `run`, and pre-baked pixel JSON are subject to the same rules. +- **Iteration scope:** Small edits on an already-approved project may continue within that approval. **New projects** or changes to **canvas size, FPS, or export conventions** require a fresh alignment round. ## Workflow -1. **准备 CLI** - 执行 `which piskel-cli`;若没有,则 `npm install -g @ne9roni/piskel-cli`。之后**只**用命令名 `piskel-cli`,不要用 `PISKEL_CLI`、`npx` 或仓库内脚本路径替代。 +1. **Prepare the CLI** + Run `which piskel-cli`; if missing, `npm install -g @ne9roni/piskel-cli`. After that use the **`piskel-cli`** command name only — do not substitute `PISKEL_CLI`, `npx`, or a repo script path unless the user’s environment explicitly requires it. + +2. **Align and wait for confirmation before any “mutating” work — cannot skip** + This step is the gate: until alignment is done and the user confirms, **do not** proceed to step 3 or run anything that **creates or changes image/project files** (see Core rules). + Restate the goal and list in one pass: **CLI defaults** you will use if unspecified (`1` layer + `1` frame, FPS `12`, `output/output.piskel`; PNG/GIF exports to `output/output.png` / `output/output.gif`; per-frame folder `output/frames`), and items that need user sign-off — **at least canvas width and height** (`project create` has no default size) and **what to draw**; also animation, transparency, export format, custom paths when relevant. + Until the user **clearly confirms** (e.g. approves your stated width/height and plan), or **one message** already states **all** required items (including width and height) and requests generation/export, **do not** run: `project create`, any `draw` / `fill` / `erase` / `clear`, any `layer` / `frame`, any `export`, or `run` that includes those steps (including writing `plan.json` first or generating pixel JSON and immediately running — all count as mutating). + Before this step you **may**: install the CLI, `--help`, and **read-only** `read` on an **existing** user `.piskel`. + + **Iteration:** If the user already approved a configuration, small follow-up edits on the same project can continue with `draw` / `export` / `run` within that scope. **New project** or **canvas size / FPS / export contract** changes require listing and confirming again. + +3. **Execute changes** + Prefer `--json` for automation; handle `ok` / `data` / `error`. For multiple steps, prefer a `plan.json` and `piskel-cli run --json`. Typical single-command order: `project create` → `draw.*` / `fill` / `erase` → `export.*` (with `layer` / `frame` as needed). On failure, read `error.code` and `error.message` before retrying. -2. **对齐需求并等用户确认(再做任何「会改图」的操作)——本步不可跳过** - **本步是门禁**:未完成本步所列对齐并得到用户确认前,**禁止**进入第 3 步,**禁止**执行任何会产出或修改图像/工程文件的操作(见上文「核心原则」)。 - 复述用户目标,并一次性列出:拟采用的 **CLI 默认值**(未说明就用:`1` 图层 + `1` 帧、FPS `12`、`output/output.piskel`;导出 png/gif 分别为 `output/output.png` / `output/output.gif`;逐帧目录 `output/frames`),以及须用户拍板的项——**至少包含画布宽高**(`project create` 无默认宽高)和**画什么**;若有动画/透明底/导出格式/自定义路径,也在此列清或给出你的默认并请对方确认。 - **在用户明确回复确认**(例如确认你列出的宽高与方案),或**同一条用户消息**里已**写明画布宽高等全部须拍板项**并明确要求生成/导出之前,**不要**执行:`project create`、任意 `draw` / `fill` / `erase` / `clear`、任意 `layer` / `frame`、任意 `export`、以及包含上述步骤的 `run`(含先写 `plan.json` 再 `run`、或脚本生成像素 JSON 后立刻执行——这些都算「改图」)。 - 此步之前**可以**做:安装 CLI、`--help`、对用户**已有** `.piskel` 的只读 `read`。 +4. **Verify and iterate** + Use `read project`, `read frame`, `read palette`, `read bounds` to inspect results before the next edit. - **迭代**:若用户已确认过一套参数,后续仅在同工程上小改,可在同一确认范围内继续 `draw` / `export` / `run`;一旦涉及**新工程**或**改变画布尺寸/帧率/导出约定**等,须再列清并确认。 +## Command reference -3. **执行改动** - 自动化调用尽量带 `--json`,按返回里的 `ok` / `data` / `error` 处理。多步操作优先写一个 `plan.json`,再 `piskel-cli run --json`。单条命令时的典型顺序:`project create` → `draw.*` / `fill` / `erase` → `export.*`(中间按需 `layer` / `frame`)。失败时先看 `error.code` 与 `error.message` 再改参数重试。 +Paths below are relative to the **`@ne9roni/piskel-cli`** package root (same tree under `node_modules/@ne9roni/piskel-cli/` or `$(npm root -g)/@ne9roni/piskel-cli/`). -4. **核对与迭代** - 需要看内容时用 `read project`、`read frame`、`read palette`、`read bounds`,再决定下一笔怎么改。 +- **Full CLI spec (all groups, flags, examples):** `docs/commands.md` +- **Plan file shape for `run`:** `skills/using-piskel-cli/reference/reference-plan-format.md` -## 命令一览(按需查帮助) +Summary of groups (see `docs/commands.md` for details): -`project` · `layer` · `frame` · `draw` / `fill` / `erase` / `clear` · `read` · `export` · `run` +`project` · `layer` · `frame` · `draw` / `fill` / `erase` / `clear` · `read` · `export` · `run` · `serve` -计划文件里 `command` 形如 `project.create`、`draw.pixels`,详见 [reference/reference-plan-format.md](reference/reference-plan-format.md)。 +Plan `command` strings look like `project.create`, `draw.pixels` (see plan reference above). diff --git a/skills/using-piskel-cli/reference/reference-plan-format.md b/skills/using-piskel-cli/reference/reference-plan-format.md index 3bfcc1d..a280062 100644 --- a/skills/using-piskel-cli/reference/reference-plan-format.md +++ b/skills/using-piskel-cli/reference/reference-plan-format.md @@ -1,19 +1,19 @@ -# 计划文件与 JSON 参考 +# Plan files and JSON reference -## 可执行文件 +## Executable resolution -与主技能 `SKILL.md` 一致:用 **`{{PISKEL}}`** 表示解析后的调用前缀(`PISKEL_CLI` → `piskel-cli` → `npx piskel-cli@1.0.0`)。 +Same as the main skill `SKILL.md`: use **`{{PISKEL}}`** for the resolved command prefix (`PISKEL_CLI` → `piskel-cli` → `npx @ne9roni/piskel-cli@…` per your environment). -## `run` 计划结构 +## `run` plan shape -顶层对象需包含 `steps` 数组;每一项: +The top-level object must contain a `steps` array. Each step has: -- `command`:点号分隔的 **两段**,对应 CLI 的「命令组 + 子命令」,例如 `project.create`、`draw.pixel`、`export.png`。 -- `args`:可选对象;其中 `project` 会映射成紧跟子命令后的工程路径参数,其余键会映射成 `--flag value`。 +- `command` — **two** dot-separated segments matching CLI `group.subcommand`, e.g. `project.create`, `draw.pixel`, `export.png`. +- `args` — optional object; `project` maps to the positional `.piskel` path right after the subcommand; other keys become `--flag value`. -布尔 `true` 会变为无值开关 `--flag`。 +Boolean `true` becomes a flag with no value (`--flag`). -## 最小示例 +## Minimal example ```json { @@ -47,11 +47,11 @@ } ``` -相对路径均相对于执行 CLI 时的当前工作目录。 +Relative paths are resolved from the current working directory when the CLI runs. -## `--json` 返回形态(摘要) +## `--json` response shape (summary) -成功: +Success: ```json { @@ -60,7 +60,7 @@ } ``` -`run` 全部步骤成功时常见: +When `run` completes all steps: ```json { @@ -71,7 +71,7 @@ } ``` -失败: +Failure: ```json { @@ -83,20 +83,20 @@ } ``` -## 执行示例 +## Running a plan -下面是一种典型执行方式(把 `{{PISKEL}}` 换成实际前缀): +Typical invocation (replace `{{PISKEL}}` with your actual prefix): ```bash {{PISKEL}} run plan.json --json ``` -如果计划内容类似上面的最小示例,常见输出会是: +For a plan similar to the minimal example above, you will usually get: - `output/example.piskel` - `output/example.png` -如果还包含 GIF 或逐帧导出步骤,则可能额外产生: +If the plan also exports GIF or per-frame PNGs, you may additionally see: - `output/example.gif` - `output/frames/frame-0.png` From b991f6a8e748013430abdac1a2b1f235dad246c1 Mon Sep 17 00:00:00 2001 From: Ne9roni Date: Mon, 20 Apr 2026 00:10:23 +0800 Subject: [PATCH 3/4] chore: release 1.1.0; normalize bin path for npm pack npm pkg fix: use dist/src/cli.js without leading ./ so publish does not strip the bin entry. Made-with: Cursor --- package-lock.json | 4 ++-- package.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 979a7d1..d73d0ce 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@ne9roni/piskel-cli", - "version": "1.0.0", + "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@ne9roni/piskel-cli", - "version": "1.0.0", + "version": "1.1.0", "license": "Apache-2.0", "dependencies": { "gifenc": "^1.0.3", diff --git a/package.json b/package.json index 2108f13..34c0167 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { "name": "@ne9roni/piskel-cli", - "version": "1.0.0", + "version": "1.1.0", "description": "Headless Piskel-compatible CLI probes", "type": "module", "main": "dist/src/cli.js", "bin": { - "piskel-cli": "./dist/src/cli.js" + "piskel-cli": "dist/src/cli.js" }, "scripts": { "sync-piskel-vendor": "node scripts/sync-piskel-vendor.mjs", From 00c4fdd53bf4bfbfa86a6e4acd5373fcdc5584a9 Mon Sep 17 00:00:00 2001 From: Ne9roni Date: Mon, 20 Apr 2026 00:16:09 +0800 Subject: [PATCH 4/4] fix(serve): handle malformed URI percent-encoding in static paths decodeURIComponent on url.pathname can throw URIError for invalid sequences (e.g. /%ZZ). Return 400 instead of crashing the request handler. Add tryDecodeUriPathname helper and unit tests. Made-with: Cursor --- src/cli/serve-editor.ts | 18 +++++++++++++++++- tests/serve-editor.test.ts | 15 ++++++++++++++- 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/cli/serve-editor.ts b/src/cli/serve-editor.ts index be780e1..67ea10a 100644 --- a/src/cli/serve-editor.ts +++ b/src/cli/serve-editor.ts @@ -56,6 +56,15 @@ function isPathUnderRoot(filePath: string, root: string): boolean { return resolvedFile === resolvedRoot || resolvedFile.startsWith(resolvedRoot + sep); } +/** Decodes a URL pathname segment; returns null if percent-encoding is malformed. */ +export function tryDecodeUriPathname(pathname: string): string | null { + try { + return decodeURIComponent(pathname); + } catch { + return null; + } +} + export interface ServeEditorOptions { projectPath?: string; port?: number; @@ -172,7 +181,14 @@ export async function serveEditor(io: ServeEditorIo, options: ServeEditorOptions return; } - let pathname = decodeURIComponent(url.pathname).replace(/^\/+/, ""); + const decodedPath = tryDecodeUriPathname(url.pathname); + if (decodedPath === null) { + res.writeHead(400); + res.end("Bad request"); + return; + } + + let pathname = decodedPath.replace(/^\/+/, ""); if (!pathname) { pathname = "index.html"; } diff --git a/tests/serve-editor.test.ts b/tests/serve-editor.test.ts index 0c62cd5..d726410 100644 --- a/tests/serve-editor.test.ts +++ b/tests/serve-editor.test.ts @@ -1,8 +1,21 @@ import { describe, expect, test } from "vitest"; -import { buildEditorPageUrl, buildSessionLoadPath } from "../src/cli/serve-editor.js"; +import { + buildEditorPageUrl, + buildSessionLoadPath, + tryDecodeUriPathname, +} from "../src/cli/serve-editor.js"; describe("serve-editor helpers", () => { + test("tryDecodeUriPathname rejects malformed percent-encoding", () => { + expect(tryDecodeUriPathname("/%ZZ")).toBeNull(); + }); + + test("tryDecodeUriPathname decodes valid paths", () => { + expect(tryDecodeUriPathname("/foo%20bar")).toBe("/foo bar"); + expect(tryDecodeUriPathname("/")).toBe("/"); + }); + test("buildSessionLoadPath", () => { expect(buildSessionLoadPath("deadbeef")).toBe("/__piskel/open/deadbeef"); });