From bbf0649cd642769863199f6a65fb23dac8667bb2 Mon Sep 17 00:00:00 2001 From: j Date: Sun, 8 Mar 2015 01:11:19 +0530 Subject: [PATCH] extra repo for ebook readers --- .gitignore | 11 + epub.js/css/annotations.css | 8 + epub.js/css/main.css | 792 + epub.js/css/normalize.css | 505 + epub.js/css/popup.css | 96 + epub.js/epub.js | 7462 +++ epub.js/epub.js.map | 1 + epub.js/epub.min.js | 7462 +++ epub.js/epub.min.map | 1 + epub.js/epub_no_underscore.js | 7461 +++ epub.js/epub_no_underscore.js.map | 23 + epub.js/font/fontello.eot | Bin 0 -> 10204 bytes epub.js/font/fontello.svg | 33 + epub.js/font/fontello.ttf | Bin 0 -> 10036 bytes epub.js/font/fontello.woff | Bin 0 -> 6032 bytes epub.js/hooks.js | 318 + epub.js/hooks.js.map | 17 + epub.js/hooks.min.js | 2 + epub.js/hooks.min.map | 1 + epub.js/hooks/extensions/highlight.js | 14 + epub.js/libs/fileStorage.min.js | 3 + epub.js/libs/inflate.js | 2 + epub.js/libs/inflate.map | 1 + epub.js/libs/jquery-2.1.0.min.js | 4 + epub.js/libs/jquery.highlight.js | 108 + epub.js/libs/loader_filesystem.min.js | 3 + epub.js/libs/screenfull.min.js | 7 + epub.js/libs/zip.min.js | 16 + epub.js/libs/zip.min.map | 1 + epub.js/plugins/hypothesis.js | 109 + epub.js/plugins/search.js | 125 + epub.js/reader.js | 1124 + epub.js/reader.js.map | 17 + epub.js/reader.min.js | 2 + epub.js/reader.min.map | 1 + pdf.js/compatibility.js | 483 + pdf.js/css/videopdf.css | 28 + pdf.js/debugger.js | 540 + pdf.js/embeds.js | 147 + pdf.js/images/annotation-check.svg | 11 + pdf.js/images/annotation-comment.svg | 16 + pdf.js/images/annotation-help.svg | 26 + pdf.js/images/annotation-insert.svg | 10 + pdf.js/images/annotation-key.svg | 11 + pdf.js/images/annotation-newparagraph.svg | 11 + pdf.js/images/annotation-note.svg | 42 + pdf.js/images/annotation-paragraph.svg | 16 + pdf.js/images/findbarButton-next-rtl.png | Bin 0 -> 272 bytes pdf.js/images/findbarButton-next.png | Bin 0 -> 268 bytes pdf.js/images/findbarButton-previous-rtl.png | Bin 0 -> 268 bytes pdf.js/images/findbarButton-previous.png | Bin 0 -> 272 bytes pdf.js/images/grab.cur | Bin 0 -> 326 bytes pdf.js/images/grabbing.cur | Bin 0 -> 326 bytes pdf.js/images/loading-icon.gif | Bin 0 -> 2545 bytes pdf.js/images/loading-small.png | Bin 0 -> 3612 bytes .../secondaryToolbarButton-firstPage.png | Bin 0 -> 340 bytes .../secondaryToolbarButton-handTool.png | Bin 0 -> 250 bytes .../secondaryToolbarButton-lastPage.png | Bin 0 -> 315 bytes .../secondaryToolbarButton-rotateCcw.png | Bin 0 -> 414 bytes .../secondaryToolbarButton-rotateCw.png | Bin 0 -> 414 bytes pdf.js/images/shadow.png | Bin 0 -> 290 bytes pdf.js/images/texture.png | Bin 0 -> 2418 bytes pdf.js/images/toolbarButton-bookmark.png | Bin 0 -> 210 bytes pdf.js/images/toolbarButton-download.png | Bin 0 -> 343 bytes pdf.js/images/toolbarButton-fullscreen.png | Bin 0 -> 491 bytes pdf.js/images/toolbarButton-menuArrows.png | Bin 0 -> 200 bytes pdf.js/images/toolbarButton-openFile.png | Bin 0 -> 348 bytes pdf.js/images/toolbarButton-pageDown-rtl.png | Bin 0 -> 462 bytes pdf.js/images/toolbarButton-pageDown.png | Bin 0 -> 296 bytes pdf.js/images/toolbarButton-pageUp-rtl.png | Bin 0 -> 310 bytes pdf.js/images/toolbarButton-pageUp.png | Bin 0 -> 307 bytes .../images/toolbarButton-presentationMode.png | Bin 0 -> 450 bytes pdf.js/images/toolbarButton-print.png | Bin 0 -> 437 bytes pdf.js/images/toolbarButton-search.png | Bin 0 -> 411 bytes ...olbarButton-secondaryToolbarToggle-rtl.png | Bin 0 -> 583 bytes .../toolbarButton-secondaryToolbarToggle.png | Bin 0 -> 296 bytes .../toolbarButton-sidebarToggle-rtl.png | Bin 0 -> 548 bytes pdf.js/images/toolbarButton-sidebarToggle.png | Bin 0 -> 306 bytes .../images/toolbarButton-viewOutline-rtl.png | Bin 0 -> 405 bytes pdf.js/images/toolbarButton-viewOutline.png | Bin 0 -> 261 bytes pdf.js/images/toolbarButton-viewThumbnail.png | Bin 0 -> 182 bytes pdf.js/images/toolbarButton-zoomIn.png | Bin 0 -> 228 bytes pdf.js/images/toolbarButton-zoomOut.png | Bin 0 -> 141 bytes pdf.js/l10n.js | 1004 + pdf.js/locale/ar/viewer.properties | 112 + pdf.js/locale/ca/viewer.properties | 131 + pdf.js/locale/cs/viewer.properties | 58 + pdf.js/locale/cy/viewer.properties | 134 + pdf.js/locale/da/viewer.properties | 132 + pdf.js/locale/de/viewer.properties | 141 + pdf.js/locale/el/viewer.properties | 124 + pdf.js/locale/en-US/viewer.properties | 141 + pdf.js/locale/es/viewer.properties | 141 + pdf.js/locale/fa/viewer.properties | 134 + pdf.js/locale/fi/viewer.properties | 129 + pdf.js/locale/fr/viewer.properties | 130 + pdf.js/locale/he/viewer.properties | 59 + pdf.js/locale/it/viewer.properties | 44 + pdf.js/locale/ja/viewer.properties | 141 + pdf.js/locale/ko/viewer.properties | 131 + pdf.js/locale/locale.properties | 87 + pdf.js/locale/lt/viewer.properties | 129 + pdf.js/locale/nl/viewer.properties | 141 + pdf.js/locale/no/viewer.properties | 134 + pdf.js/locale/pl/viewer.properties | 132 + pdf.js/locale/pt-BR/viewer.properties | 44 + pdf.js/locale/ro/viewer.properties | 55 + pdf.js/locale/ru/viewer.properties | 62 + pdf.js/locale/sr/viewer.properties | 55 + pdf.js/locale/sv/viewer.properties | 142 + pdf.js/locale/tr/viewer.properties | 129 + pdf.js/locale/vi/viewer.properties | 131 + pdf.js/locale/zh-CN/viewer.properties | 141 + pdf.js/locale/zh-TW/viewer.properties | 141 + pdf.js/minify.py | 3 + pdf.js/pdf.js | 7511 +++ pdf.js/pdf.worker.js | 39957 ++++++++++++++++ pdf.js/viewer.css | 1719 + pdf.js/viewer.js | 5397 +++ txt.js/txt.js | 62 + txt.js/txt.py | 83 + txt.js/txt.ttf | Bin 0 -> 379588 bytes 122 files changed, 86212 insertions(+) create mode 100644 .gitignore create mode 100644 epub.js/css/annotations.css create mode 100755 epub.js/css/main.css create mode 100755 epub.js/css/normalize.css create mode 100644 epub.js/css/popup.css create mode 100644 epub.js/epub.js create mode 100644 epub.js/epub.js.map create mode 100644 epub.js/epub.min.js create mode 100644 epub.js/epub.min.map create mode 100644 epub.js/epub_no_underscore.js create mode 100644 epub.js/epub_no_underscore.js.map create mode 100644 epub.js/font/fontello.eot create mode 100644 epub.js/font/fontello.svg create mode 100644 epub.js/font/fontello.ttf create mode 100644 epub.js/font/fontello.woff create mode 100644 epub.js/hooks.js create mode 100644 epub.js/hooks.js.map create mode 100644 epub.js/hooks.min.js create mode 100644 epub.js/hooks.min.map create mode 100644 epub.js/hooks/extensions/highlight.js create mode 100644 epub.js/libs/fileStorage.min.js create mode 100644 epub.js/libs/inflate.js create mode 100644 epub.js/libs/inflate.map create mode 100644 epub.js/libs/jquery-2.1.0.min.js create mode 100644 epub.js/libs/jquery.highlight.js create mode 100644 epub.js/libs/loader_filesystem.min.js create mode 100644 epub.js/libs/screenfull.min.js create mode 100644 epub.js/libs/zip.min.js create mode 100644 epub.js/libs/zip.min.map create mode 100644 epub.js/plugins/hypothesis.js create mode 100644 epub.js/plugins/search.js create mode 100644 epub.js/reader.js create mode 100644 epub.js/reader.js.map create mode 100644 epub.js/reader.min.js create mode 100644 epub.js/reader.min.map create mode 100644 pdf.js/compatibility.js create mode 100644 pdf.js/css/videopdf.css create mode 100644 pdf.js/debugger.js create mode 100644 pdf.js/embeds.js create mode 100644 pdf.js/images/annotation-check.svg create mode 100644 pdf.js/images/annotation-comment.svg create mode 100644 pdf.js/images/annotation-help.svg create mode 100644 pdf.js/images/annotation-insert.svg create mode 100644 pdf.js/images/annotation-key.svg create mode 100644 pdf.js/images/annotation-newparagraph.svg create mode 100644 pdf.js/images/annotation-note.svg create mode 100644 pdf.js/images/annotation-paragraph.svg create mode 100644 pdf.js/images/findbarButton-next-rtl.png create mode 100644 pdf.js/images/findbarButton-next.png create mode 100644 pdf.js/images/findbarButton-previous-rtl.png create mode 100644 pdf.js/images/findbarButton-previous.png create mode 100644 pdf.js/images/grab.cur create mode 100644 pdf.js/images/grabbing.cur create mode 100644 pdf.js/images/loading-icon.gif create mode 100644 pdf.js/images/loading-small.png create mode 100644 pdf.js/images/secondaryToolbarButton-firstPage.png create mode 100644 pdf.js/images/secondaryToolbarButton-handTool.png create mode 100644 pdf.js/images/secondaryToolbarButton-lastPage.png create mode 100644 pdf.js/images/secondaryToolbarButton-rotateCcw.png create mode 100644 pdf.js/images/secondaryToolbarButton-rotateCw.png create mode 100644 pdf.js/images/shadow.png create mode 100644 pdf.js/images/texture.png create mode 100644 pdf.js/images/toolbarButton-bookmark.png create mode 100644 pdf.js/images/toolbarButton-download.png create mode 100644 pdf.js/images/toolbarButton-fullscreen.png create mode 100644 pdf.js/images/toolbarButton-menuArrows.png create mode 100644 pdf.js/images/toolbarButton-openFile.png create mode 100644 pdf.js/images/toolbarButton-pageDown-rtl.png create mode 100644 pdf.js/images/toolbarButton-pageDown.png create mode 100644 pdf.js/images/toolbarButton-pageUp-rtl.png create mode 100644 pdf.js/images/toolbarButton-pageUp.png create mode 100644 pdf.js/images/toolbarButton-presentationMode.png create mode 100644 pdf.js/images/toolbarButton-print.png create mode 100644 pdf.js/images/toolbarButton-search.png create mode 100644 pdf.js/images/toolbarButton-secondaryToolbarToggle-rtl.png create mode 100644 pdf.js/images/toolbarButton-secondaryToolbarToggle.png create mode 100644 pdf.js/images/toolbarButton-sidebarToggle-rtl.png create mode 100644 pdf.js/images/toolbarButton-sidebarToggle.png create mode 100644 pdf.js/images/toolbarButton-viewOutline-rtl.png create mode 100644 pdf.js/images/toolbarButton-viewOutline.png create mode 100644 pdf.js/images/toolbarButton-viewThumbnail.png create mode 100644 pdf.js/images/toolbarButton-zoomIn.png create mode 100644 pdf.js/images/toolbarButton-zoomOut.png create mode 100644 pdf.js/l10n.js create mode 100644 pdf.js/locale/ar/viewer.properties create mode 100644 pdf.js/locale/ca/viewer.properties create mode 100644 pdf.js/locale/cs/viewer.properties create mode 100644 pdf.js/locale/cy/viewer.properties create mode 100644 pdf.js/locale/da/viewer.properties create mode 100644 pdf.js/locale/de/viewer.properties create mode 100644 pdf.js/locale/el/viewer.properties create mode 100644 pdf.js/locale/en-US/viewer.properties create mode 100644 pdf.js/locale/es/viewer.properties create mode 100644 pdf.js/locale/fa/viewer.properties create mode 100644 pdf.js/locale/fi/viewer.properties create mode 100644 pdf.js/locale/fr/viewer.properties create mode 100644 pdf.js/locale/he/viewer.properties create mode 100644 pdf.js/locale/it/viewer.properties create mode 100644 pdf.js/locale/ja/viewer.properties create mode 100644 pdf.js/locale/ko/viewer.properties create mode 100644 pdf.js/locale/locale.properties create mode 100644 pdf.js/locale/lt/viewer.properties create mode 100644 pdf.js/locale/nl/viewer.properties create mode 100644 pdf.js/locale/no/viewer.properties create mode 100644 pdf.js/locale/pl/viewer.properties create mode 100644 pdf.js/locale/pt-BR/viewer.properties create mode 100644 pdf.js/locale/ro/viewer.properties create mode 100644 pdf.js/locale/ru/viewer.properties create mode 100644 pdf.js/locale/sr/viewer.properties create mode 100644 pdf.js/locale/sv/viewer.properties create mode 100644 pdf.js/locale/tr/viewer.properties create mode 100644 pdf.js/locale/vi/viewer.properties create mode 100644 pdf.js/locale/zh-CN/viewer.properties create mode 100644 pdf.js/locale/zh-TW/viewer.properties create mode 100644 pdf.js/minify.py create mode 100644 pdf.js/pdf.js create mode 100644 pdf.js/pdf.worker.js create mode 100644 pdf.js/viewer.css create mode 100644 pdf.js/viewer.js create mode 100644 txt.js/txt.js create mode 100755 txt.js/txt.py create mode 100644 txt.js/txt.ttf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a1f33ca --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +env +*.pyc +*.pyo +*.pyd +*.gz +*.swp +*.min.js +static/oxjs +*~ +*.db +._* diff --git a/epub.js/css/annotations.css b/epub.js/css/annotations.css new file mode 100644 index 0000000..ae74f91 --- /dev/null +++ b/epub.js/css/annotations.css @@ -0,0 +1,8 @@ +.ui-loader { + display: none; +} + +.annotator-hl { + box-shadow: none !important; + cursor: pointer !important; +} \ No newline at end of file diff --git a/epub.js/css/main.css b/epub.js/css/main.css new file mode 100755 index 0000000..fe0c65d --- /dev/null +++ b/epub.js/css/main.css @@ -0,0 +1,792 @@ +@font-face { + font-family: 'fontello'; + src: url('../font/fontello.eot?60518104'); + src: url('../font/fontello.eot?60518104#iefix') format('embedded-opentype'), + url('../font/fontello.woff?60518104') format('woff'), + url('../font/fontello.ttf?60518104') format('truetype'), + url('../font/fontello.svg?60518104#fontello') format('svg'); + font-weight: normal; + font-style: normal; +} + +body { + background: #4e4e4e; + overflow: hidden; +} + +#main { + /* height: 500px; */ + position: absolute; + width: 100%; + height: 100%; + right: 0; + padding-top: 2%; + /* left: 40px; */ +/* -webkit-transform: translate(40px, 0); + -moz-transform: translate(40px, 0); */ + + /* border-radius: 5px 0px 0px 5px; */ + background: #fff; + overflow: hidden; +} + + +#titlebar { + height: 8%; + min-height: 20px; + padding: 10px; + /* margin: 0 50px 0 50px; */ + position: relative; + color: #4f4f4f; + font-weight: 100; + font-family: Georgia, "Times New Roman", Times, serif; + opacity: .5; + text-align: center; + -webkit-transition: opacity .5s; + -moz-transition: opacity .5s; + z-index: 10; +} + +#titlebar:hover { + opacity: 1; +} + +#titlebar a { + width: 18px; + height: 19px; + line-height: 20px; + overflow: hidden; + display: inline-block; + opacity: .5; + padding: 4px; + border-radius: 4px; +} + +#titlebar a::before { + visibility: visible; +} + +#titlebar a:hover { + opacity: .8; + border: 1px rgba(0,0,0,.2) solid; + padding: 3px; +} + +#titlebar a:active { + opacity: 1; + color: rgba(0,0,0,.6); + /* margin: 1px -1px -1px 1px; */ + -moz-box-shadow: inset 0 0 6px rgba(155,155,155,.8); + -webkit-box-shadow: inset 0 0 6px rgba(155,155,155,.8); + box-shadow: inset 0 0 6px rgba(155,155,155,.8); +} + +#book-title { + font-weight: 600; +} + +#title-seperator { + display: none; +} + +#viewer { + width: 88%; + height: 92%; + /* margin-left: 10%; */ + margin: 0 auto; + max-width: 1250px; + z-index: 2; + position: relative; + overflow: hidden; +} + +#viewer iframe { + border: none; +} + +#prev { + left: 40px; +} + +#next { + right: 40px; +} + +.arrow { + position: absolute; + top: 50%; + margin-top: -32px; + font-size: 64px; + color: #E2E2E2; + font-family: arial, sans-serif; + font-weight: bold; + cursor: pointer; +} + +.arrow:hover { + color: #777; +} + +.arrow:active, +.arrow.active { + color: #000; +} + +#sidebar { + background: #6b6b6b; + position: absolute; + /* left: -260px; */ + /* -webkit-transform: translate(-260px, 0); + -moz-transform: translate(-260px, 0); */ + top: 0; + min-width: 300px; + width: 25%; + height: 100%; + -webkit-transition: -webkit-transform .5s; + -moz-transition: -moz-transform .5s; + + overflow: hidden; +} + +#sidebar.open { + /* left: 0; */ + /* -webkit-transform: translate(0, 0); + -moz-transform: translate(0, 0); */ +} + +#main.closed { + /* left: 300px; */ + -webkit-transform: translate(300px, 0); + -moz-transform: translate(300px, 0); +} + +#main.single { + width: 75%; +} + +#main.single #viewer { + /* width: 60%; + margin-left: 20%; */ +} + +#panels { + background: #4e4e4e; + position: absolute; + left: 0; + top: 0; + width: 100%; + padding: 13px 0; + height: 14px; + -moz-box-shadow: 0px 1px 3px rgba(0,0,0,.6); + -webkit-box-shadow: 0px 1px 3px rgba(0,0,0,.6); + box-shadow: 0px 1px 3px rgba(0,0,0,.6); +} + +#opener { + /* padding: 10px 10px; */ + float: left; +} + +/* #opener #slider { + width: 25px; +} */ + +#metainfo { + display: inline-block; + text-align: center; + max-width: 80%; +} + +#title-controls { + float: right; +} + +#panels a { + visibility: hidden; + width: 18px; + height: 20px; + overflow: hidden; + display: inline-block; + color: #ccc; + margin-left: 6px; +} + +#panels a::before { + visibility: visible; +} + +#panels a:hover { + color: #AAA; +} + +#panels a:active { + color: #AAA; + margin: 1px 0 -1px 6px; +} + +#panels a.active, +#panels a.active:hover { + color: #AAA; +} + +#searchBox { + width: 165px; + float: left; + margin-left: 10px; + margin-top: -1px; + /* + border-radius: 5px; + background: #9b9b9b; + float: left; + margin-left: 5px; + margin-top: -5px; + padding: 3px 10px; + color: #000; + border: none; + outline: none; */ + +} + +input::-webkit-input-placeholder { + color: #454545; +} +input:-moz-placeholder { + color: #454545; +} + +#divider { + position: absolute; + width: 1px; + border-right: 1px #000 solid; + height: 80%; + z-index: 1; + left: 50%; + margin-left: -1px; + top: 10%; + opacity: .15; + display: none; +} + +#divider.show { + display: block; +} + +#loader { + position: absolute; + z-index: 10; + left: 50%; + top: 50%; + margin: -33px 0 0 -33px; +} + +#tocView, +#bookmarksView { + overflow-x: hidden; + overflow-y: hidden; + min-width: 300px; + width: 25%; + height: 100%; + visibility: hidden; + -webkit-transition: visibility 0 ease .5s; + -moz-transition: visibility 0 ease .5s; +} + + + +#sidebar.open #tocView, +#sidebar.open #bookmarksView { + overflow-y: auto; + visibility: visible; + -webkit-transition: visibility 0 ease 0; + -moz-transition: visibility 0 ease 0; +} + +#sidebar.open #tocView { + display: block; +} + +#tocView > ul, +#bookmarksView > ul { + margin-top: 15px; + margin-bottom: 50px; + padding-left: 20px; + display: block; +} + +#tocView li, +#bookmarksView li { + margin-bottom:10px; + width: 225px; + font-family: Georgia, "Times New Roman", Times, serif; + list-style: none; + text-transform: capitalize; +} + +#tocView li:active, +#tocView li.currentChapter +{ + list-style: none; +} + +.list_item a { + color: #AAA; + text-decoration: none; +} + +.list_item a.chapter { + font-size: 1em; +} + +.list_item a.section { + font-size: .8em; +} + +.list_item.currentChapter > a, +.list_item a:hover { + color: #f1f1f1 +} + +/* #tocView li.openChapter > a, */ +.list_item a:hover { + color: #E2E2E2; +} + +.list_item ul { + padding-left:10px; + margin-top: 8px; + display: none; +} + +.list_item.currentChapter > ul, +.list_item.openChapter > ul { + display: block; +} + +#tocView.hidden { + display: none; +} + +.toc_toggle { + display: inline-block; + width: 14px; + cursor: pointer; + -webkit-user-select: none; + -moz-user-select: none; + user-select: none; +} + +.toc_toggle:before { + content: '▸'; + color: #fff; + margin-right: -4px; +} + +.currentChapter > .toc_toggle:before, +.openChapter > .toc_toggle:before { + content: '▾'; +} + +.view { + width: 300px; + height: 100%; + display: none; + padding-top: 50px; + overflow-y: auto; +} + +#searchResults { + margin-bottom: 50px; + padding-left: 20px; + display: block; +} + +#searchResults li { + margin-bottom:10px; + width: 225px; + font-family: Georgia, "Times New Roman", Times, serif; + list-style: none; +} + +#searchResults a { + color: #AAA; + text-decoration: none; +} + +#searchResults p { + text-decoration: none; + font-size: 12px; + line-height: 16px; +} + +#searchResults p .match { + background: #ccc; + color: #000; +} + +#searchResults li > p { + color: #AAA; +} + +#searchResults li a:hover { + color: #E2E2E2; +} + +#searchView.shown { + display: block; + overflow-y: scroll; +} + +#notes { + padding: 0 0 0 34px; +} + +#notes li { + color: #eee; + font-size: 12px; + width: 240px; + border-top: 1px #fff solid; + padding-top: 6px; + margin-bottom: 6px; +} + +#notes li a { + color: #fff; + display: inline-block; + margin-left: 6px; +} + +#notes li a:hover { + text-decoration: underline; +} + +#notes li img { + max-width: 240px; +} + +#note-text { + display: block; + width: 260px; + height: 80px; + margin: 0 auto; + padding: 5px; + border-radius: 5px; +} + +#note-text[disabled], #note-text[disabled="disabled"]{ + opacity: .5; +} + +#note-anchor { + margin-left: 218px; + margin-top: 5px; +} + +#settingsPanel { + display:none; +} + +#settingsPanel h3 { + color:#f1f1f1; + font-family:Georgia, "Times New Roman", Times, serif; + margin-bottom:10px; +} + +#settingsPanel ul { + margin-top:60px; + list-style-type:none; +} + +#settingsPanel li { + font-size:1em; + color:#f1f1f1; +} + +#settingsPanel .xsmall { font-size:x-small; } +#settingsPanel .small { font-size:small; } +#settingsPanel .medium { font-size:medium; } +#settingsPanel .large { font-size:large; } +#settingsPanel .xlarge { font-size:x-large; } + +.highlight { background-color: yellow } + +.modal { + position: fixed; + top: 50%; + left: 50%; + width: 50%; + width: 630px; + + height: auto; + z-index: 2000; + visibility: hidden; + margin-left: -320px; + margin-top: -160px; + +} + +.overlay { + position: fixed; + width: 100%; + height: 100%; + visibility: hidden; + top: 0; + left: 0; + z-index: 1000; + opacity: 0; + background: rgba(255,255,255,0.8); + -webkit-transition: all 0.3s; + -moz-transition: all 0.3s; + transition: all 0.3s; +} + +.md-show { + visibility: visible; +} + +.md-show ~ .overlay { + opacity: 1; + visibility: visible; +} + +/* Content styles */ +.md-content { + color: #fff; + background: #6b6b6b; + position: relative; + border-radius: 3px; + margin: 0 auto; + height: 320px; +} + +.md-content h3 { + margin: 0; + padding: 6px; + text-align: center; + font-size: 22px; + font-weight: 300; + opacity: 0.8; + background: rgba(0,0,0,0.1); + border-radius: 3px 3px 0 0; +} + +.md-content > div { + padding: 15px 40px 30px; + margin: 0; + font-weight: 300; + font-size: 14px; +} + +.md-content > div p { + margin: 0; + padding: 10px 0; +} + +.md-content > div ul { + margin: 0; + padding: 0 0 30px 20px; +} + +.md-content > div ul li { + padding: 5px 0; +} + +.md-content button { + display: block; + margin: 0 auto; + font-size: 0.8em; +} + +/* Effect 1: Fade in and scale up */ +.md-effect-1 .md-content { + -webkit-transform: scale(0.7); + -moz-transform: scale(0.7); + -ms-transform: scale(0.7); + transform: scale(0.7); + opacity: 0; + -webkit-transition: all 0.3s; + -moz-transition: all 0.3s; + transition: all 0.3s; +} + +.md-show.md-effect-1 .md-content { + -webkit-transform: scale(1); + -moz-transform: scale(1); + -ms-transform: scale(1); + transform: scale(1); + opacity: 1; +} + +.md-content > .closer { + font-size: 18px; + position: absolute; + right: 0; + top: 0; + font-size: 24px; + padding: 4px; +} + +@media only screen and (max-width: 1040px) { + #viewer{ + width: 50%; + margin-left: 25%; + } + + #divider, + #divider.show { + display: none; + } +} + +@media only screen and (max-width: 900px) { + #viewer{ + width: 60%; + margin-left: 20%; + } + + #prev { + left: 20px; + } + + #next { + right: 20px; + } +} + +@media only screen and (max-width: 550px) { + #viewer{ + width: 80%; + margin-left: 10%; + } + + #prev { + left: 0; + } + + #next { + right: 0; + } + + .arrow { + height: 100%; + top: 45px; + width: 10%; + text-indent: -10000px; + } + + #main { + -webkit-transform: translate(0, 0); + -moz-transform: translate(0, 0); + -webkit-transition: -webkit-transform .3s; + -moz-transition: -moz-transform .3s; + } + + #main.closed { + -webkit-transform: translate(260px, 0); + -moz-transform: translate(260px, 0); + } + + #titlebar { + /* font-size: 16px; */ + /* margin: 0 50px 0 50px; */ + } + + #metainfo { + font-size: 10px; + } + + #tocView { + width: 260px; + } + + #tocView li { + font-size: 12px; + } + + #tocView > ul{ + padding-left: 10px; + webkit-padding-start:; + } +} + + +/* For iPad portrait layouts only */ +@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation: portrait) { + #viewer iframe { + width: 460px; + height: 740px; + } +} + /*For iPad landscape layouts only */ +@media only screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation: landscape) { + #viewer iframe { + width: 460px; + height: 415px; + } +} +/* For iPhone portrait layouts only */ +@media only screen and (max-device-width: 480px) and (orientation: portrait) { + #viewer { + width: 256px; + height: 432px; + } + #viewer iframe { + width: 256px; + height: 432px; + } +} +/* For iPhone landscape layouts only */ +@media only screen and (max-device-width: 480px) and (orientation: landscape) { + #viewer iframe { + width: 256px; + height: 124px; + } +} + +[class^="icon-"]:before, [class*=" icon-"]:before { + font-family: "fontello"; + font-style: normal; + font-weight: normal; + speak: none; + + display: inline-block; + text-decoration: inherit; + width: 1em; + margin-right: .2em; + text-align: center; + /* opacity: .8; */ + + /* For safety - reset parent styles, that can break glyph codes*/ + font-variant: normal; + text-transform: none; + + /* you can be more comfortable with increased icons size */ + font-size: 112%; +} + + +.icon-search:before { content: '\e807'; } /* '' */ +.icon-resize-full-1:before { content: '\e804'; } /* '' */ +.icon-cancel-circled2:before { content: '\e80f'; } /* '' */ +.icon-link:before { content: '\e80d'; } /* '' */ +.icon-bookmark:before { content: '\e805'; } /* '' */ +.icon-bookmark-empty:before { content: '\e806'; } /* '' */ +.icon-download-cloud:before { content: '\e811'; } /* '' */ +.icon-edit:before { content: '\e814'; } /* '' */ +.icon-menu:before { content: '\e802'; } /* '' */ +.icon-cog:before { content: '\e813'; } /* '' */ +.icon-resize-full:before { content: '\e812'; } /* '' */ +.icon-cancel-circled:before { content: '\e80e'; } /* '' */ +.icon-up-dir:before { content: '\e80c'; } /* '' */ +.icon-right-dir:before { content: '\e80b'; } /* '' */ +.icon-angle-right:before { content: '\e809'; } /* '' */ +.icon-angle-down:before { content: '\e80a'; } /* '' */ +.icon-right:before { content: '\e815'; } /* '' */ +.icon-list-1:before { content: '\e803'; } /* '' */ +.icon-list-numbered:before { content: '\e801'; } /* '' */ +.icon-columns:before { content: '\e810'; } /* '' */ +.icon-list:before { content: '\e800'; } /* '' */ +.icon-resize-small:before { content: '\e808'; } /* '' */ + +#titlebar { + display: none !important; +} diff --git a/epub.js/css/normalize.css b/epub.js/css/normalize.css new file mode 100755 index 0000000..c3e014d --- /dev/null +++ b/epub.js/css/normalize.css @@ -0,0 +1,505 @@ +/*! normalize.css v1.0.1 | MIT License | git.io/normalize */ + +/* ========================================================================== + HTML5 display definitions + ========================================================================== */ + +/* + * Corrects `block` display not defined in IE 6/7/8/9 and Firefox 3. + */ + +article, +aside, +details, +figcaption, +figure, +footer, +header, +hgroup, +nav, +section, +summary { + display: block; +} + +/* + * Corrects `inline-block` display not defined in IE 6/7/8/9 and Firefox 3. + */ + +audio, +canvas, +video { + display: inline-block; + *display: inline; + *zoom: 1; +} + +/* + * Prevents modern browsers from displaying `audio` without controls. + * Remove excess height in iOS 5 devices. + */ + +audio:not([controls]) { + display: none; + height: 0; +} + +/* + * Addresses styling for `hidden` attribute not present in IE 7/8/9, Firefox 3, + * and Safari 4. + * Known issue: no IE 6 support. + */ + +[hidden] { + display: none; +} + +/* ========================================================================== + Base + ========================================================================== */ + +/* + * 1. Corrects text resizing oddly in IE 6/7 when body `font-size` is set using + * `em` units. + * 2. Prevents iOS text size adjust after orientation change, without disabling + * user zoom. + */ + +html { + font-size: 100%; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ + -ms-text-size-adjust: 100%; /* 2 */ +} + +/* + * Addresses `font-family` inconsistency between `textarea` and other form + * elements. + */ + +html, +button, +input, +select, +textarea { + font-family: sans-serif; +} + +/* + * Addresses margins handled incorrectly in IE 6/7. + */ + +body { + margin: 0; +} + +/* ========================================================================== + Links + ========================================================================== */ + +/* + * Addresses `outline` inconsistency between Chrome and other browsers. + */ + +a:focus { + outline: thin dotted; +} + +/* + * Improves readability when focused and also mouse hovered in all browsers. + */ + +a:active, +a:hover { + outline: 0; +} + +/* ========================================================================== + Typography + ========================================================================== */ + +/* + * Addresses font sizes and margins set differently in IE 6/7. + * Addresses font sizes within `section` and `article` in Firefox 4+, Safari 5, + * and Chrome. + */ + +h1 { + font-size: 2em; + margin: 0.67em 0; +} + +h2 { + font-size: 1.5em; + margin: 0.83em 0; +} + +h3 { + font-size: 1.17em; + margin: 1em 0; +} + +h4 { + font-size: 1em; + margin: 1.33em 0; +} + +h5 { + font-size: 0.83em; + margin: 1.67em 0; +} + +h6 { + font-size: 0.75em; + margin: 2.33em 0; +} + +/* + * Addresses styling not present in IE 7/8/9, Safari 5, and Chrome. + */ + +abbr[title] { + border-bottom: 1px dotted; +} + +/* + * Addresses style set to `bolder` in Firefox 3+, Safari 4/5, and Chrome. + */ + +b, +strong { + font-weight: bold; +} + +blockquote { + margin: 1em 40px; +} + +/* + * Addresses styling not present in Safari 5 and Chrome. + */ + +dfn { + font-style: italic; +} + +/* + * Addresses styling not present in IE 6/7/8/9. + */ + +mark { + background: #ff0; + color: #000; +} + +/* + * Addresses margins set differently in IE 6/7. + */ + +p, +pre { + margin: 1em 0; +} + +/* + * Corrects font family set oddly in IE 6, Safari 4/5, and Chrome. + */ + +code, +kbd, +pre, +samp { + font-family: monospace, serif; + _font-family: 'courier new', monospace; + font-size: 1em; +} + +/* + * Improves readability of pre-formatted text in all browsers. + */ + +pre { + white-space: pre; + white-space: pre-wrap; + word-wrap: break-word; +} + +/* + * Addresses CSS quotes not supported in IE 6/7. + */ + +q { + quotes: none; +} + +/* + * Addresses `quotes` property not supported in Safari 4. + */ + +q:before, +q:after { + content: ''; + content: none; +} + +/* + * Addresses inconsistent and variable font size in all browsers. + */ + +small { + font-size: 80%; +} + +/* + * Prevents `sub` and `sup` affecting `line-height` in all browsers. + */ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sup { + top: -0.5em; +} + +sub { + bottom: -0.25em; +} + +/* ========================================================================== + Lists + ========================================================================== */ + +/* + * Addresses margins set differently in IE 6/7. + */ + +dl, +menu, +ol, +ul { + margin: 1em 0; +} + +dd { + margin: 0 0 0 40px; +} + +/* + * Addresses paddings set differently in IE 6/7. + */ + +menu, +ol, +ul { + padding: 0 0 0 40px; +} + +/* + * Corrects list images handled incorrectly in IE 7. + */ + +nav ul, +nav ol { + list-style: none; + list-style-image: none; +} + +/* ========================================================================== + Embedded content + ========================================================================== */ + +/* + * 1. Removes border when inside `a` element in IE 6/7/8/9 and Firefox 3. + * 2. Improves image quality when scaled in IE 7. + */ + +img { + border: 0; /* 1 */ + -ms-interpolation-mode: bicubic; /* 2 */ +} + +/* + * Corrects overflow displayed oddly in IE 9. + */ + +svg:not(:root) { + overflow: hidden; +} + +/* ========================================================================== + Figures + ========================================================================== */ + +/* + * Addresses margin not present in IE 6/7/8/9, Safari 5, and Opera 11. + */ + +figure { + margin: 0; +} + +/* ========================================================================== + Forms + ========================================================================== */ + +/* + * Corrects margin displayed oddly in IE 6/7. + */ + +form { + margin: 0; +} + +/* + * Define consistent border, margin, and padding. + */ + +fieldset { + border: 1px solid #c0c0c0; + margin: 0 2px; + padding: 0.35em 0.625em 0.75em; +} + +/* + * 1. Corrects color not being inherited in IE 6/7/8/9. + * 2. Corrects text not wrapping in Firefox 3. + * 3. Corrects alignment displayed oddly in IE 6/7. + */ + +legend { + border: 0; /* 1 */ + padding: 0; + white-space: normal; /* 2 */ + *margin-left: -7px; /* 3 */ +} + +/* + * 1. Corrects font size not being inherited in all browsers. + * 2. Addresses margins set differently in IE 6/7, Firefox 3+, Safari 5, + * and Chrome. + * 3. Improves appearance and consistency in all browsers. + */ + +button, +input, +select, +textarea { + font-size: 100%; /* 1 */ + margin: 0; /* 2 */ + vertical-align: baseline; /* 3 */ + *vertical-align: middle; /* 3 */ +} + +/* + * Addresses Firefox 3+ setting `line-height` on `input` using `!important` in + * the UA stylesheet. + */ + +button, +input { + line-height: normal; +} + +/* + * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio` + * and `video` controls. + * 2. Corrects inability to style clickable `input` types in iOS. + * 3. Improves usability and consistency of cursor style between image-type + * `input` and others. + * 4. Removes inner spacing in IE 7 without affecting normal text inputs. + * Known issue: inner spacing remains in IE 6. + */ + +button, +html input[type="button"], /* 1 */ +input[type="reset"], +input[type="submit"] { + -webkit-appearance: button; /* 2 */ + cursor: pointer; /* 3 */ + *overflow: visible; /* 4 */ +} + +/* + * Re-set default cursor for disabled elements. + */ + +button[disabled], +input[disabled] { + cursor: default; +} + +/* + * 1. Addresses box sizing set to content-box in IE 8/9. + * 2. Removes excess padding in IE 8/9. + * 3. Removes excess padding in IE 7. + * Known issue: excess padding remains in IE 6. + */ + +input[type="checkbox"], +input[type="radio"] { + box-sizing: border-box; /* 1 */ + padding: 0; /* 2 */ + *height: 13px; /* 3 */ + *width: 13px; /* 3 */ +} + +/* + * 1. Addresses `appearance` set to `searchfield` in Safari 5 and Chrome. + * 2. Addresses `box-sizing` set to `border-box` in Safari 5 and Chrome + * (include `-moz` to future-proof). + */ +/* +input[type="search"] { + -webkit-appearance: textfield; + -moz-box-sizing: content-box; + -webkit-box-sizing: content-box; + box-sizing: content-box; +} +*/ + +/* + * Removes inner padding and search cancel button in Safari 5 and Chrome + * on OS X. + */ + +/* input[type="search"]::-webkit-search-cancel-button, +input[type="search"]::-webkit-search-decoration { + -webkit-appearance: none; +} */ + +/* + * Removes inner padding and border in Firefox 3+. + */ + +button::-moz-focus-inner, +input::-moz-focus-inner { + border: 0; + padding: 0; +} + +/* + * 1. Removes default vertical scrollbar in IE 6/7/8/9. + * 2. Improves readability and alignment in all browsers. + */ + +textarea { + overflow: auto; /* 1 */ + vertical-align: top; /* 2 */ +} + +/* ========================================================================== + Tables + ========================================================================== */ + +/* + * Remove most spacing between table cells. + */ + +table { + border-collapse: collapse; + border-spacing: 0; +} diff --git a/epub.js/css/popup.css b/epub.js/css/popup.css new file mode 100644 index 0000000..c41aac7 --- /dev/null +++ b/epub.js/css/popup.css @@ -0,0 +1,96 @@ +/* http://davidwalsh.name/css-tooltips */ +/* base CSS element */ +.popup { + background: #eee; + border: 1px solid #ccc; + padding: 10px; + border-radius: 8px; + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); + position: fixed; + max-width: 300px; + font-size: 12px; + + display: none; + margin-left: 2px; + + margin-top: 30px; +} + +.popup.above { + margin-top: -10px; +} + +.popup.left { + margin-left: -20px; +} + +.popup.right { + margin-left: 40px; +} + +.pop_content { + max-height: 225px; + overflow-y: auto; +} + +.pop_content > p { + margin-top: 0; +} + +/* below */ +.popup:before { + position: absolute; + display: inline-block; + border-bottom: 10px solid #eee; + border-right: 10px solid transparent; + border-left: 10px solid transparent; + border-bottom-color: rgba(0, 0, 0, 0.2); + left: 50%; + top: -10px; + margin-left: -6px; + content: ''; +} + +.popup:after { + position: absolute; + display: inline-block; + border-bottom: 9px solid #eee; + border-right: 9px solid transparent; + border-left: 9px solid transparent; + left: 50%; + top: -9px; + margin-left: -5px; + content: ''; +} + +/* above */ +.popup.above:before { + border-bottom: none; + border-top: 10px solid #eee; + border-top-color: rgba(0, 0, 0, 0.2); + top: 100%; +} + +.popup.above:after { + border-bottom: none; + border-top: 9px solid #eee; + top: 100%; +} + +.popup.left:before, +.popup.left:after +{ + left: 20px; +} + +.popup.right:before, +.popup.right:after +{ + left: auto; + right: 20px; +} + + +.popup.show, .popup.on { + display: block; +} \ No newline at end of file diff --git a/epub.js/epub.js b/epub.js/epub.js new file mode 100644 index 0000000..cb42010 --- /dev/null +++ b/epub.js/epub.js @@ -0,0 +1,7462 @@ +(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,d=e.filter,g=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.4";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:d&&n.filter===d?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:g&&n.every===g?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2),e=w.isFunction(t);return w.map(n,function(n){return(e?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t,r){return w.isEmpty(t)?r?null:[]:w[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.findWhere=function(n,t){return w.where(n,t,!0)},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var k=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=k(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.indexi;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFunction(t)&&(e=r,r=t,t=!1);var u=r?w.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:w.contains(a,r))||(a.push(r),i.push(n[e]))}),i},w.union=function(){return w.uniq(c.apply(e,arguments))},w.intersection=function(n){var t=o.call(arguments,1);return w.filter(w.uniq(n),function(n){return w.every(t,function(t){return w.indexOf(t,n)>=0})})},w.difference=function(n){var t=c.apply(e,o.call(arguments,1));return w.filter(n,function(n){return!w.contains(t,n)})},w.zip=function(){for(var n=o.call(arguments),t=w.max(w.pluck(n,"length")),r=Array(t),e=0;t>e;e++)r[e]=w.pluck(n,""+e);return r},w.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},w.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=w.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},w.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},w.range=function(n,t,r){1>=arguments.length&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=Array(e);e>u;)i[u++]=n,n+=r;return i},w.bind=function(n,t){if(n.bind===j&&j)return j.apply(n,o.call(arguments,1));var r=o.call(arguments,2);return function(){return n.apply(t,r.concat(o.call(arguments)))}},w.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},w.bindAll=function(n){var t=o.call(arguments,1);return 0===t.length&&(t=w.functions(n)),A(t,function(t){n[t]=w.bind(n[t],n)}),n},w.memoize=function(n,t){var r={};return t||(t=w.identity),function(){var e=t.apply(this,arguments);return w.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},w.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},w.defer=function(n){return w.delay.apply(w,[n,1].concat(o.call(arguments,1)))},w.throttle=function(n,t){var r,e,u,i,a=0,o=function(){a=new Date,u=null,i=n.apply(r,e)};return function(){var c=new Date,l=t-(c-a);return r=this,e=arguments,0>=l?(clearTimeout(u),u=null,a=c,i=n.apply(r,e)):u||(u=setTimeout(o,l)),i}},w.debounce=function(n,t,r){var e,u;return function(){var i=this,a=arguments,o=function(){e=null,r||(u=n.apply(i,a))},c=r&&!e;return clearTimeout(e),e=setTimeout(o,t),c&&(u=n.apply(i,a)),u}},w.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},w.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},w.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},w.after=function(n,t){return 0>=n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},w.keys=_||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)w.has(n,r)&&(t[t.length]=r);return t},w.values=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push(n[r]);return t},w.pairs=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push([r,n[r]]);return t},w.invert=function(n){var t={};for(var r in n)w.has(n,r)&&(t[n[r]]=r);return t},w.functions=w.methods=function(n){var t=[];for(var r in n)w.isFunction(n[r])&&t.push(r);return t.sort()},w.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},w.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},w.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)w.contains(r,u)||(t[u]=n[u]);return t},w.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)null==n[r]&&(n[r]=t[r])}),n},w.clone=function(n){return w.isObject(n)?w.isArray(n)?n.slice():w.extend({},n):n},w.tap=function(n,t){return t(n),n};var I=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof w&&(n=n._wrapped),t instanceof w&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==t+"";case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;r.push(n),e.push(t);var a=0,o=!0;if("[object Array]"==u){if(a=n.length,o=a==t.length)for(;a--&&(o=I(n[a],t[a],r,e)););}else{var c=n.constructor,f=t.constructor;if(c!==f&&!(w.isFunction(c)&&c instanceof c&&w.isFunction(f)&&f instanceof f))return!1;for(var s in n)if(w.has(n,s)&&(a++,!(o=w.has(t,s)&&I(n[s],t[s],r,e))))break;if(o){for(s in t)if(w.has(t,s)&&!a--)break;o=!a}}return r.pop(),e.pop(),o};w.isEqual=function(n,t){return I(n,t,[],[])},w.isEmpty=function(n){if(null==n)return!0;if(w.isArray(n)||w.isString(n))return 0===n.length;for(var t in n)if(w.has(n,t))return!1;return!0},w.isElement=function(n){return!(!n||1!==n.nodeType)},w.isArray=x||function(n){return"[object Array]"==l.call(n)},w.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){w["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),w.isArguments(arguments)||(w.isArguments=function(n){return!(!n||!w.has(n,"callee"))}),"function"!=typeof/./&&(w.isFunction=function(n){return"function"==typeof n}),w.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},w.isNaN=function(n){return w.isNumber(n)&&n!=+n},w.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},w.isNull=function(n){return null===n},w.isUndefined=function(n){return n===void 0},w.has=function(n,t){return f.call(n,t)},w.noConflict=function(){return n._=t,this},w.identity=function(n){return n},w.times=function(n,t,r){for(var e=Array(n),u=0;n>u;u++)e[u]=t.call(r,u);return e},w.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var M={escape:{"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"}};M.unescape=w.invert(M.escape);var S={escape:RegExp("["+w.keys(M.escape).join("")+"]","g"),unescape:RegExp("("+w.keys(M.unescape).join("|")+")","g")};w.each(["escape","unescape"],function(n){w[n]=function(t){return null==t?"":(""+t).replace(S[n],function(t){return M[n][t]})}}),w.result=function(n,t){if(null==n)return null;var r=n[t];return w.isFunction(r)?r.call(n):r},w.mixin=function(n){A(w.functions(n),function(t){var r=w[t]=n[t];w.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),D.call(this,r.apply(w,n))}})};var N=0;w.uniqueId=function(n){var t=++N+"";return n?n+t:t},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var T=/(.)^/,q={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},B=/\\|'|\r|\n|\t|\u2028|\u2029/g;w.template=function(n,t,r){var e;r=w.defaults({},r,w.templateSettings);var u=RegExp([(r.escape||T).source,(r.interpolate||T).source,(r.evaluate||T).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(B,function(n){return"\\"+q[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,w);var c=function(n){return e.call(this,n,w)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},w.chain=function(n){return w(n).chain()};var D=function(n){return this._chain?w(n).chain():n};w.mixin(w),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];w.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],D.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];w.prototype[n]=function(){return D.call(this,t.apply(this._wrapped,arguments))}}),w.extend(w.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); +(function(global) { +var define, requireModule, require, requirejs; + +(function() { + var registry = {}, seen = {}; + + define = function(name, deps, callback) { + registry[name] = { deps: deps, callback: callback }; + }; + + requirejs = require = requireModule = function(name) { + requirejs._eak_seen = registry; + + if (seen[name]) { return seen[name]; } + seen[name] = {}; + + if (!registry[name]) { + throw new Error("Could not find module " + name); + } + + var mod = registry[name], + deps = mod.deps, + callback = mod.callback, + reified = [], + exports; + + for (var i=0, l=deps.length; i 1; + }; + + RSVP.filter(promises, filterFn).then(function(result){ + // result is [ 2, 3 ] + }); + ``` + + If any of the `promises` given to `RSVP.filter` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + var filterFn = function(item){ + return item > 1; + }; + + RSVP.filter(promises, filterFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "2" + }); + ``` + + `RSVP.filter` will also wait for any promises returned from `filterFn`. + For instance, you may want to fetch a list of users then return a subset + of those users based on some asynchronous operation: + + ```javascript + + var alice = { name: 'alice' }; + var bob = { name: 'bob' }; + var users = [ alice, bob ]; + + var promises = users.map(function(user){ + return RSVP.resolve(user); + }); + + var filterFn = function(user){ + // Here, Alice has permissions to create a blog post, but Bob does not. + return getPrivilegesForUser(user).then(function(privs){ + return privs.can_create_blog_post === true; + }); + }; + RSVP.filter(promises, filterFn).then(function(users){ + // true, because the server told us only Alice can create a blog post. + users.length === 1; + // false, because Alice is the only user present in `users` + users[0] === bob; + }); + ``` + + @method filter + @for RSVP + @param {Array} promises + @param {Function} filterFn - function to be called on each resolved value to + filter the final results. + @param {String} label optional string describing the promise. Useful for + tooling. + @return {Promise} + */ + function filter(promises, filterFn, label) { + if (!isArray(promises)) { + throw new TypeError('You must pass an array to filter.'); + } + + if (!isFunction(filterFn)){ + throw new TypeError("You must pass a function to filter's second argument."); + } + + return all(promises, label).then(function(values){ + return map(promises, filterFn, label).then(function(filterResults){ + var i, + valuesLen = values.length, + filtered = []; + + for (i = 0; i < valuesLen; i++){ + if(filterResults[i]) filtered.push(values[i]); + } + return filtered; + }); + }); + } + + __exports__["default"] = filter; + }); +define("rsvp/hash", + ["./promise","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var isNonThenable = __dependency2__.isNonThenable; + var keysOf = __dependency2__.keysOf; + + /** + `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array + for its `promises` argument. + + Returns a promise that is fulfilled when all the given promises have been + fulfilled, or rejected if any of them become rejected. The returned promise + is fulfilled with a hash that has the same key names as the `promises` object + argument. If any of the values in the object are not promises, they will + simply be copied over to the fulfilled object. + + Example: + + ```javascript + var promises = { + myPromise: RSVP.resolve(1), + yourPromise: RSVP.resolve(2), + theirPromise: RSVP.resolve(3), + notAPromise: 4 + }; + + RSVP.hash(promises).then(function(hash){ + // hash here is an object that looks like: + // { + // myPromise: 1, + // yourPromise: 2, + // theirPromise: 3, + // notAPromise: 4 + // } + }); + ```` + + If any of the `promises` given to `RSVP.hash` are rejected, the first promise + that is rejected will be given as as the first argument, or as the reason to + the rejection handler. For example: + + ```javascript + var promises = { + myPromise: RSVP.resolve(1), + rejectedPromise: RSVP.reject(new Error("rejectedPromise")), + anotherRejectedPromise: RSVP.reject(new Error("anotherRejectedPromise")), + }; + + RSVP.hash(promises).then(function(hash){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "rejectedPromise" + }); + ``` + + An important note: `RSVP.hash` is intended for plain JavaScript objects that + are just a set of keys and values. `RSVP.hash` will NOT preserve prototype + chains. + + Example: + + ```javascript + function MyConstructor(){ + this.example = RSVP.resolve("Example"); + } + + MyConstructor.prototype = { + protoProperty: RSVP.resolve("Proto Property") + }; + + var myObject = new MyConstructor(); + + RSVP.hash(myObject).then(function(hash){ + // protoProperty will not be present, instead you will just have an + // object that looks like: + // { + // example: "Example" + // } + // + // hash.hasOwnProperty('protoProperty'); // false + // 'undefined' === typeof hash.protoProperty + }); + ``` + + @method hash + @for RSVP + @param {Object} promises + @param {String} label - optional string that describes the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all properties of `promises` + have been fulfilled, or rejected if any of them become rejected. + */ + __exports__["default"] = function hash(object, label) { + return new Promise(function(resolve, reject){ + var results = {}; + var keys = keysOf(object); + var remaining = keys.length; + var entry, property; + + if (remaining === 0) { + resolve(results); + return; + } + + function fulfilledTo(property) { + return function(value) { + results[property] = value; + if (--remaining === 0) { + resolve(results); + } + }; + } + + function onRejection(reason) { + remaining = 0; + reject(reason); + } + + for (var i = 0; i < keys.length; i++) { + property = keys[i]; + entry = object[property]; + + if (isNonThenable(entry)) { + results[property] = entry; + if (--remaining === 0) { + resolve(results); + } + } else { + Promise.cast(entry).then(fulfilledTo(property), onRejection); + } + } + }); + }; + }); +define("rsvp/instrument", + ["./config","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var config = __dependency1__.config; + var now = __dependency2__.now; + + __exports__["default"] = function instrument(eventName, promise, child) { + // instrumentation should not disrupt normal usage. + try { + config.trigger(eventName, { + guid: promise._guidKey + promise._id, + eventName: eventName, + detail: promise._detail, + childGuid: child && promise._guidKey + child._id, + label: promise._label, + timeStamp: now(), + stack: new Error(promise._label).stack + }); + } catch(error) { + setTimeout(function(){ + throw error; + }, 0); + } + }; + }); +define("rsvp/map", + ["./promise","./all","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var all = __dependency2__["default"]; + var isArray = __dependency3__.isArray; + var isFunction = __dependency3__.isFunction; + + /** + + `RSVP.map` is similar to JavaScript's native `map` method, except that it + waits for all promises to become fulfilled before running the `mapFn` on + each item in given to `promises`. `RSVP.map` returns a promise that will + become fulfilled with the result of running `mapFn` on the values the promises + become fulfilled with. + + For example: + + ```javascript + + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.resolve(2); + var promise3 = RSVP.resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + var mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(result){ + // result is [ 2, 3, 4 ] + }); + ``` + + If any of the `promises` given to `RSVP.map` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + var mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "2" + }); + ``` + + `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, + say you want to get all comments from a set of blog posts, but you need + the blog posts first becuase they contain a url to those comments. + + ```javscript + + var mapFn = function(blogPost){ + // getComments does some ajax and returns an RSVP.Promise that is fulfilled + // with some comments data + return getComments(blogPost.comments_url); + }; + + // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled + // with some blog post data + RSVP.map(getBlogPosts(), mapFn).then(function(comments){ + // comments is the result of asking the server for the comments + // of all blog posts returned from getBlogPosts() + }); + ``` + + @method map + @for RSVP + @param {Array} promises + @param {Function} mapFn function to be called on each fulfilled promise. + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled with the result of calling + `mapFn` on each fulfilled promise or value when they become fulfilled. + The promise will be rejected if any of the given `promises` become rejected. + */ + __exports__["default"] = function map(promises, mapFn, label) { + + if (!isArray(promises)) { + throw new TypeError('You must pass an array to map.'); + } + + if (!isFunction(mapFn)){ + throw new TypeError("You must pass a function to map's second argument."); + } + + return all(promises, label).then(function(results){ + var resultLen = results.length, + mappedResults = [], + i; + + for (i = 0; i < resultLen; i++){ + mappedResults.push(mapFn(results[i])); + } + + return all(mappedResults, label); + }); + }; + }); +define("rsvp/node", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + var slice = Array.prototype.slice; + + function makeNodeCallbackFor(resolve, reject) { + return function (error, value) { + if (error) { + reject(error); + } else if (arguments.length > 2) { + resolve(slice.call(arguments, 1)); + } else { + resolve(value); + } + }; + } + + /** + `RSVP.denodeify` takes a "node-style" function and returns a function that + will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the + browser when you'd prefer to use promises over using callbacks. For example, + `denodeify` transforms the following: + + ```javascript + var fs = require('fs'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + handleData(data); + }); + ``` + + into: + + ```javascript + var fs = require('fs'); + + var readFile = RSVP.denodeify(fs.readFile); + + readFile('myfile.txt').then(handleData, handleError); + ``` + + Using `denodeify` makes it easier to compose asynchronous operations instead + of using callbacks. For example, instead of: + + ```javascript + var fs = require('fs'); + var log = require('some-async-logger'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + fs.writeFile('myfile2.txt', data, function(err){ + if (err) throw err; + log('success', function(err) { + if (err) throw err; + }); + }); + }); + ``` + + You can chain the operations together using `then` from the returned promise: + + ```javascript + var fs = require('fs'); + var denodeify = RSVP.denodeify; + var readFile = denodeify(fs.readFile); + var writeFile = denodeify(fs.writeFile); + var log = denodeify(require('some-async-logger')); + + readFile('myfile.txt').then(function(data){ + return writeFile('myfile2.txt', data); + }).then(function(){ + return log('SUCCESS'); + }).then(function(){ + // success handler + }, function(reason){ + // rejection handler + }); + ``` + + @method denodeify + @for RSVP + @param {Function} nodeFunc a "node-style" function that takes a callback as + its last argument. The callback expects an error to be passed as its first + argument (if an error occurred, otherwise null), and the value from the + operation as its second argument ("function(err, value){ }"). + @param {Any} binding optional argument for binding the "this" value when + calling the `nodeFunc` function. + @return {Function} a function that wraps `nodeFunc` to return an + `RSVP.Promise` + */ + __exports__["default"] = function denodeify(nodeFunc, binding) { + return function() { + var nodeArgs = slice.call(arguments), resolve, reject; + var thisArg = this || binding; + + return new Promise(function(resolve, reject) { + Promise.all(nodeArgs).then(function(nodeArgs) { + try { + nodeArgs.push(makeNodeCallbackFor(resolve, reject)); + nodeFunc.apply(thisArg, nodeArgs); + } catch(e) { + reject(e); + } + }); + }); + }; + }; + }); +define("rsvp/promise", + ["./config","./events","./instrument","./utils","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __exports__) { + "use strict"; + var config = __dependency1__.config; + var EventTarget = __dependency2__["default"]; + var instrument = __dependency3__["default"]; + var objectOrFunction = __dependency4__.objectOrFunction; + var isFunction = __dependency4__.isFunction; + var now = __dependency4__.now; + var cast = __dependency5__["default"]; + var all = __dependency6__["default"]; + var race = __dependency7__["default"]; + var Resolve = __dependency8__["default"]; + var Reject = __dependency9__["default"]; + + var guidKey = 'rsvp_' + now() + '-'; + var counter = 0; + + function noop() {} + + __exports__["default"] = Promise; + + + /** + + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]"); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} + @param {String} label optional string for labeling the promise. + Useful for tooling. + @constructor + */ + function Promise(resolver, label) { + if (!isFunction(resolver)) { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + if (!(this instanceof Promise)) { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + this._id = counter++; + this._label = label; + this._subscribers = []; + + if (config.instrument) { + instrument('created', this); + } + + if (noop !== resolver) { + invokeResolver(resolver, this); + } + } + + function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } + + function rejectPromise(reason) { + reject(promise, reason); + } + + try { + resolver(resolvePromise, rejectPromise); + } catch(e) { + rejectPromise(e); + } + } + + Promise.cast = cast; + Promise.all = all; + Promise.race = race; + Promise.resolve = Resolve; + Promise.reject = Reject; + + var PENDING = void 0; + var SEALED = 0; + var FULFILLED = 1; + var REJECTED = 2; + + function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + } + + function publish(promise, settled) { + var child, callback, subscribers = promise._subscribers, detail = promise._detail; + + if (config.instrument) { + instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); + } + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + invokeCallback(settled, child, callback, detail); + } + + promise._subscribers = null; + } + + Promise.prototype = { + /** + @property constructor + */ + constructor: Promise, + + _id: undefined, + _guidKey: guidKey, + _label: undefined, + + _state: undefined, + _detail: undefined, + _subscribers: undefined, + + _onerror: function (reason) { + config.trigger('error', reason); + }, + + /** + + A promise represents the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, "downstream" + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return "default name"; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `"default name"` + }); + + findUser().then(function (user) { + throw "Found user, but still unhappy"; + }, function (reason) { + throw "`findUser` rejected and we're unhappy"; + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be "Found user, but still unhappy". + // If `findUser` rejected, `reason` will be "`findUser` rejected and we're unhappy". + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException("Upstream error"); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javacsript + findResult().then(function(result){ + + }, function(reason){ + + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javacsript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong; + }); + ``` + + @method then + @param {Function} onFulfillment + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection, label) { + var promise = this; + this._onerror = null; + + var thenPromise = new this.constructor(noop, label); + + if (this._state) { + var callbacks = arguments; + config.async(function invokePromiseCallback() { + invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); + }); + } else { + subscribe(this, thenPromise, onFulfillment, onRejection); + } + + if (config.instrument) { + instrument('chained', promise, thenPromise); + } + + return thenPromise; + }, + + /** + `catch` is simply sugar for `then(null, onRejection)` which makes it the same + as the catch block, of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error("couldn't find that author"); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong; + }); + ``` + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection, label) { + return this.then(null, onRejection, label); + }, + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't effect the return value + } + + findAuthor().finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'finally': function(callback, label) { + var constructor = this.constructor; + + return this.then(function(value) { + return constructor.cast(callback()).then(function(){ + return value; + }); + }, function(reason) { + return constructor.cast(callback()).then(function(){ + throw reason; + }); + }, label); + } + }; + + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + try { + value = callback(detail); + succeeded = true; + } catch(e) { + failed = true; + error = e; + } + } else { + value = detail; + succeeded = true; + } + + if (handleThenable(promise, value)) { + return; + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + resolve(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } + } + + function handleThenable(promise, value) { + var then = null, + resolved; + + try { + if (promise === value) { + throw new TypeError("A promises callback cannot return that same promise."); + } + + if (objectOrFunction(value)) { + then = value.then; + + if (isFunction(then)) { + then.call(value, function(val) { + if (resolved) { return true; } + resolved = true; + + if (value !== val) { + resolve(promise, val); + } else { + fulfill(promise, val); + } + }, function(val) { + if (resolved) { return true; } + resolved = true; + + reject(promise, val); + }, 'derived from: ' + (promise._label || ' unknown promise')); + + return true; + } + } + } catch (error) { + if (resolved) { return true; } + reject(promise, error); + return true; + } + + return false; + } + + function resolve(promise, value) { + if (promise === value) { + fulfill(promise, value); + } else if (!handleThenable(promise, value)) { + fulfill(promise, value); + } + } + + function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + promise._state = SEALED; + promise._detail = value; + + config.async(publishFulfillment, promise); + } + + function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = SEALED; + promise._detail = reason; + + config.async(publishRejection, promise); + } + + function publishFulfillment(promise) { + publish(promise, promise._state = FULFILLED); + } + + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._detail); + } + + publish(promise, promise._state = REJECTED); + } + }); +define("rsvp/promise/all", + ["../utils","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var isArray = __dependency1__.isArray; + var isNonThenable = __dependency1__.isNonThenable; + + /** + + `RSVP.Promise.all` returns a new promise which is fulfilled with an array of + fulfillment values for the passed promises, or rejects with the reason of the + first passed promise that rejects. It casts all elements of the passed iterable + to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.resolve(2); + var promise3 = RSVP.resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `RSVP.all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @for RSVP.Promise + @param {Array} promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + */ + __exports__["default"] = function all(entries, label) { + + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function(resolve, reject) { + if (!isArray(entries)) { + throw new TypeError('You must pass an array to all.'); + } + + var remaining = entries.length; + var results = new Array(remaining); + var entry, pending = true; + + if (remaining === 0) { + resolve(results); + return; + } + + function fulfillmentAt(index) { + return function(value) { + results[index] = value; + if (--remaining === 0) { + resolve(results); + } + }; + } + + function onRejection(reason) { + remaining = 0; + reject(reason); + } + + for (var index = 0; index < entries.length; index++) { + entry = entries[index]; + if (isNonThenable(entry)) { + results[index] = entry; + if (--remaining === 0) { + resolve(results); + } + } else { + Constructor.cast(entry).then(fulfillmentAt(index), onRejection); + } + } + }, label); + }; + }); +define("rsvp/promise/cast", + ["exports"], + function(__exports__) { + "use strict"; + /** + + `RSVP.Promise.cast` cast coerces its argument to a promise, or returns the + argument if it is already a promise which shares a constructor with the caster; + + Example: + + ```javascript + var promise = RSVP.Promise.resolve(1); + var casted = RSVP.Promise.cast(promise); + + console.log(promise === casted); // true + ``` + + In the case of a promise whose constructor does not match, it is assimilated. + The resulting promise will fulfill or reject based on the outcome of the + promise being casted. + + In the case of a non-promise, a promise which will fulfill with that value is + returned. + + Example: + + ```javascript + var value = 1; // could be a number, boolean, string, undefined... + var casted = RSVP.Promise.cast(value); + + console.log(value === casted); // false + console.log(casted instanceof RSVP.Promise) // true + + casted.then(function(val) { + val === value // => true + }); + ``` + + `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the + following ways: + + * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you + have something that could either be a promise or a value. RSVP.resolve + will have the same effect but will create a new promise wrapper if the + argument is a promise. + * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to + promises of the exact class specified, so that the resulting object's `then` is + ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). + + @method cast + @for RSVP.Promise + @param {Object} object to be casted + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise + */ + + __exports__["default"] = function cast(object, label) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + return new Constructor(function(resolve) { + resolve(object); + }, label); + }; + }); +define("rsvp/promise/race", + ["../utils","exports"], + function(__dependency1__, __exports__) { + "use strict"; + /* global toString */ + + var isArray = __dependency1__.isArray; + var isFunction = __dependency1__.isFunction; + var isNonThenable = __dependency1__.isNonThenable; + + /** + `RSVP.Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 1"); + }, 200); + }); + + var promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 2"); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // result === "promise 2" because it was resolved before promise1 + // was resolved. + }); + ``` + + `RSVP.Promise.race` is deterministic in that only the state of the first + completed promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first completed promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 1"); + }, 200); + }); + + var promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error("promise 2")); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs because there are rejected promises! + }, function(reason){ + // reason.message === "promise2" because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + @method race + @for RSVP.Promise + @param {Array} promises array of promises to observe + @param {String} label optional string for describing the promise returned. + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. + */ + __exports__["default"] = function race(entries, label) { + /*jshint validthis:true */ + var Constructor = this, entry; + + return new Constructor(function(resolve, reject) { + if (!isArray(entries)) { + throw new TypeError('You must pass an array to race.'); + } + + var pending = true; + + function onFulfillment(value) { if (pending) { pending = false; resolve(value); } } + function onRejection(reason) { if (pending) { pending = false; reject(reason); } } + + for (var i = 0; i < entries.length; i++) { + entry = entries[i]; + if (isNonThenable(entry)) { + pending = false; + resolve(entry); + return; + } else { + Constructor.cast(entry).then(onFulfillment, onRejection); + } + } + }, label); + }; + }); +define("rsvp/promise/reject", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + It is essentially shorthand for the following: + + ```javascript + var promise = new RSVP.Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = RSVP.Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @for RSVP.Promise + @param {Any} reason value that the returned promise will be rejected with. + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. + */ + __exports__["default"] = function reject(reason, label) { + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function (resolve, reject) { + reject(reason); + }, label); + }; + }); +define("rsvp/promise/resolve", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.Promise.resolve` returns a promise that will become fulfilled with the passed + `value`. It is essentially shorthand for the following: + + ```javascript + var promise = new RSVP.Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = RSVP.Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @for RSVP.Promise + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + __exports__["default"] = function resolve(value, label) { + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function(resolve, reject) { + resolve(value); + }, label); + }; + }); +define("rsvp/race", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function race(array, label) { + return Promise.race(array, label); + }; + }); +define("rsvp/reject", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function reject(reason, label) { + return Promise.reject(reason, label); + }; + }); +define("rsvp/resolve", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function resolve(value, label) { + return Promise.resolve(value, label); + }; + }); +define("rsvp/rethrow", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event + loop in order to aid debugging. + + Promises A+ specifies that any exceptions that occur with a promise must be + caught by the promises implementation and bubbled to the last handler. For + this reason, it is recommended that you always specify a second rejection + handler function to `then`. However, `RSVP.rethrow` will throw the exception + outside of the promise, so it bubbles up to your console if in the browser, + or domain/cause uncaught exception in Node. `rethrow` will throw the error + again so the error can be handled by the promise. + + ```javascript + function throws(){ + throw new Error('Whoops!'); + } + + var promise = new RSVP.Promise(function(resolve, reject){ + throws(); + }); + + promise.catch(RSVP.rethrow).then(function(){ + // Code here doesn't run because the promise became rejected due to an + // error! + }, function (err){ + // handle the error here + }); + ``` + + The 'Whoops' error will be thrown on the next turn of the event loop + and you can watch for it in your console. You can also handle it using a + rejection handler given to `.then` or `.catch` on the returned promise. + + @method rethrow + @for RSVP + @param {Error} reason reason the promise became rejected. + @throws Error + */ + __exports__["default"] = function rethrow(reason) { + setTimeout(function() { + throw reason; + }); + throw reason; + }; + }); +define("rsvp/utils", + ["exports"], + function(__exports__) { + "use strict"; + function objectOrFunction(x) { + return typeof x === "function" || (typeof x === "object" && x !== null); + } + + __exports__.objectOrFunction = objectOrFunction;function isFunction(x) { + return typeof x === "function"; + } + + __exports__.isFunction = isFunction;function isNonThenable(x) { + return !objectOrFunction(x); + } + + __exports__.isNonThenable = isNonThenable;function isArray(x) { + return Object.prototype.toString.call(x) === "[object Array]"; + } + + __exports__.isArray = isArray;// Date.now is not available in browsers < IE9 + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility + var now = Date.now || function() { return new Date().getTime(); }; + __exports__.now = now; + var keysOf = Object.keys || function(object) { + var result = []; + + for (var prop in object) { + result.push(prop); + } + + return result; + }; + __exports__.keysOf = keysOf; + }); +define("rsvp", + ["./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all_settled","./rsvp/race","./rsvp/hash","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/asap","./rsvp/filter","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var EventTarget = __dependency2__["default"]; + var denodeify = __dependency3__["default"]; + var all = __dependency4__["default"]; + var allSettled = __dependency5__["default"]; + var race = __dependency6__["default"]; + var hash = __dependency7__["default"]; + var rethrow = __dependency8__["default"]; + var defer = __dependency9__["default"]; + var config = __dependency10__.config; + var configure = __dependency10__.configure; + var map = __dependency11__["default"]; + var resolve = __dependency12__["default"]; + var reject = __dependency13__["default"]; + var asap = __dependency14__["default"]; + var filter = __dependency15__["default"]; + + config.async = asap; // default async is asap; + + function async(callback, arg) { + config.async(callback, arg); + } + + function on() { + config.on.apply(config, arguments); + } + + function off() { + config.off.apply(config, arguments); + } + + // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` + if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') { + var callbacks = window.__PROMISE_INSTRUMENTATION__; + configure('instrument', true); + for (var eventName in callbacks) { + if (callbacks.hasOwnProperty(eventName)) { + on(eventName, callbacks[eventName]); + } + } + } + + __exports__.Promise = Promise; + __exports__.EventTarget = EventTarget; + __exports__.all = all; + __exports__.allSettled = allSettled; + __exports__.race = race; + __exports__.hash = hash; + __exports__.rethrow = rethrow; + __exports__.defer = defer; + __exports__.denodeify = denodeify; + __exports__.configure = configure; + __exports__.on = on; + __exports__.off = off; + __exports__.resolve = resolve; + __exports__.reject = reject; + __exports__.async = async; + __exports__.map = map; + __exports__.filter = filter; + }); +global.RSVP = requireModule('rsvp'); +}(window)); +'use strict'; + +var EPUBJS = EPUBJS || {}; +EPUBJS.VERSION = "0.2.3"; + +EPUBJS.plugins = EPUBJS.plugins || {}; + +EPUBJS.filePath = EPUBJS.filePath || "/epubjs/"; + +EPUBJS.Render = {}; + +(function(root) { + + var previousEpub = root.ePub || {}; + + var ePub = root.ePub = function() { + var bookPath, options; + + //-- var book = ePub("path/to/book.epub", { restore: true }) + if(typeof(arguments[0]) != 'undefined' && + typeof arguments[0] === 'string') { + + bookPath = arguments[0]; + + if( arguments[1] && typeof arguments[1] === 'object' ) { + options = arguments[1]; + options.bookPath = bookPath; + } else { + options = { 'bookPath' : bookPath }; + } + + } + + /* + * var book = ePub({ bookPath: "path/to/book.epub", restore: true }); + * + * - OR - + * + * var book = ePub({ restore: true }); + * book.open("path/to/book.epub"); + */ + + if( arguments[0] && typeof arguments[0] === 'object' ) { + options = arguments[0]; + } + + + return new EPUBJS.Book(options); + }; + + _.extend(ePub, { + noConflict : function() { + root.ePub = previousEpub; + return this; + } + }); + + //exports to multiple environments + if (typeof define === 'function' && define.amd) + //AMD + define(function(){ return ePub; }); + else if (typeof module != "undefined" && module.exports) + //Node + module.exports = ePub; + +})(window); + +EPUBJS.Book = function(options){ + + var book = this; + + this.settings = _.defaults(options || {}, { + bookPath : null, + bookKey : null, + packageUrl : null, + storage: false, //-- true (auto) or false (none) | override: 'ram', 'websqldatabase', 'indexeddb', 'filesystem' + fromStorage : false, + saved : false, + online : true, + contained : false, + width : null, + height: null, + layoutOveride : null, // Default: { spread: 'reflowable', layout: 'auto', orientation: 'auto'} + orientation : null, + minSpreadWidth: 800, //-- overridden by spread: none (never) / both (always) + gap: "auto", //-- "auto" or int + version: 1, + restore: false, + reload : false, + goto : false, + styles : {}, + headTags : {}, + withCredentials: false, + render_method: "Iframe" + }); + + this.settings.EPUBJSVERSION = EPUBJS.VERSION; + + this.spinePos = 0; + this.stored = false; + + //-- All Book events for listening + /* + book:ready + book:stored + book:online + book:offline + book:pageChanged + book:loadFailed + book:loadChapterFailed + */ + + //-- Adds Hook methods to the Book prototype + // Hooks will all return before triggering the callback. + // EPUBJS.Hooks.mixin(this); + //-- Get pre-registered hooks for events + // this.getHooks("beforeChapterDisplay"); + + this.online = this.settings.online || navigator.onLine; + this.networkListeners(); + + this.store = false; //-- False if not using storage; + + //-- Determine storage method + //-- Override options: none | ram | websqldatabase | indexeddb | filesystem + + if(this.settings.storage !== false){ + this.storage = new fileStorage.storage(this.settings.storage); + } + + this.ready = { + manifest: new RSVP.defer(), + spine: new RSVP.defer(), + metadata: new RSVP.defer(), + cover: new RSVP.defer(), + toc: new RSVP.defer(), + pageList: new RSVP.defer() + }; + + this.readyPromises = [ + this.ready.manifest.promise, + this.ready.spine.promise, + this.ready.metadata.promise, + this.ready.cover.promise, + this.ready.toc.promise + ]; + + this.pageList = []; + this.pagination = new EPUBJS.Pagination(); + this.pageListReady = this.ready.pageList.promise; + + this.ready.all = RSVP.all(this.readyPromises); + + this.ready.all.then(this._ready.bind(this)); + + // Queue for methods used before rendering + this.isRendered = false; + this._q = EPUBJS.core.queue(this); + // Queue for rendering + this._rendering = false; + this._displayQ = EPUBJS.core.queue(this); + // Queue for going to another location + this._moving = false; + this._gotoQ = EPUBJS.core.queue(this); + + /** + * Creates a new renderer. + * The renderer will handle displaying the content using the method provided in the settings + */ + this.renderer = new EPUBJS.Renderer(this.settings.render_method); + //-- Set the width at which to switch from spreads to single pages + this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + this.renderer.setGap(this.settings.gap); + //-- Pass through the renderer events + this.listenToRenderer(this.renderer); + + this.defer_opened = new RSVP.defer(); + this.opened = this.defer_opened.promise; + // BookUrl is optional, but if present start loading process + if(typeof this.settings.bookPath === 'string') { + this.open(this.settings.bookPath, this.settings.reload); + } + + window.addEventListener("beforeunload", this.unload.bind(this), false); + + //-- Listen for these promises: + //-- book.opened.then() + //-- book.rendered.then() +}; + +//-- Check bookUrl and start parsing book Assets or load them from storage +EPUBJS.Book.prototype.open = function(bookPath, forceReload){ + var book = this, + epubpackage, + opened = new RSVP.defer(); + + this.settings.bookPath = bookPath; + + //-- Get a absolute URL from the book path + this.bookUrl = this.urlFrom(bookPath); + + if(this.settings.contained || this.isContained(bookPath)){ + + this.settings.contained = this.contained = true; + + this.bookUrl = ''; + + epubpackage = this.unarchive(bookPath). + then(function(){ + return book.loadPackage(); + }); + + } else { + epubpackage = this.loadPackage(); + } + + if(this.settings.restore && !forceReload && localStorage){ + //-- Will load previous package json, or re-unpack if error + epubpackage.then(function(packageXml) { + var identifier = book.packageIdentifier(packageXml); + var restored = book.restore(identifier); + + if(!restored) { + book.unpack(packageXml); + } + opened.resolve(); + book.defer_opened.resolve(); + }); + + }else{ + + //-- Get package information from epub opf + epubpackage.then(function(packageXml) { + book.unpack(packageXml); + opened.resolve(); + book.defer_opened.resolve(); + }); + } + + //-- If there is network connection, store the books contents + if(this.online && this.settings.storage && !this.settings.contained){ + if(!this.settings.stored) opened.then(book.storeOffline()); + } + + this._registerReplacements(this.renderer); + + return opened.promise; + +}; + +EPUBJS.Book.prototype.loadPackage = function(_containerPath){ + var book = this, + parse = new EPUBJS.Parser(), + containerPath = _containerPath || "META-INF/container.xml", + containerXml, + packageXml; + + if(!this.settings.packageUrl) { //-- provide the packageUrl to skip this step + packageXml = book.loadXml(book.bookUrl + containerPath). + then(function(containerXml){ + return parse.container(containerXml); // Container has path to content + }). + then(function(paths){ + book.settings.contentsPath = book.bookUrl + paths.basePath; + book.settings.packageUrl = book.bookUrl + paths.packagePath; + book.settings.encoding = paths.encoding; + return book.loadXml(book.settings.packageUrl); // Containes manifest, spine and metadata + }); + } else { + packageXml = book.loadXml(book.settings.packageUrl); + } + + packageXml.catch(function(error) { + // handle errors in either of the two requests + console.error("Could not load book at: "+ containerPath); + book.trigger("book:loadFailed", containerPath); + }); + return packageXml; +}; + +EPUBJS.Book.prototype.packageIdentifier = function(packageXml){ + var book = this, + parse = new EPUBJS.Parser(); + + return parse.identifier(packageXml); +}; + +EPUBJS.Book.prototype.unpack = function(packageXml){ + var book = this, + parse = new EPUBJS.Parser(); + + book.contents = parse.packageContents(packageXml, book.settings.contentsPath); // Extract info from contents + + book.manifest = book.contents.manifest; + book.spine = book.contents.spine; + book.spineIndexByURL = book.contents.spineIndexByURL; + book.metadata = book.contents.metadata; + if(!book.settings.bookKey) { + book.settings.bookKey = book.generateBookKey(book.metadata.identifier); + } + + //-- Set Globbal Layout setting based on metadata + book.globalLayoutProperties = book.parseLayoutProperties(book.metadata); + + if(book.contents.coverPath) { + book.cover = book.contents.cover = book.settings.contentsPath + book.contents.coverPath; + } + + book.spineNodeIndex = book.contents.spineNodeIndex; + + book.ready.manifest.resolve(book.contents.manifest); + book.ready.spine.resolve(book.contents.spine); + book.ready.metadata.resolve(book.contents.metadata); + book.ready.cover.resolve(book.contents.cover); + + + //-- Load the TOC, optional; either the EPUB3 XHTML Navigation file or the EPUB2 NCX file + if(book.contents.navPath) { + book.settings.navUrl = book.settings.contentsPath + book.contents.navPath; + + book.loadXml(book.settings.navUrl). + then(function(navHtml){ + return parse.nav(navHtml, book.spineIndexByURL, book.spine); // Grab Table of Contents + }).then(function(toc){ + book.toc = book.contents.toc = toc; + book.ready.toc.resolve(book.contents.toc); + }, function(error) { + book.ready.toc.resolve(false); + }); + + // Load the optional pageList + book.loadXml(book.settings.navUrl). + then(function(navHtml){ + return parse.pageList(navHtml, book.spineIndexByURL, book.spine); + }).then(function(pageList){ + var epubcfi = new EPUBJS.EpubCFI(); + var wait = 0; // need to generate a cfi + + // No pageList found + if(pageList.length === 0) { + return; + } + + book.pageList = book.contents.pageList = pageList; + + // Replace HREFs with CFI + book.pageList.forEach(function(pg){ + if(!pg.cfi) { + wait += 1; + epubcfi.generateCfiFromHref(pg.href, book).then(function(cfi){ + pg.cfi = cfi; + pg.packageUrl = book.settings.packageUrl; + + wait -= 1; + if(wait === 0) { + book.pagination.process(book.pageList); + book.ready.pageList.resolve(book.pageList); + } + }); + } + }); + + if(!wait) { + book.pagination.process(book.pageList); + book.ready.pageList.resolve(book.pageList); + } + + }, function(error) { + book.ready.pageList.resolve([]); + }); + } else if(book.contents.tocPath) { + book.settings.tocUrl = book.settings.contentsPath + book.contents.tocPath; + + book.loadXml(book.settings.tocUrl). + then(function(tocXml){ + return parse.toc(tocXml, book.spineIndexByURL, book.spine); // Grab Table of Contents + }).then(function(toc){ + book.toc = book.contents.toc = toc; + book.ready.toc.resolve(book.contents.toc); + }, function(error) { + book.ready.toc.resolve(false); + }); + + } else { + book.ready.toc.resolve(false); + } + +}; + +EPUBJS.Book.prototype.createHiddenRender = function(renderer, _width, _height) { + var box = this.element.getBoundingClientRect(); + var width = _width || this.settings.width || box.width; + var height = _height || this.settings.height || box.height; + var hiddenContainer; + var hiddenEl; + renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + renderer.setGap(this.settings.gap); + + this._registerReplacements(renderer); + if(this.settings.forceSingle) { + renderer.forceSingle(true); + } + + hiddenContainer = document.createElement("div"); + hiddenContainer.style.visibility = "hidden"; + hiddenContainer.style.overflow = "hidden"; + hiddenContainer.style.width = "0"; + hiddenContainer.style.height = "0"; + this.element.appendChild(hiddenContainer); + + hiddenEl = document.createElement("div"); + hiddenEl.style.visibility = "hidden"; + hiddenEl.style.overflow = "hidden"; + hiddenEl.style.width = width + "px";//"0"; + hiddenEl.style.height = height +"px"; //"0"; + hiddenContainer.appendChild(hiddenEl); + + renderer.initialize(hiddenEl); + return hiddenContainer; +}; + +// Generates the pageList array by loading every chapter and paging through them +EPUBJS.Book.prototype.generatePageList = function(width, height){ + var pageList = []; + var pager = new EPUBJS.Renderer(this.settings.render_method, false); //hidden + var hiddenContainer = this.createHiddenRender(pager, width, height); + var deferred = new RSVP.defer(); + var spinePos = -1; + var spineLength = this.spine.length; + var totalPages = 0; + var currentPage = 0; + var nextChapter = function(deferred){ + var chapter; + var next = spinePos + 1; + var done = deferred || new RSVP.defer(); + var loaded; + if(next >= spineLength) { + done.resolve(); + } else { + spinePos = next; + chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); + pager.displayChapter(chapter, this.globalLayoutProperties).then(function(chap){ + pager.pageMap.forEach(function(item){ + currentPage += 1; + pageList.push({ + "cfi" : item.start, + "page" : currentPage + }); + + }); + + if(pager.pageMap.length % 2 > 0 && + pager.spreads) { + currentPage += 1; // Handle Spreads + pageList.push({ + "cfi" : pager.pageMap[pager.pageMap.length - 1].end, + "page" : currentPage + }); + } + + // Load up the next chapter + setTimeout(function(){ + nextChapter(done); + }, 1); + }); + } + return done.promise; + }.bind(this); + + var finished = nextChapter().then(function(){ + pager.remove(); + this.element.removeChild(hiddenContainer); + deferred.resolve(pageList); + }.bind(this)); + + return deferred.promise; +}; + +// Render out entire book and generate the pagination +// Width and Height are optional and will default to the current dimensions +EPUBJS.Book.prototype.generatePagination = function(width, height) { + var book = this; + var defered = new RSVP.defer(); + + this.ready.spine.promise.then(function(){ + book.generatePageList(width, height).then(function(pageList){ + book.pageList = book.contents.pageList = pageList; + book.pagination.process(pageList); + book.ready.pageList.resolve(book.pageList); + defered.resolve(book.pageList); + }); + }); + + return defered.promise; +}; + +// Process the pagination from a JSON array containing the pagelist +EPUBJS.Book.prototype.loadPagination = function(pagelistJSON) { + var pageList = JSON.parse(pagelistJSON); + + if(pageList && pageList.length) { + this.pageList = pageList; + this.pagination.process(this.pageList); + this.ready.pageList.resolve(this.pageList); + } + return this.pageList; +}; + +EPUBJS.Book.prototype.getPageList = function() { + return this.ready.pageList.promise; +}; + +EPUBJS.Book.prototype.getMetadata = function() { + return this.ready.metadata.promise; +}; + +EPUBJS.Book.prototype.getToc = function() { + return this.ready.toc.promise; +}; + +/* Private Helpers */ + +//-- Listeners for browser events +EPUBJS.Book.prototype.networkListeners = function(){ + var book = this; + + window.addEventListener("offline", function(e) { + book.online = false; + book.trigger("book:offline"); + }, false); + + window.addEventListener("online", function(e) { + book.online = true; + book.trigger("book:online"); + }, false); + +}; + +// Listen to all events the renderer triggers and pass them as book events +EPUBJS.Book.prototype.listenToRenderer = function(renderer){ + var book = this; + renderer.Events.forEach(function(eventName){ + renderer.on(eventName, function(e){ + book.trigger(eventName, e); + }); + }); + + renderer.on("renderer:visibleRangeChanged", function(range) { + var startPage, endPage, percent; + var pageRange = []; + + if(this.pageList.length > 0) { + startPage = this.pagination.pageFromCfi(range.start); + percent = this.pagination.percentageFromPage(startPage); + pageRange.push(startPage); + + if(range.end) { + endPage = this.pagination.pageFromCfi(range.end); + //if(startPage != endPage) { + pageRange.push(endPage); + //} + } + this.trigger("book:pageChanged", { + "anchorPage": startPage, + "percentage": percent, + "pageRange" : pageRange + }); + + // TODO: Add event for first and last page. + // (though last is going to be hard, since it could be several reflowed pages long) + } + }.bind(this)); + + renderer.on("render:loaded", this.loadChange.bind(this)); +}; + +// Listens for load events from the Renderer and checks against the current chapter +// Prevents the Render from loading a different chapter when back button is pressed +EPUBJS.Book.prototype.loadChange = function(url){ + var uri = EPUBJS.core.uri(url); + var chapter; + + if(this.currentChapter) { + chapter = EPUBJS.core.uri(this.currentChapter.absolute); + } + + if(!this._rendering && this.currentChapter && uri.path != chapter.path){ + console.warn("Miss Match", uri.path, this.currentChapter.absolute); + this.goto(uri.filename); + } +}; + +EPUBJS.Book.prototype.unlistenToRenderer = function(renderer){ + renderer.Events.forEach(function(eventName){ + renderer.off(eventName); + } ); +}; + +//-- Choose between a request from store or a request from network +EPUBJS.Book.prototype.loadXml = function(url){ + if(this.settings.fromStorage) { + return this.storage.getXml(url, this.settings.encoding); + } else if(this.settings.contained) { + return this.zip.getXml(url, this.settings.encoding); + }else{ + return EPUBJS.core.request(url, 'xml', this.settings.withCredentials); + } +}; + +//-- Turns a url into a absolute url +EPUBJS.Book.prototype.urlFrom = function(bookPath){ + var uri = EPUBJS.core.uri(bookPath), + absolute = uri.protocol, + fromRoot = uri.path[0] == "/", + location = window.location, + //-- Get URL orgin, try for native or combine + origin = location.origin || location.protocol + "//" + location.host, + baseTag = document.getElementsByTagName('base'), + base; + + + //-- Check is Base tag is set + + if(baseTag.length) { + base = baseTag[0].href; + } + + //-- 1. Check if url is absolute + if(uri.protocol){ + return uri.origin + uri.path; + } + + //-- 2. Check if url starts with /, add base url + if(!absolute && fromRoot){ + return (base || origin) + uri.path; + } + + //-- 3. Or find full path to url and add that + if(!absolute && !fromRoot){ + return EPUBJS.core.resolveUrl(base || location.pathname, uri.path); + } + +}; + + +EPUBJS.Book.prototype.unarchive = function(bookPath){ + var book = this, + unarchived; + + //-- Must use storage + // if(this.settings.storage == false ){ + // this.settings.storage = true; + // this.storage = new fileStorage.storage(); + // } + + this.zip = new EPUBJS.Unarchiver(); + this.store = this.zip; // Use zip storaged in ram + return this.zip.openZip(bookPath); +}; + +//-- Checks if url has a .epub or .zip extension +EPUBJS.Book.prototype.isContained = function(bookUrl){ + var uri = EPUBJS.core.uri(bookUrl); + + if(uri.extension && (uri.extension == "epub" || uri.extension == "zip")){ + return true; + } + + return false; +}; + +//-- Checks if the book can be retrieved from localStorage +EPUBJS.Book.prototype.isSaved = function(bookKey) { + var storedSettings; + + if(!localStorage) { + return false; + } + + storedSettings = localStorage.getItem(bookKey); + + if( !localStorage || + storedSettings === null) { + return false; + } else { + return true; + } +}; + +// Generates the Book Key using the identifer in the manifest or other string provided +EPUBJS.Book.prototype.generateBookKey = function(identifier){ + return "epubjs:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; +}; + +EPUBJS.Book.prototype.saveContents = function(){ + if(!localStorage) { + return false; + } + localStorage.setItem(this.settings.bookKey, JSON.stringify(this.contents)); +}; + +EPUBJS.Book.prototype.removeSavedContents = function() { + if(!localStorage) { + return false; + } + localStorage.removeItem(this.settings.bookKey); +}; + + + +//-- Takes a string or a element +EPUBJS.Book.prototype.renderTo = function(elem){ + var book = this, + rendered; + + if(_.isElement(elem)) { + this.element = elem; + } else if (typeof elem == "string") { + this.element = EPUBJS.core.getEl(elem); + } else { + console.error("Not an Element"); + return; + } + + rendered = this.opened. + then(function(){ + // book.render = new EPUBJS.Renderer[this.settings.renderer](book); + book.renderer.initialize(book.element, book.settings.width, book.settings.height); + book._rendered(); + return book.startDisplay(); + }); + + // rendered.then(null, function(error) { console.error(error); }); + + return rendered; +}; + +EPUBJS.Book.prototype.startDisplay = function(){ + var display; + + if(this.settings.goto) { + display = this.goto(this.settings.goto); + }else if(this.settings.previousLocationCfi) { + display = this.gotoCfi(this.settings.previousLocationCfi); + }else{ + display = this.displayChapter(this.spinePos); + } + + return display; +}; + +EPUBJS.Book.prototype.restore = function(identifier){ + + var book = this, + fetch = ['manifest', 'spine', 'metadata', 'cover', 'toc', 'spineNodeIndex', 'spineIndexByURL', 'globalLayoutProperties'], + reject = false, + bookKey = this.generateBookKey(identifier), + fromStore = localStorage.getItem(bookKey), + len = fetch.length, + i; + + if(this.settings.clearSaved) reject = true; + + if(!reject && fromStore != 'undefined' && fromStore !== null){ + book.contents = JSON.parse(fromStore); + + for(i = 0; i < len; i++) { + var item = fetch[i]; + + if(!book.contents[item]) { + reject = true; + break; + } + book[item] = book.contents[item]; + } + } + + if(reject || !fromStore || !this.contents || !this.settings.contentsPath){ + return false; + }else{ + this.settings.bookKey = bookKey; + this.ready.manifest.resolve(this.manifest); + this.ready.spine.resolve(this.spine); + this.ready.metadata.resolve(this.metadata); + this.ready.cover.resolve(this.cover); + this.ready.toc.resolve(this.toc); + return true; + } + +}; + +EPUBJS.Book.prototype.displayChapter = function(chap, end, deferred){ + var book = this, + render, + cfi, + pos, + store, + defer = deferred || new RSVP.defer(); + + var chapter; + + if(!this.isRendered) { + this._q.enqueue("displayChapter", arguments); + // Reject for now. TODO: pass promise to queue + defer.reject({ + message : "Rendering", + stack : new Error().stack + }); + return defer.promise; + } + + + if(this._rendering || this._rendering) { + // Pass along the current defer + this._displayQ.enqueue("displayChapter", [chap, end, defer]); + return defer.promise; + } + + if(_.isNumber(chap)){ + pos = chap; + }else{ + cfi = new EPUBJS.EpubCFI(chap); + pos = cfi.spinePos; + } + + if(pos < 0 || pos >= this.spine.length){ + console.warn("Not A Valid Location"); + pos = 0; + end = false; + cfi = false; + } + + //-- Create a new chapter + chapter = new EPUBJS.Chapter(this.spine[pos], this.store); + + this._rendering = true; + + render = book.renderer.displayChapter(chapter, this.globalLayoutProperties); + if(cfi) { + book.renderer.gotoCfi(cfi); + } else if(end) { + book.renderer.lastPage(); + } + //-- Success, Clear render queue + render.then(function(rendered){ + // var inwait; + //-- Set the book's spine position + book.spinePos = pos; + + defer.resolve(book.renderer); + + if(!book.settings.fromStorage && + !book.settings.contained) { + book.preloadNextChapter(); + } + + book.currentChapter = chapter; + book._rendering = false; + book._displayQ.dequeue(); + if(book._displayQ.length() === 0) { + book._gotoQ.dequeue(); + } + + }, function(error) { + // handle errors in either of the two requests + console.error("Could not load Chapter: "+ chapter.absolute); + book.trigger("book:chapterLoadFailed", chapter.absolute); + book._rendering = false; + defer.reject(error); + }); + + return defer.promise; +}; + +EPUBJS.Book.prototype.nextPage = function(){ + var next; + + if(!this.isRendered) return this._q.enqueue("nextPage", arguments); + + next = this.renderer.nextPage(); + + if(!next){ + return this.nextChapter(); + } +}; + +EPUBJS.Book.prototype.prevPage = function() { + var prev; + + if(!this.isRendered) return this._q.enqueue("prevPage", arguments); + + prev = this.renderer.prevPage(); + + if(!prev){ + return this.prevChapter(); + } +}; + +EPUBJS.Book.prototype.nextChapter = function() { + var next; + if (this.spinePos < this.spine.length - 1) { + next = this.spinePos + 1; + // Skip non linear chapters + while (this.spine[next] && this.spine[next].linear && this.spine[next].linear == 'no') { + next++; + } + if (next < this.spine.length) { + return this.displayChapter(next); + } else { + this.trigger("book:atEnd"); + } + + } else { + this.trigger("book:atEnd"); + } +}; + +EPUBJS.Book.prototype.prevChapter = function() { + var prev; + if (this.spinePos > 0) { + prev = this.spinePos - 1; + while (this.spine[prev] && this.spine[prev].linear && this.spine[prev].linear == 'no') { + prev--; + } + if (prev >= 0) { + return this.displayChapter(prev, true); + } else { + this.trigger("book:atStart"); + } + + } else { + this.trigger("book:atStart"); + } +}; + +EPUBJS.Book.prototype.getCurrentLocationCfi = function() { + if(!this.isRendered) return false; + return this.renderer.currentLocationCfi; +}; + +EPUBJS.Book.prototype.goto = function(target){ + + if(target.indexOf("epubcfi(") === 0) { + return this.gotoCfi(target); + } else if(target.indexOf("%") === target.length-1) { + return this.gotoPercentage(parseInt(target.substring(0, target.length-1))/100); + } else if(typeof target === "number" || isNaN(target) === false){ + return this.gotoPage(target); + } else { + return this.gotoHref(target); + } + +}; + +EPUBJS.Book.prototype.gotoCfi = function(cfiString, defer){ + var cfi, + spinePos, + spineItem, + rendered, + deferred = defer || new RSVP.defer(); + + if(!this.isRendered) { + console.warn("Not yet Rendered"); + this.settings.previousLocationCfi = cfiString; + return false; + } + + // Currently going to a chapter + if(this._moving || this._rendering) { + console.warn("Renderer is moving"); + this._gotoQ.enqueue("gotoCfi", [cfiString, deferred]); + return false; + } + + cfi = new EPUBJS.EpubCFI(cfiString); + spinePos = cfi.spinePos; + + if(spinePos == -1) { + return false; + } + + spineItem = this.spine[spinePos]; + promise = deferred.promise; + this._moving = true; + //-- If same chapter only stay on current chapter + if(this.currentChapter && this.spinePos === spinePos){ + this.renderer.gotoCfi(cfi); + this._moving = false; + deferred.resolve(this.renderer.currentLocationCfi); + } else { + + if(!spineItem || spinePos == -1) { + spinePos = 0; + spineItem = this.spine[spinePos]; + } + + this.currentChapter = new EPUBJS.Chapter(spineItem, this.store); + + if(this.currentChapter) { + this.spinePos = spinePos; + render = this.renderer.displayChapter(this.currentChapter, this.globalLayoutProperties); + + this.renderer.gotoCfi(cfi); + render.then(function(rendered){ + this._moving = false; + deferred.resolve(rendered.currentLocationCfi); + }.bind(this)); + } + } + + promise.then(function(){ + this._gotoQ.dequeue(); + }.bind(this)); + + return promise; +}; + +EPUBJS.Book.prototype.gotoHref = function(url, defer){ + var split, chapter, section, relativeURL, spinePos; + var deferred = defer || new RSVP.defer(); + + if(!this.isRendered) { + this.settings.goto = url; + return false; + } + + // Currently going to a chapter + if(this._moving || this._rendering) { + this._gotoQ.enqueue("gotoHref", [url, deferred]); + return false; + } + + split = url.split("#"); + chapter = split[0]; + section = split[1] || false; + // absoluteURL = (chapter.search("://") === -1) ? (this.settings.contentsPath + chapter) : chapter; + relativeURL = chapter.replace(this.settings.contentsPath, ''); + spinePos = this.spineIndexByURL[relativeURL]; + + //-- If link fragment only stay on current chapter + if(!chapter){ + spinePos = this.currentChapter ? this.currentChapter.spinePos : 0; + } + + //-- Check that URL is present in the index, or stop + if(typeof(spinePos) != "number") return false; + + if(!this.currentChapter || spinePos != this.currentChapter.spinePos){ + //-- Load new chapter if different than current + return this.displayChapter(spinePos).then(function(){ + if(section){ + this.renderer.section(section); + } + deferred.resolve(this.renderer.currentLocationCfi); + }.bind(this)); + }else{ + //-- Goto section + if(section) { + this.renderer.section(section); + } else { + // Or jump to the start + this.renderer.firstPage(); + } + deferred.resolve(this.renderer.currentLocationCfi); + } + + deferred.promise.then(function(){ + this._gotoQ.dequeue(); + }.bind(this)); + + return deferred.promise; +}; + +EPUBJS.Book.prototype.gotoPage = function(pg){ + var cfi = this.pagination.cfiFromPage(pg); + return this.gotoCfi(cfi); +}; + +EPUBJS.Book.prototype.gotoPercentage = function(percent){ + var pg = this.pagination.pageFromPercentage(percent); + return this.gotoPage(pg); +}; + +EPUBJS.Book.prototype.preloadNextChapter = function() { + var next; + var chap = this.spinePos + 1; + + if(chap >= this.spine.length){ + return false; + } + + next = new EPUBJS.Chapter(this.spine[chap]); + if(next) { + EPUBJS.core.request(next.absolute); + } +}; + + +EPUBJS.Book.prototype.storeOffline = function() { + var book = this, + assets = _.values(this.manifest); + + //-- Creates a queue of all items to load + return EPUBJS.storage.batch(assets). + then(function(){ + book.settings.stored = true; + book.trigger("book:stored"); + }); +}; + +EPUBJS.Book.prototype.availableOffline = function() { + return this.settings.stored > 0 ? true : false; +}; + +/* +EPUBJS.Book.prototype.fromStorage = function(stored) { + + if(this.contained) return; + + if(!stored){ + this.online = true; + this.tell("book:online"); + }else{ + if(!this.availableOffline){ + //-- If book hasn't been cached yet, store offline + this.storeOffline(function(){ + this.online = false; + this.tell("book:offline"); + }.bind(this)); + + }else{ + this.online = false; + this.tell("book:offline"); + } + } + +} +*/ + +EPUBJS.Book.prototype.setStyle = function(style, val, prefixed) { + var noreflow = ["color", "background", "background-color"]; + + if(!this.isRendered) return this._q.enqueue("setStyle", arguments); + + this.settings.styles[style] = val; + + this.renderer.setStyle(style, val, prefixed); + + if(noreflow.indexOf(style) === -1) { + // clearTimeout(this.reformatTimeout); + // this.reformatTimeout = setTimeout(function(){ + this.renderer.reformat(); + // }.bind(this), 10); + } +}; + +EPUBJS.Book.prototype.removeStyle = function(style) { + if(!this.isRendered) return this._q.enqueue("removeStyle", arguments); + this.renderer.removeStyle(style); + this.renderer.reformat(); + delete this.settings.styles[style]; +}; + +EPUBJS.Book.prototype.addHeadTag = function(tag, attrs) { + if(!this.isRendered) return this._q.enqueue("addHeadTag", arguments); + this.settings.headTags[tag] = attrs; +}; + +EPUBJS.Book.prototype.useSpreads = function(use) { + console.warn("useSpreads is deprecated, use forceSingle or set a layoutOveride instead"); + if(use === false) { + this.forceSingle(true); + } else { + this.forceSingle(false); + } +}; + +EPUBJS.Book.prototype.forceSingle = function(_use) { + var force = typeof _use === "undefined" ? true : _use; + + this.renderer.forceSingle(force); + this.settings.forceSingle = force; + if(this.isRendered) { + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.setMinSpreadWidth = function(width) { + this.settings.minSpreadWidth = width; + if(this.isRendered) { + this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.setGap = function(gap) { + this.settings.gap = gap; + if(this.isRendered) { + this.renderer.setGap(this.settings.gap); + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.chapter = function(path) { + var spinePos = this.spineIndexByURL[path]; + var spineItem; + var chapter; + + if(spinePos){ + spineItem = this.spine[spinePos]; + chapter = new EPUBJS.Chapter(spineItem, this.store); + chapter.load(); + } + return chapter; +}; + +EPUBJS.Book.prototype.unload = function(){ + + if(this.settings.restore && localStorage) { + this.saveContents(); + } + + this.unlistenToRenderer(this.renderer); + + this.trigger("book:unload"); +}; + +EPUBJS.Book.prototype.destroy = function() { + + window.removeEventListener("beforeunload", this.unload); + + if(this.currentChapter) this.currentChapter.unload(); + + this.unload(); + + if(this.render) this.render.remove(); + +}; + +EPUBJS.Book.prototype._ready = function() { + + this.trigger("book:ready"); + +}; + +EPUBJS.Book.prototype._rendered = function(err) { + var book = this; + + this.isRendered = true; + this.trigger("book:rendered"); + + this._q.flush(); +}; + + +EPUBJS.Book.prototype.applyStyles = function(renderer, callback){ + // if(!this.isRendered) return this._q.enqueue("applyStyles", arguments); + renderer.applyStyles(this.settings.styles); + callback(); +}; + +EPUBJS.Book.prototype.applyHeadTags = function(renderer, callback){ + // if(!this.isRendered) return this._q.enqueue("applyHeadTags", arguments); + renderer.applyHeadTags(this.settings.headTags); + callback(); +}; + +EPUBJS.Book.prototype._registerReplacements = function(renderer){ + renderer.registerHook("beforeChapterDisplay", this.applyStyles.bind(this, renderer), true); + renderer.registerHook("beforeChapterDisplay", this.applyHeadTags.bind(this, renderer), true); + renderer.registerHook("beforeChapterDisplay", EPUBJS.replace.hrefs.bind(this), true); + + if(this._needsAssetReplacement()) { + + renderer.registerHook("beforeChapterDisplay", [ + EPUBJS.replace.head, + EPUBJS.replace.resources, + EPUBJS.replace.svg + ], true); + + } + +}; + +EPUBJS.Book.prototype._needsAssetReplacement = function(){ + if(this.settings.fromStorage) { + + //-- Filesystem api links are relative, so no need to replace them + if(this.storage.getStorageType() == "filesystem") { + return false; + } + + return true; + + } else if(this.settings.contained) { + + return true; + + } else { + + return false; + + } +}; + + +//-- http://www.idpf.org/epub/fxl/ +EPUBJS.Book.prototype.parseLayoutProperties = function(metadata){ + var layout = (this.layoutOveride && this.layoutOveride.layout) || metadata.layout || "reflowable"; + var spread = (this.layoutOveride && this.layoutOveride.spread) || metadata.spread || "auto"; + var orientation = (this.layoutOveride && this.layoutOveride.orientation) || metadata.orientation || "auto"; + return { + layout : layout, + spread : spread, + orientation : orientation + }; +}; + +//-- Enable binding events to book +RSVP.EventTarget.mixin(EPUBJS.Book.prototype); + +//-- Handle RSVP Errors +RSVP.on('error', function(event) { + //console.error(event, event.detail); +}); + +RSVP.configure('instrument', true); //-- true | will logging out all RSVP rejections +// RSVP.on('created', listener); +// RSVP.on('chained', listener); +// RSVP.on('fulfilled', listener); +RSVP.on('rejected', function(event){ + console.error(event.detail.message, event.detail.stack); +}); + +EPUBJS.Chapter = function(spineObject, store){ + this.href = spineObject.href; + this.absolute = spineObject.url; + this.id = spineObject.id; + this.spinePos = spineObject.index; + this.cfiBase = spineObject.cfiBase; + this.properties = spineObject.properties; + this.manifestProperties = spineObject.manifestProperties; + this.linear = spineObject.linear; + this.pages = 1; + this.store = store; + this.epubcfi = new EPUBJS.EpubCFI(); + this.deferred = new RSVP.defer(); + this.loaded = this.deferred.promise; +}; + + +EPUBJS.Chapter.prototype.load = function(_store){ + var store = _store || this.store; + var promise; + // if(this.store && (!this.book.online || this.book.contained)) + if(store){ + promise = store.get(this.href); + }else{ + promise = EPUBJS.core.request(this.absolute, 'xml'); + } + + promise.then(function(xml){ + this.setDocument(xml); + this.deferred.resolve(this); + }.bind(this)); + + return promise; +}; + +EPUBJS.Chapter.prototype.render = function(_store){ + + return this.load().then(function(doc){ + + var serializer = new XMLSerializer(); + var contents; + var head = doc.head; + var base = doc.createElement("base"); + + base.setAttribute("href", window.location.origin + this.absolute); + head.insertBefore(base, head.firstChild); + contents = serializer.serializeToString(doc); + + return contents; + + }.bind(this)); +}; + +EPUBJS.Chapter.prototype.url = function(_store){ + var deferred = new RSVP.defer(); + var store = _store || this.store; + var loaded; + var chapter = this; + var url; + + if(store){ + if(!this.tempUrl) { + store.getUrl(this.absolute).then(function(url){ + chapter.tempUrl = url; + deferred.resolve(url); + }); + } else { + url = this.tempUrl; + deferred.resolve(url); + } + }else{ + url = this.absolute; + deferred.resolve(url); + } + /* + loaded = EPUBJS.core.request(url, 'xml', false); + loaded.then(function(contents){ + chapter.contents = contents; + deferred.resolve(chapter.absolute); + }, function(error){ + deferred.reject(error); + }); + */ + + return deferred.promise; +}; + +EPUBJS.Chapter.prototype.setPages = function(num){ + this.pages = num; +}; + +EPUBJS.Chapter.prototype.getPages = function(num){ + return this.pages; +}; + +EPUBJS.Chapter.prototype.getID = function(){ + return this.ID; +}; + +EPUBJS.Chapter.prototype.unload = function(store){ + this.document = null; + if(this.tempUrl && store) { + store.revokeUrl(this.tempUrl); + this.tempUrl = false; + } +}; + +EPUBJS.Chapter.prototype.setDocument = function(_document){ + var uri = _document.namespaceURI; + var doctype = _document.doctype; + + // Creates an empty document + this.document = _document.implementation.createDocument( + uri, + null, + null + ); + this.contents = this.document.importNode( + _document.documentElement, //node to import + true //clone its descendants + ); + + this.document.appendChild(this.contents); + + // Fix to apply wgxpath to new document in IE + if(!this.document.evaluate && document.evaluate) { + this.document.evaluate = document.evaluate; + } + + // this.deferred.resolve(this.contents); +}; + +EPUBJS.Chapter.prototype.cfiFromRange = function(_range) { + var range; + var startXpath, endXpath; + var startContainer, endContainer; + var cleanTextContent, cleanEndTextContent; + + // Check for Contents + if(!this.document) return; + startXpath = EPUBJS.core.getElementXPath(_range.startContainer); + // console.log(startContainer) + endXpath = EPUBJS.core.getElementXPath(_range.endContainer); + + startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(!_range.collapsed) { + endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } + + range = this.document.createRange(); + // Find Exact Range in original document + if(startContainer) { + try { + range.setStart(startContainer, _range.startOffset); + if(!_range.collapsed && endContainer) { + range.setEnd(endContainer, _range.endOffset); + } + } catch (e) { + console.log("missed"); + startContainer = false; + } + + } + + // Fuzzy Match + if(!startContainer) { + console.log("not found, try fuzzy match"); + cleanStartTextContent = EPUBJS.core.cleanStringForXpath(_range.startContainer.textContent); + startXpath = "//text()[contains(.," + cleanStartTextContent + ")]"; + + startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(startContainer){ + // console.log("Found with Fuzzy"); + range.setStart(startContainer, _range.startOffset); + + if(!_range.collapsed) { + cleanEndTextContent = EPUBJS.core.cleanStringForXpath(_range.endContainer.textContent); + endXpath = "//text()[contains(.," + cleanEndTextContent + ")]"; + endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + if(endContainer) { + range.setEnd(endContainer, _range.endOffset); + } + } + + } + } + + // Generate the Cfi + return this.epubcfi.generateCfiFromRange(range, this.cfiBase); +}; + +EPUBJS.Chapter.prototype.find = function(_query){ + var chapter = this; + var matches = []; + var query = _query.toLowerCase(); + //var xpath = this.document.evaluate(".//text()[contains(translate(., '"+query.toUpperCase()+"', '"+query+"'),'"+query+"')]", this.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + var find = function(node){ + // Search String + var text = node.textContent.toLowerCase(); + var range = chapter.document.createRange(); + var cfi; + var pos; + var last = -1; + var excerpt; + var limit = 150; + + while (pos != -1) { + pos = text.indexOf(query, last + 1); + + if(pos != -1) { + // If Found, Create Range + range = chapter.document.createRange(); + range.setStart(node, pos); + range.setEnd(node, pos + query.length); + + //Generate CFI + cfi = chapter.cfiFromRange(range); + + // Generate Excerpt + if(node.textContent.length < limit) { + excerpt = node.textContent; + } else { + excerpt = node.textContent.substring(pos-limit/2,pos+limit/2); + excerpt = "..." + excerpt + "..."; + } + + //Add CFI to list + matches.push({ + cfi: cfi, + excerpt: excerpt + }); + } + + last = pos; + } + + }; + + // Grab text nodes + + /* + for ( var i=0 ; i < xpath.snapshotLength; i++ ) { + find(xpath.snapshotItem(i)); + } + */ + + this.textSprint(this.document, function(node){ + find(node); + }); + + + // Return List of CFIs + return matches; +}; + + +EPUBJS.Chapter.prototype.textSprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if (node.data && ! /^\s*$/.test(node.data) ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; +var EPUBJS = EPUBJS || {}; +EPUBJS.core = {}; + +//-- Get a element for an id +EPUBJS.core.getEl = function(elem) { + return document.getElementById(elem); +}; + +//-- Get all elements for a class +EPUBJS.core.getEls = function(classes) { + return document.getElementsByClassName(classes); +}; + +EPUBJS.core.request = function(url, type, withCredentials) { + var supportsURL = window.URL; + var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; + + var deferred = new RSVP.defer(); + + var xhr = new XMLHttpRequest(); + + //-- Check from PDF.js: + // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js + var xhrPrototype = XMLHttpRequest.prototype; + + if (!('overrideMimeType' in xhrPrototype)) { + // IE10 might have response, but not overrideMimeType + Object.defineProperty(xhrPrototype, 'overrideMimeType', { + value: function xmlHttpRequestOverrideMimeType(mimeType) {} + }); + } + if(withCredentials) { + xhr.withCredentials = true; + } + xhr.open("GET", url, true); + xhr.onreadystatechange = handler; + + if(type == 'blob'){ + xhr.responseType = BLOB_RESPONSE; + } + + if(type == "json") { + xhr.setRequestHeader("Accept", "application/json"); + } + + if(type == 'xml') { + xhr.overrideMimeType('text/xml'); + } + + if(type == "binary") { + xhr.responseType = "arraybuffer"; + } + + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls + var r; + + if(type == 'xml'){ + r = this.responseXML; + }else + if(type == 'json'){ + r = JSON.parse(this.response); + }else + if(type == 'blob'){ + + if(supportsURL) { + r = this.response; + } else { + //-- Safari doesn't support responseType blob, so create a blob from arraybuffer + r = new Blob([this.response]); + } + + }else{ + r = this.response; + } + + deferred.resolve(r); + } else { + deferred.reject({ + message : this.response, + stack : new Error().stack + }); + } + } + } + + return deferred.promise; +}; + +EPUBJS.core.toArray = function(obj) { + var arr = []; + + for (var member in obj) { + var newitm; + if ( obj.hasOwnProperty(member) ) { + newitm = obj[member]; + newitm.ident = member; + arr.push(newitm); + } + } + + return arr; +}; + +//-- Parse the different parts of a url, returning a object +EPUBJS.core.uri = function(url){ + var uri = { + protocol : '', + host : '', + path : '', + origin : '', + directory : '', + base : '', + filename : '', + extension : '', + fragment : '', + href : url + }, + blob = url.indexOf('blob:'), + doubleSlash = url.indexOf('://'), + search = url.indexOf('?'), + fragment = url.indexOf("#"), + withoutProtocol, + dot, + firstSlash; + + if(blob === 0) { + uri.protocol = "blob"; + uri.base = url.indexOf(0, fragment); + return uri; + } + + if(fragment != -1) { + uri.fragment = url.slice(fragment + 1); + url = url.slice(0, fragment); + } + + if(search != -1) { + uri.search = url.slice(search + 1); + url = url.slice(0, search); + href = url; + } + + if(doubleSlash != -1) { + uri.protocol = url.slice(0, doubleSlash); + withoutProtocol = url.slice(doubleSlash+3); + firstSlash = withoutProtocol.indexOf('/'); + + if(firstSlash === -1) { + uri.host = uri.path; + uri.path = ""; + } else { + uri.host = withoutProtocol.slice(0, firstSlash); + uri.path = withoutProtocol.slice(firstSlash); + } + + + uri.origin = uri.protocol + "://" + uri.host; + + uri.directory = EPUBJS.core.folder(uri.path); + + uri.base = uri.origin + uri.directory; + // return origin; + } else { + uri.path = url; + uri.directory = EPUBJS.core.folder(url); + uri.base = uri.directory; + } + + //-- Filename + uri.filename = url.replace(uri.base, ''); + dot = uri.filename.lastIndexOf('.'); + if(dot != -1) { + uri.extension = uri.filename.slice(dot+1); + } + return uri; +}; + +//-- Parse out the folder, will return everything before the last slash + +EPUBJS.core.folder = function(url){ + + var lastSlash = url.lastIndexOf('/'); + + if(lastSlash == -1) var folder = ''; + + folder = url.slice(0, lastSlash + 1); + + return folder; + +}; + +//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 +EPUBJS.core.dataURLToBlob = function(dataURL) { + var BASE64_MARKER = ';base64,', + parts, contentType, raw, rawLength, uInt8Array; + + if (dataURL.indexOf(BASE64_MARKER) == -1) { + parts = dataURL.split(','); + contentType = parts[0].split(':')[1]; + raw = parts[1]; + + return new Blob([raw], {type: contentType}); + } + + parts = dataURL.split(BASE64_MARKER); + contentType = parts[0].split(':')[1]; + raw = window.atob(parts[1]); + rawLength = raw.length; + + uInt8Array = new Uint8Array(rawLength); + + for (var i = 0; i < rawLength; ++i) { + uInt8Array[i] = raw.charCodeAt(i); + } + + return new Blob([uInt8Array], {type: contentType}); +}; + +//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously +EPUBJS.core.addScript = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('script'); + s.type = 'text/javascript'; + s.async = false; + s.src = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.addScripts = function(srcArr, callback, target) { + var total = srcArr.length, + curr = 0, + cb = function(){ + curr++; + if(total == curr){ + if(callback) callback(); + }else{ + EPUBJS.core.addScript(srcArr[curr], cb, target); + } + }; + + EPUBJS.core.addScript(srcArr[curr], cb, target); +}; + +EPUBJS.core.addCss = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('link'); + s.type = 'text/css'; + s.rel = "stylesheet"; + s.href = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.prefixed = function(unprefixed) { + var vendors = ["Webkit", "Moz", "O", "ms" ], + prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], + upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), + length = vendors.length; + + if (typeof(document.body.style[unprefixed]) != 'undefined') { + return unprefixed; + } + + for ( var i=0; i < length; i++ ) { + if (typeof(document.body.style[vendors[i] + upper]) != 'undefined') { + return vendors[i] + upper; + } + } + + return unprefixed; +}; + +EPUBJS.core.resolveUrl = function(base, path) { + var url, + segments = [], + uri = EPUBJS.core.uri(path), + folders = base.split("/"), + paths; + + if(uri.host) { + return path; + } + + folders.pop(); + + paths = path.split("/"); + paths.forEach(function(p){ + if(p === ".."){ + folders.pop(); + }else{ + segments.push(p); + } + }); + + url = folders.concat(segments); + + return url.join("/"); +}; + +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript +EPUBJS.core.uuid = function() { + var d = new Date().getTime(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = (d + Math.random()*16)%16 | 0; + d = Math.floor(d/16); + return (c=='x' ? r : (r&0x7|0x8)).toString(16); + }); + return uuid; +}; + +// Fast quicksort insert for sorted array -- based on: +// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers +EPUBJS.core.insert = function(item, array, compareFunction) { + var location = EPUBJS.core.locationOf(item, array, compareFunction); + array.splice(location, 0, item); + + return location; +}; + +EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return pivot; + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared > 0 ? pivot : pivot + 1; + } + + if(compared === 0) { + return pivot; + } + if(compared === -1) { + return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); + } +}; + +EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return -1; // Not found + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared === 0 ? pivot : -1; + } + if(compared === 0) { + return pivot; // Found + } + if(compared === -1) { + return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); + } +}; + + +EPUBJS.core.queue = function(_scope){ + var _q = []; + var scope = _scope; + // Add an item to the queue + var enqueue = function(funcName, args, context) { + _q.push({ + "funcName" : funcName, + "args" : args, + "context" : context + }); + return _q; + }; + // Run one item + var dequeue = function(){ + var inwait; + if(_q.length) { + inwait = _q.shift(); + // Defer to any current tasks + // setTimeout(function(){ + scope[inwait.funcName].apply(inwait.context || scope, inwait.args); + // }, 0); + } + }; + + // Run All + var flush = function(){ + while(_q.length) { + dequeue(); + } + }; + // Clear all items in wait + var clear = function(){ + _q = []; + }; + + var length = function(){ + return _q.length; + }; + + return { + "enqueue" : enqueue, + "dequeue" : dequeue, + "flush" : flush, + "clear" : clear, + "length" : length + }; +}; + +// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js +/** + * Gets an XPath for an element which describes its hierarchical location. + */ +EPUBJS.core.getElementXPath = function(element) { + if (element && element.id) { + return '//*[@id="' + element.id + '"]'; + } else { + return EPUBJS.core.getElementTreeXPath(element); + } +}; + +EPUBJS.core.getElementTreeXPath = function(element) { + var paths = []; + var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); + var index, nodeName, tagName, pathIndex; + + if(element.nodeType === Node.TEXT_NODE){ + // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; + index = EPUBJS.core.indexOfTextNode(element) + 1; + + paths.push("text()["+index+"]"); + element = element.parentNode; + } + + // Use nodeName (instead of localName) so namespace prefix is included (if any). + for (; element && element.nodeType == 1; element = element.parentNode) + { + index = 0; + for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) + { + // Ignore document type declaration. + if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { + continue; + } + if (sibling.nodeName == element.nodeName) { + ++index; + } + } + nodeName = element.nodeName.toLowerCase(); + tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); + pathIndex = (index ? "[" + (index+1) + "]" : ""); + paths.splice(0, 0, tagName + pathIndex); + } + + return paths.length ? "./" + paths.join("/") : null; +}; + +EPUBJS.core.nsResolver = function(prefix) { + var ns = { + 'xhtml' : 'http://www.w3.org/1999/xhtml', + 'epub': 'http://www.idpf.org/2007/ops' + }; + return ns[prefix] || null; +}; + +//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 +EPUBJS.core.cleanStringForXpath = function(str) { + var parts = str.match(/[^'"]+|['"]/g); + parts = parts.map(function(part){ + if (part === "'") { + return '\"\'\"'; // output "'" + } + + if (part === '"') { + return "\'\"\'"; // output '"' + } + return "\'" + part + "\'"; + }); + return "concat(\'\'," + parts.join(",") + ")"; +}; + +EPUBJS.core.indexOfTextNode = function(textNode){ + var parent = textNode.parentNode; + var children = parent.childNodes; + var sib; + var index = -1; + for (var i = 0; i < children.length; i++) { + sib = children[i]; + if(sib.nodeType === Node.TEXT_NODE){ + index++; + } + if(sib == textNode) break; + } + + return index; +}; +EPUBJS.EpubCFI = function(cfiStr){ + if(cfiStr) return this.parse(cfiStr); +}; + +EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) { + var pos = parseInt(_pos), + spineNodeIndex = _spineNodeIndex + 1, + cfi = '/'+spineNodeIndex+'/'; + + cfi += (pos + 1) * 2; + + if(id) cfi += "[" + id + "]"; + + //cfi += "!"; + + return cfi; +}; + +EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) { + var parts = []; + + steps.forEach(function(part){ + var segment = ''; + segment += (part.index + 1) * 2; + + if(part.id) { + segment += "[" + part.id + "]"; + } + + parts.push(segment); + }); + + return parts.join('/'); +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) { + var steps = this.pathTo(element); + var path = this.generatePathComponent(steps); + if(!path.length) { + // Start of Chapter + return "epubcfi(" + chapter + "!/4/)"; + } else { + // First Text Node + return "epubcfi(" + chapter + "!" + path + "/1:0)"; + } +}; + +EPUBJS.EpubCFI.prototype.pathTo = function(node) { + var stack = [], + children; + + while(node && node.parentNode !== null && node.parentNode.nodeType != 9) { + children = node.parentNode.children; + + stack.unshift({ + 'id' : node.id, + // 'classList' : node.classList, + 'tagName' : node.tagName, + 'index' : children ? Array.prototype.indexOf.call(children, node) : 0 + }); + + node = node.parentNode; + } + + return stack; +}; + +EPUBJS.EpubCFI.prototype.getChapterComponent = function(cfiStr) { + + var splitStr = cfiStr.split("!"); + + return splitStr[0]; +}; + +EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) { + + var splitStr = cfiStr.split("!"); + var pathComponent = splitStr[1] ? splitStr[1].split(":") : ''; + + return pathComponent[0]; +}; + +EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) { + var splitStr = cfiStr.split(":"); + return splitStr[1] || ''; +}; + + +EPUBJS.EpubCFI.prototype.parse = function(cfiStr) { + var cfi = {}, + chapSegment, + chapterComponent, + pathComponent, + charecterOffsetComponent, + assertion, + chapId, + path, + end, + endInt, + text, + parseStep = function(part){ + var type, index, has_brackets, id; + + type = "element"; + index = parseInt(part) / 2 - 1; + has_brackets = part.match(/\[(.*)\]/); + if(has_brackets && has_brackets[1]){ + id = has_brackets[1]; + } + + return { + "type" : type, + 'index' : index, + 'id' : id || false + }; + }; + + if(typeof cfiStr !== "string") { + return {spinePos: -1}; + } + + cfi.str = cfiStr; + + if(cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length-1] === ")") { + // Remove intial epubcfi( and ending ) + cfiStr = cfiStr.slice(8, cfiStr.length-1); + } + + chapterComponent = this.getChapterComponent(cfiStr); + pathComponent = this.getPathComponent(cfiStr) || ''; + charecterOffsetComponent = this.getCharecterOffsetComponent(cfiStr); + // Make sure this is a valid cfi or return + if(!chapterComponent) { + return {spinePos: -1}; + } + + // Chapter segment is always the second one + chapSegment = chapterComponent.split("/")[2] || ''; + if(!chapSegment) return {spinePos:-1}; + + cfi.spinePos = (parseInt(chapSegment) / 2 - 1 ) || 0; + + chapId = chapSegment.match(/\[(.*)\]/); + + cfi.spineId = chapId ? chapId[1] : false; + + if(pathComponent.indexOf(',') != -1) { + // Handle ranges -- not supported yet + console.warn("CFI Ranges are not supported"); + } + + path = pathComponent.split('/'); + end = path.pop(); + + cfi.steps = []; + + path.forEach(function(part){ + var step; + + if(part) { + step = parseStep(part); + cfi.steps.push(step); + } + }); + + //-- Check if END is a text node or element + endInt = parseInt(end); + if(!isNaN(endInt)) { + + if(endInt % 2 === 0) { // Even = is an element + cfi.steps.push(parseStep(end)); + } else { + cfi.steps.push({ + "type" : "text", + 'index' : (endInt - 1 ) / 2 + }); + } + + } + + assertion = charecterOffsetComponent.match(/\[(.*)\]/); + if(assertion && assertion[1]){ + cfi.characterOffset = parseInt(charecterOffsetComponent.split('[')[0]); + // We arent handling these assertions yet + cfi.textLocationAssertion = assertion[1]; + } else { + cfi.characterOffset = parseInt(charecterOffsetComponent); + } + + return cfi; +}; + +EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) { + var doc = _doc || document; + var marker = _marker || this.createMarker(doc); + var parent; + var lastStep; + var text; + var split; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + // Get the terminal step + lastStep = cfi.steps[cfi.steps.length-1]; + + // check spinePos + if(cfi.spinePos === -1) { + // Not a valid CFI + return false; + } + + // Find the CFI elements parent + parent = this.findParent(cfi, doc); + + if(!parent) { + // CFI didn't return an element + // Maybe it isnt in the current chapter? + return false; + } + + if(lastStep && lastStep.type === "text") { + text = parent.childNodes[lastStep.index]; + if(cfi.characterOffset){ + split = text.splitText(cfi.characterOffset); + marker.classList.add("EPUBJS-CFI-SPLIT"); + parent.insertBefore(marker, split); + } else { + parent.insertBefore(marker, text); + } + } else { + parent.insertBefore(marker, parent.firstChild); + } + + return marker; +}; + +EPUBJS.EpubCFI.prototype.createMarker = function(_doc) { + var doc = _doc || document; + var element = doc.createElement('span'); + element.id = "EPUBJS-CFI-MARKER:"+ EPUBJS.core.uuid(); + element.classList.add("EPUBJS-CFI-MARKER"); + + return element; +}; + +EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) { + var doc = _doc || document; + // var id = marker.id; + + // Cleanup textnodes if they were split + if(marker.classList.contains("EPUBJS-CFI-SPLIT")){ + nextSib = marker.nextSibling; + prevSib = marker.previousSibling; + if(nextSib && + prevSib && + nextSib.nodeType === 3 && + prevSib.nodeType === 3){ + + prevSib.textContent += nextSib.textContent; + marker.parentNode.removeChild(nextSib); + } + marker.parentNode.removeChild(marker); + } else if(marker.classList.contains("EPUBJS-CFI-MARKER")) { + // Remove only elements added as markers + marker.parentNode.removeChild(marker); + } + +}; + +EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) { + var doc = _doc || document, + element = doc.getElementsByTagName('html')[0], + children = Array.prototype.slice.call(element.children), + num, index, part, sections, + text, textBegin, textEnd; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + + sections = cfi.steps.slice(0); // Clone steps array + if(!sections.length) { + return doc.getElementsByTagName('body')[0]; + } + + while(sections && sections.length > 0) { + part = sections.shift(); + // Find textNodes Parent + if(part.type === "text") { + text = element.childNodes[part.index]; + element = text.parentNode || element; + // Find element by id if present + } else if(part.id){ + element = doc.getElementById(part.id); + // Find element in parent + }else{ + element = children[part.index]; + } + // Element can't be found + if(typeof element === "undefined") { + console.error("No Element For", part, cfi.str); + return false; + } + // Get current element children and continue through steps + children = Array.prototype.slice.call(element.children); + } + + return element; +}; + +EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) { + if(typeof cfiOne === 'string') { + cfiOne = new EPUBJS.EpubCFI(cfiOne); + } + if(typeof cfiTwo === 'string') { + cfiTwo = new EPUBJS.EpubCFI(cfiTwo); + } + // Compare Spine Positions + if(cfiOne.spinePos > cfiTwo.spinePos) { + return 1; + } + if(cfiOne.spinePos < cfiTwo.spinePos) { + return -1; + } + + + // Compare Each Step in the First item + for (var i = 0; i < cfiOne.steps.length; i++) { + if(!cfiTwo.steps[i]) { + return 1; + } + if(cfiOne.steps[i].index > cfiTwo.steps[i].index) { + return 1; + } + if(cfiOne.steps[i].index < cfiTwo.steps[i].index) { + return -1; + } + // Otherwise continue checking + } + + // All steps in First present in Second + if(cfiOne.steps.length < cfiTwo.steps.length) { + return -1; + } + + // Compare the charecter offset of the text node + if(cfiOne.characterOffset > cfiTwo.characterOffset) { + return 1; + } + if(cfiOne.characterOffset < cfiTwo.characterOffset) { + return -1; + } + + // CFI's are equal + return 0; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) { + var uri = EPUBJS.core.uri(href); + var path = uri.path; + var fragment = uri.fragment; + var spinePos = book.spineIndexByURL[path]; + var loaded; + var deferred = new RSVP.defer(); + var epubcfi = new EPUBJS.EpubCFI(); + var spineItem; + + if(typeof spinePos !== "undefined"){ + spineItem = book.spine[spinePos]; + loaded = book.loadXml(spineItem.url); + loaded.then(function(doc){ + var element = doc.getElementById(fragment); + var cfi; + cfi = epubcfi.generateCfiFromElement(element, spineItem.cfiBase); + deferred.resolve(cfi); + }); + } + + return deferred.promise; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) { + var parent = anchor.parentNode; + var steps = this.pathTo(parent); + var path = this.generatePathComponent(steps); + var index = 1 + (2 * Array.prototype.indexOf.call(parent.childNodes, anchor)); + return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")"; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) { + var anchor = range.anchorNode; + var offset = range.anchorOffset; + return this.generateCfiFromTextNode(anchor, offset, base); +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) { + var start, startElement, startSteps, startPath, startOffset, startIndex; + var end, endElement, endSteps, endPath, endOffset, endIndex; + + start = range.startContainer; + + if(start.nodeType === 3) { // text node + startElement = start.parentNode; + //startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start)); + startIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(start)); + startSteps = this.pathTo(startElement); + } else if(range.collapsed) { + return this.generateCfiFromElement(start, base); // single element + } else { + startSteps = this.pathTo(start); + } + + startPath = this.generatePathComponent(startSteps); + startOffset = range.startOffset; + + if(!range.collapsed) { + end = range.endContainer; + + if(end.nodeType === 3) { // text node + endElement = end.parentNode; + // endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end)); + endIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(end)); + + endSteps = this.pathTo(endElement); + } else { + endSteps = this.pathTo(end); + } + + endPath = this.generatePathComponent(endSteps); + endOffset = range.endOffset; + + return "epubcfi(" + base + "!" + startPath + "/" + startIndex + ":" + startOffset + "," + endPath + "/" + endIndex + ":" + endOffset + ")"; + + } else { + return "epubcfi(" + base + "!" + startPath + "/"+ startIndex +":"+ startOffset +")"; + } +}; + +EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) { + var xpath = [".", "*"]; + + steps.forEach(function(step){ + var position = step.index + 1; + + if(step.id){ + xpath.push("*[position()=" + position + " and @id='" + step.id + "']"); + } else if(step.type === "text") { + xpath.push("text()[" + position + "]"); + } else { + xpath.push("*[" + position + "]"); + } + }); + + return xpath.join("/"); +}; + + +EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) { + var doc = _doc || document; + var range = doc.createRange(); + var lastStep; + var xpath; + var startContainer; + var textLength; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + + // check spinePos + if(cfi.spinePos === -1) { + // Not a valid CFI + return false; + } + + xpath = this.generateXpathFromSteps(cfi.steps); + + // Get the terminal step + lastStep = cfi.steps[cfi.steps.length-1]; + startContainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(!startContainer) { + return null; + } + + if(startContainer && cfi.characterOffset >= 0) { + textLength = startContainer.length; + + if(cfi.characterOffset < textLength) { + range.setStart(startContainer, cfi.characterOffset); + range.setEnd(startContainer, textLength ); + } else { + console.debug("offset greater than length:", cfi.characterOffset, textLength); + range.setStart(startContainer, textLength - 1 ); + range.setEnd(startContainer, textLength ); + } + } else if(startContainer) { + range.selectNode(startContainer); + } + // doc.defaultView.getSelection().addRange(range); + return range; +}; + +EPUBJS.Events = function(obj, el){ + + this.events = {}; + + if(!el){ + this.el = document.createElement('div'); + }else{ + this.el = el; + } + + obj.createEvent = this.createEvent; + obj.tell = this.tell; + obj.listen = this.listen; + obj.deafen = this.deafen; + obj.listenUntil = this.listenUntil; + + return this; +}; + +EPUBJS.Events.prototype.createEvent = function(evt){ + var e = new CustomEvent(evt); + this.events[evt] = e; + return e; +}; + +EPUBJS.Events.prototype.tell = function(evt, msg){ + var e; + + if(!this.events[evt]){ + console.warn("No event:", evt, "defined yet, creating."); + e = this.createEvent(evt); + }else{ + e = this.events[evt]; + } + + if(msg) e.msg = msg; + this.el.dispatchEvent(e); + +}; + +EPUBJS.Events.prototype.listen = function(evt, func, bindto){ + if(!this.events[evt]){ + console.warn("No event:", evt, "defined yet, creating."); + this.createEvent(evt); + return; + } + + if(bindto){ + this.el.addEventListener(evt, func.bind(bindto), false); + }else{ + this.el.addEventListener(evt, func, false); + } + +}; + +EPUBJS.Events.prototype.deafen = function(evt, func){ + this.el.removeEventListener(evt, func, false); +}; + +EPUBJS.Events.prototype.listenUntil = function(OnEvt, OffEvt, func, bindto){ + this.listen(OnEvt, func, bindto); + + function unlisten(){ + this.deafen(OnEvt, func); + this.deafen(OffEvt, unlisten); + } + + this.listen(OffEvt, unlisten, this); +}; +EPUBJS.hooks = {}; +EPUBJS.Hooks = (function(){ + function hooks(){} + + //-- Get pre-registered hooks + hooks.prototype.getHooks = function(){ + var plugs; + this.hooks = {}; + Array.prototype.slice.call(arguments).forEach(function(arg){ + this.hooks[arg] = []; + }, this); + + for (var plugType in this.hooks) { + plugs = _.values(EPUBJS.hooks[plugType]); + + plugs.forEach(function(hook){ + this.registerHook(plugType, hook); + }, this); + } + }; + + //-- Hooks allow for injecting async functions that must all complete before continuing + // Functions must have a callback as their first argument. + hooks.prototype.registerHook = function(type, toAdd, toFront){ + + if(typeof(this.hooks[type]) != "undefined"){ + + if(typeof(toAdd) === "function"){ + if(toFront) { + this.hooks[type].unshift(toAdd); + }else{ + this.hooks[type].push(toAdd); + } + }else if(Array.isArray(toAdd)){ + toAdd.forEach(function(hook){ + if(toFront) { + this.hooks[type].unshift(hook); + }else{ + this.hooks[type].push(hook); + } + }, this); + } + }else{ + //-- Allows for undefined hooks, but maybe this should error? + this.hooks[type] = [func]; + } + }; + + hooks.prototype.triggerHooks = function(type, callback, passed){ + var hooks, count; + + if(typeof(this.hooks[type]) == "undefined") return false; + + hooks = this.hooks[type]; + + count = hooks.length; + if(count === 0 && callback) { + callback(); + } + + function countdown(){ + count--; + if(count <= 0 && callback) callback(); + } + + hooks.forEach(function(hook){ + hook(countdown, passed); + }); + }; + + return { + register: function(name) { + if(EPUBJS.hooks[name] === undefined) { EPUBJS.hooks[name] = {}; } + if(typeof EPUBJS.hooks[name] !== 'object') { throw "Already registered: "+name; } + return EPUBJS.hooks[name]; + }, + mixin: function(object) { + for (var prop in hooks.prototype) { + object[prop] = hooks.prototype[prop]; + } + } + }; +})(); + + +EPUBJS.Layout = EPUBJS.Layout || {}; + +EPUBJS.Layout.Reflowable = function(){ + this.documentElement = null; + this.spreadWidth = null; +}; + +EPUBJS.Layout.Reflowable.prototype.format = function(documentElement, _width, _height, _gap){ + // Get the prefixed CSS commands + var columnAxis = EPUBJS.core.prefixed('columnAxis'); + var columnGap = EPUBJS.core.prefixed('columnGap'); + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var columnFill = EPUBJS.core.prefixed('columnFill'); + + //-- Check the width and create even width columns + var width = Math.floor(_width); + // var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 0; // Not needed for single + var section = Math.floor(width / 8); + var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); + this.documentElement = documentElement; + //-- Single Page + this.spreadWidth = (width + gap); + + + documentElement.style.overflow = "hidden"; + + // Must be set to the new calculated width or the columns will be off + documentElement.style.width = width + "px"; + + //-- Adjust height + documentElement.style.height = _height + "px"; + + //-- Add columns + documentElement.style[columnAxis] = "horizontal"; + documentElement.style[columnFill] = "auto"; + documentElement.style[columnWidth] = width+"px"; + documentElement.style[columnGap] = gap+"px"; + this.colWidth = width; + this.gap = gap; + + return { + pageWidth : this.spreadWidth, + pageHeight : _height + }; +}; + +EPUBJS.Layout.Reflowable.prototype.calculatePages = function() { + var totalWidth, displayedPages; + this.documentElement.style.width = "auto"; //-- reset width for calculations + totalWidth = this.documentElement.scrollWidth; + displayedPages = Math.ceil(totalWidth / this.spreadWidth); + + return { + displayedPages : displayedPages, + pageCount : displayedPages + }; +}; + +EPUBJS.Layout.ReflowableSpreads = function(){ + this.documentElement = null; + this.spreadWidth = null; +}; + +EPUBJS.Layout.ReflowableSpreads.prototype.format = function(documentElement, _width, _height, _gap){ + var columnAxis = EPUBJS.core.prefixed('columnAxis'); + var columnGap = EPUBJS.core.prefixed('columnGap'); + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var columnFill = EPUBJS.core.prefixed('columnFill'); + + var divisor = 2, + cutoff = 800; + + //-- Check the width and create even width columns + var fullWidth = Math.floor(_width); + var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 1; + + var section = Math.floor(width / 8); + var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); + + //-- Double Page + var colWidth = Math.floor((width - gap) / divisor); + + this.documentElement = documentElement; + this.spreadWidth = (colWidth + gap) * divisor; + + + documentElement.style.overflow = "hidden"; + + // Must be set to the new calculated width or the columns will be off + documentElement.style.width = width + "px"; + + //-- Adjust height + documentElement.style.height = _height + "px"; + + //-- Add columns + documentElement.style[columnAxis] = "horizontal"; + documentElement.style[columnFill] = "auto"; + documentElement.style[columnGap] = gap+"px"; + documentElement.style[columnWidth] = colWidth+"px"; + + this.colWidth = colWidth; + this.gap = gap; + return { + pageWidth : this.spreadWidth, + pageHeight : _height + }; +}; + +EPUBJS.Layout.ReflowableSpreads.prototype.calculatePages = function() { + var totalWidth = this.documentElement.scrollWidth; + var displayedPages = Math.ceil(totalWidth / this.spreadWidth); + + //-- Add a page to the width of the document to account an for odd number of pages + this.documentElement.style.width = ((displayedPages * this.spreadWidth) - this.gap) + "px"; + + return { + displayedPages : displayedPages, + pageCount : displayedPages * 2 + }; +}; + +EPUBJS.Layout.Fixed = function(){ + this.documentElement = null; +}; + +EPUBJS.Layout.Fixed.prototype.format = function(documentElement, _width, _height, _gap){ + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var viewport = documentElement.querySelector("[name=viewport"); + var content; + var contents; + var width, height; + this.documentElement = documentElement; + /** + * check for the viewport size + * + */ + if(viewport && viewport.hasAttribute("content")) { + content = viewport.getAttribute("content"); + contents = content.split(','); + if(contents[0]){ + width = contents[0].replace("width=", ''); + } + if(contents[1]){ + height = contents[1].replace("height=", ''); + } + } + + //-- Adjust width and height + documentElement.style.width = width + "px" || "auto"; + documentElement.style.height = height + "px" || "auto"; + + //-- Remove columns + documentElement.style[columnWidth] = "auto"; + + //-- Scroll + documentElement.style.overflow = "auto"; + + this.colWidth = width; + this.gap = 0; + + return { + pageWidth : width, + pageHeight : height + }; + +}; + +EPUBJS.Layout.Fixed.prototype.calculatePages = function(){ + return { + displayedPages : 1, + pageCount : 1 + }; +}; + +EPUBJS.Pagination = function(pageList) { + this.pages = []; + this.locations = []; + this.epubcfi = new EPUBJS.EpubCFI(); + if(pageList && pageList.length) { + this.process(pageList); + } +}; + +EPUBJS.Pagination.prototype.process = function(pageList){ + pageList.forEach(function(item){ + this.pages.push(item.page); + this.locations.push(item.cfi); + }, this); + + this.pageList = pageList; + this.firstPage = parseInt(this.pages[0]); + this.lastPage = parseInt(this.pages[this.pages.length-1]); + this.totalPages = this.lastPage - this.firstPage; +}; + +EPUBJS.Pagination.prototype.pageFromCfi = function(cfi){ + var pg = -1; + + // Check if the pageList has not been set yet + if(this.locations.length === 0) { + return -1; + } + + // TODO: check if CFI is valid? + + // check if the cfi is in the location list + // var index = this.locations.indexOf(cfi); + var index = EPUBJS.core.indexOfSorted(cfi, this.locations, this.epubcfi.compare); + if(index != -1 && index < (this.pages.length-1) ) { + pg = this.pages[index]; + } else { + // Otherwise add it to the list of locations + // Insert it in the correct position in the locations page + //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare); + index = EPUBJS.core.locationOf(cfi, this.locations, this.epubcfi.compare); + // Get the page at the location just before the new one, or return the first + pg = index-1 >= 0 ? this.pages[index-1] : this.pages[0]; + if(pg !== undefined) { + // Add the new page in so that the locations and page array match up + //this.pages.splice(index, 0, pg); + } else { + pg = -1; + } + + } + return pg; +}; + +EPUBJS.Pagination.prototype.cfiFromPage = function(pg){ + var cfi = -1; + // check that pg is an int + if(typeof pg != "number"){ + pg = parseInt(pg); + } + + // check if the cfi is in the page list + // Pages could be unsorted. + var index = this.pages.indexOf(pg); + if(index != -1) { + cfi = this.locations[index]; + } + // TODO: handle pages not in the list + return cfi; +}; + +EPUBJS.Pagination.prototype.pageFromPercentage = function(percent){ + var pg = Math.round(this.totalPages * percent); + return pg; +}; + +// Returns a value between 0 - 1 corresponding to the location of a page +EPUBJS.Pagination.prototype.percentageFromPage = function(pg){ + var percentage = (pg - this.firstPage) / this.totalPages; + return Math.round(percentage * 1000) / 1000; +}; + +// Returns a value between 0 - 1 corresponding to the location of a cfi +EPUBJS.Pagination.prototype.percentageFromCfi = function(cfi){ + var pg = this.pageFromCfi(cfi); + var percentage = this.percentageFromPage(pg); + return percentage; +}; +EPUBJS.Parser = function(baseUrl){ + this.baseUrl = baseUrl || ''; +}; + +EPUBJS.Parser.prototype.container = function(containerXml){ + //-- + var rootfile, fullpath, folder, encoding; + + if(!containerXml) { + console.error("Container File Not Found"); + return; + } + + rootfile = containerXml.querySelector("rootfile"); + + if(!rootfile) { + console.error("No RootFile Found"); + return; + } + + fullpath = rootfile.getAttribute('full-path'); + folder = EPUBJS.core.uri(fullpath).directory; + encoding = containerXml.xmlEncoding; + + //-- Now that we have the path we can parse the contents + return { + 'packagePath' : fullpath, + 'basePath' : folder, + 'encoding' : encoding + }; +}; + +EPUBJS.Parser.prototype.identifier = function(packageXml){ + var metadataNode; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = packageXml.querySelector("metadata"); + + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + return this.getElementText(metadataNode, "identifier"); +}; + +EPUBJS.Parser.prototype.packageContents = function(packageXml, baseUrl){ + var parse = this; + var metadataNode, manifestNode, spineNode; + var manifest, navPath, tocPath, coverPath; + var spineNodeIndex; + var spine; + var spineIndexByURL; + + if(baseUrl) this.baseUrl = baseUrl; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = packageXml.querySelector("metadata"); + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + manifestNode = packageXml.querySelector("manifest"); + if(!manifestNode) { + console.error("No Manifest Found"); + return; + } + + spineNode = packageXml.querySelector("spine"); + if(!spineNode) { + console.error("No Spine Found"); + return; + } + + manifest = parse.manifest(manifestNode); + navPath = parse.findNavPath(manifestNode); + tocPath = parse.findTocPath(manifestNode, spineNode); + coverPath = parse.findCoverPath(manifestNode); + + spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); + + spine = parse.spine(spineNode, manifest); + + spineIndexByURL = {}; + spine.forEach(function(item){ + spineIndexByURL[item.href] = item.index; + }); + + return { + 'metadata' : parse.metadata(metadataNode), + 'spine' : spine, + 'manifest' : manifest, + 'navPath' : navPath, + 'tocPath' : tocPath, + 'coverPath': coverPath, + 'spineNodeIndex' : spineNodeIndex, + 'spineIndexByURL' : spineIndexByURL + }; +}; + +//-- Find TOC NAV +EPUBJS.Parser.prototype.findNavPath = function(manifestNode){ + // Find item with property 'nav' + // Should catch nav irregardless of order + var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); + return node ? node.getAttribute('href') : false; +}; + +//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" +EPUBJS.Parser.prototype.findTocPath = function(manifestNode, spineNode){ + var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); + var tocId; + + // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as + // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2, + // "The item that describes the NCX must be referenced by the spine toc attribute." + if (!node) { + tocId = spineNode.getAttribute("toc"); + if(tocId) { + node = manifestNode.querySelector("item[id='" + tocId + "']"); + } + } + + return node ? node.getAttribute('href') : false; +}; + +//-- Find Cover: +EPUBJS.Parser.prototype.findCoverPath = function(manifestNode){ + var node = manifestNode.querySelector("item[properties='cover-image']"); + return node ? node.getAttribute('href') : false; +}; + +//-- Expanded to match Readium web components +EPUBJS.Parser.prototype.metadata = function(xml){ + var metadata = {}, + p = this; + + metadata.bookTitle = p.getElementText(xml, 'title'); + metadata.creator = p.getElementText(xml, 'creator'); + metadata.description = p.getElementText(xml, 'description'); + + metadata.pubdate = p.getElementText(xml, 'date'); + + metadata.publisher = p.getElementText(xml, 'publisher'); + + metadata.identifier = p.getElementText(xml, "identifier"); + metadata.language = p.getElementText(xml, "language"); + metadata.rights = p.getElementText(xml, "rights"); + + metadata.modified_date = p.querySelectorText(xml, "meta[property='dcterms:modified']"); + metadata.layout = p.querySelectorText(xml, "meta[property='rendition:layout']"); + metadata.orientation = p.querySelectorText(xml, "meta[property='rendition:orientation']"); + metadata.spread = p.querySelectorText(xml, "meta[property='rendition:spread']"); + // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); + + return metadata; +}; + +EPUBJS.Parser.prototype.getElementText = function(xml, tag){ + var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), + el; + + if(!found || found.length === 0) return ''; + + el = found[0]; + + if(el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; + +}; + +EPUBJS.Parser.prototype.querySelectorText = function(xml, q){ + var el = xml.querySelector(q); + + if(el && el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; +}; + +EPUBJS.Parser.prototype.manifest = function(manifestXml){ + var baseUrl = this.baseUrl, + manifest = {}; + + //-- Turn items into an array + var selected = manifestXml.querySelectorAll("item"), + items = Array.prototype.slice.call(selected); + + //-- Create an object with the id as key + items.forEach(function(item){ + var id = item.getAttribute('id'), + href = item.getAttribute('href') || '', + type = item.getAttribute('media-type') || '', + properties = item.getAttribute('properties') || ''; + + manifest[id] = { + 'href' : href, + 'url' : baseUrl + href, //-- Absolute URL for loading with a web worker + 'type' : type, + 'properties' : properties + }; + + }); + + return manifest; + +}; + +EPUBJS.Parser.prototype.spine = function(spineXml, manifest){ + var spine = []; + + var selected = spineXml.getElementsByTagName("itemref"), + items = Array.prototype.slice.call(selected); + + var spineNodeIndex = Array.prototype.indexOf.call(spineXml.parentNode.childNodes, spineXml); + + var epubcfi = new EPUBJS.EpubCFI(); + + //-- Add to array to mantain ordering and cross reference with manifest + items.forEach(function(item, index){ + var Id = item.getAttribute('idref'); + var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); + var props = item.getAttribute('properties') || ''; + var propArray = props.length ? props.split(' ') : []; + var manifestProps = manifest[Id].properties; + var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : []; + var vert = { + 'id' : Id, + 'linear' : item.getAttribute('linear') || '', + 'properties' : propArray, + 'manifestProperties' : manifestPropArray, + 'href' : manifest[Id].href, + 'url' : manifest[Id].url, + 'index' : index, + 'cfiBase' : cfiBase, + 'cfi' : "epub(" + cfiBase + ")" + }; + spine.push(vert); + }); + + return spine; +}; + +EPUBJS.Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ + var navEl = navHtml.querySelector('nav[*|type="toc"]'), //-- [*|type="toc"] * Doesn't seem to work + idCounter = 0; + + if(!navEl) return []; + + // Implements `> ol > li` + function findListItems(parent){ + var items = []; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('ol' == node.tagName){ + Array.prototype.slice.call(node.childNodes).forEach(function(item){ + if('li' == item.tagName){ + items.push(item); + } + }); + } + }); + + return items; + + } + + // Implements `> a, > span` + function findAnchorOrSpan(parent){ + var item = null; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('a' == node.tagName || 'span' == node.tagName){ + item = node; + } + }); + + return item; + } + + function getTOC(parent){ + var list = [], + nodes = findListItems(parent), + items = Array.prototype.slice.call(nodes), + length = items.length, + node; + + if(length === 0) return false; + + items.forEach(function(item){ + var id = item.getAttribute('id') || false, + content = findAnchorOrSpan(item), + href = content.getAttribute('href') || '', + text = content.textContent || "", + split = href.split("#"), + baseUrl = split[0], + subitems = getTOC(item), + spinePos = spineIndexByURL[baseUrl], + spineItem = bookSpine[spinePos], + cfi = spineItem ? spineItem.cfi : ''; + + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + (idCounter++); + } + } + + item.setAttribute('id', id); // Ensure all elements have an id + list.push({ + "id": id, + "href": href, + "label": text, + "subitems" : subitems, + "parent" : parent ? parent.getAttribute('id') : null, + "cfi" : cfi + }); + + }); + + return list; + } + + return getTOC(navEl); +}; + +EPUBJS.Parser.prototype.toc = function(tocXml, spineIndexByURL, bookSpine){ + var navMap = tocXml.querySelector("navMap"); + if(!navMap) return []; + + function getTOC(parent){ + var list = [], + snapshot = tocXml.evaluate("*[local-name()='navPoint']", parent, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null), + length = snapshot.snapshotLength; + + if(length === 0) return []; + + for ( var i=length-1 ; i >= 0; i-- ) { + var item = snapshot.snapshotItem(i); + + var id = item.getAttribute('id') || false, + content = item.querySelector("content"), + src = content.getAttribute('src'), + navLabel = item.querySelector("navLabel"), + text = navLabel.textContent ? navLabel.textContent : "", + split = src.split("#"), + baseUrl = split[0], + spinePos = spineIndexByURL[baseUrl], + spineItem = bookSpine[spinePos], + subitems = getTOC(item), + cfi = spineItem ? spineItem.cfi : ''; + + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + (idCounter++); + } + } + + list.unshift({ + "id": id, + "href": src, + "label": text, + "spinePos": spinePos, + "subitems" : subitems, + "parent" : parent ? parent.getAttribute('id') : null, + "cfi" : cfi + }); + + } + + return list; + } + + return getTOC(navMap); +}; + +EPUBJS.Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ + var navEl = navHtml.querySelector('nav[*|type="page-list"]'), + idCounter = 0; + + if(!navEl) return []; + + // Implements `> ol > li` + function findListItems(parent){ + var items = []; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('ol' == node.tagName){ + Array.prototype.slice.call(node.childNodes).forEach(function(item){ + if('li' == item.tagName){ + items.push(item); + } + }); + } + }); + + return items; + + } + + // Implements `> a, > span` + function findAnchorOrSpan(parent){ + var item = null; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('a' == node.tagName || 'span' == node.tagName){ + item = node; + } + }); + + return item; + } + + function getPages(parent){ + var list = [], + nodes = findListItems(parent), + items = Array.prototype.slice.call(nodes), + length = items.length, + node; + + if(length === 0) return false; + + items.forEach(function(item){ + var id = item.getAttribute('id') || false, + content = findAnchorOrSpan(item), + href = content.getAttribute('href') || '', + text = content.textContent || "", + page = parseInt(text), + isCfi = href.indexOf("epubcfi"), + split, + packageUrl, + cfi; + + if(isCfi != -1) { + split = href.split("#"); + packageUrl = split[0]; + cfi = split.length > 1 ? split[1] : false; + list.push({ + "cfi" : cfi, + "href" : href, + "packageUrl" : packageUrl, + "page" : page + }); + } else { + list.push({ + "href" : href, + "page" : page + }); + } + + }); + + return list; + } + + return getPages(navEl); +}; + +EPUBJS.Render.Iframe = function() { + this.iframe = null; + this.document = null; + this.window = null; + this.docEl = null; + this.bodyEl = null; + + this.leftPos = 0; + this.pageWidth = 0; +}; + +//-- Build up any html needed +EPUBJS.Render.Iframe.prototype.create = function(){ + this.iframe = document.createElement('iframe'); + this.iframe.id = "epubjs-iframe:" + EPUBJS.core.uuid(); + this.iframe.scrolling = "no"; + this.iframe.seamless = "seamless"; + // Back up if seamless isn't supported + this.iframe.style.border = "none"; + + this.iframe.addEventListener("load", this.loaded.bind(this), false); + return this.iframe; +}; + +/** +* Sets the source of the iframe with the given URL string +* Takes: URL string +* Returns: promise with document element +*/ +EPUBJS.Render.Iframe.prototype.load = function(chapter){ + var render = this, + deferred = new RSVP.defer(); + + chapter.url().then(function(url){ + // Reset the scroll position + render.leftPos = 0; + + if(this.window) { + this.unload(); + } + + this.iframe.onload = function(e) { + render.document = render.iframe.contentDocument; + render.docEl = render.document.documentElement; + render.headEl = render.document.head; + render.bodyEl = render.document.body || render.document.querySelector("body"); + render.window = render.iframe.contentWindow; + + render.window.addEventListener("resize", render.resized.bind(render), false); + + //-- Clear Margins + if(render.bodyEl) { + render.bodyEl.style.margin = "0"; + } + + deferred.resolve(render.docEl); + }; + + this.iframe.onerror = function(e) { + //console.error("Error Loading Contents", e); + deferred.reject({ + message : "Error Loading Contents: " + e, + stack : new Error().stack + }); + }; + + this.iframe.contentWindow.location.replace(url); + + }.bind(this)); + + return deferred.promise; +}; + + +EPUBJS.Render.Iframe.prototype.loaded = function(v){ + var url = this.iframe.contentWindow.location.href; + if(url != "about:blank"){ + this.trigger("render:loaded", url); + } +}; + +// Resize the iframe to the given width and height +EPUBJS.Render.Iframe.prototype.resize = function(width, height){ + var iframeBox; + + if(!this.iframe) return; + + this.iframe.height = height; + + if(!isNaN(width) && width % 2 !== 0){ + width += 1; //-- Prevent cutting off edges of text in columns + } + + this.iframe.width = width; + // Get the fractional height and width of the iframe + // Default to orginal if bounding rect is 0 + this.width = this.iframe.getBoundingClientRect().width || width; + this.height = this.iframe.getBoundingClientRect().height || height; +}; + + +EPUBJS.Render.Iframe.prototype.resized = function(e){ + // Get the fractional height and width of the iframe + this.width = this.iframe.getBoundingClientRect().width; + this.height = this.iframe.getBoundingClientRect().height; +}; + +EPUBJS.Render.Iframe.prototype.totalWidth = function(){ + return this.docEl.scrollWidth; +}; + +EPUBJS.Render.Iframe.prototype.totalHeight = function(){ + return this.docEl.scrollHeight; +}; + +EPUBJS.Render.Iframe.prototype.setPageDimensions = function(pageWidth, pageHeight){ + this.pageWidth = pageWidth; + this.pageHeight = pageHeight; + //-- Add a page to the width of the document to account an for odd number of pages + // this.docEl.style.width = this.docEl.scrollWidth + pageWidth + "px"; +}; + +EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){ + // this.bodyEl.style.marginLeft = -leftPos + "px"; + // this.docEl.style.marginLeft = -leftPos + "px"; + // this.docEl.style[EPUBJS.Render.Iframe.transform] = 'translate('+ (-leftPos) + 'px, 0)'; + this.document.defaultView.scrollTo(leftPos, 0); +}; + +EPUBJS.Render.Iframe.prototype.setStyle = function(style, val, prefixed){ + if(prefixed) { + style = EPUBJS.core.prefixed(style); + } + + if(this.bodyEl) this.bodyEl.style[style] = val; +}; + +EPUBJS.Render.Iframe.prototype.removeStyle = function(style){ + + if(this.bodyEl) this.bodyEl.style[style] = ''; + +}; + +EPUBJS.Render.Iframe.prototype.addHeadTag = function(tag, attrs, _doc) { + var doc = _doc || this.document; + var tagEl = doc.createElement(tag); + var headEl = doc.head; + + for(var attr in attrs) { + tagEl.setAttribute(attr, attrs[attr]); + } + + if(headEl) headEl.insertBefore(tagEl, headEl.firstChild); +}; + +EPUBJS.Render.Iframe.prototype.page = function(pg){ + this.leftPos = this.pageWidth * (pg-1); //-- pages start at 1 + this.setLeft(this.leftPos); +}; + +//-- Show the page containing an Element +EPUBJS.Render.Iframe.prototype.getPageNumberByElement = function(el){ + var left, pg; + if(!el) return; + + left = this.leftPos + el.getBoundingClientRect().left; //-- Calculate left offset compaired to scrolled position + + pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 + + return pg; +}; + +//-- Show the page containing an Element +EPUBJS.Render.Iframe.prototype.getPageNumberByRect = function(boundingClientRect){ + var left, pg; + + left = this.leftPos + boundingClientRect.left; //-- Calculate left offset compaired to scrolled position + pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 + + return pg; +}; + +// Return the root element of the content +EPUBJS.Render.Iframe.prototype.getBaseElement = function(){ + return this.bodyEl; +}; + +// Checks if an element is on the screen +EPUBJS.Render.Iframe.prototype.isElementVisible = function(el){ + var rect; + var left; + + if(el && typeof el.getBoundingClientRect === 'function'){ + rect = el.getBoundingClientRect(); + left = rect.left; //+ rect.width; + if( rect.width !== 0 && + rect.height !== 0 && // Element not visible + left >= 0 && + left < this.pageWidth ) { + return true; + } + } + + return false; +}; + + +EPUBJS.Render.Iframe.prototype.scroll = function(bool){ + if(bool) { + this.iframe.scrolling = "yes"; + } else { + this.iframe.scrolling = "no"; + } +}; + +// Cleanup event listeners +EPUBJS.Render.Iframe.prototype.unload = function(){ + this.window.removeEventListener("resize", this.resized); +}; + +//-- Enable binding events to Render +RSVP.EventTarget.mixin(EPUBJS.Render.Iframe.prototype); +EPUBJS.Renderer = function(renderMethod, hidden) { + // Dom events to listen for + this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click"]; + this.upEvent = "mouseup"; + this.downEvent = "mousedown"; + if('ontouchstart' in document.documentElement) { + this.listenedEvents.push("touchstart", "touchend"); + this.upEvent = "touchend"; + this.downEvent = "touchstart"; + } + /** + * Setup a render method. + * Options are: Iframe + */ + if(renderMethod && typeof(EPUBJS.Render[renderMethod]) != "undefined"){ + this.render = new EPUBJS.Render[renderMethod](); + } else { + console.error("Not a Valid Rendering Method"); + } + + // Listen for load events + this.render.on("render:loaded", this.loaded.bind(this)); + + // Cached for replacement urls from storage + this.caches = {}; + + // Blank Cfi for Parsing + this.epubcfi = new EPUBJS.EpubCFI(); + + this.spreads = true; + this.isForcedSingle = false; + this.resized = _.debounce(this.onResized.bind(this), 100); + + this.layoutSettings = {}; + + this.hidden = hidden || false; + //-- Adds Hook methods to the Book prototype + // Hooks will all return before triggering the callback. + EPUBJS.Hooks.mixin(this); + //-- Get pre-registered hooks for events + this.getHooks("beforeChapterDisplay"); + + //-- Queue up page changes if page map isn't ready + this._q = EPUBJS.core.queue(this); + + this._moving = false; + +}; + +//-- Renderer events for listening +EPUBJS.Renderer.prototype.Events = [ + "renderer:keydown", + "renderer:keyup", + "renderer:keypressed", + "renderer:mouseup", + "renderer:mousedown", + "renderer:click", + "renderer:touchstart", + "renderer:touchend", + "renderer:selected", + "renderer:chapterUnloaded", + "renderer:chapterDisplayed", + "renderer:locationChanged", + "renderer:visibleLocationChanged", + "renderer:resized", + "renderer:spreads" +]; + +/** +* Creates an element to render to. +* Resizes to passed width and height or to the elements size +*/ +EPUBJS.Renderer.prototype.initialize = function(element, width, height){ + this.container = element; + this.element = this.render.create(); + + this.initWidth = width; + this.initHeight = height; + + this.width = width || this.container.clientWidth; + this.height = height || this.container.clientHeight; + + this.container.appendChild(this.element); + + if(width && height){ + this.render.resize(this.width, this.height); + } else { + this.render.resize('100%', '100%'); + } + + document.addEventListener("orientationchange", this.onResized); +}; + +/** +* Display a chapter +* Takes: chapter object, global layout settings +* Returns: Promise with passed Renderer after pages has loaded +*/ +EPUBJS.Renderer.prototype.displayChapter = function(chapter, globalLayout){ + var store = false; + if(this._moving) { + console.error("Rendering In Progress"); + return; + } + this._moving = true; + // Get the url string from the chapter (may be from storage) + return chapter.url(). + then(function(url) { + + // Unload the previous chapter listener + if(this.currentChapter) { + this.currentChapter.unload(); // Remove stored blobs + + if(this.render.window){ + this.render.window.removeEventListener("resize", this.resized); + } + + this.removeEventListeners(); + this.removeSelectionListeners(); + this.trigger("renderer:chapterUnloaded"); + this.contents = null; + this.doc = null; + this.pageMap = null; + } + + this.currentChapter = chapter; + this.chapterPos = 1; + this.currentChapterCfiBase = chapter.cfiBase; + + this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties); + return this.load(chapter); + + }.bind(this)); + +}; + +/** +* Loads a url (string) and renders it, +* attaching event listeners and triggering hooks. +* Returns: Promise with the rendered contents. +*/ + +EPUBJS.Renderer.prototype.load = function(url){ + var deferred = new RSVP.defer(); + var loaded; + + // Switch to the required layout method for the settings + this.layoutMethod = this.determineLayout(this.layoutSettings); + this.layout = new EPUBJS.Layout[this.layoutMethod](); + + this.visible(false); + + render = this.render.load(url); + + render.then(function(contents) { + var formated; + this.currentChapter.setDocument(this.render.document); + this.contents = contents; + this.doc = this.render.document; + + // Format the contents using the current layout method + this.formated = this.layout.format(contents, this.render.width, this.render.height, this.gap); + this.render.setPageDimensions(this.formated.pageWidth, this.formated.pageHeight); + + // window.addEventListener("orientationchange", this.onResized.bind(this), false); + if(!this.initWidth && !this.initHeight){ + this.render.window.addEventListener("resize", this.resized, false); + } + + this.addEventListeners(); + this.addSelectionListeners(); + + //-- Trigger registered hooks before displaying + this.beforeDisplay(function(){ + var pages = this.layout.calculatePages(); + var msg = this.currentChapter; + var queued = this._q.length(); + this._moving = false; + + this.updatePages(pages); + + this.visibleRangeCfi = this.getVisibleRangeCfi(); + this.currentLocationCfi = this.visibleRangeCfi.start; + + if(queued === 0) { + this.trigger("renderer:locationChanged", this.currentLocationCfi); + this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); + } + + msg.cfi = this.currentLocationCfi; //TODO: why is this cfi passed to chapterDisplayed + this.trigger("renderer:chapterDisplayed", msg); + + this.visible(true); + + deferred.resolve(this); //-- why does this return the renderer? + }.bind(this)); + + }.bind(this)); + + return deferred.promise; +}; + +EPUBJS.Renderer.prototype.loaded = function(url){ + this.trigger("render:loaded", url); + // var uri = EPUBJS.core.uri(url); + // var relative = uri.path.replace(book.bookUrl, ''); + // console.log(url, uri, relative); +}; + +/** +* Reconciles the current chapters layout properies with +* the global layout properities. +* Takes: global layout settings object, chapter properties string +* Returns: Object with layout properties +*/ +EPUBJS.Renderer.prototype.reconcileLayoutSettings = function(global, chapter){ + var settings = {}; + + //-- Get the global defaults + for (var attr in global) { + if (global.hasOwnProperty(attr)){ + settings[attr] = global[attr]; + } + } + //-- Get the chapter's display type + chapter.forEach(function(prop){ + var rendition = prop.replace("rendition:", ''); + var split = rendition.indexOf("-"); + var property, value; + + if(split != -1){ + property = rendition.slice(0, split); + value = rendition.slice(split+1); + + settings[property] = value; + } + }); + return settings; +}; + +/** +* Uses the settings to determine which Layout Method is needed +* Triggers events based on the method choosen +* Takes: Layout settings object +* Returns: String of appropriate for EPUBJS.Layout function +*/ +EPUBJS.Renderer.prototype.determineLayout = function(settings){ + // Default is layout: reflowable & spread: auto + var spreads = this.determineSpreads(this.minSpreadWidth); + var layoutMethod = spreads ? "ReflowableSpreads" : "Reflowable"; + var scroll = false; + + if(settings.layout === "pre-paginated") { + layoutMethod = "Fixed"; + scroll = true; + spreads = false; + } + + if(settings.layout === "reflowable" && settings.spread === "none") { + layoutMethod = "Reflowable"; + scroll = false; + spreads = false; + } + + if(settings.layout === "reflowable" && settings.spread === "both") { + layoutMethod = "ReflowableSpreads"; + scroll = false; + spreads = true; + } + + this.spreads = spreads; + this.render.scroll(scroll); + this.trigger("renderer:spreads", spreads); + return layoutMethod; +}; + +// Shortcut to trigger the hook before displaying the chapter +EPUBJS.Renderer.prototype.beforeDisplay = function(callback, renderer){ + this.triggerHooks("beforeChapterDisplay", callback, this); +}; + +// Update the renderer with the information passed by the layout +EPUBJS.Renderer.prototype.updatePages = function(layout){ + this.pageMap = this.mapPage(); + // this.displayedPages = layout.displayedPages; + + if (this.spreads) { + this.displayedPages = Math.ceil(this.pageMap.length / 2); + } else { + this.displayedPages = this.pageMap.length; + } + + // this.currentChapter.pages = layout.pageCount; + this.currentChapter.pages = this.pageMap.length; + + this._q.flush(); +}; + +// Apply the layout again and jump back to the previous cfi position +EPUBJS.Renderer.prototype.reformat = function(){ + var renderer = this; + var formated, pages; + if(!this.contents) return; + + spreads = this.determineSpreads(this.minSpreadWidth); + + // Only re-layout if the spreads have switched + if(spreads != this.spreads){ + this.spreads = spreads; + this.layoutMethod = this.determineLayout(this.layoutSettings); + this.layout = new EPUBJS.Layout[this.layoutMethod](); + } + + // Reset pages + this.chapterPos = 1; + this.render.page(1); + + // Give the css styles time to update + // clearTimeout(this.timeoutTillCfi); + // this.timeoutTillCfi = setTimeout(function(){ + + renderer.formated = renderer.layout.format(renderer.contents, renderer.render.width, renderer.render.height, renderer.gap); + renderer.render.setPageDimensions(renderer.formated.pageWidth, renderer.formated.pageHeight); + + pages = renderer.layout.calculatePages(); + renderer.updatePages(pages); + + //-- Go to current page after formating + if(renderer.currentLocationCfi){ + renderer.gotoCfi(renderer.currentLocationCfi); + } + // renderer.timeoutTillCfi = null; + +}; + +// Hide and show the render's container . +EPUBJS.Renderer.prototype.visible = function(bool){ + if(typeof(bool) === "undefined") { + return this.element.style.visibility; + } + + if(bool === true && !this.hidden){ + this.element.style.visibility = "visible"; + }else if(bool === false){ + this.element.style.visibility = "hidden"; + } +}; + +// Remove the render element and clean up listeners +EPUBJS.Renderer.prototype.remove = function() { + if(this.render.window) { + this.render.unload(); + this.render.window.removeEventListener("resize", this.resized); + this.removeEventListeners(); + this.removeSelectionListeners(); + } + + this.container.removeChild(this.element); +}; + +//-- STYLES + +EPUBJS.Renderer.prototype.applyStyles = function(styles) { + for (var style in styles) { + this.render.setStyle(style, styles[style]); + } +}; + +EPUBJS.Renderer.prototype.setStyle = function(style, val, prefixed){ + this.render.setStyle(style, val, prefixed); +}; + +EPUBJS.Renderer.prototype.removeStyle = function(style){ + this.render.removeStyle(style); +}; + +//-- HEAD TAGS +EPUBJS.Renderer.prototype.applyHeadTags = function(headTags) { + for ( var headTag in headTags ) { + this.render.addHeadTag(headTag, headTags[headTag]); + } +}; + +//-- NAVIGATION + +EPUBJS.Renderer.prototype.page = function(pg){ + if(!this.pageMap) { + console.warn("pageMap not set, queuing"); + this._q.enqueue("page", arguments); + return true; + } + + if(pg >= 1 && pg <= this.displayedPages){ + this.chapterPos = pg; + + this.render.page(pg); + this.visibleRangeCfi = this.getVisibleRangeCfi(); + this.currentLocationCfi = this.visibleRangeCfi.start; + this.trigger("renderer:locationChanged", this.currentLocationCfi); + this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); + + return true; + } + //-- Return false if page is greater than the total + return false; +}; + +// Short cut to find next page's cfi starting at the last visible element +/* +EPUBJS.Renderer.prototype.nextPage = function(){ + var pg = this.chapterPos + 1; + if(pg <= this.displayedPages){ + this.chapterPos = pg; + + this.render.page(pg); + + this.currentLocationCfi = this.getPageCfi(this.visibileEl); + this.trigger("renderer:locationChanged", this.currentLocationCfi); + + return true; + } + //-- Return false if page is greater than the total + return false; +}; +*/ +EPUBJS.Renderer.prototype.nextPage = function(){ + return this.page(this.chapterPos + 1); +}; + +EPUBJS.Renderer.prototype.prevPage = function(){ + return this.page(this.chapterPos - 1); +}; + +//-- Show the page containing an Element +EPUBJS.Renderer.prototype.pageByElement = function(el){ + var pg; + if(!el) return; + + pg = this.render.getPageNumberByElement(el); + this.page(pg); +}; + +// Jump to the last page of the chapter +EPUBJS.Renderer.prototype.lastPage = function(){ + if(this._moving) { + return this._q.enqueue("lastPage", arguments); + } + + this.page(this.displayedPages); +}; + +// Jump to the first page of the chapter +EPUBJS.Renderer.prototype.firstPage = function(){ + this.page(1); +}; + +//-- Find a section by fragement id +EPUBJS.Renderer.prototype.section = function(fragment){ + var el = this.doc.getElementById(fragment), + left, pg; + + if(el){ + this.pageByElement(el); + } + +}; + +EPUBJS.Renderer.prototype.firstElementisTextNode = function(node) { + var children = node.childNodes; + var leng = children.length; + + if(leng && + children[0] && // First Child + children[0].nodeType === 3 && // This is a textNodes + children[0].textContent.trim().length) { // With non whitespace or return charecters + return true; + } + return false; +}; + +// Walk the node tree from a start element to next visible element +EPUBJS.Renderer.prototype.walk = function(node, x, y) { + var r, children, leng, + startNode = node, + prevNode, + stack = [startNode]; + + var STOP = 10000, ITER=0; + + while(!r && stack.length) { + node = stack.shift(); + if( this.containsPoint(node, x, y) && this.firstElementisTextNode(node)) { + r = node; + } + + if(!r && node && node.childElementCount > 0){ + children = node.children; + if (children && children.length) { + leng = children.length ? children.length : 0; + } else { + return r; + } + for (var i = leng-1; i >= 0; i--) { + if(children[i] != prevNode) stack.unshift(children[i]); + } + } + + if(!r && stack.length === 0 && startNode && startNode.parentNode !== null){ + stack.push(startNode.parentNode); + prevNode = startNode; + startNode = startNode.parentNode; + } + + + ITER++; + if(ITER > STOP) { + console.error("ENDLESS LOOP"); + break; + } + + } + + return r; +}; + +// Checks if an element is on the screen +EPUBJS.Renderer.prototype.containsPoint = function(el, x, y){ + var rect; + var left; + if(el && typeof el.getBoundingClientRect === 'function'){ + rect = el.getBoundingClientRect(); + // console.log(el, rect, x, y); + + if( rect.width !== 0 && + rect.height !== 0 && // Element not visible + rect.left >= x && + x <= rect.left + rect.width) { + return true; + } + } + + return false; +}; + +EPUBJS.Renderer.prototype.textSprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if ( ! /^\s*$/.test(node.data) ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; + +EPUBJS.Renderer.prototype.sprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; + +EPUBJS.Renderer.prototype.mapPage = function(){ + var renderer = this; + var map = []; + var root = this.render.getBaseElement(); + var page = 1; + var width = this.layout.colWidth + this.layout.gap; + var offset = this.formated.pageWidth * (this.chapterPos-1); + var limit = (width * page) - offset;// (width * page) - offset; + var elLimit = 0; + var prevRange; + var cfi; + var check = function(node) { + var elPos; + var elRange; + var children = Array.prototype.slice.call(node.childNodes); + if (node.nodeType == Node.ELEMENT_NODE) { + // elPos = node.getBoundingClientRect(); + elRange = document.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + + if(!elPos || (elPos.width === 0 && elPos.height === 0)) { + return; + } + + //-- Element starts new Col + if(elPos.left > elLimit) { + children.forEach(function(node){ + if(node.nodeType == Node.TEXT_NODE && + node.textContent.trim().length) { + checkText(node); + } + }); + } + + //-- Element Spans new Col + if(elPos.right > elLimit) { + children.forEach(function(node){ + if(node.nodeType == Node.TEXT_NODE && + node.textContent.trim().length) { + checkText(node); + } + }); + } + } + + }; + var checkText = function(node){ + var ranges = renderer.splitTextNodeIntoWordsRanges(node); + ranges.forEach(function(range){ + var pos = range.getBoundingClientRect(); + + if(!pos || (pos.width === 0 && pos.height === 0)) { + return; + } + if(pos.left + pos.width < limit) { + if(!map[page-1]){ + range.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(range); + // map[page-1].start = cfi; + map.push({ start: cfi, end: null }); + } + } else { + if(prevRange){ + prevRange.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(prevRange); + map[map.length-1].end = cfi; + } + + range.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(range); + map.push({ + start: cfi, + end: null + }); + + page += 1; + limit = (width * page) - offset; + elLimit = limit; + } + + prevRange = range; + }); + + + }; + + this.sprint(root, check); + // this.textSprint(root, checkText); + + if(prevRange){ + prevRange.collapse(true); + + cfi = renderer.currentChapter.cfiFromRange(prevRange); + map[map.length-1].end = cfi; + } + + // Handle empty map + if(!map.length) { + range = this.doc.createRange(); + range.selectNodeContents(root); + range.collapse(true); + + cfi = renderer.currentChapter.cfiFromRange(range); + + map.push({ start: cfi, end: cfi }); + + } + + // clean up + prevRange = null; + ranges = null; + range = null; + root = null; + + return map; +}; + + +EPUBJS.Renderer.prototype.indexOfBreakableChar = function (text, startPosition) { + var whiteCharacters = "\x2D\x20\t\r\n\b\f"; + // '-' \x2D + // ' ' \x20 + + if (! startPosition) { + startPosition = 0; + } + + for (var i = startPosition; i < text.length; i++) { + if (whiteCharacters.indexOf(text.charAt(i)) != -1) { + return i; + } + } + + return -1; +}; + + +EPUBJS.Renderer.prototype.splitTextNodeIntoWordsRanges = function(node){ + var ranges = []; + var text = node.textContent.trim(); + var range; + var rect; + var list; + // jaroslaw.bielski@7bulls.com + // Usage of indexOf() function for space character as word delimiter + // is not sufficient in case of other breakable characters like \r\n- etc + pos = this.indexOfBreakableChar(text); + + if(pos === -1) { + range = this.doc.createRange(); + range.selectNodeContents(node); + return [range]; + } + + range = this.doc.createRange(); + range.setStart(node, 0); + range.setEnd(node, pos); + ranges.push(range); + + // jaroslaw.bielski@7bulls.com + // there was a word miss in case of one letter words + range = this.doc.createRange(); + range.setStart(node, pos+1); + + while ( pos != -1 ) { + + pos = this.indexOfBreakableChar(text, pos + 1); + if(pos > 0) { + + if(range) { + range.setEnd(node, pos); + ranges.push(range); + } + + range = this.doc.createRange(); + range.setStart(node, pos+1); + } + } + + if(range) { + range.setEnd(node, text.length); + ranges.push(range); + } + + return ranges; +}; + +EPUBJS.Renderer.prototype.rangePosition = function(range){ + var rect; + var list; + + list = range.getClientRects(); + + if(list.length) { + rect = list[0]; + return rect; + } + + return null; +}; + +/* +// Get the cfi of the current page +EPUBJS.Renderer.prototype.getPageCfi = function(prevEl){ + var range = this.doc.createRange(); + var position; + // TODO : this might need to take margin / padding into account? + var x = 1;//this.formated.pageWidth/2; + var y = 1;//;this.formated.pageHeight/2; + + range = this.getRange(x, y); + + // var test = this.doc.defaultView.getSelection(); + // var r = this.doc.createRange(); + // test.removeAllRanges(); + // r.setStart(range.startContainer, range.startOffset); + // r.setEnd(range.startContainer, range.startOffset + 1); + // test.addRange(r); + + return this.currentChapter.cfiFromRange(range); +}; +*/ + +// Get the cfi of the current page +EPUBJS.Renderer.prototype.getPageCfi = function(){ + var pg; + if (this.spreads) { + pg = this.chapterPos*2; + startRange = this.pageMap[pg-2]; + } else { + pg = this.chapterPos; + startRange = this.pageMap[pg-1]; + } + return this.pageMap[(this.chapterPos * 2) -1].start; +}; + +EPUBJS.Renderer.prototype.getRange = function(x, y, forceElement){ + var range = this.doc.createRange(); + var position; + forceElement = true; // temp override + if(typeof document.caretPositionFromPoint !== "undefined" && !forceElement){ + position = this.doc.caretPositionFromPoint(x, y); + range.setStart(position.offsetNode, position.offset); + } else if(typeof document.caretRangeFromPoint !== "undefined" && !forceElement){ + range = this.doc.caretRangeFromPoint(x, y); + } else { + this.visibileEl = this.findElementAfter(x, y); + range.setStart(this.visibileEl, 1); + } + + // var test = this.doc.defaultView.getSelection(); + // var r = this.doc.createRange(); + // test.removeAllRanges(); + // r.setStart(range.startContainer, range.startOffset); + // r.setEnd(range.startContainer, range.startOffset + 1); + // test.addRange(r); + return range; +}; + +/* +EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(prevEl){ + var startX = 0; + var startY = 0; + var endX = this.width-1; + var endY = this.height-1; + var startRange = this.getRange(startX, startY); + var endRange = this.getRange(endX, endY); //fix if carret not avail + var startCfi = this.currentChapter.cfiFromRange(startRange); + var endCfi; + if(endRange) { + endCfi = this.currentChapter.cfiFromRange(endRange); + } + + return { + start: startCfi, + end: endCfi || false + }; +}; +*/ + +EPUBJS.Renderer.prototype.pagesInCurrentChapter = function() { + var pgs; + var length; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + length = this.pageMap.length; + + if(this.spreads){ + pgs = Math.ceil(length / 2); + } else { + pgs = length; + } + + return pgs; +}; + +EPUBJS.Renderer.prototype.currentRenderedPage = function(){ + var pg; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + if (this.spreads && this.layout.pageCount > 1) { + pg = this.chapterPos*2; + } else { + pg = this.chapterPos; + } + + return pg; +}; + +EPUBJS.Renderer.prototype.getRenderedPagesLeft = function(){ + var pg; + var lastPage; + var pagesLeft; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + lastPage = this.pageMap.length; + + if (this.spreads) { + pg = this.chapterPos*2; + } else { + pg = this.chapterPos; + } + + pagesLeft = lastPage - pg; + return pagesLeft; + +}; + +EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(){ + var pg; + var startRange, endRange; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + if (this.spreads) { + pg = this.chapterPos*2; + startRange = this.pageMap[pg-2]; + endRange = startRange; + + if(this.layout.pageCount > 1) { + endRange = this.pageMap[pg-1]; + } + } else { + pg = this.chapterPos; + startRange = this.pageMap[pg-1]; + endRange = startRange; + } + + if(!startRange) { + console.warn("page range miss:", pg, this.pageMap); + startRange = this.pageMap[this.pageMap.length-1]; + endRange = startRange; + } + + return { + start: startRange.start, + end: endRange.end + }; +}; + +// Goto a cfi position in the current chapter +EPUBJS.Renderer.prototype.gotoCfi = function(cfi){ + var pg; + var marker; + var range; + + if(this._moving){ + return this._q.enqueue("gotoCfi", arguments); + } + + if(_.isString(cfi)){ + cfi = this.epubcfi.parse(cfi); + } + + if(typeof document.evaluate === 'undefined') { + marker = this.epubcfi.addMarker(cfi, this.doc); + if(marker) { + pg = this.render.getPageNumberByElement(marker); + // Must Clean up Marker before going to page + this.epubcfi.removeMarker(marker, this.doc); + this.page(pg); + } + } else { + range = this.epubcfi.generateRangeFromCfi(cfi, this.doc); + if(range) { + // jaroslaw.bielski@7bulls.com + // It seems that sometimes getBoundingClientRect() returns null for first page CFI in chapter. + // It is always reproductible if few consecutive chapters have only one page. + // NOTE: This is only workaround and the issue needs an deeper investigation. + // NOTE: Observed on Android 4.2.1 using WebView widget as HTML renderer (Asus TF300T). + var rect = range.getBoundingClientRect(); + if (rect) { + pg = this.render.getPageNumberByRect(rect); + + } else { + // Goto first page in chapter + pg = 1; + } + + this.page(pg); + + // Reset the current location cfi to requested cfi + this.currentLocationCfi = cfi.str; + } + } +}; + +// Walk nodes until a visible element is found +EPUBJS.Renderer.prototype.findFirstVisible = function(startEl){ + var el = startEl || this.render.getBaseElement(); + var found; + // kgolunski@7bulls.com + // Looks like an old API usage + // Set x and y as 0 to fullfill walk method API. + found = this.walk(el, 0, 0); + + if(found) { + return found; + }else{ + return startEl; + } + +}; +// TODO: remove me - unsused +EPUBJS.Renderer.prototype.findElementAfter = function(x, y, startEl){ + var el = startEl || this.render.getBaseElement(); + var found; + found = this.walk(el, x, y); + if(found) { + return found; + }else{ + return el; + } + +}; + +/* +EPUBJS.Renderer.prototype.route = function(hash, callback){ + var location = window.location.hash.replace('#/', ''); + if(this.useHash && location.length && location != this.prevLocation){ + this.show(location, callback); + this.prevLocation = location; + return true; + } + return false; +} + +EPUBJS.Renderer.prototype.hideHashChanges = function(){ + this.useHash = false; +} + +*/ + +EPUBJS.Renderer.prototype.resize = function(width, height, setSize){ + var spreads; + + this.width = width; + this.height = height; + + if(setSize !== false) { + this.render.resize(this.width, this.height); + } + + + + if(this.contents){ + this.reformat(); + } + + this.trigger("renderer:resized", { + width: this.width, + height: this.height + }); +}; + +//-- Listeners for events in the frame + +EPUBJS.Renderer.prototype.onResized = function(e) { + var width = this.container.clientWidth; + var height = this.container.clientHeight; + + this.resize(width, height, false); +}; + +EPUBJS.Renderer.prototype.addEventListeners = function(){ + if(!this.render.document) { + return; + } + this.listenedEvents.forEach(function(eventName){ + this.render.document.addEventListener(eventName, this.triggerEvent.bind(this), false); + }, this); + +}; + +EPUBJS.Renderer.prototype.removeEventListeners = function(){ + if(!this.render.document) { + return; + } + this.listenedEvents.forEach(function(eventName){ + this.render.document.removeEventListener(eventName, this.triggerEvent, false); + }, this); + +}; + +// Pass browser events +EPUBJS.Renderer.prototype.triggerEvent = function(e){ + this.trigger("renderer:"+e.type, e); +}; + +EPUBJS.Renderer.prototype.addSelectionListeners = function(){ + this.render.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); +}; + +EPUBJS.Renderer.prototype.removeSelectionListeners = function(){ + if(!this.render.document) { + return; + } + this.doc.removeEventListener("selectionchange", this.onSelectionChange, false); +}; + +EPUBJS.Renderer.prototype.onSelectionChange = function(e){ + if (this.selectionEndTimeout) { + clearTimeout(this.selectionEndTimeout); + } + this.selectionEndTimeout = setTimeout(function() { + this.selectedRange = this.render.window.getSelection(); + this.trigger("renderer:selected", this.selectedRange); + }.bind(this), 500); +}; + + +//-- Spreads + +EPUBJS.Renderer.prototype.setMinSpreadWidth = function(width){ + this.minSpreadWidth = width; + this.spreads = this.determineSpreads(width); +}; + +EPUBJS.Renderer.prototype.determineSpreads = function(cutoff){ + if(this.isForcedSingle || !cutoff || this.width < cutoff) { + return false; //-- Single Page + }else{ + return true; //-- Double Page + } +}; + +EPUBJS.Renderer.prototype.forceSingle = function(bool){ + if(bool) { + this.isForcedSingle = true; + // this.spreads = false; + } else { + this.isForcedSingle = false; + // this.spreads = this.determineSpreads(this.minSpreadWidth); + } +}; + +EPUBJS.Renderer.prototype.setGap = function(gap){ + this.gap = gap; //-- False == auto gap +}; + +//-- Content Replacements + +EPUBJS.Renderer.prototype.replace = function(query, func, finished, progress){ + var items = this.contents.querySelectorAll(query), + resources = Array.prototype.slice.call(items), + count = resources.length; + + + if(count === 0) { + finished(false); + return; + } + resources.forEach(function(item){ + var called = false; + var after = function(result, full){ + if(called === false) { + count--; + if(progress) progress(result, full, count); + if(count <= 0 && finished) finished(true); + called = true; + } + }; + + func(item, after); + + }.bind(this)); + +}; + +EPUBJS.Renderer.prototype.replaceWithStored = function(query, attr, func, callback) { + var _oldUrls, + _newUrls = {}, + _store = this.currentChapter.store, + _cache = this.caches[query], + _uri = EPUBJS.core.uri(this.currentChapter.absolute), + _chapterBase = _uri.base, + _attr = attr, + _wait = 2000, + progress = function(url, full, count) { + _newUrls[full] = url; + }, + finished = function(notempty) { + if(callback) callback(); + + _.each(_oldUrls, function(url){ + _store.revokeUrl(url); + }); + + _cache = _newUrls; + }; + + if(!_store) return; + + if(!_cache) _cache = {}; + _oldUrls = _.clone(_cache); + + this.replace(query, function(link, done){ + var src = link.getAttribute(_attr), + full = EPUBJS.core.resolveUrl(_chapterBase, src); + + var replaceUrl = function(url) { + var timeout; + link.onload = function(){ + clearTimeout(timeout); + done(url, full); + }; + + link.onerror = function(e){ + clearTimeout(timeout); + done(url, full); + console.error(e); + }; + + if(query == "image") { + //-- SVG needs this to trigger a load event + link.setAttribute("externalResourcesRequired", "true"); + } + + if(query == "link[href]" && link.getAttribute("rel") !== "stylesheet") { + //-- Only Stylesheet links seem to have a load events, just continue others + done(url, full); + } + + link.setAttribute(_attr, url); + + //-- If elements never fire Load Event, should continue anyways + timeout = setTimeout(function(){ + done(url, full); + }, _wait); + + }; + + if(full in _oldUrls){ + replaceUrl(_oldUrls[full]); + _newUrls[full] = _oldUrls[full]; + delete _oldUrls[full]; + }else{ + func(_store, full, replaceUrl, link); + } + + }, finished, progress); +}; + +//-- Enable binding events to Renderer +RSVP.EventTarget.mixin(EPUBJS.Renderer.prototype); + +var EPUBJS = EPUBJS || {}; +EPUBJS.replace = {}; + +//-- Replaces the relative links within the book to use our internal page changer +EPUBJS.replace.hrefs = function(callback, renderer){ + var book = this; + var replacments = function(link, done){ + var href = link.getAttribute("href"), + isRelative = href.search("://"), + directory, + relative, + location; + + if(isRelative != -1){ + + link.setAttribute("target", "_blank"); + + }else{ + // Links may need to be resolved, such as ../chp1.xhtml + directory = EPUBJS.core.uri(renderer.render.window.location.href).directory; + if(directory) { + relative = EPUBJS.core.resolveUrl(directory, href); + } else { + relative = href; + } + + link.onclick = function(){ + book.goto(relative); + return false; + }; + + } + done(); + + }; + + renderer.replace("a[href]", replacments, callback); + +}; + +EPUBJS.replace.head = function(callback, renderer) { + + renderer.replaceWithStored("link[href]", "href", EPUBJS.replace.links, callback); + +}; + + +//-- Replaces assets src's to point to stored version if browser is offline +EPUBJS.replace.resources = function(callback, renderer){ + //srcs = this.doc.querySelectorAll('[src]'); + renderer.replaceWithStored("[src]", "src", EPUBJS.replace.srcs, callback); + +}; + +EPUBJS.replace.svg = function(callback, renderer) { + + renderer.replaceWithStored("image", "xlink:href", function(_store, full, done){ + _store.getUrl(full).then(done); + }, callback); + +}; + +EPUBJS.replace.srcs = function(_store, full, done){ + + _store.getUrl(full).then(done); + +}; + +//-- Replaces links in head, such as stylesheets - link[href] +EPUBJS.replace.links = function(_store, full, done, link){ + //-- Handle replacing urls in CSS + if(link.getAttribute("rel") === "stylesheet") { + EPUBJS.replace.stylesheets(_store, full).then(function(url, full){ + // done + setTimeout(function(){ + done(url, full); + }, 5); //-- Allow for css to apply before displaying chapter + }); + }else{ + _store.getUrl(full).then(done); + } +}; + +EPUBJS.replace.stylesheets = function(_store, full) { + var deferred = new RSVP.defer(); + + if(!_store) return; + + _store.getText(full).then(function(text){ + var url; + + EPUBJS.replace.cssUrls(_store, full, text).then(function(newText){ + var _URL = window.URL || window.webkitURL || window.mozURL; + + var blob = new Blob([newText], { "type" : "text\/css" }), + url = _URL.createObjectURL(blob); + + deferred.resolve(url); + + }, function(e) { + console.error(e); + }); + + }); + + return deferred.promise; +}; + +EPUBJS.replace.cssUrls = function(_store, base, text){ + var deferred = new RSVP.defer(), + promises = [], + matches = text.match(/url\(\'?\"?([^\'|^\"^\)]*)\'?\"?\)/g); + + if(!_store) return; + + if(!matches){ + deferred.resolve(text); + return deferred.promise; + } + + matches.forEach(function(str){ + var full = EPUBJS.core.resolveUrl(base, str.replace(/url\(|[|\)|\'|\"]/g, '')); + var replaced = _store.getUrl(full).then(function(url){ + text = text.replace(str, 'url("'+url+'")'); + }); + + promises.push(replaced); + }); + + RSVP.all(promises).then(function(){ + deferred.resolve(text); + }); + + return deferred.promise; +}; + + + +EPUBJS.Unarchiver = function(url){ + + this.loadLib(); + this.urlCache = {}; + +}; + +//-- Load the zip lib and set the workerScriptsPath +EPUBJS.Unarchiver.prototype.loadLib = function(callback){ + if(typeof(JSZip) == "undefined") console.error("JSZip lib not loaded"); +}; + +EPUBJS.Unarchiver.prototype.openZip = function(zipUrl, callback){ + var deferred = new RSVP.defer(); + + return EPUBJS.core.request(zipUrl, "binary").then(function(data){ + this.zip = new JSZip(data); + }.bind(this)); +}; + +EPUBJS.Unarchiver.prototype.getXml = function(url, encoding){ + + return this.getText(url, encoding). + then(function(text){ + var parser = new DOMParser(); + return parser.parseFromString(text, "text/xml"); + }); + +}; + +EPUBJS.Unarchiver.prototype.getUrl = function(url, mime){ + var unarchiver = this; + var deferred = new RSVP.defer(); + var decodededUrl = window.decodeURIComponent(url); + var entry = this.zip.file(decodededUrl); + var _URL = window.URL || window.webkitURL || window.mozURL; + var tempUrl; + + if(!entry) { + deferred.reject({ + message : "File not found in the epub: " + url, + stack : new Error().stack + }); + return deferred.promise; + } + + if(url in this.urlCache) { + deferred.resolve(this.urlCache[url]); + return deferred.promise; + } + + blob = new Blob([entry.asUint8Array()], {type : mime || this.zip.getMimeType(entry.name)}); + + tempUrl = _URL.createObjectURL(blob); + deferred.resolve(tempUrl); + unarchiver.urlCache[url] = tempUrl; + + return deferred.promise; +}; + +EPUBJS.Unarchiver.prototype.getText = function(url, encoding){ + var unarchiver = this; + var deferred = new RSVP.defer(); + var decodededUrl = window.decodeURIComponent(url); + var entry = this.zip.file(decodededUrl); + var _URL = window.URL || window.webkitURL || window.mozURL; + + if(!entry) { + console.warn("File not found in the contained epub:", url); + return deferred.promise; + } + + text = entry.asText(); + deferred.resolve(text); + + return deferred.promise; +}; + +EPUBJS.Unarchiver.prototype.revokeUrl = function(url){ + var _URL = window.URL || window.webkitURL || window.mozURL; + var fromCache = unarchiver.urlCache[url]; + if(fromCache) _URL.revokeObjectURL(fromCache); +}; + +EPUBJS.Unarchiver.prototype.failed = function(error){ + console.error(error); +}; + +EPUBJS.Unarchiver.prototype.afterSaved = function(error){ + this.callback(); +}; + +EPUBJS.Unarchiver.prototype.toStorage = function(entries){ + var timeout = 0, + delay = 20, + that = this, + count = entries.length; + + function callback(){ + count--; + if(count === 0) that.afterSaved(); + } + + entries.forEach(function(entry){ + + setTimeout(function(entry){ + that.saveEntryFileToStorage(entry, callback); + }, timeout, entry); + + timeout += delay; + }); + + console.log("time", timeout); + + //entries.forEach(this.saveEntryFileToStorage.bind(this)); +}; + +// EPUBJS.Unarchiver.prototype.saveEntryFileToStorage = function(entry, callback){ +// var that = this; +// entry.getData(new zip.BlobWriter(), function(blob) { +// EPUBJS.storage.save(entry.filename, blob, callback); +// }); +// }; + +//# sourceMappingURL=epub.js.map \ No newline at end of file diff --git a/epub.js/epub.js.map b/epub.js/epub.js.map new file mode 100644 index 0000000..dd40312 --- /dev/null +++ b/epub.js/epub.js.map @@ -0,0 +1 @@ +{"version":3,"file":"epub.min.js","sources":["epub.js"],"names":["n","this","t","_","r","e","Array","prototype","u","Object","i","Function","a","push","o","slice","c","concat","l","toString","f","hasOwnProperty","s","forEach","p","map","h","reduce","v","reduceRight","d","filter","g","every","m","some","y","indexOf","b","lastIndexOf","x","isArray","keys","j","bind","w","_wrapped","exports","module","VERSION","A","each","length","call","has","collect","O","foldl","inject","arguments","TypeError","foldr","find","detect","E","select","reject","all","identity","any","contains","include","invoke","isFunction","apply","pluck","where","isEmpty","findWhere","max","Math","computed","value","min","shuffle","random","k","sortBy","index","criteria","sort","F","groupBy","countBy","sortedIndex","toArray","values","size","first","head","take","initial","last","rest","tail","drop","compact","R","flatten","without","difference","uniq","unique","union","intersection","zip","object","range","ceil","partial","bindAll","functions","memoize","delay","setTimeout","defer","throttle","Date","clearTimeout","debounce","once","wrap","compose","after","pairs","invert","methods","extend","pick","omit","defaults","clone","isObject","tap","I","source","global","multiline","ignoreCase","constructor","pop","isEqual","isString","isElement","nodeType","isArguments","isFinite","isNaN","parseFloat","isNumber","isBoolean","isNull","isUndefined","noConflict","times","floor","M","escape","&","<",">","\"","'","/","unescape","S","RegExp","join","replace","result","mixin","D","N","uniqueId","templateSettings","evaluate","interpolate","T","q","\\","\r","\n","\t","
","
","B","template","variable","chain","_chain","define","requireModule","require","requirejs","registry","seen","name","deps","callback","resolve","child","charAt","parts","split","parentBase","part","_eak_seen","Error","mod","reified","__dependency1__","__exports__","Promise","array","label","__dependency2__","fulfilled","state","rejected","reason","isNonThenable","entries","fulfilledResolver","resolveAll","rejectedResolver","results","remaining","entry","cast","then","useNextTick","process","nextTick","flush","useMutationObserver","iterations","observer","BrowserMutationObserver","node","document","createTextNode","observe","characterData","data","useSetTimeout","queue","tuple","arg","scheduleFlush","browserGlobal","window","MutationObserver","WebKitMutationObserver","configure","config","on","EventTarget","instrument","deferred","promise","callbacks","callbacksFor","_promiseCallbacks","off","trigger","undefined","eventName","allCallbacks","splice","options","__dependency3__","promises","filterFn","filterResults","valuesLen","filtered","keysOf","fulfilledTo","property","onRejection","now","guid","_guidKey","_id","detail","_detail","childGuid","_label","timeStamp","stack","error","mapFn","resultLen","mappedResults","makeNodeCallbackFor","nodeFunc","binding","nodeArgs","thisArg","__dependency4__","__dependency5__","__dependency6__","__dependency7__","__dependency8__","__dependency9__","noop","resolver","counter","_subscribers","invokeResolver","resolvePromise","rejectPromise","subscribe","parent","onFulfillment","subscribers","FULFILLED","REJECTED","publish","settled","invokeCallback","succeeded","failed","hasCallback","handleThenable","resolved","objectOrFunction","val","fulfill","_state","PENDING","SEALED","async","publishFulfillment","publishRejection","_onerror","race","Resolve","Reject","guidKey","thenPromise","catch","finally","Constructor","fulfillmentAt","pending","getTime","prop","__dependency10__","__dependency11__","__dependency12__","__dependency13__","__dependency14__","__dependency15__","denodeify","allSettled","hash","rethrow","asap","__PROMISE_INSTRUMENTATION__","RSVP","EPUBJS","plugins","filePath","Render","root","previousEpub","ePub","bookPath","Book","amd","settings","bookKey","packageUrl","storage","fromStorage","saved","online","contained","width","height","layoutOveride","orientation","minSpreadWidth","gap","version","restore","reload","goto","styles","headTags","withCredentials","render_method","EPUBJSVERSION","spinePos","stored","navigator","onLine","networkListeners","store","fileStorage","ready","manifest","spine","metadata","cover","toc","pageList","readyPromises","pagination","Pagination","pageListReady","_ready","isRendered","_q","core","_rendering","_displayQ","_moving","_gotoQ","renderer","Renderer","setMinSpreadWidth","setGap","listenToRenderer","defer_opened","opened","open","addEventListener","unload","forceReload","epubpackage","book","bookUrl","urlFrom","isContained","unarchive","loadPackage","localStorage","packageXml","identifier","packageIdentifier","restored","unpack","storeOffline","_registerReplacements","_containerPath","parse","Parser","containerPath","loadXml","containerXml","container","paths","contentsPath","basePath","packagePath","encoding","console","contents","packageContents","spineIndexByURL","generateBookKey","globalLayoutProperties","parseLayoutProperties","coverPath","spineNodeIndex","navPath","navUrl","navHtml","nav","epubcfi","EpubCFI","wait","pg","cfi","generateCfiFromHref","href","tocPath","tocUrl","tocXml","createHiddenRender","_width","_height","hiddenContainer","hiddenEl","box","element","getBoundingClientRect","forceSingle","createElement","style","visibility","overflow","appendChild","initialize","generatePageList","pager","spineLength","currentPage","nextChapter","chapter","next","done","Chapter","displayChapter","pageMap","item","start","page","spreads","end","remove","removeChild","generatePagination","defered","loadPagination","pagelistJSON","JSON","getPageList","getMetadata","getToc","Events","startPage","endPage","percent","pageRange","pageFromCfi","percentageFromPage","anchorPage","percentage","loadChange","url","uri","currentChapter","absolute","path","warn","filename","unlistenToRenderer","getXml","request","base","protocol","fromRoot","location","origin","host","baseTag","getElementsByTagName","resolveUrl","pathname","Unarchiver","openZip","extension","isSaved","storedSettings","getItem","saveContents","setItem","stringify","removeSavedContents","removeItem","renderTo","elem","rendered","getEl","_rendered","startDisplay","display","previousLocationCfi","gotoCfi","fetch","fromStore","len","clearSaved","chap","render","pos","enqueue","lastPage","preloadNextChapter","dequeue","message","nextPage","prevPage","prev","prevChapter","linear","getCurrentLocationCfi","currentLocationCfi","target","gotoPercentage","parseInt","substring","gotoPage","gotoHref","cfiString","spineItem","section","relativeURL","firstPage","cfiFromPage","pageFromPercentage","assets","batch","availableOffline","setStyle","prefixed","noreflow","reformat","removeStyle","addHeadTag","tag","attrs","useSpreads","use","_use","force","load","destroy","removeEventListener","applyStyles","applyHeadTags","registerHook","hrefs","_needsAssetReplacement","resources","svg","getStorageType","layout","spread","event","spineObject","id","cfiBase","properties","manifestProperties","pages","loaded","_store","get","xml","setDocument","doc","serializer","XMLSerializer","setAttribute","insertBefore","firstChild","serializeToString","tempUrl","getUrl","setPages","num","getPages","getID","ID","revokeUrl","_document","namespaceURI","doctype","implementation","createDocument","importNode","documentElement","cfiFromRange","_range","startXpath","endXpath","startContainer","endContainer","cleanEndTextContent","getElementXPath","nsResolver","XPathResult","FIRST_ORDERED_NODE_TYPE","singleNodeValue","collapsed","createRange","setStart","startOffset","setEnd","endOffset","log","cleanStartTextContent","cleanStringForXpath","textContent","generateCfiFromRange","_query","matches","query","toLowerCase","excerpt","text","limit","textSprint","func","treeWalker","createTreeWalker","NodeFilter","SHOW_TEXT","acceptNode","test","FILTER_ACCEPT","FILTER_REJECT","nextNode","getElementById","getEls","classes","getElementsByClassName","type","handler","readyState","DONE","status","responseXML","response","supportsURL","Blob","URL","BLOB_RESPONSE","xhr","XMLHttpRequest","xhrPrototype","defineProperty","onreadystatechange","responseType","setRequestHeader","overrideMimeType","send","obj","arr","member","newitm","ident","withoutProtocol","dot","firstSlash","directory","fragment","blob","doubleSlash","search","folder","lastSlash","dataURLToBlob","dataURL","contentType","raw","rawLength","uInt8Array","BASE64_MARKER","atob","Uint8Array","charCodeAt","addScript","src","onload","body","addScripts","srcArr","total","curr","cb","addCss","rel","unprefixed","vendors","upper","toUpperCase","segments","folders","uuid","insert","compareFunction","locationOf","_start","_end","compared","pivot","indexOfSorted","_scope","scope","funcName","args","context","inwait","shift","clear","getElementTreeXPath","nodeName","tagName","pathIndex","isXhtml","ownerDocument","getAttribute","Node","TEXT_NODE","indexOfTextNode","parentNode","sibling","previousSibling","DOCUMENT_TYPE_NODE","prefix","ns","xhtml","epub","str","match","textNode","sib","children","childNodes","cfiStr","generateChapterComponent","_spineNodeIndex","_pos","generatePathComponent","steps","segment","generateCfiFromElement","pathTo","unshift","getChapterComponent","splitStr","getPathComponent","pathComponent","getCharecterOffsetComponent","chapSegment","chapterComponent","charecterOffsetComponent","assertion","chapId","endInt","parseStep","has_brackets","spineId","step","characterOffset","textLocationAssertion","addMarker","_doc","_marker","lastStep","marker","createMarker","findParent","splitText","classList","add","removeMarker","nextSib","nextSibling","prevSib","sections","compare","cfiOne","cfiTwo","generateCfiFromTextNode","anchor","offset","generateCfiFromRangeAnchor","anchorNode","anchorOffset","startElement","startSteps","startPath","startIndex","endElement","endSteps","endPath","endIndex","generateXpathFromSteps","xpath","position","generateRangeFromCfi","textLength","debug","selectNode","el","events","createEvent","tell","listen","deafen","listenUntil","evt","CustomEvent","msg","dispatchEvent","bindto","OnEvt","OffEvt","unlisten","hooks","Hooks","getHooks","plugs","plugType","hook","toAdd","toFront","triggerHooks","passed","countdown","count","register","Layout","Reflowable","spreadWidth","format","_gap","columnAxis","columnGap","columnWidth","columnFill","colWidth","pageWidth","pageHeight","calculatePages","totalWidth","displayedPages","scrollWidth","pageCount","ReflowableSpreads","divisor","fullWidth","Fixed","content","viewport","querySelector","hasAttribute","locations","totalPages","round","percentageFromCfi","baseUrl","rootfile","fullpath","xmlEncoding","metadataNode","getElementText","manifestNode","spineNode","findNavPath","findTocPath","findCoverPath","tocId","bookTitle","creator","description","pubdate","publisher","language","rights","modified_date","querySelectorText","found","getElementsByTagNameNS","nodeValue","manifestXml","selected","querySelectorAll","items","spineXml","Id","props","propArray","manifestProps","manifestPropArray","vert","bookSpine","findListItems","findAnchorOrSpan","getTOC","list","nodes","subitems","idCounter","navEl","snapshot","ORDERED_NODE_SNAPSHOT_TYPE","snapshotLength","snapshotItem","navLabel","navMap","isCfi","Iframe","iframe","docEl","bodyEl","leftPos","create","scrolling","seamless","border","contentDocument","headEl","contentWindow","resized","margin","onerror","resize","totalHeight","scrollHeight","setPageDimensions","setLeft","defaultView","scrollTo","tagEl","attr","getPageNumberByElement","left","getPageNumberByRect","boundingClientRect","getBaseElement","isElementVisible","rect","scroll","bool","renderMethod","hidden","listenedEvents","upEvent","downEvent","caches","isForcedSingle","onResized","layoutSettings","initWidth","initHeight","clientWidth","clientHeight","globalLayout","removeEventListeners","removeSelectionListeners","chapterPos","currentChapterCfiBase","reconcileLayoutSettings","layoutMethod","determineLayout","visible","formated","addEventListeners","addSelectionListeners","beforeDisplay","queued","updatePages","visibleRangeCfi","getVisibleRangeCfi","rendition","determineSpreads","mapPage","headTag","pageByElement","firstElementisTextNode","leng","trim","walk","prevNode","startNode","STOP","ITER","containsPoint","childElementCount","sprint","SHOW_ELEMENT","prevRange","elLimit","check","elPos","elRange","ELEMENT_NODE","selectNodeContents","checkText","right","ranges","splitTextNodeIntoWordsRanges","collapse","indexOfBreakableChar","startPosition","whiteCharacters","rangePosition","getClientRects","getPageCfi","startRange","getRange","forceElement","caretPositionFromPoint","caretRangeFromPoint","visibileEl","findElementAfter","offsetNode","pagesInCurrentChapter","pgs","currentRenderedPage","getRenderedPagesLeft","pagesLeft","endRange","findFirstVisible","startEl","setSize","triggerEvent","onSelectionChange","selectionEndTimeout","selectedRange","getSelection","cutoff","finished","progress","called","full","replaceWithStored","_oldUrls","_newUrls","_cache","_uri","_chapterBase","_attr","_wait","link","replaceUrl","timeout","replacments","relative","isRelative","onclick","links","srcs","stylesheets","getText","cssUrls","newText","_URL","webkitURL","mozURL","createObjectURL","replaced","loadLib","urlCache","zipUrl","JSZip","parser","DOMParser","parseFromString","mime","unarchiver","decodededUrl","decodeURIComponent","file","asUint8Array","getMimeType","asText","fromCache","revokeObjectURL","afterSaved","toStorage","that","saveEntryFileToStorage"],"mappings":"CAAA,WAAY,GAAIA,GAAEC,KAAKC,EAAEF,EAAEG,EAAEC,KAAKC,EAAEC,MAA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git a/epub.js/epub.min.js b/epub.js/epub.min.js new file mode 100644 index 0000000..cb42010 --- /dev/null +++ b/epub.js/epub.min.js @@ -0,0 +1,7462 @@ +(function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,h=e.reduce,v=e.reduceRight,d=e.filter,g=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.4";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduce===h)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduceRight===v)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:d&&n.filter===d?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:g&&n.every===g?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?n.indexOf(t)!=-1:E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2),e=w.isFunction(t);return w.map(n,function(n){return(e?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t,r){return w.isEmpty(t)?r?null:[]:w[r?"find":"filter"](n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.findWhere=function(n,t){return w.where(n,t,!0)},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var k=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=k(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||r===void 0)return 1;if(e>r||e===void 0)return-1}return n.indexi;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFunction(t)&&(e=r,r=t,t=!1);var u=r?w.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:w.contains(a,r))||(a.push(r),i.push(n[e]))}),i},w.union=function(){return w.uniq(c.apply(e,arguments))},w.intersection=function(n){var t=o.call(arguments,1);return w.filter(w.uniq(n),function(n){return w.every(t,function(t){return w.indexOf(t,n)>=0})})},w.difference=function(n){var t=c.apply(e,o.call(arguments,1));return w.filter(n,function(n){return!w.contains(t,n)})},w.zip=function(){for(var n=o.call(arguments),t=w.max(w.pluck(n,"length")),r=Array(t),e=0;t>e;e++)r[e]=w.pluck(n,""+e);return r},w.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},w.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=w.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},w.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},w.range=function(n,t,r){1>=arguments.length&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=Array(e);e>u;)i[u++]=n,n+=r;return i},w.bind=function(n,t){if(n.bind===j&&j)return j.apply(n,o.call(arguments,1));var r=o.call(arguments,2);return function(){return n.apply(t,r.concat(o.call(arguments)))}},w.partial=function(n){var t=o.call(arguments,1);return function(){return n.apply(this,t.concat(o.call(arguments)))}},w.bindAll=function(n){var t=o.call(arguments,1);return 0===t.length&&(t=w.functions(n)),A(t,function(t){n[t]=w.bind(n[t],n)}),n},w.memoize=function(n,t){var r={};return t||(t=w.identity),function(){var e=t.apply(this,arguments);return w.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},w.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},w.defer=function(n){return w.delay.apply(w,[n,1].concat(o.call(arguments,1)))},w.throttle=function(n,t){var r,e,u,i,a=0,o=function(){a=new Date,u=null,i=n.apply(r,e)};return function(){var c=new Date,l=t-(c-a);return r=this,e=arguments,0>=l?(clearTimeout(u),u=null,a=c,i=n.apply(r,e)):u||(u=setTimeout(o,l)),i}},w.debounce=function(n,t,r){var e,u;return function(){var i=this,a=arguments,o=function(){e=null,r||(u=n.apply(i,a))},c=r&&!e;return clearTimeout(e),e=setTimeout(o,t),c&&(u=n.apply(i,a)),u}},w.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},w.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},w.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},w.after=function(n,t){return 0>=n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},w.keys=_||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)w.has(n,r)&&(t[t.length]=r);return t},w.values=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push(n[r]);return t},w.pairs=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push([r,n[r]]);return t},w.invert=function(n){var t={};for(var r in n)w.has(n,r)&&(t[n[r]]=r);return t},w.functions=w.methods=function(n){var t=[];for(var r in n)w.isFunction(n[r])&&t.push(r);return t.sort()},w.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},w.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},w.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)w.contains(r,u)||(t[u]=n[u]);return t},w.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)null==n[r]&&(n[r]=t[r])}),n},w.clone=function(n){return w.isObject(n)?w.isArray(n)?n.slice():w.extend({},n):n},w.tap=function(n,t){return t(n),n};var I=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof w&&(n=n._wrapped),t instanceof w&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==t+"";case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;r.push(n),e.push(t);var a=0,o=!0;if("[object Array]"==u){if(a=n.length,o=a==t.length)for(;a--&&(o=I(n[a],t[a],r,e)););}else{var c=n.constructor,f=t.constructor;if(c!==f&&!(w.isFunction(c)&&c instanceof c&&w.isFunction(f)&&f instanceof f))return!1;for(var s in n)if(w.has(n,s)&&(a++,!(o=w.has(t,s)&&I(n[s],t[s],r,e))))break;if(o){for(s in t)if(w.has(t,s)&&!a--)break;o=!a}}return r.pop(),e.pop(),o};w.isEqual=function(n,t){return I(n,t,[],[])},w.isEmpty=function(n){if(null==n)return!0;if(w.isArray(n)||w.isString(n))return 0===n.length;for(var t in n)if(w.has(n,t))return!1;return!0},w.isElement=function(n){return!(!n||1!==n.nodeType)},w.isArray=x||function(n){return"[object Array]"==l.call(n)},w.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){w["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),w.isArguments(arguments)||(w.isArguments=function(n){return!(!n||!w.has(n,"callee"))}),"function"!=typeof/./&&(w.isFunction=function(n){return"function"==typeof n}),w.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},w.isNaN=function(n){return w.isNumber(n)&&n!=+n},w.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},w.isNull=function(n){return null===n},w.isUndefined=function(n){return n===void 0},w.has=function(n,t){return f.call(n,t)},w.noConflict=function(){return n._=t,this},w.identity=function(n){return n},w.times=function(n,t,r){for(var e=Array(n),u=0;n>u;u++)e[u]=t.call(r,u);return e},w.random=function(n,t){return null==t&&(t=n,n=0),n+Math.floor(Math.random()*(t-n+1))};var M={escape:{"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"}};M.unescape=w.invert(M.escape);var S={escape:RegExp("["+w.keys(M.escape).join("")+"]","g"),unescape:RegExp("("+w.keys(M.unescape).join("|")+")","g")};w.each(["escape","unescape"],function(n){w[n]=function(t){return null==t?"":(""+t).replace(S[n],function(t){return M[n][t]})}}),w.result=function(n,t){if(null==n)return null;var r=n[t];return w.isFunction(r)?r.call(n):r},w.mixin=function(n){A(w.functions(n),function(t){var r=w[t]=n[t];w.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),D.call(this,r.apply(w,n))}})};var N=0;w.uniqueId=function(n){var t=++N+"";return n?n+t:t},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var T=/(.)^/,q={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},B=/\\|'|\r|\n|\t|\u2028|\u2029/g;w.template=function(n,t,r){var e;r=w.defaults({},r,w.templateSettings);var u=RegExp([(r.escape||T).source,(r.interpolate||T).source,(r.evaluate||T).source].join("|")+"|$","g"),i=0,a="__p+='";n.replace(u,function(t,r,e,u,o){return a+=n.slice(i,o).replace(B,function(n){return"\\"+q[n]}),r&&(a+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(a+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),u&&(a+="';\n"+u+"\n__p+='"),i=o+t.length,t}),a+="';\n",r.variable||(a="with(obj||{}){\n"+a+"}\n"),a="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+a+"return __p;\n";try{e=Function(r.variable||"obj","_",a)}catch(o){throw o.source=a,o}if(t)return e(t,w);var c=function(n){return e.call(this,n,w)};return c.source="function("+(r.variable||"obj")+"){\n"+a+"}",c},w.chain=function(n){return w(n).chain()};var D=function(n){return this._chain?w(n).chain():n};w.mixin(w),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];w.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],D.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];w.prototype[n]=function(){return D.call(this,t.apply(this._wrapped,arguments))}}),w.extend(w.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this); +(function(global) { +var define, requireModule, require, requirejs; + +(function() { + var registry = {}, seen = {}; + + define = function(name, deps, callback) { + registry[name] = { deps: deps, callback: callback }; + }; + + requirejs = require = requireModule = function(name) { + requirejs._eak_seen = registry; + + if (seen[name]) { return seen[name]; } + seen[name] = {}; + + if (!registry[name]) { + throw new Error("Could not find module " + name); + } + + var mod = registry[name], + deps = mod.deps, + callback = mod.callback, + reified = [], + exports; + + for (var i=0, l=deps.length; i 1; + }; + + RSVP.filter(promises, filterFn).then(function(result){ + // result is [ 2, 3 ] + }); + ``` + + If any of the `promises` given to `RSVP.filter` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + var filterFn = function(item){ + return item > 1; + }; + + RSVP.filter(promises, filterFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "2" + }); + ``` + + `RSVP.filter` will also wait for any promises returned from `filterFn`. + For instance, you may want to fetch a list of users then return a subset + of those users based on some asynchronous operation: + + ```javascript + + var alice = { name: 'alice' }; + var bob = { name: 'bob' }; + var users = [ alice, bob ]; + + var promises = users.map(function(user){ + return RSVP.resolve(user); + }); + + var filterFn = function(user){ + // Here, Alice has permissions to create a blog post, but Bob does not. + return getPrivilegesForUser(user).then(function(privs){ + return privs.can_create_blog_post === true; + }); + }; + RSVP.filter(promises, filterFn).then(function(users){ + // true, because the server told us only Alice can create a blog post. + users.length === 1; + // false, because Alice is the only user present in `users` + users[0] === bob; + }); + ``` + + @method filter + @for RSVP + @param {Array} promises + @param {Function} filterFn - function to be called on each resolved value to + filter the final results. + @param {String} label optional string describing the promise. Useful for + tooling. + @return {Promise} + */ + function filter(promises, filterFn, label) { + if (!isArray(promises)) { + throw new TypeError('You must pass an array to filter.'); + } + + if (!isFunction(filterFn)){ + throw new TypeError("You must pass a function to filter's second argument."); + } + + return all(promises, label).then(function(values){ + return map(promises, filterFn, label).then(function(filterResults){ + var i, + valuesLen = values.length, + filtered = []; + + for (i = 0; i < valuesLen; i++){ + if(filterResults[i]) filtered.push(values[i]); + } + return filtered; + }); + }); + } + + __exports__["default"] = filter; + }); +define("rsvp/hash", + ["./promise","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var isNonThenable = __dependency2__.isNonThenable; + var keysOf = __dependency2__.keysOf; + + /** + `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array + for its `promises` argument. + + Returns a promise that is fulfilled when all the given promises have been + fulfilled, or rejected if any of them become rejected. The returned promise + is fulfilled with a hash that has the same key names as the `promises` object + argument. If any of the values in the object are not promises, they will + simply be copied over to the fulfilled object. + + Example: + + ```javascript + var promises = { + myPromise: RSVP.resolve(1), + yourPromise: RSVP.resolve(2), + theirPromise: RSVP.resolve(3), + notAPromise: 4 + }; + + RSVP.hash(promises).then(function(hash){ + // hash here is an object that looks like: + // { + // myPromise: 1, + // yourPromise: 2, + // theirPromise: 3, + // notAPromise: 4 + // } + }); + ```` + + If any of the `promises` given to `RSVP.hash` are rejected, the first promise + that is rejected will be given as as the first argument, or as the reason to + the rejection handler. For example: + + ```javascript + var promises = { + myPromise: RSVP.resolve(1), + rejectedPromise: RSVP.reject(new Error("rejectedPromise")), + anotherRejectedPromise: RSVP.reject(new Error("anotherRejectedPromise")), + }; + + RSVP.hash(promises).then(function(hash){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "rejectedPromise" + }); + ``` + + An important note: `RSVP.hash` is intended for plain JavaScript objects that + are just a set of keys and values. `RSVP.hash` will NOT preserve prototype + chains. + + Example: + + ```javascript + function MyConstructor(){ + this.example = RSVP.resolve("Example"); + } + + MyConstructor.prototype = { + protoProperty: RSVP.resolve("Proto Property") + }; + + var myObject = new MyConstructor(); + + RSVP.hash(myObject).then(function(hash){ + // protoProperty will not be present, instead you will just have an + // object that looks like: + // { + // example: "Example" + // } + // + // hash.hasOwnProperty('protoProperty'); // false + // 'undefined' === typeof hash.protoProperty + }); + ``` + + @method hash + @for RSVP + @param {Object} promises + @param {String} label - optional string that describes the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all properties of `promises` + have been fulfilled, or rejected if any of them become rejected. + */ + __exports__["default"] = function hash(object, label) { + return new Promise(function(resolve, reject){ + var results = {}; + var keys = keysOf(object); + var remaining = keys.length; + var entry, property; + + if (remaining === 0) { + resolve(results); + return; + } + + function fulfilledTo(property) { + return function(value) { + results[property] = value; + if (--remaining === 0) { + resolve(results); + } + }; + } + + function onRejection(reason) { + remaining = 0; + reject(reason); + } + + for (var i = 0; i < keys.length; i++) { + property = keys[i]; + entry = object[property]; + + if (isNonThenable(entry)) { + results[property] = entry; + if (--remaining === 0) { + resolve(results); + } + } else { + Promise.cast(entry).then(fulfilledTo(property), onRejection); + } + } + }); + }; + }); +define("rsvp/instrument", + ["./config","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var config = __dependency1__.config; + var now = __dependency2__.now; + + __exports__["default"] = function instrument(eventName, promise, child) { + // instrumentation should not disrupt normal usage. + try { + config.trigger(eventName, { + guid: promise._guidKey + promise._id, + eventName: eventName, + detail: promise._detail, + childGuid: child && promise._guidKey + child._id, + label: promise._label, + timeStamp: now(), + stack: new Error(promise._label).stack + }); + } catch(error) { + setTimeout(function(){ + throw error; + }, 0); + } + }; + }); +define("rsvp/map", + ["./promise","./all","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var all = __dependency2__["default"]; + var isArray = __dependency3__.isArray; + var isFunction = __dependency3__.isFunction; + + /** + + `RSVP.map` is similar to JavaScript's native `map` method, except that it + waits for all promises to become fulfilled before running the `mapFn` on + each item in given to `promises`. `RSVP.map` returns a promise that will + become fulfilled with the result of running `mapFn` on the values the promises + become fulfilled with. + + For example: + + ```javascript + + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.resolve(2); + var promise3 = RSVP.resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + var mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(result){ + // result is [ 2, 3, 4 ] + }); + ``` + + If any of the `promises` given to `RSVP.map` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + var mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "2" + }); + ``` + + `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, + say you want to get all comments from a set of blog posts, but you need + the blog posts first becuase they contain a url to those comments. + + ```javscript + + var mapFn = function(blogPost){ + // getComments does some ajax and returns an RSVP.Promise that is fulfilled + // with some comments data + return getComments(blogPost.comments_url); + }; + + // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled + // with some blog post data + RSVP.map(getBlogPosts(), mapFn).then(function(comments){ + // comments is the result of asking the server for the comments + // of all blog posts returned from getBlogPosts() + }); + ``` + + @method map + @for RSVP + @param {Array} promises + @param {Function} mapFn function to be called on each fulfilled promise. + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled with the result of calling + `mapFn` on each fulfilled promise or value when they become fulfilled. + The promise will be rejected if any of the given `promises` become rejected. + */ + __exports__["default"] = function map(promises, mapFn, label) { + + if (!isArray(promises)) { + throw new TypeError('You must pass an array to map.'); + } + + if (!isFunction(mapFn)){ + throw new TypeError("You must pass a function to map's second argument."); + } + + return all(promises, label).then(function(results){ + var resultLen = results.length, + mappedResults = [], + i; + + for (i = 0; i < resultLen; i++){ + mappedResults.push(mapFn(results[i])); + } + + return all(mappedResults, label); + }); + }; + }); +define("rsvp/node", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + var slice = Array.prototype.slice; + + function makeNodeCallbackFor(resolve, reject) { + return function (error, value) { + if (error) { + reject(error); + } else if (arguments.length > 2) { + resolve(slice.call(arguments, 1)); + } else { + resolve(value); + } + }; + } + + /** + `RSVP.denodeify` takes a "node-style" function and returns a function that + will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the + browser when you'd prefer to use promises over using callbacks. For example, + `denodeify` transforms the following: + + ```javascript + var fs = require('fs'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + handleData(data); + }); + ``` + + into: + + ```javascript + var fs = require('fs'); + + var readFile = RSVP.denodeify(fs.readFile); + + readFile('myfile.txt').then(handleData, handleError); + ``` + + Using `denodeify` makes it easier to compose asynchronous operations instead + of using callbacks. For example, instead of: + + ```javascript + var fs = require('fs'); + var log = require('some-async-logger'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + fs.writeFile('myfile2.txt', data, function(err){ + if (err) throw err; + log('success', function(err) { + if (err) throw err; + }); + }); + }); + ``` + + You can chain the operations together using `then` from the returned promise: + + ```javascript + var fs = require('fs'); + var denodeify = RSVP.denodeify; + var readFile = denodeify(fs.readFile); + var writeFile = denodeify(fs.writeFile); + var log = denodeify(require('some-async-logger')); + + readFile('myfile.txt').then(function(data){ + return writeFile('myfile2.txt', data); + }).then(function(){ + return log('SUCCESS'); + }).then(function(){ + // success handler + }, function(reason){ + // rejection handler + }); + ``` + + @method denodeify + @for RSVP + @param {Function} nodeFunc a "node-style" function that takes a callback as + its last argument. The callback expects an error to be passed as its first + argument (if an error occurred, otherwise null), and the value from the + operation as its second argument ("function(err, value){ }"). + @param {Any} binding optional argument for binding the "this" value when + calling the `nodeFunc` function. + @return {Function} a function that wraps `nodeFunc` to return an + `RSVP.Promise` + */ + __exports__["default"] = function denodeify(nodeFunc, binding) { + return function() { + var nodeArgs = slice.call(arguments), resolve, reject; + var thisArg = this || binding; + + return new Promise(function(resolve, reject) { + Promise.all(nodeArgs).then(function(nodeArgs) { + try { + nodeArgs.push(makeNodeCallbackFor(resolve, reject)); + nodeFunc.apply(thisArg, nodeArgs); + } catch(e) { + reject(e); + } + }); + }); + }; + }; + }); +define("rsvp/promise", + ["./config","./events","./instrument","./utils","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __exports__) { + "use strict"; + var config = __dependency1__.config; + var EventTarget = __dependency2__["default"]; + var instrument = __dependency3__["default"]; + var objectOrFunction = __dependency4__.objectOrFunction; + var isFunction = __dependency4__.isFunction; + var now = __dependency4__.now; + var cast = __dependency5__["default"]; + var all = __dependency6__["default"]; + var race = __dependency7__["default"]; + var Resolve = __dependency8__["default"]; + var Reject = __dependency9__["default"]; + + var guidKey = 'rsvp_' + now() + '-'; + var counter = 0; + + function noop() {} + + __exports__["default"] = Promise; + + + /** + + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]"); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} + @param {String} label optional string for labeling the promise. + Useful for tooling. + @constructor + */ + function Promise(resolver, label) { + if (!isFunction(resolver)) { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + if (!(this instanceof Promise)) { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + this._id = counter++; + this._label = label; + this._subscribers = []; + + if (config.instrument) { + instrument('created', this); + } + + if (noop !== resolver) { + invokeResolver(resolver, this); + } + } + + function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } + + function rejectPromise(reason) { + reject(promise, reason); + } + + try { + resolver(resolvePromise, rejectPromise); + } catch(e) { + rejectPromise(e); + } + } + + Promise.cast = cast; + Promise.all = all; + Promise.race = race; + Promise.resolve = Resolve; + Promise.reject = Reject; + + var PENDING = void 0; + var SEALED = 0; + var FULFILLED = 1; + var REJECTED = 2; + + function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + } + + function publish(promise, settled) { + var child, callback, subscribers = promise._subscribers, detail = promise._detail; + + if (config.instrument) { + instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); + } + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + invokeCallback(settled, child, callback, detail); + } + + promise._subscribers = null; + } + + Promise.prototype = { + /** + @property constructor + */ + constructor: Promise, + + _id: undefined, + _guidKey: guidKey, + _label: undefined, + + _state: undefined, + _detail: undefined, + _subscribers: undefined, + + _onerror: function (reason) { + config.trigger('error', reason); + }, + + /** + + A promise represents the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, "downstream" + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return "default name"; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `"default name"` + }); + + findUser().then(function (user) { + throw "Found user, but still unhappy"; + }, function (reason) { + throw "`findUser` rejected and we're unhappy"; + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be "Found user, but still unhappy". + // If `findUser` rejected, `reason` will be "`findUser` rejected and we're unhappy". + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException("Upstream error"); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javacsript + findResult().then(function(result){ + + }, function(reason){ + + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javacsript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong; + }); + ``` + + @method then + @param {Function} onFulfillment + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection, label) { + var promise = this; + this._onerror = null; + + var thenPromise = new this.constructor(noop, label); + + if (this._state) { + var callbacks = arguments; + config.async(function invokePromiseCallback() { + invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); + }); + } else { + subscribe(this, thenPromise, onFulfillment, onRejection); + } + + if (config.instrument) { + instrument('chained', promise, thenPromise); + } + + return thenPromise; + }, + + /** + `catch` is simply sugar for `then(null, onRejection)` which makes it the same + as the catch block, of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error("couldn't find that author"); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong; + }); + ``` + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection, label) { + return this.then(null, onRejection, label); + }, + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't effect the return value + } + + findAuthor().finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'finally': function(callback, label) { + var constructor = this.constructor; + + return this.then(function(value) { + return constructor.cast(callback()).then(function(){ + return value; + }); + }, function(reason) { + return constructor.cast(callback()).then(function(){ + throw reason; + }); + }, label); + } + }; + + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + try { + value = callback(detail); + succeeded = true; + } catch(e) { + failed = true; + error = e; + } + } else { + value = detail; + succeeded = true; + } + + if (handleThenable(promise, value)) { + return; + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + resolve(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } + } + + function handleThenable(promise, value) { + var then = null, + resolved; + + try { + if (promise === value) { + throw new TypeError("A promises callback cannot return that same promise."); + } + + if (objectOrFunction(value)) { + then = value.then; + + if (isFunction(then)) { + then.call(value, function(val) { + if (resolved) { return true; } + resolved = true; + + if (value !== val) { + resolve(promise, val); + } else { + fulfill(promise, val); + } + }, function(val) { + if (resolved) { return true; } + resolved = true; + + reject(promise, val); + }, 'derived from: ' + (promise._label || ' unknown promise')); + + return true; + } + } + } catch (error) { + if (resolved) { return true; } + reject(promise, error); + return true; + } + + return false; + } + + function resolve(promise, value) { + if (promise === value) { + fulfill(promise, value); + } else if (!handleThenable(promise, value)) { + fulfill(promise, value); + } + } + + function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + promise._state = SEALED; + promise._detail = value; + + config.async(publishFulfillment, promise); + } + + function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = SEALED; + promise._detail = reason; + + config.async(publishRejection, promise); + } + + function publishFulfillment(promise) { + publish(promise, promise._state = FULFILLED); + } + + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._detail); + } + + publish(promise, promise._state = REJECTED); + } + }); +define("rsvp/promise/all", + ["../utils","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var isArray = __dependency1__.isArray; + var isNonThenable = __dependency1__.isNonThenable; + + /** + + `RSVP.Promise.all` returns a new promise which is fulfilled with an array of + fulfillment values for the passed promises, or rejects with the reason of the + first passed promise that rejects. It casts all elements of the passed iterable + to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.resolve(2); + var promise3 = RSVP.resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `RSVP.all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @for RSVP.Promise + @param {Array} promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + */ + __exports__["default"] = function all(entries, label) { + + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function(resolve, reject) { + if (!isArray(entries)) { + throw new TypeError('You must pass an array to all.'); + } + + var remaining = entries.length; + var results = new Array(remaining); + var entry, pending = true; + + if (remaining === 0) { + resolve(results); + return; + } + + function fulfillmentAt(index) { + return function(value) { + results[index] = value; + if (--remaining === 0) { + resolve(results); + } + }; + } + + function onRejection(reason) { + remaining = 0; + reject(reason); + } + + for (var index = 0; index < entries.length; index++) { + entry = entries[index]; + if (isNonThenable(entry)) { + results[index] = entry; + if (--remaining === 0) { + resolve(results); + } + } else { + Constructor.cast(entry).then(fulfillmentAt(index), onRejection); + } + } + }, label); + }; + }); +define("rsvp/promise/cast", + ["exports"], + function(__exports__) { + "use strict"; + /** + + `RSVP.Promise.cast` cast coerces its argument to a promise, or returns the + argument if it is already a promise which shares a constructor with the caster; + + Example: + + ```javascript + var promise = RSVP.Promise.resolve(1); + var casted = RSVP.Promise.cast(promise); + + console.log(promise === casted); // true + ``` + + In the case of a promise whose constructor does not match, it is assimilated. + The resulting promise will fulfill or reject based on the outcome of the + promise being casted. + + In the case of a non-promise, a promise which will fulfill with that value is + returned. + + Example: + + ```javascript + var value = 1; // could be a number, boolean, string, undefined... + var casted = RSVP.Promise.cast(value); + + console.log(value === casted); // false + console.log(casted instanceof RSVP.Promise) // true + + casted.then(function(val) { + val === value // => true + }); + ``` + + `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the + following ways: + + * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you + have something that could either be a promise or a value. RSVP.resolve + will have the same effect but will create a new promise wrapper if the + argument is a promise. + * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to + promises of the exact class specified, so that the resulting object's `then` is + ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). + + @method cast + @for RSVP.Promise + @param {Object} object to be casted + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise + */ + + __exports__["default"] = function cast(object, label) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + return new Constructor(function(resolve) { + resolve(object); + }, label); + }; + }); +define("rsvp/promise/race", + ["../utils","exports"], + function(__dependency1__, __exports__) { + "use strict"; + /* global toString */ + + var isArray = __dependency1__.isArray; + var isFunction = __dependency1__.isFunction; + var isNonThenable = __dependency1__.isNonThenable; + + /** + `RSVP.Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 1"); + }, 200); + }); + + var promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 2"); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // result === "promise 2" because it was resolved before promise1 + // was resolved. + }); + ``` + + `RSVP.Promise.race` is deterministic in that only the state of the first + completed promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first completed promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 1"); + }, 200); + }); + + var promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error("promise 2")); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs because there are rejected promises! + }, function(reason){ + // reason.message === "promise2" because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + @method race + @for RSVP.Promise + @param {Array} promises array of promises to observe + @param {String} label optional string for describing the promise returned. + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. + */ + __exports__["default"] = function race(entries, label) { + /*jshint validthis:true */ + var Constructor = this, entry; + + return new Constructor(function(resolve, reject) { + if (!isArray(entries)) { + throw new TypeError('You must pass an array to race.'); + } + + var pending = true; + + function onFulfillment(value) { if (pending) { pending = false; resolve(value); } } + function onRejection(reason) { if (pending) { pending = false; reject(reason); } } + + for (var i = 0; i < entries.length; i++) { + entry = entries[i]; + if (isNonThenable(entry)) { + pending = false; + resolve(entry); + return; + } else { + Constructor.cast(entry).then(onFulfillment, onRejection); + } + } + }, label); + }; + }); +define("rsvp/promise/reject", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + It is essentially shorthand for the following: + + ```javascript + var promise = new RSVP.Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = RSVP.Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @for RSVP.Promise + @param {Any} reason value that the returned promise will be rejected with. + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. + */ + __exports__["default"] = function reject(reason, label) { + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function (resolve, reject) { + reject(reason); + }, label); + }; + }); +define("rsvp/promise/resolve", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.Promise.resolve` returns a promise that will become fulfilled with the passed + `value`. It is essentially shorthand for the following: + + ```javascript + var promise = new RSVP.Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = RSVP.Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @for RSVP.Promise + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + __exports__["default"] = function resolve(value, label) { + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function(resolve, reject) { + resolve(value); + }, label); + }; + }); +define("rsvp/race", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function race(array, label) { + return Promise.race(array, label); + }; + }); +define("rsvp/reject", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function reject(reason, label) { + return Promise.reject(reason, label); + }; + }); +define("rsvp/resolve", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function resolve(value, label) { + return Promise.resolve(value, label); + }; + }); +define("rsvp/rethrow", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event + loop in order to aid debugging. + + Promises A+ specifies that any exceptions that occur with a promise must be + caught by the promises implementation and bubbled to the last handler. For + this reason, it is recommended that you always specify a second rejection + handler function to `then`. However, `RSVP.rethrow` will throw the exception + outside of the promise, so it bubbles up to your console if in the browser, + or domain/cause uncaught exception in Node. `rethrow` will throw the error + again so the error can be handled by the promise. + + ```javascript + function throws(){ + throw new Error('Whoops!'); + } + + var promise = new RSVP.Promise(function(resolve, reject){ + throws(); + }); + + promise.catch(RSVP.rethrow).then(function(){ + // Code here doesn't run because the promise became rejected due to an + // error! + }, function (err){ + // handle the error here + }); + ``` + + The 'Whoops' error will be thrown on the next turn of the event loop + and you can watch for it in your console. You can also handle it using a + rejection handler given to `.then` or `.catch` on the returned promise. + + @method rethrow + @for RSVP + @param {Error} reason reason the promise became rejected. + @throws Error + */ + __exports__["default"] = function rethrow(reason) { + setTimeout(function() { + throw reason; + }); + throw reason; + }; + }); +define("rsvp/utils", + ["exports"], + function(__exports__) { + "use strict"; + function objectOrFunction(x) { + return typeof x === "function" || (typeof x === "object" && x !== null); + } + + __exports__.objectOrFunction = objectOrFunction;function isFunction(x) { + return typeof x === "function"; + } + + __exports__.isFunction = isFunction;function isNonThenable(x) { + return !objectOrFunction(x); + } + + __exports__.isNonThenable = isNonThenable;function isArray(x) { + return Object.prototype.toString.call(x) === "[object Array]"; + } + + __exports__.isArray = isArray;// Date.now is not available in browsers < IE9 + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility + var now = Date.now || function() { return new Date().getTime(); }; + __exports__.now = now; + var keysOf = Object.keys || function(object) { + var result = []; + + for (var prop in object) { + result.push(prop); + } + + return result; + }; + __exports__.keysOf = keysOf; + }); +define("rsvp", + ["./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all_settled","./rsvp/race","./rsvp/hash","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/asap","./rsvp/filter","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var EventTarget = __dependency2__["default"]; + var denodeify = __dependency3__["default"]; + var all = __dependency4__["default"]; + var allSettled = __dependency5__["default"]; + var race = __dependency6__["default"]; + var hash = __dependency7__["default"]; + var rethrow = __dependency8__["default"]; + var defer = __dependency9__["default"]; + var config = __dependency10__.config; + var configure = __dependency10__.configure; + var map = __dependency11__["default"]; + var resolve = __dependency12__["default"]; + var reject = __dependency13__["default"]; + var asap = __dependency14__["default"]; + var filter = __dependency15__["default"]; + + config.async = asap; // default async is asap; + + function async(callback, arg) { + config.async(callback, arg); + } + + function on() { + config.on.apply(config, arguments); + } + + function off() { + config.off.apply(config, arguments); + } + + // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` + if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') { + var callbacks = window.__PROMISE_INSTRUMENTATION__; + configure('instrument', true); + for (var eventName in callbacks) { + if (callbacks.hasOwnProperty(eventName)) { + on(eventName, callbacks[eventName]); + } + } + } + + __exports__.Promise = Promise; + __exports__.EventTarget = EventTarget; + __exports__.all = all; + __exports__.allSettled = allSettled; + __exports__.race = race; + __exports__.hash = hash; + __exports__.rethrow = rethrow; + __exports__.defer = defer; + __exports__.denodeify = denodeify; + __exports__.configure = configure; + __exports__.on = on; + __exports__.off = off; + __exports__.resolve = resolve; + __exports__.reject = reject; + __exports__.async = async; + __exports__.map = map; + __exports__.filter = filter; + }); +global.RSVP = requireModule('rsvp'); +}(window)); +'use strict'; + +var EPUBJS = EPUBJS || {}; +EPUBJS.VERSION = "0.2.3"; + +EPUBJS.plugins = EPUBJS.plugins || {}; + +EPUBJS.filePath = EPUBJS.filePath || "/epubjs/"; + +EPUBJS.Render = {}; + +(function(root) { + + var previousEpub = root.ePub || {}; + + var ePub = root.ePub = function() { + var bookPath, options; + + //-- var book = ePub("path/to/book.epub", { restore: true }) + if(typeof(arguments[0]) != 'undefined' && + typeof arguments[0] === 'string') { + + bookPath = arguments[0]; + + if( arguments[1] && typeof arguments[1] === 'object' ) { + options = arguments[1]; + options.bookPath = bookPath; + } else { + options = { 'bookPath' : bookPath }; + } + + } + + /* + * var book = ePub({ bookPath: "path/to/book.epub", restore: true }); + * + * - OR - + * + * var book = ePub({ restore: true }); + * book.open("path/to/book.epub"); + */ + + if( arguments[0] && typeof arguments[0] === 'object' ) { + options = arguments[0]; + } + + + return new EPUBJS.Book(options); + }; + + _.extend(ePub, { + noConflict : function() { + root.ePub = previousEpub; + return this; + } + }); + + //exports to multiple environments + if (typeof define === 'function' && define.amd) + //AMD + define(function(){ return ePub; }); + else if (typeof module != "undefined" && module.exports) + //Node + module.exports = ePub; + +})(window); + +EPUBJS.Book = function(options){ + + var book = this; + + this.settings = _.defaults(options || {}, { + bookPath : null, + bookKey : null, + packageUrl : null, + storage: false, //-- true (auto) or false (none) | override: 'ram', 'websqldatabase', 'indexeddb', 'filesystem' + fromStorage : false, + saved : false, + online : true, + contained : false, + width : null, + height: null, + layoutOveride : null, // Default: { spread: 'reflowable', layout: 'auto', orientation: 'auto'} + orientation : null, + minSpreadWidth: 800, //-- overridden by spread: none (never) / both (always) + gap: "auto", //-- "auto" or int + version: 1, + restore: false, + reload : false, + goto : false, + styles : {}, + headTags : {}, + withCredentials: false, + render_method: "Iframe" + }); + + this.settings.EPUBJSVERSION = EPUBJS.VERSION; + + this.spinePos = 0; + this.stored = false; + + //-- All Book events for listening + /* + book:ready + book:stored + book:online + book:offline + book:pageChanged + book:loadFailed + book:loadChapterFailed + */ + + //-- Adds Hook methods to the Book prototype + // Hooks will all return before triggering the callback. + // EPUBJS.Hooks.mixin(this); + //-- Get pre-registered hooks for events + // this.getHooks("beforeChapterDisplay"); + + this.online = this.settings.online || navigator.onLine; + this.networkListeners(); + + this.store = false; //-- False if not using storage; + + //-- Determine storage method + //-- Override options: none | ram | websqldatabase | indexeddb | filesystem + + if(this.settings.storage !== false){ + this.storage = new fileStorage.storage(this.settings.storage); + } + + this.ready = { + manifest: new RSVP.defer(), + spine: new RSVP.defer(), + metadata: new RSVP.defer(), + cover: new RSVP.defer(), + toc: new RSVP.defer(), + pageList: new RSVP.defer() + }; + + this.readyPromises = [ + this.ready.manifest.promise, + this.ready.spine.promise, + this.ready.metadata.promise, + this.ready.cover.promise, + this.ready.toc.promise + ]; + + this.pageList = []; + this.pagination = new EPUBJS.Pagination(); + this.pageListReady = this.ready.pageList.promise; + + this.ready.all = RSVP.all(this.readyPromises); + + this.ready.all.then(this._ready.bind(this)); + + // Queue for methods used before rendering + this.isRendered = false; + this._q = EPUBJS.core.queue(this); + // Queue for rendering + this._rendering = false; + this._displayQ = EPUBJS.core.queue(this); + // Queue for going to another location + this._moving = false; + this._gotoQ = EPUBJS.core.queue(this); + + /** + * Creates a new renderer. + * The renderer will handle displaying the content using the method provided in the settings + */ + this.renderer = new EPUBJS.Renderer(this.settings.render_method); + //-- Set the width at which to switch from spreads to single pages + this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + this.renderer.setGap(this.settings.gap); + //-- Pass through the renderer events + this.listenToRenderer(this.renderer); + + this.defer_opened = new RSVP.defer(); + this.opened = this.defer_opened.promise; + // BookUrl is optional, but if present start loading process + if(typeof this.settings.bookPath === 'string') { + this.open(this.settings.bookPath, this.settings.reload); + } + + window.addEventListener("beforeunload", this.unload.bind(this), false); + + //-- Listen for these promises: + //-- book.opened.then() + //-- book.rendered.then() +}; + +//-- Check bookUrl and start parsing book Assets or load them from storage +EPUBJS.Book.prototype.open = function(bookPath, forceReload){ + var book = this, + epubpackage, + opened = new RSVP.defer(); + + this.settings.bookPath = bookPath; + + //-- Get a absolute URL from the book path + this.bookUrl = this.urlFrom(bookPath); + + if(this.settings.contained || this.isContained(bookPath)){ + + this.settings.contained = this.contained = true; + + this.bookUrl = ''; + + epubpackage = this.unarchive(bookPath). + then(function(){ + return book.loadPackage(); + }); + + } else { + epubpackage = this.loadPackage(); + } + + if(this.settings.restore && !forceReload && localStorage){ + //-- Will load previous package json, or re-unpack if error + epubpackage.then(function(packageXml) { + var identifier = book.packageIdentifier(packageXml); + var restored = book.restore(identifier); + + if(!restored) { + book.unpack(packageXml); + } + opened.resolve(); + book.defer_opened.resolve(); + }); + + }else{ + + //-- Get package information from epub opf + epubpackage.then(function(packageXml) { + book.unpack(packageXml); + opened.resolve(); + book.defer_opened.resolve(); + }); + } + + //-- If there is network connection, store the books contents + if(this.online && this.settings.storage && !this.settings.contained){ + if(!this.settings.stored) opened.then(book.storeOffline()); + } + + this._registerReplacements(this.renderer); + + return opened.promise; + +}; + +EPUBJS.Book.prototype.loadPackage = function(_containerPath){ + var book = this, + parse = new EPUBJS.Parser(), + containerPath = _containerPath || "META-INF/container.xml", + containerXml, + packageXml; + + if(!this.settings.packageUrl) { //-- provide the packageUrl to skip this step + packageXml = book.loadXml(book.bookUrl + containerPath). + then(function(containerXml){ + return parse.container(containerXml); // Container has path to content + }). + then(function(paths){ + book.settings.contentsPath = book.bookUrl + paths.basePath; + book.settings.packageUrl = book.bookUrl + paths.packagePath; + book.settings.encoding = paths.encoding; + return book.loadXml(book.settings.packageUrl); // Containes manifest, spine and metadata + }); + } else { + packageXml = book.loadXml(book.settings.packageUrl); + } + + packageXml.catch(function(error) { + // handle errors in either of the two requests + console.error("Could not load book at: "+ containerPath); + book.trigger("book:loadFailed", containerPath); + }); + return packageXml; +}; + +EPUBJS.Book.prototype.packageIdentifier = function(packageXml){ + var book = this, + parse = new EPUBJS.Parser(); + + return parse.identifier(packageXml); +}; + +EPUBJS.Book.prototype.unpack = function(packageXml){ + var book = this, + parse = new EPUBJS.Parser(); + + book.contents = parse.packageContents(packageXml, book.settings.contentsPath); // Extract info from contents + + book.manifest = book.contents.manifest; + book.spine = book.contents.spine; + book.spineIndexByURL = book.contents.spineIndexByURL; + book.metadata = book.contents.metadata; + if(!book.settings.bookKey) { + book.settings.bookKey = book.generateBookKey(book.metadata.identifier); + } + + //-- Set Globbal Layout setting based on metadata + book.globalLayoutProperties = book.parseLayoutProperties(book.metadata); + + if(book.contents.coverPath) { + book.cover = book.contents.cover = book.settings.contentsPath + book.contents.coverPath; + } + + book.spineNodeIndex = book.contents.spineNodeIndex; + + book.ready.manifest.resolve(book.contents.manifest); + book.ready.spine.resolve(book.contents.spine); + book.ready.metadata.resolve(book.contents.metadata); + book.ready.cover.resolve(book.contents.cover); + + + //-- Load the TOC, optional; either the EPUB3 XHTML Navigation file or the EPUB2 NCX file + if(book.contents.navPath) { + book.settings.navUrl = book.settings.contentsPath + book.contents.navPath; + + book.loadXml(book.settings.navUrl). + then(function(navHtml){ + return parse.nav(navHtml, book.spineIndexByURL, book.spine); // Grab Table of Contents + }).then(function(toc){ + book.toc = book.contents.toc = toc; + book.ready.toc.resolve(book.contents.toc); + }, function(error) { + book.ready.toc.resolve(false); + }); + + // Load the optional pageList + book.loadXml(book.settings.navUrl). + then(function(navHtml){ + return parse.pageList(navHtml, book.spineIndexByURL, book.spine); + }).then(function(pageList){ + var epubcfi = new EPUBJS.EpubCFI(); + var wait = 0; // need to generate a cfi + + // No pageList found + if(pageList.length === 0) { + return; + } + + book.pageList = book.contents.pageList = pageList; + + // Replace HREFs with CFI + book.pageList.forEach(function(pg){ + if(!pg.cfi) { + wait += 1; + epubcfi.generateCfiFromHref(pg.href, book).then(function(cfi){ + pg.cfi = cfi; + pg.packageUrl = book.settings.packageUrl; + + wait -= 1; + if(wait === 0) { + book.pagination.process(book.pageList); + book.ready.pageList.resolve(book.pageList); + } + }); + } + }); + + if(!wait) { + book.pagination.process(book.pageList); + book.ready.pageList.resolve(book.pageList); + } + + }, function(error) { + book.ready.pageList.resolve([]); + }); + } else if(book.contents.tocPath) { + book.settings.tocUrl = book.settings.contentsPath + book.contents.tocPath; + + book.loadXml(book.settings.tocUrl). + then(function(tocXml){ + return parse.toc(tocXml, book.spineIndexByURL, book.spine); // Grab Table of Contents + }).then(function(toc){ + book.toc = book.contents.toc = toc; + book.ready.toc.resolve(book.contents.toc); + }, function(error) { + book.ready.toc.resolve(false); + }); + + } else { + book.ready.toc.resolve(false); + } + +}; + +EPUBJS.Book.prototype.createHiddenRender = function(renderer, _width, _height) { + var box = this.element.getBoundingClientRect(); + var width = _width || this.settings.width || box.width; + var height = _height || this.settings.height || box.height; + var hiddenContainer; + var hiddenEl; + renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + renderer.setGap(this.settings.gap); + + this._registerReplacements(renderer); + if(this.settings.forceSingle) { + renderer.forceSingle(true); + } + + hiddenContainer = document.createElement("div"); + hiddenContainer.style.visibility = "hidden"; + hiddenContainer.style.overflow = "hidden"; + hiddenContainer.style.width = "0"; + hiddenContainer.style.height = "0"; + this.element.appendChild(hiddenContainer); + + hiddenEl = document.createElement("div"); + hiddenEl.style.visibility = "hidden"; + hiddenEl.style.overflow = "hidden"; + hiddenEl.style.width = width + "px";//"0"; + hiddenEl.style.height = height +"px"; //"0"; + hiddenContainer.appendChild(hiddenEl); + + renderer.initialize(hiddenEl); + return hiddenContainer; +}; + +// Generates the pageList array by loading every chapter and paging through them +EPUBJS.Book.prototype.generatePageList = function(width, height){ + var pageList = []; + var pager = new EPUBJS.Renderer(this.settings.render_method, false); //hidden + var hiddenContainer = this.createHiddenRender(pager, width, height); + var deferred = new RSVP.defer(); + var spinePos = -1; + var spineLength = this.spine.length; + var totalPages = 0; + var currentPage = 0; + var nextChapter = function(deferred){ + var chapter; + var next = spinePos + 1; + var done = deferred || new RSVP.defer(); + var loaded; + if(next >= spineLength) { + done.resolve(); + } else { + spinePos = next; + chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); + pager.displayChapter(chapter, this.globalLayoutProperties).then(function(chap){ + pager.pageMap.forEach(function(item){ + currentPage += 1; + pageList.push({ + "cfi" : item.start, + "page" : currentPage + }); + + }); + + if(pager.pageMap.length % 2 > 0 && + pager.spreads) { + currentPage += 1; // Handle Spreads + pageList.push({ + "cfi" : pager.pageMap[pager.pageMap.length - 1].end, + "page" : currentPage + }); + } + + // Load up the next chapter + setTimeout(function(){ + nextChapter(done); + }, 1); + }); + } + return done.promise; + }.bind(this); + + var finished = nextChapter().then(function(){ + pager.remove(); + this.element.removeChild(hiddenContainer); + deferred.resolve(pageList); + }.bind(this)); + + return deferred.promise; +}; + +// Render out entire book and generate the pagination +// Width and Height are optional and will default to the current dimensions +EPUBJS.Book.prototype.generatePagination = function(width, height) { + var book = this; + var defered = new RSVP.defer(); + + this.ready.spine.promise.then(function(){ + book.generatePageList(width, height).then(function(pageList){ + book.pageList = book.contents.pageList = pageList; + book.pagination.process(pageList); + book.ready.pageList.resolve(book.pageList); + defered.resolve(book.pageList); + }); + }); + + return defered.promise; +}; + +// Process the pagination from a JSON array containing the pagelist +EPUBJS.Book.prototype.loadPagination = function(pagelistJSON) { + var pageList = JSON.parse(pagelistJSON); + + if(pageList && pageList.length) { + this.pageList = pageList; + this.pagination.process(this.pageList); + this.ready.pageList.resolve(this.pageList); + } + return this.pageList; +}; + +EPUBJS.Book.prototype.getPageList = function() { + return this.ready.pageList.promise; +}; + +EPUBJS.Book.prototype.getMetadata = function() { + return this.ready.metadata.promise; +}; + +EPUBJS.Book.prototype.getToc = function() { + return this.ready.toc.promise; +}; + +/* Private Helpers */ + +//-- Listeners for browser events +EPUBJS.Book.prototype.networkListeners = function(){ + var book = this; + + window.addEventListener("offline", function(e) { + book.online = false; + book.trigger("book:offline"); + }, false); + + window.addEventListener("online", function(e) { + book.online = true; + book.trigger("book:online"); + }, false); + +}; + +// Listen to all events the renderer triggers and pass them as book events +EPUBJS.Book.prototype.listenToRenderer = function(renderer){ + var book = this; + renderer.Events.forEach(function(eventName){ + renderer.on(eventName, function(e){ + book.trigger(eventName, e); + }); + }); + + renderer.on("renderer:visibleRangeChanged", function(range) { + var startPage, endPage, percent; + var pageRange = []; + + if(this.pageList.length > 0) { + startPage = this.pagination.pageFromCfi(range.start); + percent = this.pagination.percentageFromPage(startPage); + pageRange.push(startPage); + + if(range.end) { + endPage = this.pagination.pageFromCfi(range.end); + //if(startPage != endPage) { + pageRange.push(endPage); + //} + } + this.trigger("book:pageChanged", { + "anchorPage": startPage, + "percentage": percent, + "pageRange" : pageRange + }); + + // TODO: Add event for first and last page. + // (though last is going to be hard, since it could be several reflowed pages long) + } + }.bind(this)); + + renderer.on("render:loaded", this.loadChange.bind(this)); +}; + +// Listens for load events from the Renderer and checks against the current chapter +// Prevents the Render from loading a different chapter when back button is pressed +EPUBJS.Book.prototype.loadChange = function(url){ + var uri = EPUBJS.core.uri(url); + var chapter; + + if(this.currentChapter) { + chapter = EPUBJS.core.uri(this.currentChapter.absolute); + } + + if(!this._rendering && this.currentChapter && uri.path != chapter.path){ + console.warn("Miss Match", uri.path, this.currentChapter.absolute); + this.goto(uri.filename); + } +}; + +EPUBJS.Book.prototype.unlistenToRenderer = function(renderer){ + renderer.Events.forEach(function(eventName){ + renderer.off(eventName); + } ); +}; + +//-- Choose between a request from store or a request from network +EPUBJS.Book.prototype.loadXml = function(url){ + if(this.settings.fromStorage) { + return this.storage.getXml(url, this.settings.encoding); + } else if(this.settings.contained) { + return this.zip.getXml(url, this.settings.encoding); + }else{ + return EPUBJS.core.request(url, 'xml', this.settings.withCredentials); + } +}; + +//-- Turns a url into a absolute url +EPUBJS.Book.prototype.urlFrom = function(bookPath){ + var uri = EPUBJS.core.uri(bookPath), + absolute = uri.protocol, + fromRoot = uri.path[0] == "/", + location = window.location, + //-- Get URL orgin, try for native or combine + origin = location.origin || location.protocol + "//" + location.host, + baseTag = document.getElementsByTagName('base'), + base; + + + //-- Check is Base tag is set + + if(baseTag.length) { + base = baseTag[0].href; + } + + //-- 1. Check if url is absolute + if(uri.protocol){ + return uri.origin + uri.path; + } + + //-- 2. Check if url starts with /, add base url + if(!absolute && fromRoot){ + return (base || origin) + uri.path; + } + + //-- 3. Or find full path to url and add that + if(!absolute && !fromRoot){ + return EPUBJS.core.resolveUrl(base || location.pathname, uri.path); + } + +}; + + +EPUBJS.Book.prototype.unarchive = function(bookPath){ + var book = this, + unarchived; + + //-- Must use storage + // if(this.settings.storage == false ){ + // this.settings.storage = true; + // this.storage = new fileStorage.storage(); + // } + + this.zip = new EPUBJS.Unarchiver(); + this.store = this.zip; // Use zip storaged in ram + return this.zip.openZip(bookPath); +}; + +//-- Checks if url has a .epub or .zip extension +EPUBJS.Book.prototype.isContained = function(bookUrl){ + var uri = EPUBJS.core.uri(bookUrl); + + if(uri.extension && (uri.extension == "epub" || uri.extension == "zip")){ + return true; + } + + return false; +}; + +//-- Checks if the book can be retrieved from localStorage +EPUBJS.Book.prototype.isSaved = function(bookKey) { + var storedSettings; + + if(!localStorage) { + return false; + } + + storedSettings = localStorage.getItem(bookKey); + + if( !localStorage || + storedSettings === null) { + return false; + } else { + return true; + } +}; + +// Generates the Book Key using the identifer in the manifest or other string provided +EPUBJS.Book.prototype.generateBookKey = function(identifier){ + return "epubjs:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; +}; + +EPUBJS.Book.prototype.saveContents = function(){ + if(!localStorage) { + return false; + } + localStorage.setItem(this.settings.bookKey, JSON.stringify(this.contents)); +}; + +EPUBJS.Book.prototype.removeSavedContents = function() { + if(!localStorage) { + return false; + } + localStorage.removeItem(this.settings.bookKey); +}; + + + +//-- Takes a string or a element +EPUBJS.Book.prototype.renderTo = function(elem){ + var book = this, + rendered; + + if(_.isElement(elem)) { + this.element = elem; + } else if (typeof elem == "string") { + this.element = EPUBJS.core.getEl(elem); + } else { + console.error("Not an Element"); + return; + } + + rendered = this.opened. + then(function(){ + // book.render = new EPUBJS.Renderer[this.settings.renderer](book); + book.renderer.initialize(book.element, book.settings.width, book.settings.height); + book._rendered(); + return book.startDisplay(); + }); + + // rendered.then(null, function(error) { console.error(error); }); + + return rendered; +}; + +EPUBJS.Book.prototype.startDisplay = function(){ + var display; + + if(this.settings.goto) { + display = this.goto(this.settings.goto); + }else if(this.settings.previousLocationCfi) { + display = this.gotoCfi(this.settings.previousLocationCfi); + }else{ + display = this.displayChapter(this.spinePos); + } + + return display; +}; + +EPUBJS.Book.prototype.restore = function(identifier){ + + var book = this, + fetch = ['manifest', 'spine', 'metadata', 'cover', 'toc', 'spineNodeIndex', 'spineIndexByURL', 'globalLayoutProperties'], + reject = false, + bookKey = this.generateBookKey(identifier), + fromStore = localStorage.getItem(bookKey), + len = fetch.length, + i; + + if(this.settings.clearSaved) reject = true; + + if(!reject && fromStore != 'undefined' && fromStore !== null){ + book.contents = JSON.parse(fromStore); + + for(i = 0; i < len; i++) { + var item = fetch[i]; + + if(!book.contents[item]) { + reject = true; + break; + } + book[item] = book.contents[item]; + } + } + + if(reject || !fromStore || !this.contents || !this.settings.contentsPath){ + return false; + }else{ + this.settings.bookKey = bookKey; + this.ready.manifest.resolve(this.manifest); + this.ready.spine.resolve(this.spine); + this.ready.metadata.resolve(this.metadata); + this.ready.cover.resolve(this.cover); + this.ready.toc.resolve(this.toc); + return true; + } + +}; + +EPUBJS.Book.prototype.displayChapter = function(chap, end, deferred){ + var book = this, + render, + cfi, + pos, + store, + defer = deferred || new RSVP.defer(); + + var chapter; + + if(!this.isRendered) { + this._q.enqueue("displayChapter", arguments); + // Reject for now. TODO: pass promise to queue + defer.reject({ + message : "Rendering", + stack : new Error().stack + }); + return defer.promise; + } + + + if(this._rendering || this._rendering) { + // Pass along the current defer + this._displayQ.enqueue("displayChapter", [chap, end, defer]); + return defer.promise; + } + + if(_.isNumber(chap)){ + pos = chap; + }else{ + cfi = new EPUBJS.EpubCFI(chap); + pos = cfi.spinePos; + } + + if(pos < 0 || pos >= this.spine.length){ + console.warn("Not A Valid Location"); + pos = 0; + end = false; + cfi = false; + } + + //-- Create a new chapter + chapter = new EPUBJS.Chapter(this.spine[pos], this.store); + + this._rendering = true; + + render = book.renderer.displayChapter(chapter, this.globalLayoutProperties); + if(cfi) { + book.renderer.gotoCfi(cfi); + } else if(end) { + book.renderer.lastPage(); + } + //-- Success, Clear render queue + render.then(function(rendered){ + // var inwait; + //-- Set the book's spine position + book.spinePos = pos; + + defer.resolve(book.renderer); + + if(!book.settings.fromStorage && + !book.settings.contained) { + book.preloadNextChapter(); + } + + book.currentChapter = chapter; + book._rendering = false; + book._displayQ.dequeue(); + if(book._displayQ.length() === 0) { + book._gotoQ.dequeue(); + } + + }, function(error) { + // handle errors in either of the two requests + console.error("Could not load Chapter: "+ chapter.absolute); + book.trigger("book:chapterLoadFailed", chapter.absolute); + book._rendering = false; + defer.reject(error); + }); + + return defer.promise; +}; + +EPUBJS.Book.prototype.nextPage = function(){ + var next; + + if(!this.isRendered) return this._q.enqueue("nextPage", arguments); + + next = this.renderer.nextPage(); + + if(!next){ + return this.nextChapter(); + } +}; + +EPUBJS.Book.prototype.prevPage = function() { + var prev; + + if(!this.isRendered) return this._q.enqueue("prevPage", arguments); + + prev = this.renderer.prevPage(); + + if(!prev){ + return this.prevChapter(); + } +}; + +EPUBJS.Book.prototype.nextChapter = function() { + var next; + if (this.spinePos < this.spine.length - 1) { + next = this.spinePos + 1; + // Skip non linear chapters + while (this.spine[next] && this.spine[next].linear && this.spine[next].linear == 'no') { + next++; + } + if (next < this.spine.length) { + return this.displayChapter(next); + } else { + this.trigger("book:atEnd"); + } + + } else { + this.trigger("book:atEnd"); + } +}; + +EPUBJS.Book.prototype.prevChapter = function() { + var prev; + if (this.spinePos > 0) { + prev = this.spinePos - 1; + while (this.spine[prev] && this.spine[prev].linear && this.spine[prev].linear == 'no') { + prev--; + } + if (prev >= 0) { + return this.displayChapter(prev, true); + } else { + this.trigger("book:atStart"); + } + + } else { + this.trigger("book:atStart"); + } +}; + +EPUBJS.Book.prototype.getCurrentLocationCfi = function() { + if(!this.isRendered) return false; + return this.renderer.currentLocationCfi; +}; + +EPUBJS.Book.prototype.goto = function(target){ + + if(target.indexOf("epubcfi(") === 0) { + return this.gotoCfi(target); + } else if(target.indexOf("%") === target.length-1) { + return this.gotoPercentage(parseInt(target.substring(0, target.length-1))/100); + } else if(typeof target === "number" || isNaN(target) === false){ + return this.gotoPage(target); + } else { + return this.gotoHref(target); + } + +}; + +EPUBJS.Book.prototype.gotoCfi = function(cfiString, defer){ + var cfi, + spinePos, + spineItem, + rendered, + deferred = defer || new RSVP.defer(); + + if(!this.isRendered) { + console.warn("Not yet Rendered"); + this.settings.previousLocationCfi = cfiString; + return false; + } + + // Currently going to a chapter + if(this._moving || this._rendering) { + console.warn("Renderer is moving"); + this._gotoQ.enqueue("gotoCfi", [cfiString, deferred]); + return false; + } + + cfi = new EPUBJS.EpubCFI(cfiString); + spinePos = cfi.spinePos; + + if(spinePos == -1) { + return false; + } + + spineItem = this.spine[spinePos]; + promise = deferred.promise; + this._moving = true; + //-- If same chapter only stay on current chapter + if(this.currentChapter && this.spinePos === spinePos){ + this.renderer.gotoCfi(cfi); + this._moving = false; + deferred.resolve(this.renderer.currentLocationCfi); + } else { + + if(!spineItem || spinePos == -1) { + spinePos = 0; + spineItem = this.spine[spinePos]; + } + + this.currentChapter = new EPUBJS.Chapter(spineItem, this.store); + + if(this.currentChapter) { + this.spinePos = spinePos; + render = this.renderer.displayChapter(this.currentChapter, this.globalLayoutProperties); + + this.renderer.gotoCfi(cfi); + render.then(function(rendered){ + this._moving = false; + deferred.resolve(rendered.currentLocationCfi); + }.bind(this)); + } + } + + promise.then(function(){ + this._gotoQ.dequeue(); + }.bind(this)); + + return promise; +}; + +EPUBJS.Book.prototype.gotoHref = function(url, defer){ + var split, chapter, section, relativeURL, spinePos; + var deferred = defer || new RSVP.defer(); + + if(!this.isRendered) { + this.settings.goto = url; + return false; + } + + // Currently going to a chapter + if(this._moving || this._rendering) { + this._gotoQ.enqueue("gotoHref", [url, deferred]); + return false; + } + + split = url.split("#"); + chapter = split[0]; + section = split[1] || false; + // absoluteURL = (chapter.search("://") === -1) ? (this.settings.contentsPath + chapter) : chapter; + relativeURL = chapter.replace(this.settings.contentsPath, ''); + spinePos = this.spineIndexByURL[relativeURL]; + + //-- If link fragment only stay on current chapter + if(!chapter){ + spinePos = this.currentChapter ? this.currentChapter.spinePos : 0; + } + + //-- Check that URL is present in the index, or stop + if(typeof(spinePos) != "number") return false; + + if(!this.currentChapter || spinePos != this.currentChapter.spinePos){ + //-- Load new chapter if different than current + return this.displayChapter(spinePos).then(function(){ + if(section){ + this.renderer.section(section); + } + deferred.resolve(this.renderer.currentLocationCfi); + }.bind(this)); + }else{ + //-- Goto section + if(section) { + this.renderer.section(section); + } else { + // Or jump to the start + this.renderer.firstPage(); + } + deferred.resolve(this.renderer.currentLocationCfi); + } + + deferred.promise.then(function(){ + this._gotoQ.dequeue(); + }.bind(this)); + + return deferred.promise; +}; + +EPUBJS.Book.prototype.gotoPage = function(pg){ + var cfi = this.pagination.cfiFromPage(pg); + return this.gotoCfi(cfi); +}; + +EPUBJS.Book.prototype.gotoPercentage = function(percent){ + var pg = this.pagination.pageFromPercentage(percent); + return this.gotoPage(pg); +}; + +EPUBJS.Book.prototype.preloadNextChapter = function() { + var next; + var chap = this.spinePos + 1; + + if(chap >= this.spine.length){ + return false; + } + + next = new EPUBJS.Chapter(this.spine[chap]); + if(next) { + EPUBJS.core.request(next.absolute); + } +}; + + +EPUBJS.Book.prototype.storeOffline = function() { + var book = this, + assets = _.values(this.manifest); + + //-- Creates a queue of all items to load + return EPUBJS.storage.batch(assets). + then(function(){ + book.settings.stored = true; + book.trigger("book:stored"); + }); +}; + +EPUBJS.Book.prototype.availableOffline = function() { + return this.settings.stored > 0 ? true : false; +}; + +/* +EPUBJS.Book.prototype.fromStorage = function(stored) { + + if(this.contained) return; + + if(!stored){ + this.online = true; + this.tell("book:online"); + }else{ + if(!this.availableOffline){ + //-- If book hasn't been cached yet, store offline + this.storeOffline(function(){ + this.online = false; + this.tell("book:offline"); + }.bind(this)); + + }else{ + this.online = false; + this.tell("book:offline"); + } + } + +} +*/ + +EPUBJS.Book.prototype.setStyle = function(style, val, prefixed) { + var noreflow = ["color", "background", "background-color"]; + + if(!this.isRendered) return this._q.enqueue("setStyle", arguments); + + this.settings.styles[style] = val; + + this.renderer.setStyle(style, val, prefixed); + + if(noreflow.indexOf(style) === -1) { + // clearTimeout(this.reformatTimeout); + // this.reformatTimeout = setTimeout(function(){ + this.renderer.reformat(); + // }.bind(this), 10); + } +}; + +EPUBJS.Book.prototype.removeStyle = function(style) { + if(!this.isRendered) return this._q.enqueue("removeStyle", arguments); + this.renderer.removeStyle(style); + this.renderer.reformat(); + delete this.settings.styles[style]; +}; + +EPUBJS.Book.prototype.addHeadTag = function(tag, attrs) { + if(!this.isRendered) return this._q.enqueue("addHeadTag", arguments); + this.settings.headTags[tag] = attrs; +}; + +EPUBJS.Book.prototype.useSpreads = function(use) { + console.warn("useSpreads is deprecated, use forceSingle or set a layoutOveride instead"); + if(use === false) { + this.forceSingle(true); + } else { + this.forceSingle(false); + } +}; + +EPUBJS.Book.prototype.forceSingle = function(_use) { + var force = typeof _use === "undefined" ? true : _use; + + this.renderer.forceSingle(force); + this.settings.forceSingle = force; + if(this.isRendered) { + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.setMinSpreadWidth = function(width) { + this.settings.minSpreadWidth = width; + if(this.isRendered) { + this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.setGap = function(gap) { + this.settings.gap = gap; + if(this.isRendered) { + this.renderer.setGap(this.settings.gap); + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.chapter = function(path) { + var spinePos = this.spineIndexByURL[path]; + var spineItem; + var chapter; + + if(spinePos){ + spineItem = this.spine[spinePos]; + chapter = new EPUBJS.Chapter(spineItem, this.store); + chapter.load(); + } + return chapter; +}; + +EPUBJS.Book.prototype.unload = function(){ + + if(this.settings.restore && localStorage) { + this.saveContents(); + } + + this.unlistenToRenderer(this.renderer); + + this.trigger("book:unload"); +}; + +EPUBJS.Book.prototype.destroy = function() { + + window.removeEventListener("beforeunload", this.unload); + + if(this.currentChapter) this.currentChapter.unload(); + + this.unload(); + + if(this.render) this.render.remove(); + +}; + +EPUBJS.Book.prototype._ready = function() { + + this.trigger("book:ready"); + +}; + +EPUBJS.Book.prototype._rendered = function(err) { + var book = this; + + this.isRendered = true; + this.trigger("book:rendered"); + + this._q.flush(); +}; + + +EPUBJS.Book.prototype.applyStyles = function(renderer, callback){ + // if(!this.isRendered) return this._q.enqueue("applyStyles", arguments); + renderer.applyStyles(this.settings.styles); + callback(); +}; + +EPUBJS.Book.prototype.applyHeadTags = function(renderer, callback){ + // if(!this.isRendered) return this._q.enqueue("applyHeadTags", arguments); + renderer.applyHeadTags(this.settings.headTags); + callback(); +}; + +EPUBJS.Book.prototype._registerReplacements = function(renderer){ + renderer.registerHook("beforeChapterDisplay", this.applyStyles.bind(this, renderer), true); + renderer.registerHook("beforeChapterDisplay", this.applyHeadTags.bind(this, renderer), true); + renderer.registerHook("beforeChapterDisplay", EPUBJS.replace.hrefs.bind(this), true); + + if(this._needsAssetReplacement()) { + + renderer.registerHook("beforeChapterDisplay", [ + EPUBJS.replace.head, + EPUBJS.replace.resources, + EPUBJS.replace.svg + ], true); + + } + +}; + +EPUBJS.Book.prototype._needsAssetReplacement = function(){ + if(this.settings.fromStorage) { + + //-- Filesystem api links are relative, so no need to replace them + if(this.storage.getStorageType() == "filesystem") { + return false; + } + + return true; + + } else if(this.settings.contained) { + + return true; + + } else { + + return false; + + } +}; + + +//-- http://www.idpf.org/epub/fxl/ +EPUBJS.Book.prototype.parseLayoutProperties = function(metadata){ + var layout = (this.layoutOveride && this.layoutOveride.layout) || metadata.layout || "reflowable"; + var spread = (this.layoutOveride && this.layoutOveride.spread) || metadata.spread || "auto"; + var orientation = (this.layoutOveride && this.layoutOveride.orientation) || metadata.orientation || "auto"; + return { + layout : layout, + spread : spread, + orientation : orientation + }; +}; + +//-- Enable binding events to book +RSVP.EventTarget.mixin(EPUBJS.Book.prototype); + +//-- Handle RSVP Errors +RSVP.on('error', function(event) { + //console.error(event, event.detail); +}); + +RSVP.configure('instrument', true); //-- true | will logging out all RSVP rejections +// RSVP.on('created', listener); +// RSVP.on('chained', listener); +// RSVP.on('fulfilled', listener); +RSVP.on('rejected', function(event){ + console.error(event.detail.message, event.detail.stack); +}); + +EPUBJS.Chapter = function(spineObject, store){ + this.href = spineObject.href; + this.absolute = spineObject.url; + this.id = spineObject.id; + this.spinePos = spineObject.index; + this.cfiBase = spineObject.cfiBase; + this.properties = spineObject.properties; + this.manifestProperties = spineObject.manifestProperties; + this.linear = spineObject.linear; + this.pages = 1; + this.store = store; + this.epubcfi = new EPUBJS.EpubCFI(); + this.deferred = new RSVP.defer(); + this.loaded = this.deferred.promise; +}; + + +EPUBJS.Chapter.prototype.load = function(_store){ + var store = _store || this.store; + var promise; + // if(this.store && (!this.book.online || this.book.contained)) + if(store){ + promise = store.get(this.href); + }else{ + promise = EPUBJS.core.request(this.absolute, 'xml'); + } + + promise.then(function(xml){ + this.setDocument(xml); + this.deferred.resolve(this); + }.bind(this)); + + return promise; +}; + +EPUBJS.Chapter.prototype.render = function(_store){ + + return this.load().then(function(doc){ + + var serializer = new XMLSerializer(); + var contents; + var head = doc.head; + var base = doc.createElement("base"); + + base.setAttribute("href", window.location.origin + this.absolute); + head.insertBefore(base, head.firstChild); + contents = serializer.serializeToString(doc); + + return contents; + + }.bind(this)); +}; + +EPUBJS.Chapter.prototype.url = function(_store){ + var deferred = new RSVP.defer(); + var store = _store || this.store; + var loaded; + var chapter = this; + var url; + + if(store){ + if(!this.tempUrl) { + store.getUrl(this.absolute).then(function(url){ + chapter.tempUrl = url; + deferred.resolve(url); + }); + } else { + url = this.tempUrl; + deferred.resolve(url); + } + }else{ + url = this.absolute; + deferred.resolve(url); + } + /* + loaded = EPUBJS.core.request(url, 'xml', false); + loaded.then(function(contents){ + chapter.contents = contents; + deferred.resolve(chapter.absolute); + }, function(error){ + deferred.reject(error); + }); + */ + + return deferred.promise; +}; + +EPUBJS.Chapter.prototype.setPages = function(num){ + this.pages = num; +}; + +EPUBJS.Chapter.prototype.getPages = function(num){ + return this.pages; +}; + +EPUBJS.Chapter.prototype.getID = function(){ + return this.ID; +}; + +EPUBJS.Chapter.prototype.unload = function(store){ + this.document = null; + if(this.tempUrl && store) { + store.revokeUrl(this.tempUrl); + this.tempUrl = false; + } +}; + +EPUBJS.Chapter.prototype.setDocument = function(_document){ + var uri = _document.namespaceURI; + var doctype = _document.doctype; + + // Creates an empty document + this.document = _document.implementation.createDocument( + uri, + null, + null + ); + this.contents = this.document.importNode( + _document.documentElement, //node to import + true //clone its descendants + ); + + this.document.appendChild(this.contents); + + // Fix to apply wgxpath to new document in IE + if(!this.document.evaluate && document.evaluate) { + this.document.evaluate = document.evaluate; + } + + // this.deferred.resolve(this.contents); +}; + +EPUBJS.Chapter.prototype.cfiFromRange = function(_range) { + var range; + var startXpath, endXpath; + var startContainer, endContainer; + var cleanTextContent, cleanEndTextContent; + + // Check for Contents + if(!this.document) return; + startXpath = EPUBJS.core.getElementXPath(_range.startContainer); + // console.log(startContainer) + endXpath = EPUBJS.core.getElementXPath(_range.endContainer); + + startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(!_range.collapsed) { + endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } + + range = this.document.createRange(); + // Find Exact Range in original document + if(startContainer) { + try { + range.setStart(startContainer, _range.startOffset); + if(!_range.collapsed && endContainer) { + range.setEnd(endContainer, _range.endOffset); + } + } catch (e) { + console.log("missed"); + startContainer = false; + } + + } + + // Fuzzy Match + if(!startContainer) { + console.log("not found, try fuzzy match"); + cleanStartTextContent = EPUBJS.core.cleanStringForXpath(_range.startContainer.textContent); + startXpath = "//text()[contains(.," + cleanStartTextContent + ")]"; + + startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(startContainer){ + // console.log("Found with Fuzzy"); + range.setStart(startContainer, _range.startOffset); + + if(!_range.collapsed) { + cleanEndTextContent = EPUBJS.core.cleanStringForXpath(_range.endContainer.textContent); + endXpath = "//text()[contains(.," + cleanEndTextContent + ")]"; + endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + if(endContainer) { + range.setEnd(endContainer, _range.endOffset); + } + } + + } + } + + // Generate the Cfi + return this.epubcfi.generateCfiFromRange(range, this.cfiBase); +}; + +EPUBJS.Chapter.prototype.find = function(_query){ + var chapter = this; + var matches = []; + var query = _query.toLowerCase(); + //var xpath = this.document.evaluate(".//text()[contains(translate(., '"+query.toUpperCase()+"', '"+query+"'),'"+query+"')]", this.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + var find = function(node){ + // Search String + var text = node.textContent.toLowerCase(); + var range = chapter.document.createRange(); + var cfi; + var pos; + var last = -1; + var excerpt; + var limit = 150; + + while (pos != -1) { + pos = text.indexOf(query, last + 1); + + if(pos != -1) { + // If Found, Create Range + range = chapter.document.createRange(); + range.setStart(node, pos); + range.setEnd(node, pos + query.length); + + //Generate CFI + cfi = chapter.cfiFromRange(range); + + // Generate Excerpt + if(node.textContent.length < limit) { + excerpt = node.textContent; + } else { + excerpt = node.textContent.substring(pos-limit/2,pos+limit/2); + excerpt = "..." + excerpt + "..."; + } + + //Add CFI to list + matches.push({ + cfi: cfi, + excerpt: excerpt + }); + } + + last = pos; + } + + }; + + // Grab text nodes + + /* + for ( var i=0 ; i < xpath.snapshotLength; i++ ) { + find(xpath.snapshotItem(i)); + } + */ + + this.textSprint(this.document, function(node){ + find(node); + }); + + + // Return List of CFIs + return matches; +}; + + +EPUBJS.Chapter.prototype.textSprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if (node.data && ! /^\s*$/.test(node.data) ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; +var EPUBJS = EPUBJS || {}; +EPUBJS.core = {}; + +//-- Get a element for an id +EPUBJS.core.getEl = function(elem) { + return document.getElementById(elem); +}; + +//-- Get all elements for a class +EPUBJS.core.getEls = function(classes) { + return document.getElementsByClassName(classes); +}; + +EPUBJS.core.request = function(url, type, withCredentials) { + var supportsURL = window.URL; + var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; + + var deferred = new RSVP.defer(); + + var xhr = new XMLHttpRequest(); + + //-- Check from PDF.js: + // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js + var xhrPrototype = XMLHttpRequest.prototype; + + if (!('overrideMimeType' in xhrPrototype)) { + // IE10 might have response, but not overrideMimeType + Object.defineProperty(xhrPrototype, 'overrideMimeType', { + value: function xmlHttpRequestOverrideMimeType(mimeType) {} + }); + } + if(withCredentials) { + xhr.withCredentials = true; + } + xhr.open("GET", url, true); + xhr.onreadystatechange = handler; + + if(type == 'blob'){ + xhr.responseType = BLOB_RESPONSE; + } + + if(type == "json") { + xhr.setRequestHeader("Accept", "application/json"); + } + + if(type == 'xml') { + xhr.overrideMimeType('text/xml'); + } + + if(type == "binary") { + xhr.responseType = "arraybuffer"; + } + + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls + var r; + + if(type == 'xml'){ + r = this.responseXML; + }else + if(type == 'json'){ + r = JSON.parse(this.response); + }else + if(type == 'blob'){ + + if(supportsURL) { + r = this.response; + } else { + //-- Safari doesn't support responseType blob, so create a blob from arraybuffer + r = new Blob([this.response]); + } + + }else{ + r = this.response; + } + + deferred.resolve(r); + } else { + deferred.reject({ + message : this.response, + stack : new Error().stack + }); + } + } + } + + return deferred.promise; +}; + +EPUBJS.core.toArray = function(obj) { + var arr = []; + + for (var member in obj) { + var newitm; + if ( obj.hasOwnProperty(member) ) { + newitm = obj[member]; + newitm.ident = member; + arr.push(newitm); + } + } + + return arr; +}; + +//-- Parse the different parts of a url, returning a object +EPUBJS.core.uri = function(url){ + var uri = { + protocol : '', + host : '', + path : '', + origin : '', + directory : '', + base : '', + filename : '', + extension : '', + fragment : '', + href : url + }, + blob = url.indexOf('blob:'), + doubleSlash = url.indexOf('://'), + search = url.indexOf('?'), + fragment = url.indexOf("#"), + withoutProtocol, + dot, + firstSlash; + + if(blob === 0) { + uri.protocol = "blob"; + uri.base = url.indexOf(0, fragment); + return uri; + } + + if(fragment != -1) { + uri.fragment = url.slice(fragment + 1); + url = url.slice(0, fragment); + } + + if(search != -1) { + uri.search = url.slice(search + 1); + url = url.slice(0, search); + href = url; + } + + if(doubleSlash != -1) { + uri.protocol = url.slice(0, doubleSlash); + withoutProtocol = url.slice(doubleSlash+3); + firstSlash = withoutProtocol.indexOf('/'); + + if(firstSlash === -1) { + uri.host = uri.path; + uri.path = ""; + } else { + uri.host = withoutProtocol.slice(0, firstSlash); + uri.path = withoutProtocol.slice(firstSlash); + } + + + uri.origin = uri.protocol + "://" + uri.host; + + uri.directory = EPUBJS.core.folder(uri.path); + + uri.base = uri.origin + uri.directory; + // return origin; + } else { + uri.path = url; + uri.directory = EPUBJS.core.folder(url); + uri.base = uri.directory; + } + + //-- Filename + uri.filename = url.replace(uri.base, ''); + dot = uri.filename.lastIndexOf('.'); + if(dot != -1) { + uri.extension = uri.filename.slice(dot+1); + } + return uri; +}; + +//-- Parse out the folder, will return everything before the last slash + +EPUBJS.core.folder = function(url){ + + var lastSlash = url.lastIndexOf('/'); + + if(lastSlash == -1) var folder = ''; + + folder = url.slice(0, lastSlash + 1); + + return folder; + +}; + +//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 +EPUBJS.core.dataURLToBlob = function(dataURL) { + var BASE64_MARKER = ';base64,', + parts, contentType, raw, rawLength, uInt8Array; + + if (dataURL.indexOf(BASE64_MARKER) == -1) { + parts = dataURL.split(','); + contentType = parts[0].split(':')[1]; + raw = parts[1]; + + return new Blob([raw], {type: contentType}); + } + + parts = dataURL.split(BASE64_MARKER); + contentType = parts[0].split(':')[1]; + raw = window.atob(parts[1]); + rawLength = raw.length; + + uInt8Array = new Uint8Array(rawLength); + + for (var i = 0; i < rawLength; ++i) { + uInt8Array[i] = raw.charCodeAt(i); + } + + return new Blob([uInt8Array], {type: contentType}); +}; + +//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously +EPUBJS.core.addScript = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('script'); + s.type = 'text/javascript'; + s.async = false; + s.src = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.addScripts = function(srcArr, callback, target) { + var total = srcArr.length, + curr = 0, + cb = function(){ + curr++; + if(total == curr){ + if(callback) callback(); + }else{ + EPUBJS.core.addScript(srcArr[curr], cb, target); + } + }; + + EPUBJS.core.addScript(srcArr[curr], cb, target); +}; + +EPUBJS.core.addCss = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('link'); + s.type = 'text/css'; + s.rel = "stylesheet"; + s.href = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.prefixed = function(unprefixed) { + var vendors = ["Webkit", "Moz", "O", "ms" ], + prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], + upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), + length = vendors.length; + + if (typeof(document.body.style[unprefixed]) != 'undefined') { + return unprefixed; + } + + for ( var i=0; i < length; i++ ) { + if (typeof(document.body.style[vendors[i] + upper]) != 'undefined') { + return vendors[i] + upper; + } + } + + return unprefixed; +}; + +EPUBJS.core.resolveUrl = function(base, path) { + var url, + segments = [], + uri = EPUBJS.core.uri(path), + folders = base.split("/"), + paths; + + if(uri.host) { + return path; + } + + folders.pop(); + + paths = path.split("/"); + paths.forEach(function(p){ + if(p === ".."){ + folders.pop(); + }else{ + segments.push(p); + } + }); + + url = folders.concat(segments); + + return url.join("/"); +}; + +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript +EPUBJS.core.uuid = function() { + var d = new Date().getTime(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = (d + Math.random()*16)%16 | 0; + d = Math.floor(d/16); + return (c=='x' ? r : (r&0x7|0x8)).toString(16); + }); + return uuid; +}; + +// Fast quicksort insert for sorted array -- based on: +// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers +EPUBJS.core.insert = function(item, array, compareFunction) { + var location = EPUBJS.core.locationOf(item, array, compareFunction); + array.splice(location, 0, item); + + return location; +}; + +EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return pivot; + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared > 0 ? pivot : pivot + 1; + } + + if(compared === 0) { + return pivot; + } + if(compared === -1) { + return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); + } +}; + +EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return -1; // Not found + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared === 0 ? pivot : -1; + } + if(compared === 0) { + return pivot; // Found + } + if(compared === -1) { + return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); + } +}; + + +EPUBJS.core.queue = function(_scope){ + var _q = []; + var scope = _scope; + // Add an item to the queue + var enqueue = function(funcName, args, context) { + _q.push({ + "funcName" : funcName, + "args" : args, + "context" : context + }); + return _q; + }; + // Run one item + var dequeue = function(){ + var inwait; + if(_q.length) { + inwait = _q.shift(); + // Defer to any current tasks + // setTimeout(function(){ + scope[inwait.funcName].apply(inwait.context || scope, inwait.args); + // }, 0); + } + }; + + // Run All + var flush = function(){ + while(_q.length) { + dequeue(); + } + }; + // Clear all items in wait + var clear = function(){ + _q = []; + }; + + var length = function(){ + return _q.length; + }; + + return { + "enqueue" : enqueue, + "dequeue" : dequeue, + "flush" : flush, + "clear" : clear, + "length" : length + }; +}; + +// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js +/** + * Gets an XPath for an element which describes its hierarchical location. + */ +EPUBJS.core.getElementXPath = function(element) { + if (element && element.id) { + return '//*[@id="' + element.id + '"]'; + } else { + return EPUBJS.core.getElementTreeXPath(element); + } +}; + +EPUBJS.core.getElementTreeXPath = function(element) { + var paths = []; + var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); + var index, nodeName, tagName, pathIndex; + + if(element.nodeType === Node.TEXT_NODE){ + // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; + index = EPUBJS.core.indexOfTextNode(element) + 1; + + paths.push("text()["+index+"]"); + element = element.parentNode; + } + + // Use nodeName (instead of localName) so namespace prefix is included (if any). + for (; element && element.nodeType == 1; element = element.parentNode) + { + index = 0; + for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) + { + // Ignore document type declaration. + if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { + continue; + } + if (sibling.nodeName == element.nodeName) { + ++index; + } + } + nodeName = element.nodeName.toLowerCase(); + tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); + pathIndex = (index ? "[" + (index+1) + "]" : ""); + paths.splice(0, 0, tagName + pathIndex); + } + + return paths.length ? "./" + paths.join("/") : null; +}; + +EPUBJS.core.nsResolver = function(prefix) { + var ns = { + 'xhtml' : 'http://www.w3.org/1999/xhtml', + 'epub': 'http://www.idpf.org/2007/ops' + }; + return ns[prefix] || null; +}; + +//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 +EPUBJS.core.cleanStringForXpath = function(str) { + var parts = str.match(/[^'"]+|['"]/g); + parts = parts.map(function(part){ + if (part === "'") { + return '\"\'\"'; // output "'" + } + + if (part === '"') { + return "\'\"\'"; // output '"' + } + return "\'" + part + "\'"; + }); + return "concat(\'\'," + parts.join(",") + ")"; +}; + +EPUBJS.core.indexOfTextNode = function(textNode){ + var parent = textNode.parentNode; + var children = parent.childNodes; + var sib; + var index = -1; + for (var i = 0; i < children.length; i++) { + sib = children[i]; + if(sib.nodeType === Node.TEXT_NODE){ + index++; + } + if(sib == textNode) break; + } + + return index; +}; +EPUBJS.EpubCFI = function(cfiStr){ + if(cfiStr) return this.parse(cfiStr); +}; + +EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) { + var pos = parseInt(_pos), + spineNodeIndex = _spineNodeIndex + 1, + cfi = '/'+spineNodeIndex+'/'; + + cfi += (pos + 1) * 2; + + if(id) cfi += "[" + id + "]"; + + //cfi += "!"; + + return cfi; +}; + +EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) { + var parts = []; + + steps.forEach(function(part){ + var segment = ''; + segment += (part.index + 1) * 2; + + if(part.id) { + segment += "[" + part.id + "]"; + } + + parts.push(segment); + }); + + return parts.join('/'); +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) { + var steps = this.pathTo(element); + var path = this.generatePathComponent(steps); + if(!path.length) { + // Start of Chapter + return "epubcfi(" + chapter + "!/4/)"; + } else { + // First Text Node + return "epubcfi(" + chapter + "!" + path + "/1:0)"; + } +}; + +EPUBJS.EpubCFI.prototype.pathTo = function(node) { + var stack = [], + children; + + while(node && node.parentNode !== null && node.parentNode.nodeType != 9) { + children = node.parentNode.children; + + stack.unshift({ + 'id' : node.id, + // 'classList' : node.classList, + 'tagName' : node.tagName, + 'index' : children ? Array.prototype.indexOf.call(children, node) : 0 + }); + + node = node.parentNode; + } + + return stack; +}; + +EPUBJS.EpubCFI.prototype.getChapterComponent = function(cfiStr) { + + var splitStr = cfiStr.split("!"); + + return splitStr[0]; +}; + +EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) { + + var splitStr = cfiStr.split("!"); + var pathComponent = splitStr[1] ? splitStr[1].split(":") : ''; + + return pathComponent[0]; +}; + +EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) { + var splitStr = cfiStr.split(":"); + return splitStr[1] || ''; +}; + + +EPUBJS.EpubCFI.prototype.parse = function(cfiStr) { + var cfi = {}, + chapSegment, + chapterComponent, + pathComponent, + charecterOffsetComponent, + assertion, + chapId, + path, + end, + endInt, + text, + parseStep = function(part){ + var type, index, has_brackets, id; + + type = "element"; + index = parseInt(part) / 2 - 1; + has_brackets = part.match(/\[(.*)\]/); + if(has_brackets && has_brackets[1]){ + id = has_brackets[1]; + } + + return { + "type" : type, + 'index' : index, + 'id' : id || false + }; + }; + + if(typeof cfiStr !== "string") { + return {spinePos: -1}; + } + + cfi.str = cfiStr; + + if(cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length-1] === ")") { + // Remove intial epubcfi( and ending ) + cfiStr = cfiStr.slice(8, cfiStr.length-1); + } + + chapterComponent = this.getChapterComponent(cfiStr); + pathComponent = this.getPathComponent(cfiStr) || ''; + charecterOffsetComponent = this.getCharecterOffsetComponent(cfiStr); + // Make sure this is a valid cfi or return + if(!chapterComponent) { + return {spinePos: -1}; + } + + // Chapter segment is always the second one + chapSegment = chapterComponent.split("/")[2] || ''; + if(!chapSegment) return {spinePos:-1}; + + cfi.spinePos = (parseInt(chapSegment) / 2 - 1 ) || 0; + + chapId = chapSegment.match(/\[(.*)\]/); + + cfi.spineId = chapId ? chapId[1] : false; + + if(pathComponent.indexOf(',') != -1) { + // Handle ranges -- not supported yet + console.warn("CFI Ranges are not supported"); + } + + path = pathComponent.split('/'); + end = path.pop(); + + cfi.steps = []; + + path.forEach(function(part){ + var step; + + if(part) { + step = parseStep(part); + cfi.steps.push(step); + } + }); + + //-- Check if END is a text node or element + endInt = parseInt(end); + if(!isNaN(endInt)) { + + if(endInt % 2 === 0) { // Even = is an element + cfi.steps.push(parseStep(end)); + } else { + cfi.steps.push({ + "type" : "text", + 'index' : (endInt - 1 ) / 2 + }); + } + + } + + assertion = charecterOffsetComponent.match(/\[(.*)\]/); + if(assertion && assertion[1]){ + cfi.characterOffset = parseInt(charecterOffsetComponent.split('[')[0]); + // We arent handling these assertions yet + cfi.textLocationAssertion = assertion[1]; + } else { + cfi.characterOffset = parseInt(charecterOffsetComponent); + } + + return cfi; +}; + +EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) { + var doc = _doc || document; + var marker = _marker || this.createMarker(doc); + var parent; + var lastStep; + var text; + var split; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + // Get the terminal step + lastStep = cfi.steps[cfi.steps.length-1]; + + // check spinePos + if(cfi.spinePos === -1) { + // Not a valid CFI + return false; + } + + // Find the CFI elements parent + parent = this.findParent(cfi, doc); + + if(!parent) { + // CFI didn't return an element + // Maybe it isnt in the current chapter? + return false; + } + + if(lastStep && lastStep.type === "text") { + text = parent.childNodes[lastStep.index]; + if(cfi.characterOffset){ + split = text.splitText(cfi.characterOffset); + marker.classList.add("EPUBJS-CFI-SPLIT"); + parent.insertBefore(marker, split); + } else { + parent.insertBefore(marker, text); + } + } else { + parent.insertBefore(marker, parent.firstChild); + } + + return marker; +}; + +EPUBJS.EpubCFI.prototype.createMarker = function(_doc) { + var doc = _doc || document; + var element = doc.createElement('span'); + element.id = "EPUBJS-CFI-MARKER:"+ EPUBJS.core.uuid(); + element.classList.add("EPUBJS-CFI-MARKER"); + + return element; +}; + +EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) { + var doc = _doc || document; + // var id = marker.id; + + // Cleanup textnodes if they were split + if(marker.classList.contains("EPUBJS-CFI-SPLIT")){ + nextSib = marker.nextSibling; + prevSib = marker.previousSibling; + if(nextSib && + prevSib && + nextSib.nodeType === 3 && + prevSib.nodeType === 3){ + + prevSib.textContent += nextSib.textContent; + marker.parentNode.removeChild(nextSib); + } + marker.parentNode.removeChild(marker); + } else if(marker.classList.contains("EPUBJS-CFI-MARKER")) { + // Remove only elements added as markers + marker.parentNode.removeChild(marker); + } + +}; + +EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) { + var doc = _doc || document, + element = doc.getElementsByTagName('html')[0], + children = Array.prototype.slice.call(element.children), + num, index, part, sections, + text, textBegin, textEnd; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + + sections = cfi.steps.slice(0); // Clone steps array + if(!sections.length) { + return doc.getElementsByTagName('body')[0]; + } + + while(sections && sections.length > 0) { + part = sections.shift(); + // Find textNodes Parent + if(part.type === "text") { + text = element.childNodes[part.index]; + element = text.parentNode || element; + // Find element by id if present + } else if(part.id){ + element = doc.getElementById(part.id); + // Find element in parent + }else{ + element = children[part.index]; + } + // Element can't be found + if(typeof element === "undefined") { + console.error("No Element For", part, cfi.str); + return false; + } + // Get current element children and continue through steps + children = Array.prototype.slice.call(element.children); + } + + return element; +}; + +EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) { + if(typeof cfiOne === 'string') { + cfiOne = new EPUBJS.EpubCFI(cfiOne); + } + if(typeof cfiTwo === 'string') { + cfiTwo = new EPUBJS.EpubCFI(cfiTwo); + } + // Compare Spine Positions + if(cfiOne.spinePos > cfiTwo.spinePos) { + return 1; + } + if(cfiOne.spinePos < cfiTwo.spinePos) { + return -1; + } + + + // Compare Each Step in the First item + for (var i = 0; i < cfiOne.steps.length; i++) { + if(!cfiTwo.steps[i]) { + return 1; + } + if(cfiOne.steps[i].index > cfiTwo.steps[i].index) { + return 1; + } + if(cfiOne.steps[i].index < cfiTwo.steps[i].index) { + return -1; + } + // Otherwise continue checking + } + + // All steps in First present in Second + if(cfiOne.steps.length < cfiTwo.steps.length) { + return -1; + } + + // Compare the charecter offset of the text node + if(cfiOne.characterOffset > cfiTwo.characterOffset) { + return 1; + } + if(cfiOne.characterOffset < cfiTwo.characterOffset) { + return -1; + } + + // CFI's are equal + return 0; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) { + var uri = EPUBJS.core.uri(href); + var path = uri.path; + var fragment = uri.fragment; + var spinePos = book.spineIndexByURL[path]; + var loaded; + var deferred = new RSVP.defer(); + var epubcfi = new EPUBJS.EpubCFI(); + var spineItem; + + if(typeof spinePos !== "undefined"){ + spineItem = book.spine[spinePos]; + loaded = book.loadXml(spineItem.url); + loaded.then(function(doc){ + var element = doc.getElementById(fragment); + var cfi; + cfi = epubcfi.generateCfiFromElement(element, spineItem.cfiBase); + deferred.resolve(cfi); + }); + } + + return deferred.promise; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) { + var parent = anchor.parentNode; + var steps = this.pathTo(parent); + var path = this.generatePathComponent(steps); + var index = 1 + (2 * Array.prototype.indexOf.call(parent.childNodes, anchor)); + return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")"; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) { + var anchor = range.anchorNode; + var offset = range.anchorOffset; + return this.generateCfiFromTextNode(anchor, offset, base); +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) { + var start, startElement, startSteps, startPath, startOffset, startIndex; + var end, endElement, endSteps, endPath, endOffset, endIndex; + + start = range.startContainer; + + if(start.nodeType === 3) { // text node + startElement = start.parentNode; + //startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start)); + startIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(start)); + startSteps = this.pathTo(startElement); + } else if(range.collapsed) { + return this.generateCfiFromElement(start, base); // single element + } else { + startSteps = this.pathTo(start); + } + + startPath = this.generatePathComponent(startSteps); + startOffset = range.startOffset; + + if(!range.collapsed) { + end = range.endContainer; + + if(end.nodeType === 3) { // text node + endElement = end.parentNode; + // endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end)); + endIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(end)); + + endSteps = this.pathTo(endElement); + } else { + endSteps = this.pathTo(end); + } + + endPath = this.generatePathComponent(endSteps); + endOffset = range.endOffset; + + return "epubcfi(" + base + "!" + startPath + "/" + startIndex + ":" + startOffset + "," + endPath + "/" + endIndex + ":" + endOffset + ")"; + + } else { + return "epubcfi(" + base + "!" + startPath + "/"+ startIndex +":"+ startOffset +")"; + } +}; + +EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) { + var xpath = [".", "*"]; + + steps.forEach(function(step){ + var position = step.index + 1; + + if(step.id){ + xpath.push("*[position()=" + position + " and @id='" + step.id + "']"); + } else if(step.type === "text") { + xpath.push("text()[" + position + "]"); + } else { + xpath.push("*[" + position + "]"); + } + }); + + return xpath.join("/"); +}; + + +EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) { + var doc = _doc || document; + var range = doc.createRange(); + var lastStep; + var xpath; + var startContainer; + var textLength; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + + // check spinePos + if(cfi.spinePos === -1) { + // Not a valid CFI + return false; + } + + xpath = this.generateXpathFromSteps(cfi.steps); + + // Get the terminal step + lastStep = cfi.steps[cfi.steps.length-1]; + startContainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(!startContainer) { + return null; + } + + if(startContainer && cfi.characterOffset >= 0) { + textLength = startContainer.length; + + if(cfi.characterOffset < textLength) { + range.setStart(startContainer, cfi.characterOffset); + range.setEnd(startContainer, textLength ); + } else { + console.debug("offset greater than length:", cfi.characterOffset, textLength); + range.setStart(startContainer, textLength - 1 ); + range.setEnd(startContainer, textLength ); + } + } else if(startContainer) { + range.selectNode(startContainer); + } + // doc.defaultView.getSelection().addRange(range); + return range; +}; + +EPUBJS.Events = function(obj, el){ + + this.events = {}; + + if(!el){ + this.el = document.createElement('div'); + }else{ + this.el = el; + } + + obj.createEvent = this.createEvent; + obj.tell = this.tell; + obj.listen = this.listen; + obj.deafen = this.deafen; + obj.listenUntil = this.listenUntil; + + return this; +}; + +EPUBJS.Events.prototype.createEvent = function(evt){ + var e = new CustomEvent(evt); + this.events[evt] = e; + return e; +}; + +EPUBJS.Events.prototype.tell = function(evt, msg){ + var e; + + if(!this.events[evt]){ + console.warn("No event:", evt, "defined yet, creating."); + e = this.createEvent(evt); + }else{ + e = this.events[evt]; + } + + if(msg) e.msg = msg; + this.el.dispatchEvent(e); + +}; + +EPUBJS.Events.prototype.listen = function(evt, func, bindto){ + if(!this.events[evt]){ + console.warn("No event:", evt, "defined yet, creating."); + this.createEvent(evt); + return; + } + + if(bindto){ + this.el.addEventListener(evt, func.bind(bindto), false); + }else{ + this.el.addEventListener(evt, func, false); + } + +}; + +EPUBJS.Events.prototype.deafen = function(evt, func){ + this.el.removeEventListener(evt, func, false); +}; + +EPUBJS.Events.prototype.listenUntil = function(OnEvt, OffEvt, func, bindto){ + this.listen(OnEvt, func, bindto); + + function unlisten(){ + this.deafen(OnEvt, func); + this.deafen(OffEvt, unlisten); + } + + this.listen(OffEvt, unlisten, this); +}; +EPUBJS.hooks = {}; +EPUBJS.Hooks = (function(){ + function hooks(){} + + //-- Get pre-registered hooks + hooks.prototype.getHooks = function(){ + var plugs; + this.hooks = {}; + Array.prototype.slice.call(arguments).forEach(function(arg){ + this.hooks[arg] = []; + }, this); + + for (var plugType in this.hooks) { + plugs = _.values(EPUBJS.hooks[plugType]); + + plugs.forEach(function(hook){ + this.registerHook(plugType, hook); + }, this); + } + }; + + //-- Hooks allow for injecting async functions that must all complete before continuing + // Functions must have a callback as their first argument. + hooks.prototype.registerHook = function(type, toAdd, toFront){ + + if(typeof(this.hooks[type]) != "undefined"){ + + if(typeof(toAdd) === "function"){ + if(toFront) { + this.hooks[type].unshift(toAdd); + }else{ + this.hooks[type].push(toAdd); + } + }else if(Array.isArray(toAdd)){ + toAdd.forEach(function(hook){ + if(toFront) { + this.hooks[type].unshift(hook); + }else{ + this.hooks[type].push(hook); + } + }, this); + } + }else{ + //-- Allows for undefined hooks, but maybe this should error? + this.hooks[type] = [func]; + } + }; + + hooks.prototype.triggerHooks = function(type, callback, passed){ + var hooks, count; + + if(typeof(this.hooks[type]) == "undefined") return false; + + hooks = this.hooks[type]; + + count = hooks.length; + if(count === 0 && callback) { + callback(); + } + + function countdown(){ + count--; + if(count <= 0 && callback) callback(); + } + + hooks.forEach(function(hook){ + hook(countdown, passed); + }); + }; + + return { + register: function(name) { + if(EPUBJS.hooks[name] === undefined) { EPUBJS.hooks[name] = {}; } + if(typeof EPUBJS.hooks[name] !== 'object') { throw "Already registered: "+name; } + return EPUBJS.hooks[name]; + }, + mixin: function(object) { + for (var prop in hooks.prototype) { + object[prop] = hooks.prototype[prop]; + } + } + }; +})(); + + +EPUBJS.Layout = EPUBJS.Layout || {}; + +EPUBJS.Layout.Reflowable = function(){ + this.documentElement = null; + this.spreadWidth = null; +}; + +EPUBJS.Layout.Reflowable.prototype.format = function(documentElement, _width, _height, _gap){ + // Get the prefixed CSS commands + var columnAxis = EPUBJS.core.prefixed('columnAxis'); + var columnGap = EPUBJS.core.prefixed('columnGap'); + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var columnFill = EPUBJS.core.prefixed('columnFill'); + + //-- Check the width and create even width columns + var width = Math.floor(_width); + // var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 0; // Not needed for single + var section = Math.floor(width / 8); + var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); + this.documentElement = documentElement; + //-- Single Page + this.spreadWidth = (width + gap); + + + documentElement.style.overflow = "hidden"; + + // Must be set to the new calculated width or the columns will be off + documentElement.style.width = width + "px"; + + //-- Adjust height + documentElement.style.height = _height + "px"; + + //-- Add columns + documentElement.style[columnAxis] = "horizontal"; + documentElement.style[columnFill] = "auto"; + documentElement.style[columnWidth] = width+"px"; + documentElement.style[columnGap] = gap+"px"; + this.colWidth = width; + this.gap = gap; + + return { + pageWidth : this.spreadWidth, + pageHeight : _height + }; +}; + +EPUBJS.Layout.Reflowable.prototype.calculatePages = function() { + var totalWidth, displayedPages; + this.documentElement.style.width = "auto"; //-- reset width for calculations + totalWidth = this.documentElement.scrollWidth; + displayedPages = Math.ceil(totalWidth / this.spreadWidth); + + return { + displayedPages : displayedPages, + pageCount : displayedPages + }; +}; + +EPUBJS.Layout.ReflowableSpreads = function(){ + this.documentElement = null; + this.spreadWidth = null; +}; + +EPUBJS.Layout.ReflowableSpreads.prototype.format = function(documentElement, _width, _height, _gap){ + var columnAxis = EPUBJS.core.prefixed('columnAxis'); + var columnGap = EPUBJS.core.prefixed('columnGap'); + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var columnFill = EPUBJS.core.prefixed('columnFill'); + + var divisor = 2, + cutoff = 800; + + //-- Check the width and create even width columns + var fullWidth = Math.floor(_width); + var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 1; + + var section = Math.floor(width / 8); + var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); + + //-- Double Page + var colWidth = Math.floor((width - gap) / divisor); + + this.documentElement = documentElement; + this.spreadWidth = (colWidth + gap) * divisor; + + + documentElement.style.overflow = "hidden"; + + // Must be set to the new calculated width or the columns will be off + documentElement.style.width = width + "px"; + + //-- Adjust height + documentElement.style.height = _height + "px"; + + //-- Add columns + documentElement.style[columnAxis] = "horizontal"; + documentElement.style[columnFill] = "auto"; + documentElement.style[columnGap] = gap+"px"; + documentElement.style[columnWidth] = colWidth+"px"; + + this.colWidth = colWidth; + this.gap = gap; + return { + pageWidth : this.spreadWidth, + pageHeight : _height + }; +}; + +EPUBJS.Layout.ReflowableSpreads.prototype.calculatePages = function() { + var totalWidth = this.documentElement.scrollWidth; + var displayedPages = Math.ceil(totalWidth / this.spreadWidth); + + //-- Add a page to the width of the document to account an for odd number of pages + this.documentElement.style.width = ((displayedPages * this.spreadWidth) - this.gap) + "px"; + + return { + displayedPages : displayedPages, + pageCount : displayedPages * 2 + }; +}; + +EPUBJS.Layout.Fixed = function(){ + this.documentElement = null; +}; + +EPUBJS.Layout.Fixed.prototype.format = function(documentElement, _width, _height, _gap){ + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var viewport = documentElement.querySelector("[name=viewport"); + var content; + var contents; + var width, height; + this.documentElement = documentElement; + /** + * check for the viewport size + * + */ + if(viewport && viewport.hasAttribute("content")) { + content = viewport.getAttribute("content"); + contents = content.split(','); + if(contents[0]){ + width = contents[0].replace("width=", ''); + } + if(contents[1]){ + height = contents[1].replace("height=", ''); + } + } + + //-- Adjust width and height + documentElement.style.width = width + "px" || "auto"; + documentElement.style.height = height + "px" || "auto"; + + //-- Remove columns + documentElement.style[columnWidth] = "auto"; + + //-- Scroll + documentElement.style.overflow = "auto"; + + this.colWidth = width; + this.gap = 0; + + return { + pageWidth : width, + pageHeight : height + }; + +}; + +EPUBJS.Layout.Fixed.prototype.calculatePages = function(){ + return { + displayedPages : 1, + pageCount : 1 + }; +}; + +EPUBJS.Pagination = function(pageList) { + this.pages = []; + this.locations = []; + this.epubcfi = new EPUBJS.EpubCFI(); + if(pageList && pageList.length) { + this.process(pageList); + } +}; + +EPUBJS.Pagination.prototype.process = function(pageList){ + pageList.forEach(function(item){ + this.pages.push(item.page); + this.locations.push(item.cfi); + }, this); + + this.pageList = pageList; + this.firstPage = parseInt(this.pages[0]); + this.lastPage = parseInt(this.pages[this.pages.length-1]); + this.totalPages = this.lastPage - this.firstPage; +}; + +EPUBJS.Pagination.prototype.pageFromCfi = function(cfi){ + var pg = -1; + + // Check if the pageList has not been set yet + if(this.locations.length === 0) { + return -1; + } + + // TODO: check if CFI is valid? + + // check if the cfi is in the location list + // var index = this.locations.indexOf(cfi); + var index = EPUBJS.core.indexOfSorted(cfi, this.locations, this.epubcfi.compare); + if(index != -1 && index < (this.pages.length-1) ) { + pg = this.pages[index]; + } else { + // Otherwise add it to the list of locations + // Insert it in the correct position in the locations page + //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare); + index = EPUBJS.core.locationOf(cfi, this.locations, this.epubcfi.compare); + // Get the page at the location just before the new one, or return the first + pg = index-1 >= 0 ? this.pages[index-1] : this.pages[0]; + if(pg !== undefined) { + // Add the new page in so that the locations and page array match up + //this.pages.splice(index, 0, pg); + } else { + pg = -1; + } + + } + return pg; +}; + +EPUBJS.Pagination.prototype.cfiFromPage = function(pg){ + var cfi = -1; + // check that pg is an int + if(typeof pg != "number"){ + pg = parseInt(pg); + } + + // check if the cfi is in the page list + // Pages could be unsorted. + var index = this.pages.indexOf(pg); + if(index != -1) { + cfi = this.locations[index]; + } + // TODO: handle pages not in the list + return cfi; +}; + +EPUBJS.Pagination.prototype.pageFromPercentage = function(percent){ + var pg = Math.round(this.totalPages * percent); + return pg; +}; + +// Returns a value between 0 - 1 corresponding to the location of a page +EPUBJS.Pagination.prototype.percentageFromPage = function(pg){ + var percentage = (pg - this.firstPage) / this.totalPages; + return Math.round(percentage * 1000) / 1000; +}; + +// Returns a value between 0 - 1 corresponding to the location of a cfi +EPUBJS.Pagination.prototype.percentageFromCfi = function(cfi){ + var pg = this.pageFromCfi(cfi); + var percentage = this.percentageFromPage(pg); + return percentage; +}; +EPUBJS.Parser = function(baseUrl){ + this.baseUrl = baseUrl || ''; +}; + +EPUBJS.Parser.prototype.container = function(containerXml){ + //-- + var rootfile, fullpath, folder, encoding; + + if(!containerXml) { + console.error("Container File Not Found"); + return; + } + + rootfile = containerXml.querySelector("rootfile"); + + if(!rootfile) { + console.error("No RootFile Found"); + return; + } + + fullpath = rootfile.getAttribute('full-path'); + folder = EPUBJS.core.uri(fullpath).directory; + encoding = containerXml.xmlEncoding; + + //-- Now that we have the path we can parse the contents + return { + 'packagePath' : fullpath, + 'basePath' : folder, + 'encoding' : encoding + }; +}; + +EPUBJS.Parser.prototype.identifier = function(packageXml){ + var metadataNode; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = packageXml.querySelector("metadata"); + + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + return this.getElementText(metadataNode, "identifier"); +}; + +EPUBJS.Parser.prototype.packageContents = function(packageXml, baseUrl){ + var parse = this; + var metadataNode, manifestNode, spineNode; + var manifest, navPath, tocPath, coverPath; + var spineNodeIndex; + var spine; + var spineIndexByURL; + + if(baseUrl) this.baseUrl = baseUrl; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = packageXml.querySelector("metadata"); + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + manifestNode = packageXml.querySelector("manifest"); + if(!manifestNode) { + console.error("No Manifest Found"); + return; + } + + spineNode = packageXml.querySelector("spine"); + if(!spineNode) { + console.error("No Spine Found"); + return; + } + + manifest = parse.manifest(manifestNode); + navPath = parse.findNavPath(manifestNode); + tocPath = parse.findTocPath(manifestNode, spineNode); + coverPath = parse.findCoverPath(manifestNode); + + spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); + + spine = parse.spine(spineNode, manifest); + + spineIndexByURL = {}; + spine.forEach(function(item){ + spineIndexByURL[item.href] = item.index; + }); + + return { + 'metadata' : parse.metadata(metadataNode), + 'spine' : spine, + 'manifest' : manifest, + 'navPath' : navPath, + 'tocPath' : tocPath, + 'coverPath': coverPath, + 'spineNodeIndex' : spineNodeIndex, + 'spineIndexByURL' : spineIndexByURL + }; +}; + +//-- Find TOC NAV +EPUBJS.Parser.prototype.findNavPath = function(manifestNode){ + // Find item with property 'nav' + // Should catch nav irregardless of order + var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); + return node ? node.getAttribute('href') : false; +}; + +//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" +EPUBJS.Parser.prototype.findTocPath = function(manifestNode, spineNode){ + var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); + var tocId; + + // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as + // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2, + // "The item that describes the NCX must be referenced by the spine toc attribute." + if (!node) { + tocId = spineNode.getAttribute("toc"); + if(tocId) { + node = manifestNode.querySelector("item[id='" + tocId + "']"); + } + } + + return node ? node.getAttribute('href') : false; +}; + +//-- Find Cover: +EPUBJS.Parser.prototype.findCoverPath = function(manifestNode){ + var node = manifestNode.querySelector("item[properties='cover-image']"); + return node ? node.getAttribute('href') : false; +}; + +//-- Expanded to match Readium web components +EPUBJS.Parser.prototype.metadata = function(xml){ + var metadata = {}, + p = this; + + metadata.bookTitle = p.getElementText(xml, 'title'); + metadata.creator = p.getElementText(xml, 'creator'); + metadata.description = p.getElementText(xml, 'description'); + + metadata.pubdate = p.getElementText(xml, 'date'); + + metadata.publisher = p.getElementText(xml, 'publisher'); + + metadata.identifier = p.getElementText(xml, "identifier"); + metadata.language = p.getElementText(xml, "language"); + metadata.rights = p.getElementText(xml, "rights"); + + metadata.modified_date = p.querySelectorText(xml, "meta[property='dcterms:modified']"); + metadata.layout = p.querySelectorText(xml, "meta[property='rendition:layout']"); + metadata.orientation = p.querySelectorText(xml, "meta[property='rendition:orientation']"); + metadata.spread = p.querySelectorText(xml, "meta[property='rendition:spread']"); + // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); + + return metadata; +}; + +EPUBJS.Parser.prototype.getElementText = function(xml, tag){ + var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), + el; + + if(!found || found.length === 0) return ''; + + el = found[0]; + + if(el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; + +}; + +EPUBJS.Parser.prototype.querySelectorText = function(xml, q){ + var el = xml.querySelector(q); + + if(el && el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; +}; + +EPUBJS.Parser.prototype.manifest = function(manifestXml){ + var baseUrl = this.baseUrl, + manifest = {}; + + //-- Turn items into an array + var selected = manifestXml.querySelectorAll("item"), + items = Array.prototype.slice.call(selected); + + //-- Create an object with the id as key + items.forEach(function(item){ + var id = item.getAttribute('id'), + href = item.getAttribute('href') || '', + type = item.getAttribute('media-type') || '', + properties = item.getAttribute('properties') || ''; + + manifest[id] = { + 'href' : href, + 'url' : baseUrl + href, //-- Absolute URL for loading with a web worker + 'type' : type, + 'properties' : properties + }; + + }); + + return manifest; + +}; + +EPUBJS.Parser.prototype.spine = function(spineXml, manifest){ + var spine = []; + + var selected = spineXml.getElementsByTagName("itemref"), + items = Array.prototype.slice.call(selected); + + var spineNodeIndex = Array.prototype.indexOf.call(spineXml.parentNode.childNodes, spineXml); + + var epubcfi = new EPUBJS.EpubCFI(); + + //-- Add to array to mantain ordering and cross reference with manifest + items.forEach(function(item, index){ + var Id = item.getAttribute('idref'); + var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); + var props = item.getAttribute('properties') || ''; + var propArray = props.length ? props.split(' ') : []; + var manifestProps = manifest[Id].properties; + var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : []; + var vert = { + 'id' : Id, + 'linear' : item.getAttribute('linear') || '', + 'properties' : propArray, + 'manifestProperties' : manifestPropArray, + 'href' : manifest[Id].href, + 'url' : manifest[Id].url, + 'index' : index, + 'cfiBase' : cfiBase, + 'cfi' : "epub(" + cfiBase + ")" + }; + spine.push(vert); + }); + + return spine; +}; + +EPUBJS.Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ + var navEl = navHtml.querySelector('nav[*|type="toc"]'), //-- [*|type="toc"] * Doesn't seem to work + idCounter = 0; + + if(!navEl) return []; + + // Implements `> ol > li` + function findListItems(parent){ + var items = []; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('ol' == node.tagName){ + Array.prototype.slice.call(node.childNodes).forEach(function(item){ + if('li' == item.tagName){ + items.push(item); + } + }); + } + }); + + return items; + + } + + // Implements `> a, > span` + function findAnchorOrSpan(parent){ + var item = null; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('a' == node.tagName || 'span' == node.tagName){ + item = node; + } + }); + + return item; + } + + function getTOC(parent){ + var list = [], + nodes = findListItems(parent), + items = Array.prototype.slice.call(nodes), + length = items.length, + node; + + if(length === 0) return false; + + items.forEach(function(item){ + var id = item.getAttribute('id') || false, + content = findAnchorOrSpan(item), + href = content.getAttribute('href') || '', + text = content.textContent || "", + split = href.split("#"), + baseUrl = split[0], + subitems = getTOC(item), + spinePos = spineIndexByURL[baseUrl], + spineItem = bookSpine[spinePos], + cfi = spineItem ? spineItem.cfi : ''; + + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + (idCounter++); + } + } + + item.setAttribute('id', id); // Ensure all elements have an id + list.push({ + "id": id, + "href": href, + "label": text, + "subitems" : subitems, + "parent" : parent ? parent.getAttribute('id') : null, + "cfi" : cfi + }); + + }); + + return list; + } + + return getTOC(navEl); +}; + +EPUBJS.Parser.prototype.toc = function(tocXml, spineIndexByURL, bookSpine){ + var navMap = tocXml.querySelector("navMap"); + if(!navMap) return []; + + function getTOC(parent){ + var list = [], + snapshot = tocXml.evaluate("*[local-name()='navPoint']", parent, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null), + length = snapshot.snapshotLength; + + if(length === 0) return []; + + for ( var i=length-1 ; i >= 0; i-- ) { + var item = snapshot.snapshotItem(i); + + var id = item.getAttribute('id') || false, + content = item.querySelector("content"), + src = content.getAttribute('src'), + navLabel = item.querySelector("navLabel"), + text = navLabel.textContent ? navLabel.textContent : "", + split = src.split("#"), + baseUrl = split[0], + spinePos = spineIndexByURL[baseUrl], + spineItem = bookSpine[spinePos], + subitems = getTOC(item), + cfi = spineItem ? spineItem.cfi : ''; + + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + (idCounter++); + } + } + + list.unshift({ + "id": id, + "href": src, + "label": text, + "spinePos": spinePos, + "subitems" : subitems, + "parent" : parent ? parent.getAttribute('id') : null, + "cfi" : cfi + }); + + } + + return list; + } + + return getTOC(navMap); +}; + +EPUBJS.Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ + var navEl = navHtml.querySelector('nav[*|type="page-list"]'), + idCounter = 0; + + if(!navEl) return []; + + // Implements `> ol > li` + function findListItems(parent){ + var items = []; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('ol' == node.tagName){ + Array.prototype.slice.call(node.childNodes).forEach(function(item){ + if('li' == item.tagName){ + items.push(item); + } + }); + } + }); + + return items; + + } + + // Implements `> a, > span` + function findAnchorOrSpan(parent){ + var item = null; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('a' == node.tagName || 'span' == node.tagName){ + item = node; + } + }); + + return item; + } + + function getPages(parent){ + var list = [], + nodes = findListItems(parent), + items = Array.prototype.slice.call(nodes), + length = items.length, + node; + + if(length === 0) return false; + + items.forEach(function(item){ + var id = item.getAttribute('id') || false, + content = findAnchorOrSpan(item), + href = content.getAttribute('href') || '', + text = content.textContent || "", + page = parseInt(text), + isCfi = href.indexOf("epubcfi"), + split, + packageUrl, + cfi; + + if(isCfi != -1) { + split = href.split("#"); + packageUrl = split[0]; + cfi = split.length > 1 ? split[1] : false; + list.push({ + "cfi" : cfi, + "href" : href, + "packageUrl" : packageUrl, + "page" : page + }); + } else { + list.push({ + "href" : href, + "page" : page + }); + } + + }); + + return list; + } + + return getPages(navEl); +}; + +EPUBJS.Render.Iframe = function() { + this.iframe = null; + this.document = null; + this.window = null; + this.docEl = null; + this.bodyEl = null; + + this.leftPos = 0; + this.pageWidth = 0; +}; + +//-- Build up any html needed +EPUBJS.Render.Iframe.prototype.create = function(){ + this.iframe = document.createElement('iframe'); + this.iframe.id = "epubjs-iframe:" + EPUBJS.core.uuid(); + this.iframe.scrolling = "no"; + this.iframe.seamless = "seamless"; + // Back up if seamless isn't supported + this.iframe.style.border = "none"; + + this.iframe.addEventListener("load", this.loaded.bind(this), false); + return this.iframe; +}; + +/** +* Sets the source of the iframe with the given URL string +* Takes: URL string +* Returns: promise with document element +*/ +EPUBJS.Render.Iframe.prototype.load = function(chapter){ + var render = this, + deferred = new RSVP.defer(); + + chapter.url().then(function(url){ + // Reset the scroll position + render.leftPos = 0; + + if(this.window) { + this.unload(); + } + + this.iframe.onload = function(e) { + render.document = render.iframe.contentDocument; + render.docEl = render.document.documentElement; + render.headEl = render.document.head; + render.bodyEl = render.document.body || render.document.querySelector("body"); + render.window = render.iframe.contentWindow; + + render.window.addEventListener("resize", render.resized.bind(render), false); + + //-- Clear Margins + if(render.bodyEl) { + render.bodyEl.style.margin = "0"; + } + + deferred.resolve(render.docEl); + }; + + this.iframe.onerror = function(e) { + //console.error("Error Loading Contents", e); + deferred.reject({ + message : "Error Loading Contents: " + e, + stack : new Error().stack + }); + }; + + this.iframe.contentWindow.location.replace(url); + + }.bind(this)); + + return deferred.promise; +}; + + +EPUBJS.Render.Iframe.prototype.loaded = function(v){ + var url = this.iframe.contentWindow.location.href; + if(url != "about:blank"){ + this.trigger("render:loaded", url); + } +}; + +// Resize the iframe to the given width and height +EPUBJS.Render.Iframe.prototype.resize = function(width, height){ + var iframeBox; + + if(!this.iframe) return; + + this.iframe.height = height; + + if(!isNaN(width) && width % 2 !== 0){ + width += 1; //-- Prevent cutting off edges of text in columns + } + + this.iframe.width = width; + // Get the fractional height and width of the iframe + // Default to orginal if bounding rect is 0 + this.width = this.iframe.getBoundingClientRect().width || width; + this.height = this.iframe.getBoundingClientRect().height || height; +}; + + +EPUBJS.Render.Iframe.prototype.resized = function(e){ + // Get the fractional height and width of the iframe + this.width = this.iframe.getBoundingClientRect().width; + this.height = this.iframe.getBoundingClientRect().height; +}; + +EPUBJS.Render.Iframe.prototype.totalWidth = function(){ + return this.docEl.scrollWidth; +}; + +EPUBJS.Render.Iframe.prototype.totalHeight = function(){ + return this.docEl.scrollHeight; +}; + +EPUBJS.Render.Iframe.prototype.setPageDimensions = function(pageWidth, pageHeight){ + this.pageWidth = pageWidth; + this.pageHeight = pageHeight; + //-- Add a page to the width of the document to account an for odd number of pages + // this.docEl.style.width = this.docEl.scrollWidth + pageWidth + "px"; +}; + +EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){ + // this.bodyEl.style.marginLeft = -leftPos + "px"; + // this.docEl.style.marginLeft = -leftPos + "px"; + // this.docEl.style[EPUBJS.Render.Iframe.transform] = 'translate('+ (-leftPos) + 'px, 0)'; + this.document.defaultView.scrollTo(leftPos, 0); +}; + +EPUBJS.Render.Iframe.prototype.setStyle = function(style, val, prefixed){ + if(prefixed) { + style = EPUBJS.core.prefixed(style); + } + + if(this.bodyEl) this.bodyEl.style[style] = val; +}; + +EPUBJS.Render.Iframe.prototype.removeStyle = function(style){ + + if(this.bodyEl) this.bodyEl.style[style] = ''; + +}; + +EPUBJS.Render.Iframe.prototype.addHeadTag = function(tag, attrs, _doc) { + var doc = _doc || this.document; + var tagEl = doc.createElement(tag); + var headEl = doc.head; + + for(var attr in attrs) { + tagEl.setAttribute(attr, attrs[attr]); + } + + if(headEl) headEl.insertBefore(tagEl, headEl.firstChild); +}; + +EPUBJS.Render.Iframe.prototype.page = function(pg){ + this.leftPos = this.pageWidth * (pg-1); //-- pages start at 1 + this.setLeft(this.leftPos); +}; + +//-- Show the page containing an Element +EPUBJS.Render.Iframe.prototype.getPageNumberByElement = function(el){ + var left, pg; + if(!el) return; + + left = this.leftPos + el.getBoundingClientRect().left; //-- Calculate left offset compaired to scrolled position + + pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 + + return pg; +}; + +//-- Show the page containing an Element +EPUBJS.Render.Iframe.prototype.getPageNumberByRect = function(boundingClientRect){ + var left, pg; + + left = this.leftPos + boundingClientRect.left; //-- Calculate left offset compaired to scrolled position + pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 + + return pg; +}; + +// Return the root element of the content +EPUBJS.Render.Iframe.prototype.getBaseElement = function(){ + return this.bodyEl; +}; + +// Checks if an element is on the screen +EPUBJS.Render.Iframe.prototype.isElementVisible = function(el){ + var rect; + var left; + + if(el && typeof el.getBoundingClientRect === 'function'){ + rect = el.getBoundingClientRect(); + left = rect.left; //+ rect.width; + if( rect.width !== 0 && + rect.height !== 0 && // Element not visible + left >= 0 && + left < this.pageWidth ) { + return true; + } + } + + return false; +}; + + +EPUBJS.Render.Iframe.prototype.scroll = function(bool){ + if(bool) { + this.iframe.scrolling = "yes"; + } else { + this.iframe.scrolling = "no"; + } +}; + +// Cleanup event listeners +EPUBJS.Render.Iframe.prototype.unload = function(){ + this.window.removeEventListener("resize", this.resized); +}; + +//-- Enable binding events to Render +RSVP.EventTarget.mixin(EPUBJS.Render.Iframe.prototype); +EPUBJS.Renderer = function(renderMethod, hidden) { + // Dom events to listen for + this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click"]; + this.upEvent = "mouseup"; + this.downEvent = "mousedown"; + if('ontouchstart' in document.documentElement) { + this.listenedEvents.push("touchstart", "touchend"); + this.upEvent = "touchend"; + this.downEvent = "touchstart"; + } + /** + * Setup a render method. + * Options are: Iframe + */ + if(renderMethod && typeof(EPUBJS.Render[renderMethod]) != "undefined"){ + this.render = new EPUBJS.Render[renderMethod](); + } else { + console.error("Not a Valid Rendering Method"); + } + + // Listen for load events + this.render.on("render:loaded", this.loaded.bind(this)); + + // Cached for replacement urls from storage + this.caches = {}; + + // Blank Cfi for Parsing + this.epubcfi = new EPUBJS.EpubCFI(); + + this.spreads = true; + this.isForcedSingle = false; + this.resized = _.debounce(this.onResized.bind(this), 100); + + this.layoutSettings = {}; + + this.hidden = hidden || false; + //-- Adds Hook methods to the Book prototype + // Hooks will all return before triggering the callback. + EPUBJS.Hooks.mixin(this); + //-- Get pre-registered hooks for events + this.getHooks("beforeChapterDisplay"); + + //-- Queue up page changes if page map isn't ready + this._q = EPUBJS.core.queue(this); + + this._moving = false; + +}; + +//-- Renderer events for listening +EPUBJS.Renderer.prototype.Events = [ + "renderer:keydown", + "renderer:keyup", + "renderer:keypressed", + "renderer:mouseup", + "renderer:mousedown", + "renderer:click", + "renderer:touchstart", + "renderer:touchend", + "renderer:selected", + "renderer:chapterUnloaded", + "renderer:chapterDisplayed", + "renderer:locationChanged", + "renderer:visibleLocationChanged", + "renderer:resized", + "renderer:spreads" +]; + +/** +* Creates an element to render to. +* Resizes to passed width and height or to the elements size +*/ +EPUBJS.Renderer.prototype.initialize = function(element, width, height){ + this.container = element; + this.element = this.render.create(); + + this.initWidth = width; + this.initHeight = height; + + this.width = width || this.container.clientWidth; + this.height = height || this.container.clientHeight; + + this.container.appendChild(this.element); + + if(width && height){ + this.render.resize(this.width, this.height); + } else { + this.render.resize('100%', '100%'); + } + + document.addEventListener("orientationchange", this.onResized); +}; + +/** +* Display a chapter +* Takes: chapter object, global layout settings +* Returns: Promise with passed Renderer after pages has loaded +*/ +EPUBJS.Renderer.prototype.displayChapter = function(chapter, globalLayout){ + var store = false; + if(this._moving) { + console.error("Rendering In Progress"); + return; + } + this._moving = true; + // Get the url string from the chapter (may be from storage) + return chapter.url(). + then(function(url) { + + // Unload the previous chapter listener + if(this.currentChapter) { + this.currentChapter.unload(); // Remove stored blobs + + if(this.render.window){ + this.render.window.removeEventListener("resize", this.resized); + } + + this.removeEventListeners(); + this.removeSelectionListeners(); + this.trigger("renderer:chapterUnloaded"); + this.contents = null; + this.doc = null; + this.pageMap = null; + } + + this.currentChapter = chapter; + this.chapterPos = 1; + this.currentChapterCfiBase = chapter.cfiBase; + + this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties); + return this.load(chapter); + + }.bind(this)); + +}; + +/** +* Loads a url (string) and renders it, +* attaching event listeners and triggering hooks. +* Returns: Promise with the rendered contents. +*/ + +EPUBJS.Renderer.prototype.load = function(url){ + var deferred = new RSVP.defer(); + var loaded; + + // Switch to the required layout method for the settings + this.layoutMethod = this.determineLayout(this.layoutSettings); + this.layout = new EPUBJS.Layout[this.layoutMethod](); + + this.visible(false); + + render = this.render.load(url); + + render.then(function(contents) { + var formated; + this.currentChapter.setDocument(this.render.document); + this.contents = contents; + this.doc = this.render.document; + + // Format the contents using the current layout method + this.formated = this.layout.format(contents, this.render.width, this.render.height, this.gap); + this.render.setPageDimensions(this.formated.pageWidth, this.formated.pageHeight); + + // window.addEventListener("orientationchange", this.onResized.bind(this), false); + if(!this.initWidth && !this.initHeight){ + this.render.window.addEventListener("resize", this.resized, false); + } + + this.addEventListeners(); + this.addSelectionListeners(); + + //-- Trigger registered hooks before displaying + this.beforeDisplay(function(){ + var pages = this.layout.calculatePages(); + var msg = this.currentChapter; + var queued = this._q.length(); + this._moving = false; + + this.updatePages(pages); + + this.visibleRangeCfi = this.getVisibleRangeCfi(); + this.currentLocationCfi = this.visibleRangeCfi.start; + + if(queued === 0) { + this.trigger("renderer:locationChanged", this.currentLocationCfi); + this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); + } + + msg.cfi = this.currentLocationCfi; //TODO: why is this cfi passed to chapterDisplayed + this.trigger("renderer:chapterDisplayed", msg); + + this.visible(true); + + deferred.resolve(this); //-- why does this return the renderer? + }.bind(this)); + + }.bind(this)); + + return deferred.promise; +}; + +EPUBJS.Renderer.prototype.loaded = function(url){ + this.trigger("render:loaded", url); + // var uri = EPUBJS.core.uri(url); + // var relative = uri.path.replace(book.bookUrl, ''); + // console.log(url, uri, relative); +}; + +/** +* Reconciles the current chapters layout properies with +* the global layout properities. +* Takes: global layout settings object, chapter properties string +* Returns: Object with layout properties +*/ +EPUBJS.Renderer.prototype.reconcileLayoutSettings = function(global, chapter){ + var settings = {}; + + //-- Get the global defaults + for (var attr in global) { + if (global.hasOwnProperty(attr)){ + settings[attr] = global[attr]; + } + } + //-- Get the chapter's display type + chapter.forEach(function(prop){ + var rendition = prop.replace("rendition:", ''); + var split = rendition.indexOf("-"); + var property, value; + + if(split != -1){ + property = rendition.slice(0, split); + value = rendition.slice(split+1); + + settings[property] = value; + } + }); + return settings; +}; + +/** +* Uses the settings to determine which Layout Method is needed +* Triggers events based on the method choosen +* Takes: Layout settings object +* Returns: String of appropriate for EPUBJS.Layout function +*/ +EPUBJS.Renderer.prototype.determineLayout = function(settings){ + // Default is layout: reflowable & spread: auto + var spreads = this.determineSpreads(this.minSpreadWidth); + var layoutMethod = spreads ? "ReflowableSpreads" : "Reflowable"; + var scroll = false; + + if(settings.layout === "pre-paginated") { + layoutMethod = "Fixed"; + scroll = true; + spreads = false; + } + + if(settings.layout === "reflowable" && settings.spread === "none") { + layoutMethod = "Reflowable"; + scroll = false; + spreads = false; + } + + if(settings.layout === "reflowable" && settings.spread === "both") { + layoutMethod = "ReflowableSpreads"; + scroll = false; + spreads = true; + } + + this.spreads = spreads; + this.render.scroll(scroll); + this.trigger("renderer:spreads", spreads); + return layoutMethod; +}; + +// Shortcut to trigger the hook before displaying the chapter +EPUBJS.Renderer.prototype.beforeDisplay = function(callback, renderer){ + this.triggerHooks("beforeChapterDisplay", callback, this); +}; + +// Update the renderer with the information passed by the layout +EPUBJS.Renderer.prototype.updatePages = function(layout){ + this.pageMap = this.mapPage(); + // this.displayedPages = layout.displayedPages; + + if (this.spreads) { + this.displayedPages = Math.ceil(this.pageMap.length / 2); + } else { + this.displayedPages = this.pageMap.length; + } + + // this.currentChapter.pages = layout.pageCount; + this.currentChapter.pages = this.pageMap.length; + + this._q.flush(); +}; + +// Apply the layout again and jump back to the previous cfi position +EPUBJS.Renderer.prototype.reformat = function(){ + var renderer = this; + var formated, pages; + if(!this.contents) return; + + spreads = this.determineSpreads(this.minSpreadWidth); + + // Only re-layout if the spreads have switched + if(spreads != this.spreads){ + this.spreads = spreads; + this.layoutMethod = this.determineLayout(this.layoutSettings); + this.layout = new EPUBJS.Layout[this.layoutMethod](); + } + + // Reset pages + this.chapterPos = 1; + this.render.page(1); + + // Give the css styles time to update + // clearTimeout(this.timeoutTillCfi); + // this.timeoutTillCfi = setTimeout(function(){ + + renderer.formated = renderer.layout.format(renderer.contents, renderer.render.width, renderer.render.height, renderer.gap); + renderer.render.setPageDimensions(renderer.formated.pageWidth, renderer.formated.pageHeight); + + pages = renderer.layout.calculatePages(); + renderer.updatePages(pages); + + //-- Go to current page after formating + if(renderer.currentLocationCfi){ + renderer.gotoCfi(renderer.currentLocationCfi); + } + // renderer.timeoutTillCfi = null; + +}; + +// Hide and show the render's container . +EPUBJS.Renderer.prototype.visible = function(bool){ + if(typeof(bool) === "undefined") { + return this.element.style.visibility; + } + + if(bool === true && !this.hidden){ + this.element.style.visibility = "visible"; + }else if(bool === false){ + this.element.style.visibility = "hidden"; + } +}; + +// Remove the render element and clean up listeners +EPUBJS.Renderer.prototype.remove = function() { + if(this.render.window) { + this.render.unload(); + this.render.window.removeEventListener("resize", this.resized); + this.removeEventListeners(); + this.removeSelectionListeners(); + } + + this.container.removeChild(this.element); +}; + +//-- STYLES + +EPUBJS.Renderer.prototype.applyStyles = function(styles) { + for (var style in styles) { + this.render.setStyle(style, styles[style]); + } +}; + +EPUBJS.Renderer.prototype.setStyle = function(style, val, prefixed){ + this.render.setStyle(style, val, prefixed); +}; + +EPUBJS.Renderer.prototype.removeStyle = function(style){ + this.render.removeStyle(style); +}; + +//-- HEAD TAGS +EPUBJS.Renderer.prototype.applyHeadTags = function(headTags) { + for ( var headTag in headTags ) { + this.render.addHeadTag(headTag, headTags[headTag]); + } +}; + +//-- NAVIGATION + +EPUBJS.Renderer.prototype.page = function(pg){ + if(!this.pageMap) { + console.warn("pageMap not set, queuing"); + this._q.enqueue("page", arguments); + return true; + } + + if(pg >= 1 && pg <= this.displayedPages){ + this.chapterPos = pg; + + this.render.page(pg); + this.visibleRangeCfi = this.getVisibleRangeCfi(); + this.currentLocationCfi = this.visibleRangeCfi.start; + this.trigger("renderer:locationChanged", this.currentLocationCfi); + this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); + + return true; + } + //-- Return false if page is greater than the total + return false; +}; + +// Short cut to find next page's cfi starting at the last visible element +/* +EPUBJS.Renderer.prototype.nextPage = function(){ + var pg = this.chapterPos + 1; + if(pg <= this.displayedPages){ + this.chapterPos = pg; + + this.render.page(pg); + + this.currentLocationCfi = this.getPageCfi(this.visibileEl); + this.trigger("renderer:locationChanged", this.currentLocationCfi); + + return true; + } + //-- Return false if page is greater than the total + return false; +}; +*/ +EPUBJS.Renderer.prototype.nextPage = function(){ + return this.page(this.chapterPos + 1); +}; + +EPUBJS.Renderer.prototype.prevPage = function(){ + return this.page(this.chapterPos - 1); +}; + +//-- Show the page containing an Element +EPUBJS.Renderer.prototype.pageByElement = function(el){ + var pg; + if(!el) return; + + pg = this.render.getPageNumberByElement(el); + this.page(pg); +}; + +// Jump to the last page of the chapter +EPUBJS.Renderer.prototype.lastPage = function(){ + if(this._moving) { + return this._q.enqueue("lastPage", arguments); + } + + this.page(this.displayedPages); +}; + +// Jump to the first page of the chapter +EPUBJS.Renderer.prototype.firstPage = function(){ + this.page(1); +}; + +//-- Find a section by fragement id +EPUBJS.Renderer.prototype.section = function(fragment){ + var el = this.doc.getElementById(fragment), + left, pg; + + if(el){ + this.pageByElement(el); + } + +}; + +EPUBJS.Renderer.prototype.firstElementisTextNode = function(node) { + var children = node.childNodes; + var leng = children.length; + + if(leng && + children[0] && // First Child + children[0].nodeType === 3 && // This is a textNodes + children[0].textContent.trim().length) { // With non whitespace or return charecters + return true; + } + return false; +}; + +// Walk the node tree from a start element to next visible element +EPUBJS.Renderer.prototype.walk = function(node, x, y) { + var r, children, leng, + startNode = node, + prevNode, + stack = [startNode]; + + var STOP = 10000, ITER=0; + + while(!r && stack.length) { + node = stack.shift(); + if( this.containsPoint(node, x, y) && this.firstElementisTextNode(node)) { + r = node; + } + + if(!r && node && node.childElementCount > 0){ + children = node.children; + if (children && children.length) { + leng = children.length ? children.length : 0; + } else { + return r; + } + for (var i = leng-1; i >= 0; i--) { + if(children[i] != prevNode) stack.unshift(children[i]); + } + } + + if(!r && stack.length === 0 && startNode && startNode.parentNode !== null){ + stack.push(startNode.parentNode); + prevNode = startNode; + startNode = startNode.parentNode; + } + + + ITER++; + if(ITER > STOP) { + console.error("ENDLESS LOOP"); + break; + } + + } + + return r; +}; + +// Checks if an element is on the screen +EPUBJS.Renderer.prototype.containsPoint = function(el, x, y){ + var rect; + var left; + if(el && typeof el.getBoundingClientRect === 'function'){ + rect = el.getBoundingClientRect(); + // console.log(el, rect, x, y); + + if( rect.width !== 0 && + rect.height !== 0 && // Element not visible + rect.left >= x && + x <= rect.left + rect.width) { + return true; + } + } + + return false; +}; + +EPUBJS.Renderer.prototype.textSprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if ( ! /^\s*$/.test(node.data) ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; + +EPUBJS.Renderer.prototype.sprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; + +EPUBJS.Renderer.prototype.mapPage = function(){ + var renderer = this; + var map = []; + var root = this.render.getBaseElement(); + var page = 1; + var width = this.layout.colWidth + this.layout.gap; + var offset = this.formated.pageWidth * (this.chapterPos-1); + var limit = (width * page) - offset;// (width * page) - offset; + var elLimit = 0; + var prevRange; + var cfi; + var check = function(node) { + var elPos; + var elRange; + var children = Array.prototype.slice.call(node.childNodes); + if (node.nodeType == Node.ELEMENT_NODE) { + // elPos = node.getBoundingClientRect(); + elRange = document.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + + if(!elPos || (elPos.width === 0 && elPos.height === 0)) { + return; + } + + //-- Element starts new Col + if(elPos.left > elLimit) { + children.forEach(function(node){ + if(node.nodeType == Node.TEXT_NODE && + node.textContent.trim().length) { + checkText(node); + } + }); + } + + //-- Element Spans new Col + if(elPos.right > elLimit) { + children.forEach(function(node){ + if(node.nodeType == Node.TEXT_NODE && + node.textContent.trim().length) { + checkText(node); + } + }); + } + } + + }; + var checkText = function(node){ + var ranges = renderer.splitTextNodeIntoWordsRanges(node); + ranges.forEach(function(range){ + var pos = range.getBoundingClientRect(); + + if(!pos || (pos.width === 0 && pos.height === 0)) { + return; + } + if(pos.left + pos.width < limit) { + if(!map[page-1]){ + range.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(range); + // map[page-1].start = cfi; + map.push({ start: cfi, end: null }); + } + } else { + if(prevRange){ + prevRange.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(prevRange); + map[map.length-1].end = cfi; + } + + range.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(range); + map.push({ + start: cfi, + end: null + }); + + page += 1; + limit = (width * page) - offset; + elLimit = limit; + } + + prevRange = range; + }); + + + }; + + this.sprint(root, check); + // this.textSprint(root, checkText); + + if(prevRange){ + prevRange.collapse(true); + + cfi = renderer.currentChapter.cfiFromRange(prevRange); + map[map.length-1].end = cfi; + } + + // Handle empty map + if(!map.length) { + range = this.doc.createRange(); + range.selectNodeContents(root); + range.collapse(true); + + cfi = renderer.currentChapter.cfiFromRange(range); + + map.push({ start: cfi, end: cfi }); + + } + + // clean up + prevRange = null; + ranges = null; + range = null; + root = null; + + return map; +}; + + +EPUBJS.Renderer.prototype.indexOfBreakableChar = function (text, startPosition) { + var whiteCharacters = "\x2D\x20\t\r\n\b\f"; + // '-' \x2D + // ' ' \x20 + + if (! startPosition) { + startPosition = 0; + } + + for (var i = startPosition; i < text.length; i++) { + if (whiteCharacters.indexOf(text.charAt(i)) != -1) { + return i; + } + } + + return -1; +}; + + +EPUBJS.Renderer.prototype.splitTextNodeIntoWordsRanges = function(node){ + var ranges = []; + var text = node.textContent.trim(); + var range; + var rect; + var list; + // jaroslaw.bielski@7bulls.com + // Usage of indexOf() function for space character as word delimiter + // is not sufficient in case of other breakable characters like \r\n- etc + pos = this.indexOfBreakableChar(text); + + if(pos === -1) { + range = this.doc.createRange(); + range.selectNodeContents(node); + return [range]; + } + + range = this.doc.createRange(); + range.setStart(node, 0); + range.setEnd(node, pos); + ranges.push(range); + + // jaroslaw.bielski@7bulls.com + // there was a word miss in case of one letter words + range = this.doc.createRange(); + range.setStart(node, pos+1); + + while ( pos != -1 ) { + + pos = this.indexOfBreakableChar(text, pos + 1); + if(pos > 0) { + + if(range) { + range.setEnd(node, pos); + ranges.push(range); + } + + range = this.doc.createRange(); + range.setStart(node, pos+1); + } + } + + if(range) { + range.setEnd(node, text.length); + ranges.push(range); + } + + return ranges; +}; + +EPUBJS.Renderer.prototype.rangePosition = function(range){ + var rect; + var list; + + list = range.getClientRects(); + + if(list.length) { + rect = list[0]; + return rect; + } + + return null; +}; + +/* +// Get the cfi of the current page +EPUBJS.Renderer.prototype.getPageCfi = function(prevEl){ + var range = this.doc.createRange(); + var position; + // TODO : this might need to take margin / padding into account? + var x = 1;//this.formated.pageWidth/2; + var y = 1;//;this.formated.pageHeight/2; + + range = this.getRange(x, y); + + // var test = this.doc.defaultView.getSelection(); + // var r = this.doc.createRange(); + // test.removeAllRanges(); + // r.setStart(range.startContainer, range.startOffset); + // r.setEnd(range.startContainer, range.startOffset + 1); + // test.addRange(r); + + return this.currentChapter.cfiFromRange(range); +}; +*/ + +// Get the cfi of the current page +EPUBJS.Renderer.prototype.getPageCfi = function(){ + var pg; + if (this.spreads) { + pg = this.chapterPos*2; + startRange = this.pageMap[pg-2]; + } else { + pg = this.chapterPos; + startRange = this.pageMap[pg-1]; + } + return this.pageMap[(this.chapterPos * 2) -1].start; +}; + +EPUBJS.Renderer.prototype.getRange = function(x, y, forceElement){ + var range = this.doc.createRange(); + var position; + forceElement = true; // temp override + if(typeof document.caretPositionFromPoint !== "undefined" && !forceElement){ + position = this.doc.caretPositionFromPoint(x, y); + range.setStart(position.offsetNode, position.offset); + } else if(typeof document.caretRangeFromPoint !== "undefined" && !forceElement){ + range = this.doc.caretRangeFromPoint(x, y); + } else { + this.visibileEl = this.findElementAfter(x, y); + range.setStart(this.visibileEl, 1); + } + + // var test = this.doc.defaultView.getSelection(); + // var r = this.doc.createRange(); + // test.removeAllRanges(); + // r.setStart(range.startContainer, range.startOffset); + // r.setEnd(range.startContainer, range.startOffset + 1); + // test.addRange(r); + return range; +}; + +/* +EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(prevEl){ + var startX = 0; + var startY = 0; + var endX = this.width-1; + var endY = this.height-1; + var startRange = this.getRange(startX, startY); + var endRange = this.getRange(endX, endY); //fix if carret not avail + var startCfi = this.currentChapter.cfiFromRange(startRange); + var endCfi; + if(endRange) { + endCfi = this.currentChapter.cfiFromRange(endRange); + } + + return { + start: startCfi, + end: endCfi || false + }; +}; +*/ + +EPUBJS.Renderer.prototype.pagesInCurrentChapter = function() { + var pgs; + var length; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + length = this.pageMap.length; + + if(this.spreads){ + pgs = Math.ceil(length / 2); + } else { + pgs = length; + } + + return pgs; +}; + +EPUBJS.Renderer.prototype.currentRenderedPage = function(){ + var pg; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + if (this.spreads && this.layout.pageCount > 1) { + pg = this.chapterPos*2; + } else { + pg = this.chapterPos; + } + + return pg; +}; + +EPUBJS.Renderer.prototype.getRenderedPagesLeft = function(){ + var pg; + var lastPage; + var pagesLeft; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + lastPage = this.pageMap.length; + + if (this.spreads) { + pg = this.chapterPos*2; + } else { + pg = this.chapterPos; + } + + pagesLeft = lastPage - pg; + return pagesLeft; + +}; + +EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(){ + var pg; + var startRange, endRange; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + if (this.spreads) { + pg = this.chapterPos*2; + startRange = this.pageMap[pg-2]; + endRange = startRange; + + if(this.layout.pageCount > 1) { + endRange = this.pageMap[pg-1]; + } + } else { + pg = this.chapterPos; + startRange = this.pageMap[pg-1]; + endRange = startRange; + } + + if(!startRange) { + console.warn("page range miss:", pg, this.pageMap); + startRange = this.pageMap[this.pageMap.length-1]; + endRange = startRange; + } + + return { + start: startRange.start, + end: endRange.end + }; +}; + +// Goto a cfi position in the current chapter +EPUBJS.Renderer.prototype.gotoCfi = function(cfi){ + var pg; + var marker; + var range; + + if(this._moving){ + return this._q.enqueue("gotoCfi", arguments); + } + + if(_.isString(cfi)){ + cfi = this.epubcfi.parse(cfi); + } + + if(typeof document.evaluate === 'undefined') { + marker = this.epubcfi.addMarker(cfi, this.doc); + if(marker) { + pg = this.render.getPageNumberByElement(marker); + // Must Clean up Marker before going to page + this.epubcfi.removeMarker(marker, this.doc); + this.page(pg); + } + } else { + range = this.epubcfi.generateRangeFromCfi(cfi, this.doc); + if(range) { + // jaroslaw.bielski@7bulls.com + // It seems that sometimes getBoundingClientRect() returns null for first page CFI in chapter. + // It is always reproductible if few consecutive chapters have only one page. + // NOTE: This is only workaround and the issue needs an deeper investigation. + // NOTE: Observed on Android 4.2.1 using WebView widget as HTML renderer (Asus TF300T). + var rect = range.getBoundingClientRect(); + if (rect) { + pg = this.render.getPageNumberByRect(rect); + + } else { + // Goto first page in chapter + pg = 1; + } + + this.page(pg); + + // Reset the current location cfi to requested cfi + this.currentLocationCfi = cfi.str; + } + } +}; + +// Walk nodes until a visible element is found +EPUBJS.Renderer.prototype.findFirstVisible = function(startEl){ + var el = startEl || this.render.getBaseElement(); + var found; + // kgolunski@7bulls.com + // Looks like an old API usage + // Set x and y as 0 to fullfill walk method API. + found = this.walk(el, 0, 0); + + if(found) { + return found; + }else{ + return startEl; + } + +}; +// TODO: remove me - unsused +EPUBJS.Renderer.prototype.findElementAfter = function(x, y, startEl){ + var el = startEl || this.render.getBaseElement(); + var found; + found = this.walk(el, x, y); + if(found) { + return found; + }else{ + return el; + } + +}; + +/* +EPUBJS.Renderer.prototype.route = function(hash, callback){ + var location = window.location.hash.replace('#/', ''); + if(this.useHash && location.length && location != this.prevLocation){ + this.show(location, callback); + this.prevLocation = location; + return true; + } + return false; +} + +EPUBJS.Renderer.prototype.hideHashChanges = function(){ + this.useHash = false; +} + +*/ + +EPUBJS.Renderer.prototype.resize = function(width, height, setSize){ + var spreads; + + this.width = width; + this.height = height; + + if(setSize !== false) { + this.render.resize(this.width, this.height); + } + + + + if(this.contents){ + this.reformat(); + } + + this.trigger("renderer:resized", { + width: this.width, + height: this.height + }); +}; + +//-- Listeners for events in the frame + +EPUBJS.Renderer.prototype.onResized = function(e) { + var width = this.container.clientWidth; + var height = this.container.clientHeight; + + this.resize(width, height, false); +}; + +EPUBJS.Renderer.prototype.addEventListeners = function(){ + if(!this.render.document) { + return; + } + this.listenedEvents.forEach(function(eventName){ + this.render.document.addEventListener(eventName, this.triggerEvent.bind(this), false); + }, this); + +}; + +EPUBJS.Renderer.prototype.removeEventListeners = function(){ + if(!this.render.document) { + return; + } + this.listenedEvents.forEach(function(eventName){ + this.render.document.removeEventListener(eventName, this.triggerEvent, false); + }, this); + +}; + +// Pass browser events +EPUBJS.Renderer.prototype.triggerEvent = function(e){ + this.trigger("renderer:"+e.type, e); +}; + +EPUBJS.Renderer.prototype.addSelectionListeners = function(){ + this.render.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); +}; + +EPUBJS.Renderer.prototype.removeSelectionListeners = function(){ + if(!this.render.document) { + return; + } + this.doc.removeEventListener("selectionchange", this.onSelectionChange, false); +}; + +EPUBJS.Renderer.prototype.onSelectionChange = function(e){ + if (this.selectionEndTimeout) { + clearTimeout(this.selectionEndTimeout); + } + this.selectionEndTimeout = setTimeout(function() { + this.selectedRange = this.render.window.getSelection(); + this.trigger("renderer:selected", this.selectedRange); + }.bind(this), 500); +}; + + +//-- Spreads + +EPUBJS.Renderer.prototype.setMinSpreadWidth = function(width){ + this.minSpreadWidth = width; + this.spreads = this.determineSpreads(width); +}; + +EPUBJS.Renderer.prototype.determineSpreads = function(cutoff){ + if(this.isForcedSingle || !cutoff || this.width < cutoff) { + return false; //-- Single Page + }else{ + return true; //-- Double Page + } +}; + +EPUBJS.Renderer.prototype.forceSingle = function(bool){ + if(bool) { + this.isForcedSingle = true; + // this.spreads = false; + } else { + this.isForcedSingle = false; + // this.spreads = this.determineSpreads(this.minSpreadWidth); + } +}; + +EPUBJS.Renderer.prototype.setGap = function(gap){ + this.gap = gap; //-- False == auto gap +}; + +//-- Content Replacements + +EPUBJS.Renderer.prototype.replace = function(query, func, finished, progress){ + var items = this.contents.querySelectorAll(query), + resources = Array.prototype.slice.call(items), + count = resources.length; + + + if(count === 0) { + finished(false); + return; + } + resources.forEach(function(item){ + var called = false; + var after = function(result, full){ + if(called === false) { + count--; + if(progress) progress(result, full, count); + if(count <= 0 && finished) finished(true); + called = true; + } + }; + + func(item, after); + + }.bind(this)); + +}; + +EPUBJS.Renderer.prototype.replaceWithStored = function(query, attr, func, callback) { + var _oldUrls, + _newUrls = {}, + _store = this.currentChapter.store, + _cache = this.caches[query], + _uri = EPUBJS.core.uri(this.currentChapter.absolute), + _chapterBase = _uri.base, + _attr = attr, + _wait = 2000, + progress = function(url, full, count) { + _newUrls[full] = url; + }, + finished = function(notempty) { + if(callback) callback(); + + _.each(_oldUrls, function(url){ + _store.revokeUrl(url); + }); + + _cache = _newUrls; + }; + + if(!_store) return; + + if(!_cache) _cache = {}; + _oldUrls = _.clone(_cache); + + this.replace(query, function(link, done){ + var src = link.getAttribute(_attr), + full = EPUBJS.core.resolveUrl(_chapterBase, src); + + var replaceUrl = function(url) { + var timeout; + link.onload = function(){ + clearTimeout(timeout); + done(url, full); + }; + + link.onerror = function(e){ + clearTimeout(timeout); + done(url, full); + console.error(e); + }; + + if(query == "image") { + //-- SVG needs this to trigger a load event + link.setAttribute("externalResourcesRequired", "true"); + } + + if(query == "link[href]" && link.getAttribute("rel") !== "stylesheet") { + //-- Only Stylesheet links seem to have a load events, just continue others + done(url, full); + } + + link.setAttribute(_attr, url); + + //-- If elements never fire Load Event, should continue anyways + timeout = setTimeout(function(){ + done(url, full); + }, _wait); + + }; + + if(full in _oldUrls){ + replaceUrl(_oldUrls[full]); + _newUrls[full] = _oldUrls[full]; + delete _oldUrls[full]; + }else{ + func(_store, full, replaceUrl, link); + } + + }, finished, progress); +}; + +//-- Enable binding events to Renderer +RSVP.EventTarget.mixin(EPUBJS.Renderer.prototype); + +var EPUBJS = EPUBJS || {}; +EPUBJS.replace = {}; + +//-- Replaces the relative links within the book to use our internal page changer +EPUBJS.replace.hrefs = function(callback, renderer){ + var book = this; + var replacments = function(link, done){ + var href = link.getAttribute("href"), + isRelative = href.search("://"), + directory, + relative, + location; + + if(isRelative != -1){ + + link.setAttribute("target", "_blank"); + + }else{ + // Links may need to be resolved, such as ../chp1.xhtml + directory = EPUBJS.core.uri(renderer.render.window.location.href).directory; + if(directory) { + relative = EPUBJS.core.resolveUrl(directory, href); + } else { + relative = href; + } + + link.onclick = function(){ + book.goto(relative); + return false; + }; + + } + done(); + + }; + + renderer.replace("a[href]", replacments, callback); + +}; + +EPUBJS.replace.head = function(callback, renderer) { + + renderer.replaceWithStored("link[href]", "href", EPUBJS.replace.links, callback); + +}; + + +//-- Replaces assets src's to point to stored version if browser is offline +EPUBJS.replace.resources = function(callback, renderer){ + //srcs = this.doc.querySelectorAll('[src]'); + renderer.replaceWithStored("[src]", "src", EPUBJS.replace.srcs, callback); + +}; + +EPUBJS.replace.svg = function(callback, renderer) { + + renderer.replaceWithStored("image", "xlink:href", function(_store, full, done){ + _store.getUrl(full).then(done); + }, callback); + +}; + +EPUBJS.replace.srcs = function(_store, full, done){ + + _store.getUrl(full).then(done); + +}; + +//-- Replaces links in head, such as stylesheets - link[href] +EPUBJS.replace.links = function(_store, full, done, link){ + //-- Handle replacing urls in CSS + if(link.getAttribute("rel") === "stylesheet") { + EPUBJS.replace.stylesheets(_store, full).then(function(url, full){ + // done + setTimeout(function(){ + done(url, full); + }, 5); //-- Allow for css to apply before displaying chapter + }); + }else{ + _store.getUrl(full).then(done); + } +}; + +EPUBJS.replace.stylesheets = function(_store, full) { + var deferred = new RSVP.defer(); + + if(!_store) return; + + _store.getText(full).then(function(text){ + var url; + + EPUBJS.replace.cssUrls(_store, full, text).then(function(newText){ + var _URL = window.URL || window.webkitURL || window.mozURL; + + var blob = new Blob([newText], { "type" : "text\/css" }), + url = _URL.createObjectURL(blob); + + deferred.resolve(url); + + }, function(e) { + console.error(e); + }); + + }); + + return deferred.promise; +}; + +EPUBJS.replace.cssUrls = function(_store, base, text){ + var deferred = new RSVP.defer(), + promises = [], + matches = text.match(/url\(\'?\"?([^\'|^\"^\)]*)\'?\"?\)/g); + + if(!_store) return; + + if(!matches){ + deferred.resolve(text); + return deferred.promise; + } + + matches.forEach(function(str){ + var full = EPUBJS.core.resolveUrl(base, str.replace(/url\(|[|\)|\'|\"]/g, '')); + var replaced = _store.getUrl(full).then(function(url){ + text = text.replace(str, 'url("'+url+'")'); + }); + + promises.push(replaced); + }); + + RSVP.all(promises).then(function(){ + deferred.resolve(text); + }); + + return deferred.promise; +}; + + + +EPUBJS.Unarchiver = function(url){ + + this.loadLib(); + this.urlCache = {}; + +}; + +//-- Load the zip lib and set the workerScriptsPath +EPUBJS.Unarchiver.prototype.loadLib = function(callback){ + if(typeof(JSZip) == "undefined") console.error("JSZip lib not loaded"); +}; + +EPUBJS.Unarchiver.prototype.openZip = function(zipUrl, callback){ + var deferred = new RSVP.defer(); + + return EPUBJS.core.request(zipUrl, "binary").then(function(data){ + this.zip = new JSZip(data); + }.bind(this)); +}; + +EPUBJS.Unarchiver.prototype.getXml = function(url, encoding){ + + return this.getText(url, encoding). + then(function(text){ + var parser = new DOMParser(); + return parser.parseFromString(text, "text/xml"); + }); + +}; + +EPUBJS.Unarchiver.prototype.getUrl = function(url, mime){ + var unarchiver = this; + var deferred = new RSVP.defer(); + var decodededUrl = window.decodeURIComponent(url); + var entry = this.zip.file(decodededUrl); + var _URL = window.URL || window.webkitURL || window.mozURL; + var tempUrl; + + if(!entry) { + deferred.reject({ + message : "File not found in the epub: " + url, + stack : new Error().stack + }); + return deferred.promise; + } + + if(url in this.urlCache) { + deferred.resolve(this.urlCache[url]); + return deferred.promise; + } + + blob = new Blob([entry.asUint8Array()], {type : mime || this.zip.getMimeType(entry.name)}); + + tempUrl = _URL.createObjectURL(blob); + deferred.resolve(tempUrl); + unarchiver.urlCache[url] = tempUrl; + + return deferred.promise; +}; + +EPUBJS.Unarchiver.prototype.getText = function(url, encoding){ + var unarchiver = this; + var deferred = new RSVP.defer(); + var decodededUrl = window.decodeURIComponent(url); + var entry = this.zip.file(decodededUrl); + var _URL = window.URL || window.webkitURL || window.mozURL; + + if(!entry) { + console.warn("File not found in the contained epub:", url); + return deferred.promise; + } + + text = entry.asText(); + deferred.resolve(text); + + return deferred.promise; +}; + +EPUBJS.Unarchiver.prototype.revokeUrl = function(url){ + var _URL = window.URL || window.webkitURL || window.mozURL; + var fromCache = unarchiver.urlCache[url]; + if(fromCache) _URL.revokeObjectURL(fromCache); +}; + +EPUBJS.Unarchiver.prototype.failed = function(error){ + console.error(error); +}; + +EPUBJS.Unarchiver.prototype.afterSaved = function(error){ + this.callback(); +}; + +EPUBJS.Unarchiver.prototype.toStorage = function(entries){ + var timeout = 0, + delay = 20, + that = this, + count = entries.length; + + function callback(){ + count--; + if(count === 0) that.afterSaved(); + } + + entries.forEach(function(entry){ + + setTimeout(function(entry){ + that.saveEntryFileToStorage(entry, callback); + }, timeout, entry); + + timeout += delay; + }); + + console.log("time", timeout); + + //entries.forEach(this.saveEntryFileToStorage.bind(this)); +}; + +// EPUBJS.Unarchiver.prototype.saveEntryFileToStorage = function(entry, callback){ +// var that = this; +// entry.getData(new zip.BlobWriter(), function(blob) { +// EPUBJS.storage.save(entry.filename, blob, callback); +// }); +// }; + +//# sourceMappingURL=epub.js.map \ No newline at end of file diff --git a/epub.js/epub.min.map b/epub.js/epub.min.map new file mode 100644 index 0000000..dd40312 --- /dev/null +++ b/epub.js/epub.min.map @@ -0,0 +1 @@ +{"version":3,"file":"epub.min.js","sources":["epub.js"],"names":["n","this","t","_","r","e","Array","prototype","u","Object","i","Function","a","push","o","slice","c","concat","l","toString","f","hasOwnProperty","s","forEach","p","map","h","reduce","v","reduceRight","d","filter","g","every","m","some","y","indexOf","b","lastIndexOf","x","isArray","keys","j","bind","w","_wrapped","exports","module","VERSION","A","each","length","call","has","collect","O","foldl","inject","arguments","TypeError","foldr","find","detect","E","select","reject","all","identity","any","contains","include","invoke","isFunction","apply","pluck","where","isEmpty","findWhere","max","Math","computed","value","min","shuffle","random","k","sortBy","index","criteria","sort","F","groupBy","countBy","sortedIndex","toArray","values","size","first","head","take","initial","last","rest","tail","drop","compact","R","flatten","without","difference","uniq","unique","union","intersection","zip","object","range","ceil","partial","bindAll","functions","memoize","delay","setTimeout","defer","throttle","Date","clearTimeout","debounce","once","wrap","compose","after","pairs","invert","methods","extend","pick","omit","defaults","clone","isObject","tap","I","source","global","multiline","ignoreCase","constructor","pop","isEqual","isString","isElement","nodeType","isArguments","isFinite","isNaN","parseFloat","isNumber","isBoolean","isNull","isUndefined","noConflict","times","floor","M","escape","&","<",">","\"","'","/","unescape","S","RegExp","join","replace","result","mixin","D","N","uniqueId","templateSettings","evaluate","interpolate","T","q","\\","\r","\n","\t","
","
","B","template","variable","chain","_chain","define","requireModule","require","requirejs","registry","seen","name","deps","callback","resolve","child","charAt","parts","split","parentBase","part","_eak_seen","Error","mod","reified","__dependency1__","__exports__","Promise","array","label","__dependency2__","fulfilled","state","rejected","reason","isNonThenable","entries","fulfilledResolver","resolveAll","rejectedResolver","results","remaining","entry","cast","then","useNextTick","process","nextTick","flush","useMutationObserver","iterations","observer","BrowserMutationObserver","node","document","createTextNode","observe","characterData","data","useSetTimeout","queue","tuple","arg","scheduleFlush","browserGlobal","window","MutationObserver","WebKitMutationObserver","configure","config","on","EventTarget","instrument","deferred","promise","callbacks","callbacksFor","_promiseCallbacks","off","trigger","undefined","eventName","allCallbacks","splice","options","__dependency3__","promises","filterFn","filterResults","valuesLen","filtered","keysOf","fulfilledTo","property","onRejection","now","guid","_guidKey","_id","detail","_detail","childGuid","_label","timeStamp","stack","error","mapFn","resultLen","mappedResults","makeNodeCallbackFor","nodeFunc","binding","nodeArgs","thisArg","__dependency4__","__dependency5__","__dependency6__","__dependency7__","__dependency8__","__dependency9__","noop","resolver","counter","_subscribers","invokeResolver","resolvePromise","rejectPromise","subscribe","parent","onFulfillment","subscribers","FULFILLED","REJECTED","publish","settled","invokeCallback","succeeded","failed","hasCallback","handleThenable","resolved","objectOrFunction","val","fulfill","_state","PENDING","SEALED","async","publishFulfillment","publishRejection","_onerror","race","Resolve","Reject","guidKey","thenPromise","catch","finally","Constructor","fulfillmentAt","pending","getTime","prop","__dependency10__","__dependency11__","__dependency12__","__dependency13__","__dependency14__","__dependency15__","denodeify","allSettled","hash","rethrow","asap","__PROMISE_INSTRUMENTATION__","RSVP","EPUBJS","plugins","filePath","Render","root","previousEpub","ePub","bookPath","Book","amd","settings","bookKey","packageUrl","storage","fromStorage","saved","online","contained","width","height","layoutOveride","orientation","minSpreadWidth","gap","version","restore","reload","goto","styles","headTags","withCredentials","render_method","EPUBJSVERSION","spinePos","stored","navigator","onLine","networkListeners","store","fileStorage","ready","manifest","spine","metadata","cover","toc","pageList","readyPromises","pagination","Pagination","pageListReady","_ready","isRendered","_q","core","_rendering","_displayQ","_moving","_gotoQ","renderer","Renderer","setMinSpreadWidth","setGap","listenToRenderer","defer_opened","opened","open","addEventListener","unload","forceReload","epubpackage","book","bookUrl","urlFrom","isContained","unarchive","loadPackage","localStorage","packageXml","identifier","packageIdentifier","restored","unpack","storeOffline","_registerReplacements","_containerPath","parse","Parser","containerPath","loadXml","containerXml","container","paths","contentsPath","basePath","packagePath","encoding","console","contents","packageContents","spineIndexByURL","generateBookKey","globalLayoutProperties","parseLayoutProperties","coverPath","spineNodeIndex","navPath","navUrl","navHtml","nav","epubcfi","EpubCFI","wait","pg","cfi","generateCfiFromHref","href","tocPath","tocUrl","tocXml","createHiddenRender","_width","_height","hiddenContainer","hiddenEl","box","element","getBoundingClientRect","forceSingle","createElement","style","visibility","overflow","appendChild","initialize","generatePageList","pager","spineLength","currentPage","nextChapter","chapter","next","done","Chapter","displayChapter","pageMap","item","start","page","spreads","end","remove","removeChild","generatePagination","defered","loadPagination","pagelistJSON","JSON","getPageList","getMetadata","getToc","Events","startPage","endPage","percent","pageRange","pageFromCfi","percentageFromPage","anchorPage","percentage","loadChange","url","uri","currentChapter","absolute","path","warn","filename","unlistenToRenderer","getXml","request","base","protocol","fromRoot","location","origin","host","baseTag","getElementsByTagName","resolveUrl","pathname","Unarchiver","openZip","extension","isSaved","storedSettings","getItem","saveContents","setItem","stringify","removeSavedContents","removeItem","renderTo","elem","rendered","getEl","_rendered","startDisplay","display","previousLocationCfi","gotoCfi","fetch","fromStore","len","clearSaved","chap","render","pos","enqueue","lastPage","preloadNextChapter","dequeue","message","nextPage","prevPage","prev","prevChapter","linear","getCurrentLocationCfi","currentLocationCfi","target","gotoPercentage","parseInt","substring","gotoPage","gotoHref","cfiString","spineItem","section","relativeURL","firstPage","cfiFromPage","pageFromPercentage","assets","batch","availableOffline","setStyle","prefixed","noreflow","reformat","removeStyle","addHeadTag","tag","attrs","useSpreads","use","_use","force","load","destroy","removeEventListener","applyStyles","applyHeadTags","registerHook","hrefs","_needsAssetReplacement","resources","svg","getStorageType","layout","spread","event","spineObject","id","cfiBase","properties","manifestProperties","pages","loaded","_store","get","xml","setDocument","doc","serializer","XMLSerializer","setAttribute","insertBefore","firstChild","serializeToString","tempUrl","getUrl","setPages","num","getPages","getID","ID","revokeUrl","_document","namespaceURI","doctype","implementation","createDocument","importNode","documentElement","cfiFromRange","_range","startXpath","endXpath","startContainer","endContainer","cleanEndTextContent","getElementXPath","nsResolver","XPathResult","FIRST_ORDERED_NODE_TYPE","singleNodeValue","collapsed","createRange","setStart","startOffset","setEnd","endOffset","log","cleanStartTextContent","cleanStringForXpath","textContent","generateCfiFromRange","_query","matches","query","toLowerCase","excerpt","text","limit","textSprint","func","treeWalker","createTreeWalker","NodeFilter","SHOW_TEXT","acceptNode","test","FILTER_ACCEPT","FILTER_REJECT","nextNode","getElementById","getEls","classes","getElementsByClassName","type","handler","readyState","DONE","status","responseXML","response","supportsURL","Blob","URL","BLOB_RESPONSE","xhr","XMLHttpRequest","xhrPrototype","defineProperty","onreadystatechange","responseType","setRequestHeader","overrideMimeType","send","obj","arr","member","newitm","ident","withoutProtocol","dot","firstSlash","directory","fragment","blob","doubleSlash","search","folder","lastSlash","dataURLToBlob","dataURL","contentType","raw","rawLength","uInt8Array","BASE64_MARKER","atob","Uint8Array","charCodeAt","addScript","src","onload","body","addScripts","srcArr","total","curr","cb","addCss","rel","unprefixed","vendors","upper","toUpperCase","segments","folders","uuid","insert","compareFunction","locationOf","_start","_end","compared","pivot","indexOfSorted","_scope","scope","funcName","args","context","inwait","shift","clear","getElementTreeXPath","nodeName","tagName","pathIndex","isXhtml","ownerDocument","getAttribute","Node","TEXT_NODE","indexOfTextNode","parentNode","sibling","previousSibling","DOCUMENT_TYPE_NODE","prefix","ns","xhtml","epub","str","match","textNode","sib","children","childNodes","cfiStr","generateChapterComponent","_spineNodeIndex","_pos","generatePathComponent","steps","segment","generateCfiFromElement","pathTo","unshift","getChapterComponent","splitStr","getPathComponent","pathComponent","getCharecterOffsetComponent","chapSegment","chapterComponent","charecterOffsetComponent","assertion","chapId","endInt","parseStep","has_brackets","spineId","step","characterOffset","textLocationAssertion","addMarker","_doc","_marker","lastStep","marker","createMarker","findParent","splitText","classList","add","removeMarker","nextSib","nextSibling","prevSib","sections","compare","cfiOne","cfiTwo","generateCfiFromTextNode","anchor","offset","generateCfiFromRangeAnchor","anchorNode","anchorOffset","startElement","startSteps","startPath","startIndex","endElement","endSteps","endPath","endIndex","generateXpathFromSteps","xpath","position","generateRangeFromCfi","textLength","debug","selectNode","el","events","createEvent","tell","listen","deafen","listenUntil","evt","CustomEvent","msg","dispatchEvent","bindto","OnEvt","OffEvt","unlisten","hooks","Hooks","getHooks","plugs","plugType","hook","toAdd","toFront","triggerHooks","passed","countdown","count","register","Layout","Reflowable","spreadWidth","format","_gap","columnAxis","columnGap","columnWidth","columnFill","colWidth","pageWidth","pageHeight","calculatePages","totalWidth","displayedPages","scrollWidth","pageCount","ReflowableSpreads","divisor","fullWidth","Fixed","content","viewport","querySelector","hasAttribute","locations","totalPages","round","percentageFromCfi","baseUrl","rootfile","fullpath","xmlEncoding","metadataNode","getElementText","manifestNode","spineNode","findNavPath","findTocPath","findCoverPath","tocId","bookTitle","creator","description","pubdate","publisher","language","rights","modified_date","querySelectorText","found","getElementsByTagNameNS","nodeValue","manifestXml","selected","querySelectorAll","items","spineXml","Id","props","propArray","manifestProps","manifestPropArray","vert","bookSpine","findListItems","findAnchorOrSpan","getTOC","list","nodes","subitems","idCounter","navEl","snapshot","ORDERED_NODE_SNAPSHOT_TYPE","snapshotLength","snapshotItem","navLabel","navMap","isCfi","Iframe","iframe","docEl","bodyEl","leftPos","create","scrolling","seamless","border","contentDocument","headEl","contentWindow","resized","margin","onerror","resize","totalHeight","scrollHeight","setPageDimensions","setLeft","defaultView","scrollTo","tagEl","attr","getPageNumberByElement","left","getPageNumberByRect","boundingClientRect","getBaseElement","isElementVisible","rect","scroll","bool","renderMethod","hidden","listenedEvents","upEvent","downEvent","caches","isForcedSingle","onResized","layoutSettings","initWidth","initHeight","clientWidth","clientHeight","globalLayout","removeEventListeners","removeSelectionListeners","chapterPos","currentChapterCfiBase","reconcileLayoutSettings","layoutMethod","determineLayout","visible","formated","addEventListeners","addSelectionListeners","beforeDisplay","queued","updatePages","visibleRangeCfi","getVisibleRangeCfi","rendition","determineSpreads","mapPage","headTag","pageByElement","firstElementisTextNode","leng","trim","walk","prevNode","startNode","STOP","ITER","containsPoint","childElementCount","sprint","SHOW_ELEMENT","prevRange","elLimit","check","elPos","elRange","ELEMENT_NODE","selectNodeContents","checkText","right","ranges","splitTextNodeIntoWordsRanges","collapse","indexOfBreakableChar","startPosition","whiteCharacters","rangePosition","getClientRects","getPageCfi","startRange","getRange","forceElement","caretPositionFromPoint","caretRangeFromPoint","visibileEl","findElementAfter","offsetNode","pagesInCurrentChapter","pgs","currentRenderedPage","getRenderedPagesLeft","pagesLeft","endRange","findFirstVisible","startEl","setSize","triggerEvent","onSelectionChange","selectionEndTimeout","selectedRange","getSelection","cutoff","finished","progress","called","full","replaceWithStored","_oldUrls","_newUrls","_cache","_uri","_chapterBase","_attr","_wait","link","replaceUrl","timeout","replacments","relative","isRelative","onclick","links","srcs","stylesheets","getText","cssUrls","newText","_URL","webkitURL","mozURL","createObjectURL","replaced","loadLib","urlCache","zipUrl","JSZip","parser","DOMParser","parseFromString","mime","unarchiver","decodededUrl","decodeURIComponent","file","asUint8Array","getMimeType","asText","fromCache","revokeObjectURL","afterSaved","toStorage","that","saveEntryFileToStorage"],"mappings":"CAAA,WAAY,GAAIA,GAAEC,KAAKC,EAAEF,EAAEG,EAAEC,KAAKC,EAAEC,MAAMC,UAAUC,EAAEC,OAAOF,UAAUG,EAAEC,SAASJ,UA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c,GACjBgf,EAAWP,SAAShmB,GAAOuH,EAEpBzY,EAASC,UAlBfD,EAAS1M,QACR+gB,QAAU,+BAAiCnD,EAC3CnP,OAAQ,GAAIlF,QAAQkF,QAEd/B,EAASC,UAiBlBsG,OAAO+L,WAAW3iB,UAAU8mC,QAAU,SAASvlB,GAC9C,CAAA,GACIlR,GAAW,GAAIsG,MAAKrP,MACpBygC,EAAel4B,OAAOm4B,mBAAmBzmB,GACzCjT,EAAQ5O,KAAKkH,IAAIqhC,KAAKF,EACfl4B,QAAOsd,KAAOtd,OAAOq3B,WAAar3B,OAAOs3B,OAEpD,MAAI74B,IAKJmd,KAAOnd,EAAM85B,SACb/3B,EAAS3D,QAAQ+e,MAEVpb,EAASC,UAPfuM,QAAQ+E,KAAK,wCAAyCL,GAC/ClR,EAASC,UASlBsG,OAAO+L,WAAW3iB,UAAUqpB,UAAY,SAAS9H,GAChD,GAAI0lB,GAAOp3B,OAAOsd,KAAOtd,OAAOq3B,WAAar3B,OAAOs3B,OAChDkB,EAAYP,WAAWP,SAAShmB,EACjC8mB,IAAWpB,EAAKqB,gBAAgBD,IAGpCzxB,OAAO+L,WAAW3iB,UAAUqU,OAAS,SAAShC,GAC7CwK,QAAQxK,MAAMA,IAGfuE,OAAO+L,WAAW3iB,UAAUuoC,WAAa,WACxC7oC,KAAK+M,YAGNmK,OAAO+L,WAAW3iB,UAAUwoC,UAAY,SAASx6B,GAMhD,QAASvB,KACRosB,IACa,IAAVA,GAAa4P,EAAKF,aAPtB,GAAIjC,GAAU,EACbl/B,EAAQ,GACRqhC,EAAO/oC,KACPm5B,EAAQ7qB,EAAQnL,MAOjBmL,GAAQhN,QAAQ,SAASsN,GAExBjH,WAAW,SAASiH,GACnBm6B,EAAKC,uBAAuBp6B,EAAO7B,IACjC65B,EAASh4B,GAEZg4B,GAAWl/B,IAGZyV,QAAQkO,IAAI,OAAQub"} \ No newline at end of file diff --git a/epub.js/epub_no_underscore.js b/epub.js/epub_no_underscore.js new file mode 100644 index 0000000..7835d6f --- /dev/null +++ b/epub.js/epub_no_underscore.js @@ -0,0 +1,7461 @@ +(function(global) { +var define, requireModule, require, requirejs; + +(function() { + var registry = {}, seen = {}; + + define = function(name, deps, callback) { + registry[name] = { deps: deps, callback: callback }; + }; + + requirejs = require = requireModule = function(name) { + requirejs._eak_seen = registry; + + if (seen[name]) { return seen[name]; } + seen[name] = {}; + + if (!registry[name]) { + throw new Error("Could not find module " + name); + } + + var mod = registry[name], + deps = mod.deps, + callback = mod.callback, + reified = [], + exports; + + for (var i=0, l=deps.length; i 1; + }; + + RSVP.filter(promises, filterFn).then(function(result){ + // result is [ 2, 3 ] + }); + ``` + + If any of the `promises` given to `RSVP.filter` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + var filterFn = function(item){ + return item > 1; + }; + + RSVP.filter(promises, filterFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "2" + }); + ``` + + `RSVP.filter` will also wait for any promises returned from `filterFn`. + For instance, you may want to fetch a list of users then return a subset + of those users based on some asynchronous operation: + + ```javascript + + var alice = { name: 'alice' }; + var bob = { name: 'bob' }; + var users = [ alice, bob ]; + + var promises = users.map(function(user){ + return RSVP.resolve(user); + }); + + var filterFn = function(user){ + // Here, Alice has permissions to create a blog post, but Bob does not. + return getPrivilegesForUser(user).then(function(privs){ + return privs.can_create_blog_post === true; + }); + }; + RSVP.filter(promises, filterFn).then(function(users){ + // true, because the server told us only Alice can create a blog post. + users.length === 1; + // false, because Alice is the only user present in `users` + users[0] === bob; + }); + ``` + + @method filter + @for RSVP + @param {Array} promises + @param {Function} filterFn - function to be called on each resolved value to + filter the final results. + @param {String} label optional string describing the promise. Useful for + tooling. + @return {Promise} + */ + function filter(promises, filterFn, label) { + if (!isArray(promises)) { + throw new TypeError('You must pass an array to filter.'); + } + + if (!isFunction(filterFn)){ + throw new TypeError("You must pass a function to filter's second argument."); + } + + return all(promises, label).then(function(values){ + return map(promises, filterFn, label).then(function(filterResults){ + var i, + valuesLen = values.length, + filtered = []; + + for (i = 0; i < valuesLen; i++){ + if(filterResults[i]) filtered.push(values[i]); + } + return filtered; + }); + }); + } + + __exports__["default"] = filter; + }); +define("rsvp/hash", + ["./promise","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var isNonThenable = __dependency2__.isNonThenable; + var keysOf = __dependency2__.keysOf; + + /** + `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array + for its `promises` argument. + + Returns a promise that is fulfilled when all the given promises have been + fulfilled, or rejected if any of them become rejected. The returned promise + is fulfilled with a hash that has the same key names as the `promises` object + argument. If any of the values in the object are not promises, they will + simply be copied over to the fulfilled object. + + Example: + + ```javascript + var promises = { + myPromise: RSVP.resolve(1), + yourPromise: RSVP.resolve(2), + theirPromise: RSVP.resolve(3), + notAPromise: 4 + }; + + RSVP.hash(promises).then(function(hash){ + // hash here is an object that looks like: + // { + // myPromise: 1, + // yourPromise: 2, + // theirPromise: 3, + // notAPromise: 4 + // } + }); + ```` + + If any of the `promises` given to `RSVP.hash` are rejected, the first promise + that is rejected will be given as as the first argument, or as the reason to + the rejection handler. For example: + + ```javascript + var promises = { + myPromise: RSVP.resolve(1), + rejectedPromise: RSVP.reject(new Error("rejectedPromise")), + anotherRejectedPromise: RSVP.reject(new Error("anotherRejectedPromise")), + }; + + RSVP.hash(promises).then(function(hash){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "rejectedPromise" + }); + ``` + + An important note: `RSVP.hash` is intended for plain JavaScript objects that + are just a set of keys and values. `RSVP.hash` will NOT preserve prototype + chains. + + Example: + + ```javascript + function MyConstructor(){ + this.example = RSVP.resolve("Example"); + } + + MyConstructor.prototype = { + protoProperty: RSVP.resolve("Proto Property") + }; + + var myObject = new MyConstructor(); + + RSVP.hash(myObject).then(function(hash){ + // protoProperty will not be present, instead you will just have an + // object that looks like: + // { + // example: "Example" + // } + // + // hash.hasOwnProperty('protoProperty'); // false + // 'undefined' === typeof hash.protoProperty + }); + ``` + + @method hash + @for RSVP + @param {Object} promises + @param {String} label - optional string that describes the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all properties of `promises` + have been fulfilled, or rejected if any of them become rejected. + */ + __exports__["default"] = function hash(object, label) { + return new Promise(function(resolve, reject){ + var results = {}; + var keys = keysOf(object); + var remaining = keys.length; + var entry, property; + + if (remaining === 0) { + resolve(results); + return; + } + + function fulfilledTo(property) { + return function(value) { + results[property] = value; + if (--remaining === 0) { + resolve(results); + } + }; + } + + function onRejection(reason) { + remaining = 0; + reject(reason); + } + + for (var i = 0; i < keys.length; i++) { + property = keys[i]; + entry = object[property]; + + if (isNonThenable(entry)) { + results[property] = entry; + if (--remaining === 0) { + resolve(results); + } + } else { + Promise.cast(entry).then(fulfilledTo(property), onRejection); + } + } + }); + }; + }); +define("rsvp/instrument", + ["./config","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var config = __dependency1__.config; + var now = __dependency2__.now; + + __exports__["default"] = function instrument(eventName, promise, child) { + // instrumentation should not disrupt normal usage. + try { + config.trigger(eventName, { + guid: promise._guidKey + promise._id, + eventName: eventName, + detail: promise._detail, + childGuid: child && promise._guidKey + child._id, + label: promise._label, + timeStamp: now(), + stack: new Error(promise._label).stack + }); + } catch(error) { + setTimeout(function(){ + throw error; + }, 0); + } + }; + }); +define("rsvp/map", + ["./promise","./all","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var all = __dependency2__["default"]; + var isArray = __dependency3__.isArray; + var isFunction = __dependency3__.isFunction; + + /** + + `RSVP.map` is similar to JavaScript's native `map` method, except that it + waits for all promises to become fulfilled before running the `mapFn` on + each item in given to `promises`. `RSVP.map` returns a promise that will + become fulfilled with the result of running `mapFn` on the values the promises + become fulfilled with. + + For example: + + ```javascript + + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.resolve(2); + var promise3 = RSVP.resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + var mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(result){ + // result is [ 2, 3, 4 ] + }); + ``` + + If any of the `promises` given to `RSVP.map` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + var mapFn = function(item){ + return item + 1; + }; + + RSVP.map(promises, mapFn).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(reason) { + // reason.message === "2" + }); + ``` + + `RSVP.map` will also wait if a promise is returned from `mapFn`. For example, + say you want to get all comments from a set of blog posts, but you need + the blog posts first becuase they contain a url to those comments. + + ```javscript + + var mapFn = function(blogPost){ + // getComments does some ajax and returns an RSVP.Promise that is fulfilled + // with some comments data + return getComments(blogPost.comments_url); + }; + + // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled + // with some blog post data + RSVP.map(getBlogPosts(), mapFn).then(function(comments){ + // comments is the result of asking the server for the comments + // of all blog posts returned from getBlogPosts() + }); + ``` + + @method map + @for RSVP + @param {Array} promises + @param {Function} mapFn function to be called on each fulfilled promise. + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled with the result of calling + `mapFn` on each fulfilled promise or value when they become fulfilled. + The promise will be rejected if any of the given `promises` become rejected. + */ + __exports__["default"] = function map(promises, mapFn, label) { + + if (!isArray(promises)) { + throw new TypeError('You must pass an array to map.'); + } + + if (!isFunction(mapFn)){ + throw new TypeError("You must pass a function to map's second argument."); + } + + return all(promises, label).then(function(results){ + var resultLen = results.length, + mappedResults = [], + i; + + for (i = 0; i < resultLen; i++){ + mappedResults.push(mapFn(results[i])); + } + + return all(mappedResults, label); + }); + }; + }); +define("rsvp/node", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + var slice = Array.prototype.slice; + + function makeNodeCallbackFor(resolve, reject) { + return function (error, value) { + if (error) { + reject(error); + } else if (arguments.length > 2) { + resolve(slice.call(arguments, 1)); + } else { + resolve(value); + } + }; + } + + /** + `RSVP.denodeify` takes a "node-style" function and returns a function that + will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the + browser when you'd prefer to use promises over using callbacks. For example, + `denodeify` transforms the following: + + ```javascript + var fs = require('fs'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + handleData(data); + }); + ``` + + into: + + ```javascript + var fs = require('fs'); + + var readFile = RSVP.denodeify(fs.readFile); + + readFile('myfile.txt').then(handleData, handleError); + ``` + + Using `denodeify` makes it easier to compose asynchronous operations instead + of using callbacks. For example, instead of: + + ```javascript + var fs = require('fs'); + var log = require('some-async-logger'); + + fs.readFile('myfile.txt', function(err, data){ + if (err) return handleError(err); + fs.writeFile('myfile2.txt', data, function(err){ + if (err) throw err; + log('success', function(err) { + if (err) throw err; + }); + }); + }); + ``` + + You can chain the operations together using `then` from the returned promise: + + ```javascript + var fs = require('fs'); + var denodeify = RSVP.denodeify; + var readFile = denodeify(fs.readFile); + var writeFile = denodeify(fs.writeFile); + var log = denodeify(require('some-async-logger')); + + readFile('myfile.txt').then(function(data){ + return writeFile('myfile2.txt', data); + }).then(function(){ + return log('SUCCESS'); + }).then(function(){ + // success handler + }, function(reason){ + // rejection handler + }); + ``` + + @method denodeify + @for RSVP + @param {Function} nodeFunc a "node-style" function that takes a callback as + its last argument. The callback expects an error to be passed as its first + argument (if an error occurred, otherwise null), and the value from the + operation as its second argument ("function(err, value){ }"). + @param {Any} binding optional argument for binding the "this" value when + calling the `nodeFunc` function. + @return {Function} a function that wraps `nodeFunc` to return an + `RSVP.Promise` + */ + __exports__["default"] = function denodeify(nodeFunc, binding) { + return function() { + var nodeArgs = slice.call(arguments), resolve, reject; + var thisArg = this || binding; + + return new Promise(function(resolve, reject) { + Promise.all(nodeArgs).then(function(nodeArgs) { + try { + nodeArgs.push(makeNodeCallbackFor(resolve, reject)); + nodeFunc.apply(thisArg, nodeArgs); + } catch(e) { + reject(e); + } + }); + }); + }; + }; + }); +define("rsvp/promise", + ["./config","./events","./instrument","./utils","./promise/cast","./promise/all","./promise/race","./promise/resolve","./promise/reject","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __exports__) { + "use strict"; + var config = __dependency1__.config; + var EventTarget = __dependency2__["default"]; + var instrument = __dependency3__["default"]; + var objectOrFunction = __dependency4__.objectOrFunction; + var isFunction = __dependency4__.isFunction; + var now = __dependency4__.now; + var cast = __dependency5__["default"]; + var all = __dependency6__["default"]; + var race = __dependency7__["default"]; + var Resolve = __dependency8__["default"]; + var Reject = __dependency9__["default"]; + + var guidKey = 'rsvp_' + now() + '-'; + var counter = 0; + + function noop() {} + + __exports__["default"] = Promise; + + + /** + + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error("getJSON: `" + url + "` failed with status: [" + this.status + "]"); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} + @param {String} label optional string for labeling the promise. + Useful for tooling. + @constructor + */ + function Promise(resolver, label) { + if (!isFunction(resolver)) { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + if (!(this instanceof Promise)) { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + this._id = counter++; + this._label = label; + this._subscribers = []; + + if (config.instrument) { + instrument('created', this); + } + + if (noop !== resolver) { + invokeResolver(resolver, this); + } + } + + function invokeResolver(resolver, promise) { + function resolvePromise(value) { + resolve(promise, value); + } + + function rejectPromise(reason) { + reject(promise, reason); + } + + try { + resolver(resolvePromise, rejectPromise); + } catch(e) { + rejectPromise(e); + } + } + + Promise.cast = cast; + Promise.all = all; + Promise.race = race; + Promise.resolve = Resolve; + Promise.reject = Reject; + + var PENDING = void 0; + var SEALED = 0; + var FULFILLED = 1; + var REJECTED = 2; + + function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + } + + function publish(promise, settled) { + var child, callback, subscribers = promise._subscribers, detail = promise._detail; + + if (config.instrument) { + instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise); + } + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + invokeCallback(settled, child, callback, detail); + } + + promise._subscribers = null; + } + + Promise.prototype = { + /** + @property constructor + */ + constructor: Promise, + + _id: undefined, + _guidKey: guidKey, + _label: undefined, + + _state: undefined, + _detail: undefined, + _subscribers: undefined, + + _onerror: function (reason) { + config.trigger('error', reason); + }, + + /** + + A promise represents the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, "downstream" + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return "default name"; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `"default name"` + }); + + findUser().then(function (user) { + throw "Found user, but still unhappy"; + }, function (reason) { + throw "`findUser` rejected and we're unhappy"; + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be "Found user, but still unhappy". + // If `findUser` rejected, `reason` will be "`findUser` rejected and we're unhappy". + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException("Upstream error"); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javacsript + findResult().then(function(result){ + + }, function(reason){ + + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javacsript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong; + }); + ``` + + @method then + @param {Function} onFulfillment + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection, label) { + var promise = this; + this._onerror = null; + + var thenPromise = new this.constructor(noop, label); + + if (this._state) { + var callbacks = arguments; + config.async(function invokePromiseCallback() { + invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); + }); + } else { + subscribe(this, thenPromise, onFulfillment, onRejection); + } + + if (config.instrument) { + instrument('chained', promise, thenPromise); + } + + return thenPromise; + }, + + /** + `catch` is simply sugar for `then(null, onRejection)` which makes it the same + as the catch block, of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error("couldn't find that author"); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong; + }); + ``` + + @method catch + @param {Function} onRejection + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection, label) { + return this.then(null, onRejection, label); + }, + + /** + `finally` will be invoked regardless of the promise's fate just as native + try/catch/finally behaves + + ```js + findAuthor() { + if (Math.random() > 0.5) { + throw new Error(); + } + return new Author(); + } + + try { + return findAuthor(); // succeed or fail + } catch(error) { + return findOtherAuther(); + } finally { + // always runs + // doesn't effect the return value + } + + findAuthor().finally(function(){ + // author was either found, or not + }); + ``` + + @method finally + @param {Function} callback + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} + */ + 'finally': function(callback, label) { + var constructor = this.constructor; + + return this.then(function(value) { + return constructor.cast(callback()).then(function(){ + return value; + }); + }, function(reason) { + return constructor.cast(callback()).then(function(){ + throw reason; + }); + }, label); + } + }; + + function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + try { + value = callback(detail); + succeeded = true; + } catch(e) { + failed = true; + error = e; + } + } else { + value = detail; + succeeded = true; + } + + if (handleThenable(promise, value)) { + return; + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + resolve(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } + } + + function handleThenable(promise, value) { + var then = null, + resolved; + + try { + if (promise === value) { + throw new TypeError("A promises callback cannot return that same promise."); + } + + if (objectOrFunction(value)) { + then = value.then; + + if (isFunction(then)) { + then.call(value, function(val) { + if (resolved) { return true; } + resolved = true; + + if (value !== val) { + resolve(promise, val); + } else { + fulfill(promise, val); + } + }, function(val) { + if (resolved) { return true; } + resolved = true; + + reject(promise, val); + }, 'derived from: ' + (promise._label || ' unknown promise')); + + return true; + } + } + } catch (error) { + if (resolved) { return true; } + reject(promise, error); + return true; + } + + return false; + } + + function resolve(promise, value) { + if (promise === value) { + fulfill(promise, value); + } else if (!handleThenable(promise, value)) { + fulfill(promise, value); + } + } + + function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + promise._state = SEALED; + promise._detail = value; + + config.async(publishFulfillment, promise); + } + + function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = SEALED; + promise._detail = reason; + + config.async(publishRejection, promise); + } + + function publishFulfillment(promise) { + publish(promise, promise._state = FULFILLED); + } + + function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._detail); + } + + publish(promise, promise._state = REJECTED); + } + }); +define("rsvp/promise/all", + ["../utils","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var isArray = __dependency1__.isArray; + var isNonThenable = __dependency1__.isNonThenable; + + /** + + `RSVP.Promise.all` returns a new promise which is fulfilled with an array of + fulfillment values for the passed promises, or rejects with the reason of the + first passed promise that rejects. It casts all elements of the passed iterable + to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.resolve(2); + var promise3 = RSVP.resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `RSVP.all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = RSVP.resolve(1); + var promise2 = RSVP.reject(new Error("2")); + var promise3 = RSVP.reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + RSVP.Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @for RSVP.Promise + @param {Array} promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + */ + __exports__["default"] = function all(entries, label) { + + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function(resolve, reject) { + if (!isArray(entries)) { + throw new TypeError('You must pass an array to all.'); + } + + var remaining = entries.length; + var results = new Array(remaining); + var entry, pending = true; + + if (remaining === 0) { + resolve(results); + return; + } + + function fulfillmentAt(index) { + return function(value) { + results[index] = value; + if (--remaining === 0) { + resolve(results); + } + }; + } + + function onRejection(reason) { + remaining = 0; + reject(reason); + } + + for (var index = 0; index < entries.length; index++) { + entry = entries[index]; + if (isNonThenable(entry)) { + results[index] = entry; + if (--remaining === 0) { + resolve(results); + } + } else { + Constructor.cast(entry).then(fulfillmentAt(index), onRejection); + } + } + }, label); + }; + }); +define("rsvp/promise/cast", + ["exports"], + function(__exports__) { + "use strict"; + /** + + `RSVP.Promise.cast` cast coerces its argument to a promise, or returns the + argument if it is already a promise which shares a constructor with the caster; + + Example: + + ```javascript + var promise = RSVP.Promise.resolve(1); + var casted = RSVP.Promise.cast(promise); + + console.log(promise === casted); // true + ``` + + In the case of a promise whose constructor does not match, it is assimilated. + The resulting promise will fulfill or reject based on the outcome of the + promise being casted. + + In the case of a non-promise, a promise which will fulfill with that value is + returned. + + Example: + + ```javascript + var value = 1; // could be a number, boolean, string, undefined... + var casted = RSVP.Promise.cast(value); + + console.log(value === casted); // false + console.log(casted instanceof RSVP.Promise) // true + + casted.then(function(val) { + val === value // => true + }); + ``` + + `RSVP.Promise.cast` is similar to `RSVP.Promise.resolve`, but `RSVP.Promise.cast` differs in the + following ways: + + * `RSVP.Promise.cast` serves as a memory-efficient way of getting a promise, when you + have something that could either be a promise or a value. RSVP.resolve + will have the same effect but will create a new promise wrapper if the + argument is a promise. + * `RSVP.Promise.cast` is a way of casting incoming thenables or promise subclasses to + promises of the exact class specified, so that the resulting object's `then` is + ensured to have the behavior of the constructor you are calling cast on (i.e., RSVP.Promise). + + @method cast + @for RSVP.Promise + @param {Object} object to be casted + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise + */ + + __exports__["default"] = function cast(object, label) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + return new Constructor(function(resolve) { + resolve(object); + }, label); + }; + }); +define("rsvp/promise/race", + ["../utils","exports"], + function(__dependency1__, __exports__) { + "use strict"; + /* global toString */ + + var isArray = __dependency1__.isArray; + var isFunction = __dependency1__.isFunction; + var isNonThenable = __dependency1__.isNonThenable; + + /** + `RSVP.Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 1"); + }, 200); + }); + + var promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 2"); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // result === "promise 2" because it was resolved before promise1 + // was resolved. + }); + ``` + + `RSVP.Promise.race` is deterministic in that only the state of the first + completed promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first completed promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + resolve("promise 1"); + }, 200); + }); + + var promise2 = new RSVP.Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error("promise 2")); + }, 100); + }); + + RSVP.Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs because there are rejected promises! + }, function(reason){ + // reason.message === "promise2" because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + @method race + @for RSVP.Promise + @param {Array} promises array of promises to observe + @param {String} label optional string for describing the promise returned. + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. + */ + __exports__["default"] = function race(entries, label) { + /*jshint validthis:true */ + var Constructor = this, entry; + + return new Constructor(function(resolve, reject) { + if (!isArray(entries)) { + throw new TypeError('You must pass an array to race.'); + } + + var pending = true; + + function onFulfillment(value) { if (pending) { pending = false; resolve(value); } } + function onRejection(reason) { if (pending) { pending = false; reject(reason); } } + + for (var i = 0; i < entries.length; i++) { + entry = entries[i]; + if (isNonThenable(entry)) { + pending = false; + resolve(entry); + return; + } else { + Constructor.cast(entry).then(onFulfillment, onRejection); + } + } + }, label); + }; + }); +define("rsvp/promise/reject", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.Promise.reject` returns a promise rejected with the passed `reason`. + It is essentially shorthand for the following: + + ```javascript + var promise = new RSVP.Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = RSVP.Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @for RSVP.Promise + @param {Any} reason value that the returned promise will be rejected with. + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. + */ + __exports__["default"] = function reject(reason, label) { + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function (resolve, reject) { + reject(reason); + }, label); + }; + }); +define("rsvp/promise/resolve", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.Promise.resolve` returns a promise that will become fulfilled with the passed + `value`. It is essentially shorthand for the following: + + ```javascript + var promise = new RSVP.Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = RSVP.Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @for RSVP.Promise + @param {Any} value value that the returned promise will be resolved with + @param {String} label optional string for identifying the returned promise. + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` + */ + __exports__["default"] = function resolve(value, label) { + /*jshint validthis:true */ + var Constructor = this; + + return new Constructor(function(resolve, reject) { + resolve(value); + }, label); + }; + }); +define("rsvp/race", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function race(array, label) { + return Promise.race(array, label); + }; + }); +define("rsvp/reject", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function reject(reason, label) { + return Promise.reject(reason, label); + }; + }); +define("rsvp/resolve", + ["./promise","exports"], + function(__dependency1__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + + __exports__["default"] = function resolve(value, label) { + return Promise.resolve(value, label); + }; + }); +define("rsvp/rethrow", + ["exports"], + function(__exports__) { + "use strict"; + /** + `RSVP.rethrow` will rethrow an error on the next turn of the JavaScript event + loop in order to aid debugging. + + Promises A+ specifies that any exceptions that occur with a promise must be + caught by the promises implementation and bubbled to the last handler. For + this reason, it is recommended that you always specify a second rejection + handler function to `then`. However, `RSVP.rethrow` will throw the exception + outside of the promise, so it bubbles up to your console if in the browser, + or domain/cause uncaught exception in Node. `rethrow` will throw the error + again so the error can be handled by the promise. + + ```javascript + function throws(){ + throw new Error('Whoops!'); + } + + var promise = new RSVP.Promise(function(resolve, reject){ + throws(); + }); + + promise.catch(RSVP.rethrow).then(function(){ + // Code here doesn't run because the promise became rejected due to an + // error! + }, function (err){ + // handle the error here + }); + ``` + + The 'Whoops' error will be thrown on the next turn of the event loop + and you can watch for it in your console. You can also handle it using a + rejection handler given to `.then` or `.catch` on the returned promise. + + @method rethrow + @for RSVP + @param {Error} reason reason the promise became rejected. + @throws Error + */ + __exports__["default"] = function rethrow(reason) { + setTimeout(function() { + throw reason; + }); + throw reason; + }; + }); +define("rsvp/utils", + ["exports"], + function(__exports__) { + "use strict"; + function objectOrFunction(x) { + return typeof x === "function" || (typeof x === "object" && x !== null); + } + + __exports__.objectOrFunction = objectOrFunction;function isFunction(x) { + return typeof x === "function"; + } + + __exports__.isFunction = isFunction;function isNonThenable(x) { + return !objectOrFunction(x); + } + + __exports__.isNonThenable = isNonThenable;function isArray(x) { + return Object.prototype.toString.call(x) === "[object Array]"; + } + + __exports__.isArray = isArray;// Date.now is not available in browsers < IE9 + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility + var now = Date.now || function() { return new Date().getTime(); }; + __exports__.now = now; + var keysOf = Object.keys || function(object) { + var result = []; + + for (var prop in object) { + result.push(prop); + } + + return result; + }; + __exports__.keysOf = keysOf; + }); +define("rsvp", + ["./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all_settled","./rsvp/race","./rsvp/hash","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/asap","./rsvp/filter","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __dependency8__, __dependency9__, __dependency10__, __dependency11__, __dependency12__, __dependency13__, __dependency14__, __dependency15__, __exports__) { + "use strict"; + var Promise = __dependency1__["default"]; + var EventTarget = __dependency2__["default"]; + var denodeify = __dependency3__["default"]; + var all = __dependency4__["default"]; + var allSettled = __dependency5__["default"]; + var race = __dependency6__["default"]; + var hash = __dependency7__["default"]; + var rethrow = __dependency8__["default"]; + var defer = __dependency9__["default"]; + var config = __dependency10__.config; + var configure = __dependency10__.configure; + var map = __dependency11__["default"]; + var resolve = __dependency12__["default"]; + var reject = __dependency13__["default"]; + var asap = __dependency14__["default"]; + var filter = __dependency15__["default"]; + + config.async = asap; // default async is asap; + + function async(callback, arg) { + config.async(callback, arg); + } + + function on() { + config.on.apply(config, arguments); + } + + function off() { + config.off.apply(config, arguments); + } + + // Set up instrumentation through `window.__PROMISE_INTRUMENTATION__` + if (typeof window !== 'undefined' && typeof window.__PROMISE_INSTRUMENTATION__ === 'object') { + var callbacks = window.__PROMISE_INSTRUMENTATION__; + configure('instrument', true); + for (var eventName in callbacks) { + if (callbacks.hasOwnProperty(eventName)) { + on(eventName, callbacks[eventName]); + } + } + } + + __exports__.Promise = Promise; + __exports__.EventTarget = EventTarget; + __exports__.all = all; + __exports__.allSettled = allSettled; + __exports__.race = race; + __exports__.hash = hash; + __exports__.rethrow = rethrow; + __exports__.defer = defer; + __exports__.denodeify = denodeify; + __exports__.configure = configure; + __exports__.on = on; + __exports__.off = off; + __exports__.resolve = resolve; + __exports__.reject = reject; + __exports__.async = async; + __exports__.map = map; + __exports__.filter = filter; + }); +global.RSVP = requireModule('rsvp'); +}(window)); +'use strict'; + +var EPUBJS = EPUBJS || {}; +EPUBJS.VERSION = "0.2.3"; + +EPUBJS.plugins = EPUBJS.plugins || {}; + +EPUBJS.filePath = EPUBJS.filePath || "/epubjs/"; + +EPUBJS.Render = {}; + +(function(root) { + + var previousEpub = root.ePub || {}; + + var ePub = root.ePub = function() { + var bookPath, options; + + //-- var book = ePub("path/to/book.epub", { restore: true }) + if(typeof(arguments[0]) != 'undefined' && + typeof arguments[0] === 'string') { + + bookPath = arguments[0]; + + if( arguments[1] && typeof arguments[1] === 'object' ) { + options = arguments[1]; + options.bookPath = bookPath; + } else { + options = { 'bookPath' : bookPath }; + } + + } + + /* + * var book = ePub({ bookPath: "path/to/book.epub", restore: true }); + * + * - OR - + * + * var book = ePub({ restore: true }); + * book.open("path/to/book.epub"); + */ + + if( arguments[0] && typeof arguments[0] === 'object' ) { + options = arguments[0]; + } + + + return new EPUBJS.Book(options); + }; + + _.extend(ePub, { + noConflict : function() { + root.ePub = previousEpub; + return this; + } + }); + + //exports to multiple environments + if (typeof define === 'function' && define.amd) + //AMD + define(function(){ return ePub; }); + else if (typeof module != "undefined" && module.exports) + //Node + module.exports = ePub; + +})(window); + +EPUBJS.Book = function(options){ + + var book = this; + + this.settings = _.defaults(options || {}, { + bookPath : null, + bookKey : null, + packageUrl : null, + storage: false, //-- true (auto) or false (none) | override: 'ram', 'websqldatabase', 'indexeddb', 'filesystem' + fromStorage : false, + saved : false, + online : true, + contained : false, + width : null, + height: null, + layoutOveride : null, // Default: { spread: 'reflowable', layout: 'auto', orientation: 'auto'} + orientation : null, + minSpreadWidth: 800, //-- overridden by spread: none (never) / both (always) + gap: "auto", //-- "auto" or int + version: 1, + restore: false, + reload : false, + goto : false, + styles : {}, + headTags : {}, + withCredentials: false, + render_method: "Iframe" + }); + + this.settings.EPUBJSVERSION = EPUBJS.VERSION; + + this.spinePos = 0; + this.stored = false; + + //-- All Book events for listening + /* + book:ready + book:stored + book:online + book:offline + book:pageChanged + book:loadFailed + book:loadChapterFailed + */ + + //-- Adds Hook methods to the Book prototype + // Hooks will all return before triggering the callback. + // EPUBJS.Hooks.mixin(this); + //-- Get pre-registered hooks for events + // this.getHooks("beforeChapterDisplay"); + + this.online = this.settings.online || navigator.onLine; + this.networkListeners(); + + this.store = false; //-- False if not using storage; + + //-- Determine storage method + //-- Override options: none | ram | websqldatabase | indexeddb | filesystem + + if(this.settings.storage !== false){ + this.storage = new fileStorage.storage(this.settings.storage); + } + + this.ready = { + manifest: new RSVP.defer(), + spine: new RSVP.defer(), + metadata: new RSVP.defer(), + cover: new RSVP.defer(), + toc: new RSVP.defer(), + pageList: new RSVP.defer() + }; + + this.readyPromises = [ + this.ready.manifest.promise, + this.ready.spine.promise, + this.ready.metadata.promise, + this.ready.cover.promise, + this.ready.toc.promise + ]; + + this.pageList = []; + this.pagination = new EPUBJS.Pagination(); + this.pageListReady = this.ready.pageList.promise; + + this.ready.all = RSVP.all(this.readyPromises); + + this.ready.all.then(this._ready.bind(this)); + + // Queue for methods used before rendering + this.isRendered = false; + this._q = EPUBJS.core.queue(this); + // Queue for rendering + this._rendering = false; + this._displayQ = EPUBJS.core.queue(this); + // Queue for going to another location + this._moving = false; + this._gotoQ = EPUBJS.core.queue(this); + + /** + * Creates a new renderer. + * The renderer will handle displaying the content using the method provided in the settings + */ + this.renderer = new EPUBJS.Renderer(this.settings.render_method); + //-- Set the width at which to switch from spreads to single pages + this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + this.renderer.setGap(this.settings.gap); + //-- Pass through the renderer events + this.listenToRenderer(this.renderer); + + this.defer_opened = new RSVP.defer(); + this.opened = this.defer_opened.promise; + // BookUrl is optional, but if present start loading process + if(typeof this.settings.bookPath === 'string') { + this.open(this.settings.bookPath, this.settings.reload); + } + + window.addEventListener("beforeunload", this.unload.bind(this), false); + + //-- Listen for these promises: + //-- book.opened.then() + //-- book.rendered.then() +}; + +//-- Check bookUrl and start parsing book Assets or load them from storage +EPUBJS.Book.prototype.open = function(bookPath, forceReload){ + var book = this, + epubpackage, + opened = new RSVP.defer(); + + this.settings.bookPath = bookPath; + + //-- Get a absolute URL from the book path + this.bookUrl = this.urlFrom(bookPath); + + if(this.settings.contained || this.isContained(bookPath)){ + + this.settings.contained = this.contained = true; + + this.bookUrl = ''; + + epubpackage = this.unarchive(bookPath). + then(function(){ + return book.loadPackage(); + }); + + } else { + epubpackage = this.loadPackage(); + } + + if(this.settings.restore && !forceReload && localStorage){ + //-- Will load previous package json, or re-unpack if error + epubpackage.then(function(packageXml) { + var identifier = book.packageIdentifier(packageXml); + var restored = book.restore(identifier); + + if(!restored) { + book.unpack(packageXml); + } + opened.resolve(); + book.defer_opened.resolve(); + }); + + }else{ + + //-- Get package information from epub opf + epubpackage.then(function(packageXml) { + book.unpack(packageXml); + opened.resolve(); + book.defer_opened.resolve(); + }); + } + + //-- If there is network connection, store the books contents + if(this.online && this.settings.storage && !this.settings.contained){ + if(!this.settings.stored) opened.then(book.storeOffline()); + } + + this._registerReplacements(this.renderer); + + return opened.promise; + +}; + +EPUBJS.Book.prototype.loadPackage = function(_containerPath){ + var book = this, + parse = new EPUBJS.Parser(), + containerPath = _containerPath || "META-INF/container.xml", + containerXml, + packageXml; + + if(!this.settings.packageUrl) { //-- provide the packageUrl to skip this step + packageXml = book.loadXml(book.bookUrl + containerPath). + then(function(containerXml){ + return parse.container(containerXml); // Container has path to content + }). + then(function(paths){ + book.settings.contentsPath = book.bookUrl + paths.basePath; + book.settings.packageUrl = book.bookUrl + paths.packagePath; + book.settings.encoding = paths.encoding; + return book.loadXml(book.settings.packageUrl); // Containes manifest, spine and metadata + }); + } else { + packageXml = book.loadXml(book.settings.packageUrl); + } + + packageXml.catch(function(error) { + // handle errors in either of the two requests + console.error("Could not load book at: "+ containerPath); + book.trigger("book:loadFailed", containerPath); + }); + return packageXml; +}; + +EPUBJS.Book.prototype.packageIdentifier = function(packageXml){ + var book = this, + parse = new EPUBJS.Parser(); + + return parse.identifier(packageXml); +}; + +EPUBJS.Book.prototype.unpack = function(packageXml){ + var book = this, + parse = new EPUBJS.Parser(); + + book.contents = parse.packageContents(packageXml, book.settings.contentsPath); // Extract info from contents + + book.manifest = book.contents.manifest; + book.spine = book.contents.spine; + book.spineIndexByURL = book.contents.spineIndexByURL; + book.metadata = book.contents.metadata; + if(!book.settings.bookKey) { + book.settings.bookKey = book.generateBookKey(book.metadata.identifier); + } + + //-- Set Globbal Layout setting based on metadata + book.globalLayoutProperties = book.parseLayoutProperties(book.metadata); + + if(book.contents.coverPath) { + book.cover = book.contents.cover = book.settings.contentsPath + book.contents.coverPath; + } + + book.spineNodeIndex = book.contents.spineNodeIndex; + + book.ready.manifest.resolve(book.contents.manifest); + book.ready.spine.resolve(book.contents.spine); + book.ready.metadata.resolve(book.contents.metadata); + book.ready.cover.resolve(book.contents.cover); + + + //-- Load the TOC, optional; either the EPUB3 XHTML Navigation file or the EPUB2 NCX file + if(book.contents.navPath) { + book.settings.navUrl = book.settings.contentsPath + book.contents.navPath; + + book.loadXml(book.settings.navUrl). + then(function(navHtml){ + return parse.nav(navHtml, book.spineIndexByURL, book.spine); // Grab Table of Contents + }).then(function(toc){ + book.toc = book.contents.toc = toc; + book.ready.toc.resolve(book.contents.toc); + }, function(error) { + book.ready.toc.resolve(false); + }); + + // Load the optional pageList + book.loadXml(book.settings.navUrl). + then(function(navHtml){ + return parse.pageList(navHtml, book.spineIndexByURL, book.spine); + }).then(function(pageList){ + var epubcfi = new EPUBJS.EpubCFI(); + var wait = 0; // need to generate a cfi + + // No pageList found + if(pageList.length === 0) { + return; + } + + book.pageList = book.contents.pageList = pageList; + + // Replace HREFs with CFI + book.pageList.forEach(function(pg){ + if(!pg.cfi) { + wait += 1; + epubcfi.generateCfiFromHref(pg.href, book).then(function(cfi){ + pg.cfi = cfi; + pg.packageUrl = book.settings.packageUrl; + + wait -= 1; + if(wait === 0) { + book.pagination.process(book.pageList); + book.ready.pageList.resolve(book.pageList); + } + }); + } + }); + + if(!wait) { + book.pagination.process(book.pageList); + book.ready.pageList.resolve(book.pageList); + } + + }, function(error) { + book.ready.pageList.resolve([]); + }); + } else if(book.contents.tocPath) { + book.settings.tocUrl = book.settings.contentsPath + book.contents.tocPath; + + book.loadXml(book.settings.tocUrl). + then(function(tocXml){ + return parse.toc(tocXml, book.spineIndexByURL, book.spine); // Grab Table of Contents + }).then(function(toc){ + book.toc = book.contents.toc = toc; + book.ready.toc.resolve(book.contents.toc); + }, function(error) { + book.ready.toc.resolve(false); + }); + + } else { + book.ready.toc.resolve(false); + } + +}; + +EPUBJS.Book.prototype.createHiddenRender = function(renderer, _width, _height) { + var box = this.element.getBoundingClientRect(); + var width = _width || this.settings.width || box.width; + var height = _height || this.settings.height || box.height; + var hiddenContainer; + var hiddenEl; + renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + renderer.setGap(this.settings.gap); + + this._registerReplacements(renderer); + if(this.settings.forceSingle) { + renderer.forceSingle(true); + } + + hiddenContainer = document.createElement("div"); + hiddenContainer.style.visibility = "hidden"; + hiddenContainer.style.overflow = "hidden"; + hiddenContainer.style.width = "0"; + hiddenContainer.style.height = "0"; + this.element.appendChild(hiddenContainer); + + hiddenEl = document.createElement("div"); + hiddenEl.style.visibility = "hidden"; + hiddenEl.style.overflow = "hidden"; + hiddenEl.style.width = width + "px";//"0"; + hiddenEl.style.height = height +"px"; //"0"; + hiddenContainer.appendChild(hiddenEl); + + renderer.initialize(hiddenEl); + return hiddenContainer; +}; + +// Generates the pageList array by loading every chapter and paging through them +EPUBJS.Book.prototype.generatePageList = function(width, height){ + var pageList = []; + var pager = new EPUBJS.Renderer(this.settings.render_method, false); //hidden + var hiddenContainer = this.createHiddenRender(pager, width, height); + var deferred = new RSVP.defer(); + var spinePos = -1; + var spineLength = this.spine.length; + var totalPages = 0; + var currentPage = 0; + var nextChapter = function(deferred){ + var chapter; + var next = spinePos + 1; + var done = deferred || new RSVP.defer(); + var loaded; + if(next >= spineLength) { + done.resolve(); + } else { + spinePos = next; + chapter = new EPUBJS.Chapter(this.spine[spinePos], this.store); + pager.displayChapter(chapter, this.globalLayoutProperties).then(function(chap){ + pager.pageMap.forEach(function(item){ + currentPage += 1; + pageList.push({ + "cfi" : item.start, + "page" : currentPage + }); + + }); + + if(pager.pageMap.length % 2 > 0 && + pager.spreads) { + currentPage += 1; // Handle Spreads + pageList.push({ + "cfi" : pager.pageMap[pager.pageMap.length - 1].end, + "page" : currentPage + }); + } + + // Load up the next chapter + setTimeout(function(){ + nextChapter(done); + }, 1); + }); + } + return done.promise; + }.bind(this); + + var finished = nextChapter().then(function(){ + pager.remove(); + this.element.removeChild(hiddenContainer); + deferred.resolve(pageList); + }.bind(this)); + + return deferred.promise; +}; + +// Render out entire book and generate the pagination +// Width and Height are optional and will default to the current dimensions +EPUBJS.Book.prototype.generatePagination = function(width, height) { + var book = this; + var defered = new RSVP.defer(); + + this.ready.spine.promise.then(function(){ + book.generatePageList(width, height).then(function(pageList){ + book.pageList = book.contents.pageList = pageList; + book.pagination.process(pageList); + book.ready.pageList.resolve(book.pageList); + defered.resolve(book.pageList); + }); + }); + + return defered.promise; +}; + +// Process the pagination from a JSON array containing the pagelist +EPUBJS.Book.prototype.loadPagination = function(pagelistJSON) { + var pageList = JSON.parse(pagelistJSON); + + if(pageList && pageList.length) { + this.pageList = pageList; + this.pagination.process(this.pageList); + this.ready.pageList.resolve(this.pageList); + } + return this.pageList; +}; + +EPUBJS.Book.prototype.getPageList = function() { + return this.ready.pageList.promise; +}; + +EPUBJS.Book.prototype.getMetadata = function() { + return this.ready.metadata.promise; +}; + +EPUBJS.Book.prototype.getToc = function() { + return this.ready.toc.promise; +}; + +/* Private Helpers */ + +//-- Listeners for browser events +EPUBJS.Book.prototype.networkListeners = function(){ + var book = this; + + window.addEventListener("offline", function(e) { + book.online = false; + book.trigger("book:offline"); + }, false); + + window.addEventListener("online", function(e) { + book.online = true; + book.trigger("book:online"); + }, false); + +}; + +// Listen to all events the renderer triggers and pass them as book events +EPUBJS.Book.prototype.listenToRenderer = function(renderer){ + var book = this; + renderer.Events.forEach(function(eventName){ + renderer.on(eventName, function(e){ + book.trigger(eventName, e); + }); + }); + + renderer.on("renderer:visibleRangeChanged", function(range) { + var startPage, endPage, percent; + var pageRange = []; + + if(this.pageList.length > 0) { + startPage = this.pagination.pageFromCfi(range.start); + percent = this.pagination.percentageFromPage(startPage); + pageRange.push(startPage); + + if(range.end) { + endPage = this.pagination.pageFromCfi(range.end); + //if(startPage != endPage) { + pageRange.push(endPage); + //} + } + this.trigger("book:pageChanged", { + "anchorPage": startPage, + "percentage": percent, + "pageRange" : pageRange + }); + + // TODO: Add event for first and last page. + // (though last is going to be hard, since it could be several reflowed pages long) + } + }.bind(this)); + + renderer.on("render:loaded", this.loadChange.bind(this)); +}; + +// Listens for load events from the Renderer and checks against the current chapter +// Prevents the Render from loading a different chapter when back button is pressed +EPUBJS.Book.prototype.loadChange = function(url){ + var uri = EPUBJS.core.uri(url); + var chapter; + + if(this.currentChapter) { + chapter = EPUBJS.core.uri(this.currentChapter.absolute); + } + + if(!this._rendering && this.currentChapter && uri.path != chapter.path){ + console.warn("Miss Match", uri.path, this.currentChapter.absolute); + this.goto(uri.filename); + } +}; + +EPUBJS.Book.prototype.unlistenToRenderer = function(renderer){ + renderer.Events.forEach(function(eventName){ + renderer.off(eventName); + } ); +}; + +//-- Choose between a request from store or a request from network +EPUBJS.Book.prototype.loadXml = function(url){ + if(this.settings.fromStorage) { + return this.storage.getXml(url, this.settings.encoding); + } else if(this.settings.contained) { + return this.zip.getXml(url, this.settings.encoding); + }else{ + return EPUBJS.core.request(url, 'xml', this.settings.withCredentials); + } +}; + +//-- Turns a url into a absolute url +EPUBJS.Book.prototype.urlFrom = function(bookPath){ + var uri = EPUBJS.core.uri(bookPath), + absolute = uri.protocol, + fromRoot = uri.path[0] == "/", + location = window.location, + //-- Get URL orgin, try for native or combine + origin = location.origin || location.protocol + "//" + location.host, + baseTag = document.getElementsByTagName('base'), + base; + + + //-- Check is Base tag is set + + if(baseTag.length) { + base = baseTag[0].href; + } + + //-- 1. Check if url is absolute + if(uri.protocol){ + return uri.origin + uri.path; + } + + //-- 2. Check if url starts with /, add base url + if(!absolute && fromRoot){ + return (base || origin) + uri.path; + } + + //-- 3. Or find full path to url and add that + if(!absolute && !fromRoot){ + return EPUBJS.core.resolveUrl(base || location.pathname, uri.path); + } + +}; + + +EPUBJS.Book.prototype.unarchive = function(bookPath){ + var book = this, + unarchived; + + //-- Must use storage + // if(this.settings.storage == false ){ + // this.settings.storage = true; + // this.storage = new fileStorage.storage(); + // } + + this.zip = new EPUBJS.Unarchiver(); + this.store = this.zip; // Use zip storaged in ram + return this.zip.openZip(bookPath); +}; + +//-- Checks if url has a .epub or .zip extension +EPUBJS.Book.prototype.isContained = function(bookUrl){ + var uri = EPUBJS.core.uri(bookUrl); + + if(uri.extension && (uri.extension == "epub" || uri.extension == "zip")){ + return true; + } + + return false; +}; + +//-- Checks if the book can be retrieved from localStorage +EPUBJS.Book.prototype.isSaved = function(bookKey) { + var storedSettings; + + if(!localStorage) { + return false; + } + + storedSettings = localStorage.getItem(bookKey); + + if( !localStorage || + storedSettings === null) { + return false; + } else { + return true; + } +}; + +// Generates the Book Key using the identifer in the manifest or other string provided +EPUBJS.Book.prototype.generateBookKey = function(identifier){ + return "epubjs:" + EPUBJS.VERSION + ":" + window.location.host + ":" + identifier; +}; + +EPUBJS.Book.prototype.saveContents = function(){ + if(!localStorage) { + return false; + } + localStorage.setItem(this.settings.bookKey, JSON.stringify(this.contents)); +}; + +EPUBJS.Book.prototype.removeSavedContents = function() { + if(!localStorage) { + return false; + } + localStorage.removeItem(this.settings.bookKey); +}; + + + +//-- Takes a string or a element +EPUBJS.Book.prototype.renderTo = function(elem){ + var book = this, + rendered; + + if(_.isElement(elem)) { + this.element = elem; + } else if (typeof elem == "string") { + this.element = EPUBJS.core.getEl(elem); + } else { + console.error("Not an Element"); + return; + } + + rendered = this.opened. + then(function(){ + // book.render = new EPUBJS.Renderer[this.settings.renderer](book); + book.renderer.initialize(book.element, book.settings.width, book.settings.height); + book._rendered(); + return book.startDisplay(); + }); + + // rendered.then(null, function(error) { console.error(error); }); + + return rendered; +}; + +EPUBJS.Book.prototype.startDisplay = function(){ + var display; + + if(this.settings.goto) { + display = this.goto(this.settings.goto); + }else if(this.settings.previousLocationCfi) { + display = this.gotoCfi(this.settings.previousLocationCfi); + }else{ + display = this.displayChapter(this.spinePos); + } + + return display; +}; + +EPUBJS.Book.prototype.restore = function(identifier){ + + var book = this, + fetch = ['manifest', 'spine', 'metadata', 'cover', 'toc', 'spineNodeIndex', 'spineIndexByURL', 'globalLayoutProperties'], + reject = false, + bookKey = this.generateBookKey(identifier), + fromStore = localStorage.getItem(bookKey), + len = fetch.length, + i; + + if(this.settings.clearSaved) reject = true; + + if(!reject && fromStore != 'undefined' && fromStore !== null){ + book.contents = JSON.parse(fromStore); + + for(i = 0; i < len; i++) { + var item = fetch[i]; + + if(!book.contents[item]) { + reject = true; + break; + } + book[item] = book.contents[item]; + } + } + + if(reject || !fromStore || !this.contents || !this.settings.contentsPath){ + return false; + }else{ + this.settings.bookKey = bookKey; + this.ready.manifest.resolve(this.manifest); + this.ready.spine.resolve(this.spine); + this.ready.metadata.resolve(this.metadata); + this.ready.cover.resolve(this.cover); + this.ready.toc.resolve(this.toc); + return true; + } + +}; + +EPUBJS.Book.prototype.displayChapter = function(chap, end, deferred){ + var book = this, + render, + cfi, + pos, + store, + defer = deferred || new RSVP.defer(); + + var chapter; + + if(!this.isRendered) { + this._q.enqueue("displayChapter", arguments); + // Reject for now. TODO: pass promise to queue + defer.reject({ + message : "Rendering", + stack : new Error().stack + }); + return defer.promise; + } + + + if(this._rendering || this._rendering) { + // Pass along the current defer + this._displayQ.enqueue("displayChapter", [chap, end, defer]); + return defer.promise; + } + + if(_.isNumber(chap)){ + pos = chap; + }else{ + cfi = new EPUBJS.EpubCFI(chap); + pos = cfi.spinePos; + } + + if(pos < 0 || pos >= this.spine.length){ + console.warn("Not A Valid Location"); + pos = 0; + end = false; + cfi = false; + } + + //-- Create a new chapter + chapter = new EPUBJS.Chapter(this.spine[pos], this.store); + + this._rendering = true; + + render = book.renderer.displayChapter(chapter, this.globalLayoutProperties); + if(cfi) { + book.renderer.gotoCfi(cfi); + } else if(end) { + book.renderer.lastPage(); + } + //-- Success, Clear render queue + render.then(function(rendered){ + // var inwait; + //-- Set the book's spine position + book.spinePos = pos; + + defer.resolve(book.renderer); + + if(!book.settings.fromStorage && + !book.settings.contained) { + book.preloadNextChapter(); + } + + book.currentChapter = chapter; + book._rendering = false; + book._displayQ.dequeue(); + if(book._displayQ.length() === 0) { + book._gotoQ.dequeue(); + } + + }, function(error) { + // handle errors in either of the two requests + console.error("Could not load Chapter: "+ chapter.absolute); + book.trigger("book:chapterLoadFailed", chapter.absolute); + book._rendering = false; + defer.reject(error); + }); + + return defer.promise; +}; + +EPUBJS.Book.prototype.nextPage = function(){ + var next; + + if(!this.isRendered) return this._q.enqueue("nextPage", arguments); + + next = this.renderer.nextPage(); + + if(!next){ + return this.nextChapter(); + } +}; + +EPUBJS.Book.prototype.prevPage = function() { + var prev; + + if(!this.isRendered) return this._q.enqueue("prevPage", arguments); + + prev = this.renderer.prevPage(); + + if(!prev){ + return this.prevChapter(); + } +}; + +EPUBJS.Book.prototype.nextChapter = function() { + var next; + if (this.spinePos < this.spine.length - 1) { + next = this.spinePos + 1; + // Skip non linear chapters + while (this.spine[next] && this.spine[next].linear && this.spine[next].linear == 'no') { + next++; + } + if (next < this.spine.length) { + return this.displayChapter(next); + } else { + this.trigger("book:atEnd"); + } + + } else { + this.trigger("book:atEnd"); + } +}; + +EPUBJS.Book.prototype.prevChapter = function() { + var prev; + if (this.spinePos > 0) { + prev = this.spinePos - 1; + while (this.spine[prev] && this.spine[prev].linear && this.spine[prev].linear == 'no') { + prev--; + } + if (prev >= 0) { + return this.displayChapter(prev, true); + } else { + this.trigger("book:atStart"); + } + + } else { + this.trigger("book:atStart"); + } +}; + +EPUBJS.Book.prototype.getCurrentLocationCfi = function() { + if(!this.isRendered) return false; + return this.renderer.currentLocationCfi; +}; + +EPUBJS.Book.prototype.goto = function(target){ + + if(target.indexOf("epubcfi(") === 0) { + return this.gotoCfi(target); + } else if(target.indexOf("%") === target.length-1) { + return this.gotoPercentage(parseInt(target.substring(0, target.length-1))/100); + } else if(typeof target === "number" || isNaN(target) === false){ + return this.gotoPage(target); + } else { + return this.gotoHref(target); + } + +}; + +EPUBJS.Book.prototype.gotoCfi = function(cfiString, defer){ + var cfi, + spinePos, + spineItem, + rendered, + deferred = defer || new RSVP.defer(); + + if(!this.isRendered) { + console.warn("Not yet Rendered"); + this.settings.previousLocationCfi = cfiString; + return false; + } + + // Currently going to a chapter + if(this._moving || this._rendering) { + console.warn("Renderer is moving"); + this._gotoQ.enqueue("gotoCfi", [cfiString, deferred]); + return false; + } + + cfi = new EPUBJS.EpubCFI(cfiString); + spinePos = cfi.spinePos; + + if(spinePos == -1) { + return false; + } + + spineItem = this.spine[spinePos]; + promise = deferred.promise; + this._moving = true; + //-- If same chapter only stay on current chapter + if(this.currentChapter && this.spinePos === spinePos){ + this.renderer.gotoCfi(cfi); + this._moving = false; + deferred.resolve(this.renderer.currentLocationCfi); + } else { + + if(!spineItem || spinePos == -1) { + spinePos = 0; + spineItem = this.spine[spinePos]; + } + + this.currentChapter = new EPUBJS.Chapter(spineItem, this.store); + + if(this.currentChapter) { + this.spinePos = spinePos; + render = this.renderer.displayChapter(this.currentChapter, this.globalLayoutProperties); + + this.renderer.gotoCfi(cfi); + render.then(function(rendered){ + this._moving = false; + deferred.resolve(rendered.currentLocationCfi); + }.bind(this)); + } + } + + promise.then(function(){ + this._gotoQ.dequeue(); + }.bind(this)); + + return promise; +}; + +EPUBJS.Book.prototype.gotoHref = function(url, defer){ + var split, chapter, section, relativeURL, spinePos; + var deferred = defer || new RSVP.defer(); + + if(!this.isRendered) { + this.settings.goto = url; + return false; + } + + // Currently going to a chapter + if(this._moving || this._rendering) { + this._gotoQ.enqueue("gotoHref", [url, deferred]); + return false; + } + + split = url.split("#"); + chapter = split[0]; + section = split[1] || false; + // absoluteURL = (chapter.search("://") === -1) ? (this.settings.contentsPath + chapter) : chapter; + relativeURL = chapter.replace(this.settings.contentsPath, ''); + spinePos = this.spineIndexByURL[relativeURL]; + + //-- If link fragment only stay on current chapter + if(!chapter){ + spinePos = this.currentChapter ? this.currentChapter.spinePos : 0; + } + + //-- Check that URL is present in the index, or stop + if(typeof(spinePos) != "number") return false; + + if(!this.currentChapter || spinePos != this.currentChapter.spinePos){ + //-- Load new chapter if different than current + return this.displayChapter(spinePos).then(function(){ + if(section){ + this.renderer.section(section); + } + deferred.resolve(this.renderer.currentLocationCfi); + }.bind(this)); + }else{ + //-- Goto section + if(section) { + this.renderer.section(section); + } else { + // Or jump to the start + this.renderer.firstPage(); + } + deferred.resolve(this.renderer.currentLocationCfi); + } + + deferred.promise.then(function(){ + this._gotoQ.dequeue(); + }.bind(this)); + + return deferred.promise; +}; + +EPUBJS.Book.prototype.gotoPage = function(pg){ + var cfi = this.pagination.cfiFromPage(pg); + return this.gotoCfi(cfi); +}; + +EPUBJS.Book.prototype.gotoPercentage = function(percent){ + var pg = this.pagination.pageFromPercentage(percent); + return this.gotoPage(pg); +}; + +EPUBJS.Book.prototype.preloadNextChapter = function() { + var next; + var chap = this.spinePos + 1; + + if(chap >= this.spine.length){ + return false; + } + + next = new EPUBJS.Chapter(this.spine[chap]); + if(next) { + EPUBJS.core.request(next.absolute); + } +}; + + +EPUBJS.Book.prototype.storeOffline = function() { + var book = this, + assets = _.values(this.manifest); + + //-- Creates a queue of all items to load + return EPUBJS.storage.batch(assets). + then(function(){ + book.settings.stored = true; + book.trigger("book:stored"); + }); +}; + +EPUBJS.Book.prototype.availableOffline = function() { + return this.settings.stored > 0 ? true : false; +}; + +/* +EPUBJS.Book.prototype.fromStorage = function(stored) { + + if(this.contained) return; + + if(!stored){ + this.online = true; + this.tell("book:online"); + }else{ + if(!this.availableOffline){ + //-- If book hasn't been cached yet, store offline + this.storeOffline(function(){ + this.online = false; + this.tell("book:offline"); + }.bind(this)); + + }else{ + this.online = false; + this.tell("book:offline"); + } + } + +} +*/ + +EPUBJS.Book.prototype.setStyle = function(style, val, prefixed) { + var noreflow = ["color", "background", "background-color"]; + + if(!this.isRendered) return this._q.enqueue("setStyle", arguments); + + this.settings.styles[style] = val; + + this.renderer.setStyle(style, val, prefixed); + + if(noreflow.indexOf(style) === -1) { + // clearTimeout(this.reformatTimeout); + // this.reformatTimeout = setTimeout(function(){ + this.renderer.reformat(); + // }.bind(this), 10); + } +}; + +EPUBJS.Book.prototype.removeStyle = function(style) { + if(!this.isRendered) return this._q.enqueue("removeStyle", arguments); + this.renderer.removeStyle(style); + this.renderer.reformat(); + delete this.settings.styles[style]; +}; + +EPUBJS.Book.prototype.addHeadTag = function(tag, attrs) { + if(!this.isRendered) return this._q.enqueue("addHeadTag", arguments); + this.settings.headTags[tag] = attrs; +}; + +EPUBJS.Book.prototype.useSpreads = function(use) { + console.warn("useSpreads is deprecated, use forceSingle or set a layoutOveride instead"); + if(use === false) { + this.forceSingle(true); + } else { + this.forceSingle(false); + } +}; + +EPUBJS.Book.prototype.forceSingle = function(_use) { + var force = typeof _use === "undefined" ? true : _use; + + this.renderer.forceSingle(force); + this.settings.forceSingle = force; + if(this.isRendered) { + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.setMinSpreadWidth = function(width) { + this.settings.minSpreadWidth = width; + if(this.isRendered) { + this.renderer.setMinSpreadWidth(this.settings.minSpreadWidth); + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.setGap = function(gap) { + this.settings.gap = gap; + if(this.isRendered) { + this.renderer.setGap(this.settings.gap); + this.renderer.reformat(); + } +}; + +EPUBJS.Book.prototype.chapter = function(path) { + var spinePos = this.spineIndexByURL[path]; + var spineItem; + var chapter; + + if(spinePos){ + spineItem = this.spine[spinePos]; + chapter = new EPUBJS.Chapter(spineItem, this.store); + chapter.load(); + } + return chapter; +}; + +EPUBJS.Book.prototype.unload = function(){ + + if(this.settings.restore && localStorage) { + this.saveContents(); + } + + this.unlistenToRenderer(this.renderer); + + this.trigger("book:unload"); +}; + +EPUBJS.Book.prototype.destroy = function() { + + window.removeEventListener("beforeunload", this.unload); + + if(this.currentChapter) this.currentChapter.unload(); + + this.unload(); + + if(this.render) this.render.remove(); + +}; + +EPUBJS.Book.prototype._ready = function() { + + this.trigger("book:ready"); + +}; + +EPUBJS.Book.prototype._rendered = function(err) { + var book = this; + + this.isRendered = true; + this.trigger("book:rendered"); + + this._q.flush(); +}; + + +EPUBJS.Book.prototype.applyStyles = function(renderer, callback){ + // if(!this.isRendered) return this._q.enqueue("applyStyles", arguments); + renderer.applyStyles(this.settings.styles); + callback(); +}; + +EPUBJS.Book.prototype.applyHeadTags = function(renderer, callback){ + // if(!this.isRendered) return this._q.enqueue("applyHeadTags", arguments); + renderer.applyHeadTags(this.settings.headTags); + callback(); +}; + +EPUBJS.Book.prototype._registerReplacements = function(renderer){ + renderer.registerHook("beforeChapterDisplay", this.applyStyles.bind(this, renderer), true); + renderer.registerHook("beforeChapterDisplay", this.applyHeadTags.bind(this, renderer), true); + renderer.registerHook("beforeChapterDisplay", EPUBJS.replace.hrefs.bind(this), true); + + if(this._needsAssetReplacement()) { + + renderer.registerHook("beforeChapterDisplay", [ + EPUBJS.replace.head, + EPUBJS.replace.resources, + EPUBJS.replace.svg + ], true); + + } + +}; + +EPUBJS.Book.prototype._needsAssetReplacement = function(){ + if(this.settings.fromStorage) { + + //-- Filesystem api links are relative, so no need to replace them + if(this.storage.getStorageType() == "filesystem") { + return false; + } + + return true; + + } else if(this.settings.contained) { + + return true; + + } else { + + return false; + + } +}; + + +//-- http://www.idpf.org/epub/fxl/ +EPUBJS.Book.prototype.parseLayoutProperties = function(metadata){ + var layout = (this.layoutOveride && this.layoutOveride.layout) || metadata.layout || "reflowable"; + var spread = (this.layoutOveride && this.layoutOveride.spread) || metadata.spread || "auto"; + var orientation = (this.layoutOveride && this.layoutOveride.orientation) || metadata.orientation || "auto"; + return { + layout : layout, + spread : spread, + orientation : orientation + }; +}; + +//-- Enable binding events to book +RSVP.EventTarget.mixin(EPUBJS.Book.prototype); + +//-- Handle RSVP Errors +RSVP.on('error', function(event) { + //console.error(event, event.detail); +}); + +RSVP.configure('instrument', true); //-- true | will logging out all RSVP rejections +// RSVP.on('created', listener); +// RSVP.on('chained', listener); +// RSVP.on('fulfilled', listener); +RSVP.on('rejected', function(event){ + console.error(event.detail.message, event.detail.stack); +}); + +EPUBJS.Chapter = function(spineObject, store){ + this.href = spineObject.href; + this.absolute = spineObject.url; + this.id = spineObject.id; + this.spinePos = spineObject.index; + this.cfiBase = spineObject.cfiBase; + this.properties = spineObject.properties; + this.manifestProperties = spineObject.manifestProperties; + this.linear = spineObject.linear; + this.pages = 1; + this.store = store; + this.epubcfi = new EPUBJS.EpubCFI(); + this.deferred = new RSVP.defer(); + this.loaded = this.deferred.promise; +}; + + +EPUBJS.Chapter.prototype.load = function(_store){ + var store = _store || this.store; + var promise; + // if(this.store && (!this.book.online || this.book.contained)) + if(store){ + promise = store.get(this.href); + }else{ + promise = EPUBJS.core.request(this.absolute, 'xml'); + } + + promise.then(function(xml){ + this.setDocument(xml); + this.deferred.resolve(this); + }.bind(this)); + + return promise; +}; + +EPUBJS.Chapter.prototype.render = function(_store){ + + return this.load().then(function(doc){ + + var serializer = new XMLSerializer(); + var contents; + var head = doc.head; + var base = doc.createElement("base"); + + base.setAttribute("href", window.location.origin + this.absolute); + head.insertBefore(base, head.firstChild); + contents = serializer.serializeToString(doc); + + return contents; + + }.bind(this)); +}; + +EPUBJS.Chapter.prototype.url = function(_store){ + var deferred = new RSVP.defer(); + var store = _store || this.store; + var loaded; + var chapter = this; + var url; + + if(store){ + if(!this.tempUrl) { + store.getUrl(this.absolute).then(function(url){ + chapter.tempUrl = url; + deferred.resolve(url); + }); + } else { + url = this.tempUrl; + deferred.resolve(url); + } + }else{ + url = this.absolute; + deferred.resolve(url); + } + /* + loaded = EPUBJS.core.request(url, 'xml', false); + loaded.then(function(contents){ + chapter.contents = contents; + deferred.resolve(chapter.absolute); + }, function(error){ + deferred.reject(error); + }); + */ + + return deferred.promise; +}; + +EPUBJS.Chapter.prototype.setPages = function(num){ + this.pages = num; +}; + +EPUBJS.Chapter.prototype.getPages = function(num){ + return this.pages; +}; + +EPUBJS.Chapter.prototype.getID = function(){ + return this.ID; +}; + +EPUBJS.Chapter.prototype.unload = function(store){ + this.document = null; + if(this.tempUrl && store) { + store.revokeUrl(this.tempUrl); + this.tempUrl = false; + } +}; + +EPUBJS.Chapter.prototype.setDocument = function(_document){ + var uri = _document.namespaceURI; + var doctype = _document.doctype; + + // Creates an empty document + this.document = _document.implementation.createDocument( + uri, + null, + null + ); + this.contents = this.document.importNode( + _document.documentElement, //node to import + true //clone its descendants + ); + + this.document.appendChild(this.contents); + + // Fix to apply wgxpath to new document in IE + if(!this.document.evaluate && document.evaluate) { + this.document.evaluate = document.evaluate; + } + + // this.deferred.resolve(this.contents); +}; + +EPUBJS.Chapter.prototype.cfiFromRange = function(_range) { + var range; + var startXpath, endXpath; + var startContainer, endContainer; + var cleanTextContent, cleanEndTextContent; + + // Check for Contents + if(!this.document) return; + startXpath = EPUBJS.core.getElementXPath(_range.startContainer); + // console.log(startContainer) + endXpath = EPUBJS.core.getElementXPath(_range.endContainer); + + startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(!_range.collapsed) { + endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + } + + range = this.document.createRange(); + // Find Exact Range in original document + if(startContainer) { + try { + range.setStart(startContainer, _range.startOffset); + if(!_range.collapsed && endContainer) { + range.setEnd(endContainer, _range.endOffset); + } + } catch (e) { + console.log("missed"); + startContainer = false; + } + + } + + // Fuzzy Match + if(!startContainer) { + console.log("not found, try fuzzy match"); + cleanStartTextContent = EPUBJS.core.cleanStringForXpath(_range.startContainer.textContent); + startXpath = "//text()[contains(.," + cleanStartTextContent + ")]"; + + startContainer = this.document.evaluate(startXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(startContainer){ + // console.log("Found with Fuzzy"); + range.setStart(startContainer, _range.startOffset); + + if(!_range.collapsed) { + cleanEndTextContent = EPUBJS.core.cleanStringForXpath(_range.endContainer.textContent); + endXpath = "//text()[contains(.," + cleanEndTextContent + ")]"; + endContainer = this.document.evaluate(endXpath, this.document, EPUBJS.core.nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + if(endContainer) { + range.setEnd(endContainer, _range.endOffset); + } + } + + } + } + + // Generate the Cfi + return this.epubcfi.generateCfiFromRange(range, this.cfiBase); +}; + +EPUBJS.Chapter.prototype.find = function(_query){ + var chapter = this; + var matches = []; + var query = _query.toLowerCase(); + //var xpath = this.document.evaluate(".//text()[contains(translate(., '"+query.toUpperCase()+"', '"+query+"'),'"+query+"')]", this.document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); + var find = function(node){ + // Search String + var text = node.textContent.toLowerCase(); + var range = chapter.document.createRange(); + var cfi; + var pos; + var last = -1; + var excerpt; + var limit = 150; + + while (pos != -1) { + pos = text.indexOf(query, last + 1); + + if(pos != -1) { + // If Found, Create Range + range = chapter.document.createRange(); + range.setStart(node, pos); + range.setEnd(node, pos + query.length); + + //Generate CFI + cfi = chapter.cfiFromRange(range); + + // Generate Excerpt + if(node.textContent.length < limit) { + excerpt = node.textContent; + } else { + excerpt = node.textContent.substring(pos-limit/2,pos+limit/2); + excerpt = "..." + excerpt + "..."; + } + + //Add CFI to list + matches.push({ + cfi: cfi, + excerpt: excerpt + }); + } + + last = pos; + } + + }; + + // Grab text nodes + + /* + for ( var i=0 ; i < xpath.snapshotLength; i++ ) { + find(xpath.snapshotItem(i)); + } + */ + + this.textSprint(this.document, function(node){ + find(node); + }); + + + // Return List of CFIs + return matches; +}; + + +EPUBJS.Chapter.prototype.textSprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if (node.data && ! /^\s*$/.test(node.data) ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; +var EPUBJS = EPUBJS || {}; +EPUBJS.core = {}; + +//-- Get a element for an id +EPUBJS.core.getEl = function(elem) { + return document.getElementById(elem); +}; + +//-- Get all elements for a class +EPUBJS.core.getEls = function(classes) { + return document.getElementsByClassName(classes); +}; + +EPUBJS.core.request = function(url, type, withCredentials) { + var supportsURL = window.URL; + var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; + + var deferred = new RSVP.defer(); + + var xhr = new XMLHttpRequest(); + + //-- Check from PDF.js: + // https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js + var xhrPrototype = XMLHttpRequest.prototype; + + if (!('overrideMimeType' in xhrPrototype)) { + // IE10 might have response, but not overrideMimeType + Object.defineProperty(xhrPrototype, 'overrideMimeType', { + value: function xmlHttpRequestOverrideMimeType(mimeType) {} + }); + } + if(withCredentials) { + xhr.withCredentials = true; + } + xhr.open("GET", url, true); + xhr.onreadystatechange = handler; + + if(type == 'blob'){ + xhr.responseType = BLOB_RESPONSE; + } + + if(type == "json") { + xhr.setRequestHeader("Accept", "application/json"); + } + + if(type == 'xml') { + xhr.overrideMimeType('text/xml'); + } + + if(type == "binary") { + xhr.responseType = "arraybuffer"; + } + + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls + var r; + + if(type == 'xml'){ + r = this.responseXML; + }else + if(type == 'json'){ + r = JSON.parse(this.response); + }else + if(type == 'blob'){ + + if(supportsURL) { + r = this.response; + } else { + //-- Safari doesn't support responseType blob, so create a blob from arraybuffer + r = new Blob([this.response]); + } + + }else{ + r = this.response; + } + + deferred.resolve(r); + } else { + deferred.reject({ + message : this.response, + stack : new Error().stack + }); + } + } + } + + return deferred.promise; +}; + +EPUBJS.core.toArray = function(obj) { + var arr = []; + + for (var member in obj) { + var newitm; + if ( obj.hasOwnProperty(member) ) { + newitm = obj[member]; + newitm.ident = member; + arr.push(newitm); + } + } + + return arr; +}; + +//-- Parse the different parts of a url, returning a object +EPUBJS.core.uri = function(url){ + var uri = { + protocol : '', + host : '', + path : '', + origin : '', + directory : '', + base : '', + filename : '', + extension : '', + fragment : '', + href : url + }, + blob = url.indexOf('blob:'), + doubleSlash = url.indexOf('://'), + search = url.indexOf('?'), + fragment = url.indexOf("#"), + withoutProtocol, + dot, + firstSlash; + + if(blob === 0) { + uri.protocol = "blob"; + uri.base = url.indexOf(0, fragment); + return uri; + } + + if(fragment != -1) { + uri.fragment = url.slice(fragment + 1); + url = url.slice(0, fragment); + } + + if(search != -1) { + uri.search = url.slice(search + 1); + url = url.slice(0, search); + href = url; + } + + if(doubleSlash != -1) { + uri.protocol = url.slice(0, doubleSlash); + withoutProtocol = url.slice(doubleSlash+3); + firstSlash = withoutProtocol.indexOf('/'); + + if(firstSlash === -1) { + uri.host = uri.path; + uri.path = ""; + } else { + uri.host = withoutProtocol.slice(0, firstSlash); + uri.path = withoutProtocol.slice(firstSlash); + } + + + uri.origin = uri.protocol + "://" + uri.host; + + uri.directory = EPUBJS.core.folder(uri.path); + + uri.base = uri.origin + uri.directory; + // return origin; + } else { + uri.path = url; + uri.directory = EPUBJS.core.folder(url); + uri.base = uri.directory; + } + + //-- Filename + uri.filename = url.replace(uri.base, ''); + dot = uri.filename.lastIndexOf('.'); + if(dot != -1) { + uri.extension = uri.filename.slice(dot+1); + } + return uri; +}; + +//-- Parse out the folder, will return everything before the last slash + +EPUBJS.core.folder = function(url){ + + var lastSlash = url.lastIndexOf('/'); + + if(lastSlash == -1) var folder = ''; + + folder = url.slice(0, lastSlash + 1); + + return folder; + +}; + +//-- https://github.com/ebidel/filer.js/blob/master/src/filer.js#L128 +EPUBJS.core.dataURLToBlob = function(dataURL) { + var BASE64_MARKER = ';base64,', + parts, contentType, raw, rawLength, uInt8Array; + + if (dataURL.indexOf(BASE64_MARKER) == -1) { + parts = dataURL.split(','); + contentType = parts[0].split(':')[1]; + raw = parts[1]; + + return new Blob([raw], {type: contentType}); + } + + parts = dataURL.split(BASE64_MARKER); + contentType = parts[0].split(':')[1]; + raw = window.atob(parts[1]); + rawLength = raw.length; + + uInt8Array = new Uint8Array(rawLength); + + for (var i = 0; i < rawLength; ++i) { + uInt8Array[i] = raw.charCodeAt(i); + } + + return new Blob([uInt8Array], {type: contentType}); +}; + +//-- Load scripts async: http://stackoverflow.com/questions/7718935/load-scripts-asynchronously +EPUBJS.core.addScript = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('script'); + s.type = 'text/javascript'; + s.async = false; + s.src = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.addScripts = function(srcArr, callback, target) { + var total = srcArr.length, + curr = 0, + cb = function(){ + curr++; + if(total == curr){ + if(callback) callback(); + }else{ + EPUBJS.core.addScript(srcArr[curr], cb, target); + } + }; + + EPUBJS.core.addScript(srcArr[curr], cb, target); +}; + +EPUBJS.core.addCss = function(src, callback, target) { + var s, r; + r = false; + s = document.createElement('link'); + s.type = 'text/css'; + s.rel = "stylesheet"; + s.href = src; + s.onload = s.onreadystatechange = function() { + if ( !r && (!this.readyState || this.readyState == 'complete') ) { + r = true; + if(callback) callback(); + } + }; + target = target || document.body; + target.appendChild(s); +}; + +EPUBJS.core.prefixed = function(unprefixed) { + var vendors = ["Webkit", "Moz", "O", "ms" ], + prefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'], + upper = unprefixed[0].toUpperCase() + unprefixed.slice(1), + length = vendors.length; + + if (typeof(document.body.style[unprefixed]) != 'undefined') { + return unprefixed; + } + + for ( var i=0; i < length; i++ ) { + if (typeof(document.body.style[vendors[i] + upper]) != 'undefined') { + return vendors[i] + upper; + } + } + + return unprefixed; +}; + +EPUBJS.core.resolveUrl = function(base, path) { + var url, + segments = [], + uri = EPUBJS.core.uri(path), + folders = base.split("/"), + paths; + + if(uri.host) { + return path; + } + + folders.pop(); + + paths = path.split("/"); + paths.forEach(function(p){ + if(p === ".."){ + folders.pop(); + }else{ + segments.push(p); + } + }); + + url = folders.concat(segments); + + return url.join("/"); +}; + +// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript +EPUBJS.core.uuid = function() { + var d = new Date().getTime(); + var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { + var r = (d + Math.random()*16)%16 | 0; + d = Math.floor(d/16); + return (c=='x' ? r : (r&0x7|0x8)).toString(16); + }); + return uuid; +}; + +// Fast quicksort insert for sorted array -- based on: +// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers +EPUBJS.core.insert = function(item, array, compareFunction) { + var location = EPUBJS.core.locationOf(item, array, compareFunction); + array.splice(location, 0, item); + + return location; +}; + +EPUBJS.core.locationOf = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return pivot; + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared > 0 ? pivot : pivot + 1; + } + + if(compared === 0) { + return pivot; + } + if(compared === -1) { + return EPUBJS.core.locationOf(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.locationOf(item, array, compareFunction, start, pivot); + } +}; + +EPUBJS.core.indexOfSorted = function(item, array, compareFunction, _start, _end) { + var start = _start || 0; + var end = _end || array.length; + var pivot = parseInt(start + (end - start) / 2); + var compared; + if(!compareFunction){ + compareFunction = function(a, b) { + if(a > b) return 1; + if(a < b) return -1; + if(a = b) return 0; + }; + } + if(end-start <= 0) { + return -1; // Not found + } + + compared = compareFunction(array[pivot], item); + if(end-start === 1) { + return compared === 0 ? pivot : -1; + } + if(compared === 0) { + return pivot; // Found + } + if(compared === -1) { + return EPUBJS.core.indexOfSorted(item, array, compareFunction, pivot, end); + } else{ + return EPUBJS.core.indexOfSorted(item, array, compareFunction, start, pivot); + } +}; + + +EPUBJS.core.queue = function(_scope){ + var _q = []; + var scope = _scope; + // Add an item to the queue + var enqueue = function(funcName, args, context) { + _q.push({ + "funcName" : funcName, + "args" : args, + "context" : context + }); + return _q; + }; + // Run one item + var dequeue = function(){ + var inwait; + if(_q.length) { + inwait = _q.shift(); + // Defer to any current tasks + // setTimeout(function(){ + scope[inwait.funcName].apply(inwait.context || scope, inwait.args); + // }, 0); + } + }; + + // Run All + var flush = function(){ + while(_q.length) { + dequeue(); + } + }; + // Clear all items in wait + var clear = function(){ + _q = []; + }; + + var length = function(){ + return _q.length; + }; + + return { + "enqueue" : enqueue, + "dequeue" : dequeue, + "flush" : flush, + "clear" : clear, + "length" : length + }; +}; + +// From: https://code.google.com/p/fbug/source/browse/branches/firebug1.10/content/firebug/lib/xpath.js +/** + * Gets an XPath for an element which describes its hierarchical location. + */ +EPUBJS.core.getElementXPath = function(element) { + if (element && element.id) { + return '//*[@id="' + element.id + '"]'; + } else { + return EPUBJS.core.getElementTreeXPath(element); + } +}; + +EPUBJS.core.getElementTreeXPath = function(element) { + var paths = []; + var isXhtml = (element.ownerDocument.documentElement.getAttribute('xmlns') === "http://www.w3.org/1999/xhtml"); + var index, nodeName, tagName, pathIndex; + + if(element.nodeType === Node.TEXT_NODE){ + // index = Array.prototype.indexOf.call(element.parentNode.childNodes, element) + 1; + index = EPUBJS.core.indexOfTextNode(element) + 1; + + paths.push("text()["+index+"]"); + element = element.parentNode; + } + + // Use nodeName (instead of localName) so namespace prefix is included (if any). + for (; element && element.nodeType == 1; element = element.parentNode) + { + index = 0; + for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling) + { + // Ignore document type declaration. + if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE) { + continue; + } + if (sibling.nodeName == element.nodeName) { + ++index; + } + } + nodeName = element.nodeName.toLowerCase(); + tagName = (isXhtml ? "xhtml:" + nodeName : nodeName); + pathIndex = (index ? "[" + (index+1) + "]" : ""); + paths.splice(0, 0, tagName + pathIndex); + } + + return paths.length ? "./" + paths.join("/") : null; +}; + +EPUBJS.core.nsResolver = function(prefix) { + var ns = { + 'xhtml' : 'http://www.w3.org/1999/xhtml', + 'epub': 'http://www.idpf.org/2007/ops' + }; + return ns[prefix] || null; +}; + +//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496 +EPUBJS.core.cleanStringForXpath = function(str) { + var parts = str.match(/[^'"]+|['"]/g); + parts = parts.map(function(part){ + if (part === "'") { + return '\"\'\"'; // output "'" + } + + if (part === '"') { + return "\'\"\'"; // output '"' + } + return "\'" + part + "\'"; + }); + return "concat(\'\'," + parts.join(",") + ")"; +}; + +EPUBJS.core.indexOfTextNode = function(textNode){ + var parent = textNode.parentNode; + var children = parent.childNodes; + var sib; + var index = -1; + for (var i = 0; i < children.length; i++) { + sib = children[i]; + if(sib.nodeType === Node.TEXT_NODE){ + index++; + } + if(sib == textNode) break; + } + + return index; +}; +EPUBJS.EpubCFI = function(cfiStr){ + if(cfiStr) return this.parse(cfiStr); +}; + +EPUBJS.EpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) { + var pos = parseInt(_pos), + spineNodeIndex = _spineNodeIndex + 1, + cfi = '/'+spineNodeIndex+'/'; + + cfi += (pos + 1) * 2; + + if(id) cfi += "[" + id + "]"; + + //cfi += "!"; + + return cfi; +}; + +EPUBJS.EpubCFI.prototype.generatePathComponent = function(steps) { + var parts = []; + + steps.forEach(function(part){ + var segment = ''; + segment += (part.index + 1) * 2; + + if(part.id) { + segment += "[" + part.id + "]"; + } + + parts.push(segment); + }); + + return parts.join('/'); +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromElement = function(element, chapter) { + var steps = this.pathTo(element); + var path = this.generatePathComponent(steps); + if(!path.length) { + // Start of Chapter + return "epubcfi(" + chapter + "!/4/)"; + } else { + // First Text Node + return "epubcfi(" + chapter + "!" + path + "/1:0)"; + } +}; + +EPUBJS.EpubCFI.prototype.pathTo = function(node) { + var stack = [], + children; + + while(node && node.parentNode !== null && node.parentNode.nodeType != 9) { + children = node.parentNode.children; + + stack.unshift({ + 'id' : node.id, + // 'classList' : node.classList, + 'tagName' : node.tagName, + 'index' : children ? Array.prototype.indexOf.call(children, node) : 0 + }); + + node = node.parentNode; + } + + return stack; +}; + +EPUBJS.EpubCFI.prototype.getChapterComponent = function(cfiStr) { + + var splitStr = cfiStr.split("!"); + + return splitStr[0]; +}; + +EPUBJS.EpubCFI.prototype.getPathComponent = function(cfiStr) { + + var splitStr = cfiStr.split("!"); + var pathComponent = splitStr[1] ? splitStr[1].split(":") : ''; + + return pathComponent[0]; +}; + +EPUBJS.EpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) { + var splitStr = cfiStr.split(":"); + return splitStr[1] || ''; +}; + + +EPUBJS.EpubCFI.prototype.parse = function(cfiStr) { + var cfi = {}, + chapSegment, + chapterComponent, + pathComponent, + charecterOffsetComponent, + assertion, + chapId, + path, + end, + endInt, + text, + parseStep = function(part){ + var type, index, has_brackets, id; + + type = "element"; + index = parseInt(part) / 2 - 1; + has_brackets = part.match(/\[(.*)\]/); + if(has_brackets && has_brackets[1]){ + id = has_brackets[1]; + } + + return { + "type" : type, + 'index' : index, + 'id' : id || false + }; + }; + + if(typeof cfiStr !== "string") { + return {spinePos: -1}; + } + + cfi.str = cfiStr; + + if(cfiStr.indexOf("epubcfi(") === 0 && cfiStr[cfiStr.length-1] === ")") { + // Remove intial epubcfi( and ending ) + cfiStr = cfiStr.slice(8, cfiStr.length-1); + } + + chapterComponent = this.getChapterComponent(cfiStr); + pathComponent = this.getPathComponent(cfiStr) || ''; + charecterOffsetComponent = this.getCharecterOffsetComponent(cfiStr); + // Make sure this is a valid cfi or return + if(!chapterComponent) { + return {spinePos: -1}; + } + + // Chapter segment is always the second one + chapSegment = chapterComponent.split("/")[2] || ''; + if(!chapSegment) return {spinePos:-1}; + + cfi.spinePos = (parseInt(chapSegment) / 2 - 1 ) || 0; + + chapId = chapSegment.match(/\[(.*)\]/); + + cfi.spineId = chapId ? chapId[1] : false; + + if(pathComponent.indexOf(',') != -1) { + // Handle ranges -- not supported yet + console.warn("CFI Ranges are not supported"); + } + + path = pathComponent.split('/'); + end = path.pop(); + + cfi.steps = []; + + path.forEach(function(part){ + var step; + + if(part) { + step = parseStep(part); + cfi.steps.push(step); + } + }); + + //-- Check if END is a text node or element + endInt = parseInt(end); + if(!isNaN(endInt)) { + + if(endInt % 2 === 0) { // Even = is an element + cfi.steps.push(parseStep(end)); + } else { + cfi.steps.push({ + "type" : "text", + 'index' : (endInt - 1 ) / 2 + }); + } + + } + + assertion = charecterOffsetComponent.match(/\[(.*)\]/); + if(assertion && assertion[1]){ + cfi.characterOffset = parseInt(charecterOffsetComponent.split('[')[0]); + // We arent handling these assertions yet + cfi.textLocationAssertion = assertion[1]; + } else { + cfi.characterOffset = parseInt(charecterOffsetComponent); + } + + return cfi; +}; + +EPUBJS.EpubCFI.prototype.addMarker = function(cfi, _doc, _marker) { + var doc = _doc || document; + var marker = _marker || this.createMarker(doc); + var parent; + var lastStep; + var text; + var split; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + // Get the terminal step + lastStep = cfi.steps[cfi.steps.length-1]; + + // check spinePos + if(cfi.spinePos === -1) { + // Not a valid CFI + return false; + } + + // Find the CFI elements parent + parent = this.findParent(cfi, doc); + + if(!parent) { + // CFI didn't return an element + // Maybe it isnt in the current chapter? + return false; + } + + if(lastStep && lastStep.type === "text") { + text = parent.childNodes[lastStep.index]; + if(cfi.characterOffset){ + split = text.splitText(cfi.characterOffset); + marker.classList.add("EPUBJS-CFI-SPLIT"); + parent.insertBefore(marker, split); + } else { + parent.insertBefore(marker, text); + } + } else { + parent.insertBefore(marker, parent.firstChild); + } + + return marker; +}; + +EPUBJS.EpubCFI.prototype.createMarker = function(_doc) { + var doc = _doc || document; + var element = doc.createElement('span'); + element.id = "EPUBJS-CFI-MARKER:"+ EPUBJS.core.uuid(); + element.classList.add("EPUBJS-CFI-MARKER"); + + return element; +}; + +EPUBJS.EpubCFI.prototype.removeMarker = function(marker, _doc) { + var doc = _doc || document; + // var id = marker.id; + + // Cleanup textnodes if they were split + if(marker.classList.contains("EPUBJS-CFI-SPLIT")){ + nextSib = marker.nextSibling; + prevSib = marker.previousSibling; + if(nextSib && + prevSib && + nextSib.nodeType === 3 && + prevSib.nodeType === 3){ + + prevSib.textContent += nextSib.textContent; + marker.parentNode.removeChild(nextSib); + } + marker.parentNode.removeChild(marker); + } else if(marker.classList.contains("EPUBJS-CFI-MARKER")) { + // Remove only elements added as markers + marker.parentNode.removeChild(marker); + } + +}; + +EPUBJS.EpubCFI.prototype.findParent = function(cfi, _doc) { + var doc = _doc || document, + element = doc.getElementsByTagName('html')[0], + children = Array.prototype.slice.call(element.children), + num, index, part, sections, + text, textBegin, textEnd; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + + sections = cfi.steps.slice(0); // Clone steps array + if(!sections.length) { + return doc.getElementsByTagName('body')[0]; + } + + while(sections && sections.length > 0) { + part = sections.shift(); + // Find textNodes Parent + if(part.type === "text") { + text = element.childNodes[part.index]; + element = text.parentNode || element; + // Find element by id if present + } else if(part.id){ + element = doc.getElementById(part.id); + // Find element in parent + }else{ + element = children[part.index]; + } + // Element can't be found + if(typeof element === "undefined") { + console.error("No Element For", part, cfi.str); + return false; + } + // Get current element children and continue through steps + children = Array.prototype.slice.call(element.children); + } + + return element; +}; + +EPUBJS.EpubCFI.prototype.compare = function(cfiOne, cfiTwo) { + if(typeof cfiOne === 'string') { + cfiOne = new EPUBJS.EpubCFI(cfiOne); + } + if(typeof cfiTwo === 'string') { + cfiTwo = new EPUBJS.EpubCFI(cfiTwo); + } + // Compare Spine Positions + if(cfiOne.spinePos > cfiTwo.spinePos) { + return 1; + } + if(cfiOne.spinePos < cfiTwo.spinePos) { + return -1; + } + + + // Compare Each Step in the First item + for (var i = 0; i < cfiOne.steps.length; i++) { + if(!cfiTwo.steps[i]) { + return 1; + } + if(cfiOne.steps[i].index > cfiTwo.steps[i].index) { + return 1; + } + if(cfiOne.steps[i].index < cfiTwo.steps[i].index) { + return -1; + } + // Otherwise continue checking + } + + // All steps in First present in Second + if(cfiOne.steps.length < cfiTwo.steps.length) { + return -1; + } + + // Compare the charecter offset of the text node + if(cfiOne.characterOffset > cfiTwo.characterOffset) { + return 1; + } + if(cfiOne.characterOffset < cfiTwo.characterOffset) { + return -1; + } + + // CFI's are equal + return 0; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromHref = function(href, book) { + var uri = EPUBJS.core.uri(href); + var path = uri.path; + var fragment = uri.fragment; + var spinePos = book.spineIndexByURL[path]; + var loaded; + var deferred = new RSVP.defer(); + var epubcfi = new EPUBJS.EpubCFI(); + var spineItem; + + if(typeof spinePos !== "undefined"){ + spineItem = book.spine[spinePos]; + loaded = book.loadXml(spineItem.url); + loaded.then(function(doc){ + var element = doc.getElementById(fragment); + var cfi; + cfi = epubcfi.generateCfiFromElement(element, spineItem.cfiBase); + deferred.resolve(cfi); + }); + } + + return deferred.promise; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromTextNode = function(anchor, offset, base) { + var parent = anchor.parentNode; + var steps = this.pathTo(parent); + var path = this.generatePathComponent(steps); + var index = 1 + (2 * Array.prototype.indexOf.call(parent.childNodes, anchor)); + return "epubcfi(" + base + "!" + path + "/"+index+":"+(offset || 0)+")"; +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromRangeAnchor = function(range, base) { + var anchor = range.anchorNode; + var offset = range.anchorOffset; + return this.generateCfiFromTextNode(anchor, offset, base); +}; + +EPUBJS.EpubCFI.prototype.generateCfiFromRange = function(range, base) { + var start, startElement, startSteps, startPath, startOffset, startIndex; + var end, endElement, endSteps, endPath, endOffset, endIndex; + + start = range.startContainer; + + if(start.nodeType === 3) { // text node + startElement = start.parentNode; + //startIndex = 1 + (2 * Array.prototype.indexOf.call(startElement.childNodes, start)); + startIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(start)); + startSteps = this.pathTo(startElement); + } else if(range.collapsed) { + return this.generateCfiFromElement(start, base); // single element + } else { + startSteps = this.pathTo(start); + } + + startPath = this.generatePathComponent(startSteps); + startOffset = range.startOffset; + + if(!range.collapsed) { + end = range.endContainer; + + if(end.nodeType === 3) { // text node + endElement = end.parentNode; + // endIndex = 1 + (2 * Array.prototype.indexOf.call(endElement.childNodes, end)); + endIndex = 1 + (2 * EPUBJS.core.indexOfTextNode(end)); + + endSteps = this.pathTo(endElement); + } else { + endSteps = this.pathTo(end); + } + + endPath = this.generatePathComponent(endSteps); + endOffset = range.endOffset; + + return "epubcfi(" + base + "!" + startPath + "/" + startIndex + ":" + startOffset + "," + endPath + "/" + endIndex + ":" + endOffset + ")"; + + } else { + return "epubcfi(" + base + "!" + startPath + "/"+ startIndex +":"+ startOffset +")"; + } +}; + +EPUBJS.EpubCFI.prototype.generateXpathFromSteps = function(steps) { + var xpath = [".", "*"]; + + steps.forEach(function(step){ + var position = step.index + 1; + + if(step.id){ + xpath.push("*[position()=" + position + " and @id='" + step.id + "']"); + } else if(step.type === "text") { + xpath.push("text()[" + position + "]"); + } else { + xpath.push("*[" + position + "]"); + } + }); + + return xpath.join("/"); +}; + + +EPUBJS.EpubCFI.prototype.generateRangeFromCfi = function(cfi, _doc) { + var doc = _doc || document; + var range = doc.createRange(); + var lastStep; + var xpath; + var startContainer; + var textLength; + + if(typeof cfi === 'string') { + cfi = this.parse(cfi); + } + + // check spinePos + if(cfi.spinePos === -1) { + // Not a valid CFI + return false; + } + + xpath = this.generateXpathFromSteps(cfi.steps); + + // Get the terminal step + lastStep = cfi.steps[cfi.steps.length-1]; + startContainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; + + if(!startContainer) { + return null; + } + + if(startContainer && cfi.characterOffset >= 0) { + textLength = startContainer.length; + + if(cfi.characterOffset < textLength) { + range.setStart(startContainer, cfi.characterOffset); + range.setEnd(startContainer, textLength ); + } else { + console.debug("offset greater than length:", cfi.characterOffset, textLength); + range.setStart(startContainer, textLength - 1 ); + range.setEnd(startContainer, textLength ); + } + } else if(startContainer) { + range.selectNode(startContainer); + } + // doc.defaultView.getSelection().addRange(range); + return range; +}; + +EPUBJS.Events = function(obj, el){ + + this.events = {}; + + if(!el){ + this.el = document.createElement('div'); + }else{ + this.el = el; + } + + obj.createEvent = this.createEvent; + obj.tell = this.tell; + obj.listen = this.listen; + obj.deafen = this.deafen; + obj.listenUntil = this.listenUntil; + + return this; +}; + +EPUBJS.Events.prototype.createEvent = function(evt){ + var e = new CustomEvent(evt); + this.events[evt] = e; + return e; +}; + +EPUBJS.Events.prototype.tell = function(evt, msg){ + var e; + + if(!this.events[evt]){ + console.warn("No event:", evt, "defined yet, creating."); + e = this.createEvent(evt); + }else{ + e = this.events[evt]; + } + + if(msg) e.msg = msg; + this.el.dispatchEvent(e); + +}; + +EPUBJS.Events.prototype.listen = function(evt, func, bindto){ + if(!this.events[evt]){ + console.warn("No event:", evt, "defined yet, creating."); + this.createEvent(evt); + return; + } + + if(bindto){ + this.el.addEventListener(evt, func.bind(bindto), false); + }else{ + this.el.addEventListener(evt, func, false); + } + +}; + +EPUBJS.Events.prototype.deafen = function(evt, func){ + this.el.removeEventListener(evt, func, false); +}; + +EPUBJS.Events.prototype.listenUntil = function(OnEvt, OffEvt, func, bindto){ + this.listen(OnEvt, func, bindto); + + function unlisten(){ + this.deafen(OnEvt, func); + this.deafen(OffEvt, unlisten); + } + + this.listen(OffEvt, unlisten, this); +}; +EPUBJS.hooks = {}; +EPUBJS.Hooks = (function(){ + function hooks(){} + + //-- Get pre-registered hooks + hooks.prototype.getHooks = function(){ + var plugs; + this.hooks = {}; + Array.prototype.slice.call(arguments).forEach(function(arg){ + this.hooks[arg] = []; + }, this); + + for (var plugType in this.hooks) { + plugs = _.values(EPUBJS.hooks[plugType]); + + plugs.forEach(function(hook){ + this.registerHook(plugType, hook); + }, this); + } + }; + + //-- Hooks allow for injecting async functions that must all complete before continuing + // Functions must have a callback as their first argument. + hooks.prototype.registerHook = function(type, toAdd, toFront){ + + if(typeof(this.hooks[type]) != "undefined"){ + + if(typeof(toAdd) === "function"){ + if(toFront) { + this.hooks[type].unshift(toAdd); + }else{ + this.hooks[type].push(toAdd); + } + }else if(Array.isArray(toAdd)){ + toAdd.forEach(function(hook){ + if(toFront) { + this.hooks[type].unshift(hook); + }else{ + this.hooks[type].push(hook); + } + }, this); + } + }else{ + //-- Allows for undefined hooks, but maybe this should error? + this.hooks[type] = [func]; + } + }; + + hooks.prototype.triggerHooks = function(type, callback, passed){ + var hooks, count; + + if(typeof(this.hooks[type]) == "undefined") return false; + + hooks = this.hooks[type]; + + count = hooks.length; + if(count === 0 && callback) { + callback(); + } + + function countdown(){ + count--; + if(count <= 0 && callback) callback(); + } + + hooks.forEach(function(hook){ + hook(countdown, passed); + }); + }; + + return { + register: function(name) { + if(EPUBJS.hooks[name] === undefined) { EPUBJS.hooks[name] = {}; } + if(typeof EPUBJS.hooks[name] !== 'object') { throw "Already registered: "+name; } + return EPUBJS.hooks[name]; + }, + mixin: function(object) { + for (var prop in hooks.prototype) { + object[prop] = hooks.prototype[prop]; + } + } + }; +})(); + + +EPUBJS.Layout = EPUBJS.Layout || {}; + +EPUBJS.Layout.Reflowable = function(){ + this.documentElement = null; + this.spreadWidth = null; +}; + +EPUBJS.Layout.Reflowable.prototype.format = function(documentElement, _width, _height, _gap){ + // Get the prefixed CSS commands + var columnAxis = EPUBJS.core.prefixed('columnAxis'); + var columnGap = EPUBJS.core.prefixed('columnGap'); + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var columnFill = EPUBJS.core.prefixed('columnFill'); + + //-- Check the width and create even width columns + var width = Math.floor(_width); + // var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 0; // Not needed for single + var section = Math.floor(width / 8); + var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); + this.documentElement = documentElement; + //-- Single Page + this.spreadWidth = (width + gap); + + + documentElement.style.overflow = "hidden"; + + // Must be set to the new calculated width or the columns will be off + documentElement.style.width = width + "px"; + + //-- Adjust height + documentElement.style.height = _height + "px"; + + //-- Add columns + documentElement.style[columnAxis] = "horizontal"; + documentElement.style[columnFill] = "auto"; + documentElement.style[columnWidth] = width+"px"; + documentElement.style[columnGap] = gap+"px"; + this.colWidth = width; + this.gap = gap; + + return { + pageWidth : this.spreadWidth, + pageHeight : _height + }; +}; + +EPUBJS.Layout.Reflowable.prototype.calculatePages = function() { + var totalWidth, displayedPages; + this.documentElement.style.width = "auto"; //-- reset width for calculations + totalWidth = this.documentElement.scrollWidth; + displayedPages = Math.ceil(totalWidth / this.spreadWidth); + + return { + displayedPages : displayedPages, + pageCount : displayedPages + }; +}; + +EPUBJS.Layout.ReflowableSpreads = function(){ + this.documentElement = null; + this.spreadWidth = null; +}; + +EPUBJS.Layout.ReflowableSpreads.prototype.format = function(documentElement, _width, _height, _gap){ + var columnAxis = EPUBJS.core.prefixed('columnAxis'); + var columnGap = EPUBJS.core.prefixed('columnGap'); + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var columnFill = EPUBJS.core.prefixed('columnFill'); + + var divisor = 2, + cutoff = 800; + + //-- Check the width and create even width columns + var fullWidth = Math.floor(_width); + var width = (fullWidth % 2 === 0) ? fullWidth : fullWidth - 1; + + var section = Math.floor(width / 8); + var gap = (_gap >= 0) ? _gap : ((section % 2 === 0) ? section : section - 1); + + //-- Double Page + var colWidth = Math.floor((width - gap) / divisor); + + this.documentElement = documentElement; + this.spreadWidth = (colWidth + gap) * divisor; + + + documentElement.style.overflow = "hidden"; + + // Must be set to the new calculated width or the columns will be off + documentElement.style.width = width + "px"; + + //-- Adjust height + documentElement.style.height = _height + "px"; + + //-- Add columns + documentElement.style[columnAxis] = "horizontal"; + documentElement.style[columnFill] = "auto"; + documentElement.style[columnGap] = gap+"px"; + documentElement.style[columnWidth] = colWidth+"px"; + + this.colWidth = colWidth; + this.gap = gap; + return { + pageWidth : this.spreadWidth, + pageHeight : _height + }; +}; + +EPUBJS.Layout.ReflowableSpreads.prototype.calculatePages = function() { + var totalWidth = this.documentElement.scrollWidth; + var displayedPages = Math.ceil(totalWidth / this.spreadWidth); + + //-- Add a page to the width of the document to account an for odd number of pages + this.documentElement.style.width = ((displayedPages * this.spreadWidth) - this.gap) + "px"; + + return { + displayedPages : displayedPages, + pageCount : displayedPages * 2 + }; +}; + +EPUBJS.Layout.Fixed = function(){ + this.documentElement = null; +}; + +EPUBJS.Layout.Fixed.prototype.format = function(documentElement, _width, _height, _gap){ + var columnWidth = EPUBJS.core.prefixed('columnWidth'); + var viewport = documentElement.querySelector("[name=viewport"); + var content; + var contents; + var width, height; + this.documentElement = documentElement; + /** + * check for the viewport size + * + */ + if(viewport && viewport.hasAttribute("content")) { + content = viewport.getAttribute("content"); + contents = content.split(','); + if(contents[0]){ + width = contents[0].replace("width=", ''); + } + if(contents[1]){ + height = contents[1].replace("height=", ''); + } + } + + //-- Adjust width and height + documentElement.style.width = width + "px" || "auto"; + documentElement.style.height = height + "px" || "auto"; + + //-- Remove columns + documentElement.style[columnWidth] = "auto"; + + //-- Scroll + documentElement.style.overflow = "auto"; + + this.colWidth = width; + this.gap = 0; + + return { + pageWidth : width, + pageHeight : height + }; + +}; + +EPUBJS.Layout.Fixed.prototype.calculatePages = function(){ + return { + displayedPages : 1, + pageCount : 1 + }; +}; + +EPUBJS.Pagination = function(pageList) { + this.pages = []; + this.locations = []; + this.epubcfi = new EPUBJS.EpubCFI(); + if(pageList && pageList.length) { + this.process(pageList); + } +}; + +EPUBJS.Pagination.prototype.process = function(pageList){ + pageList.forEach(function(item){ + this.pages.push(item.page); + this.locations.push(item.cfi); + }, this); + + this.pageList = pageList; + this.firstPage = parseInt(this.pages[0]); + this.lastPage = parseInt(this.pages[this.pages.length-1]); + this.totalPages = this.lastPage - this.firstPage; +}; + +EPUBJS.Pagination.prototype.pageFromCfi = function(cfi){ + var pg = -1; + + // Check if the pageList has not been set yet + if(this.locations.length === 0) { + return -1; + } + + // TODO: check if CFI is valid? + + // check if the cfi is in the location list + // var index = this.locations.indexOf(cfi); + var index = EPUBJS.core.indexOfSorted(cfi, this.locations, this.epubcfi.compare); + if(index != -1 && index < (this.pages.length-1) ) { + pg = this.pages[index]; + } else { + // Otherwise add it to the list of locations + // Insert it in the correct position in the locations page + //index = EPUBJS.core.insert(cfi, this.locations, this.epubcfi.compare); + index = EPUBJS.core.locationOf(cfi, this.locations, this.epubcfi.compare); + // Get the page at the location just before the new one, or return the first + pg = index-1 >= 0 ? this.pages[index-1] : this.pages[0]; + if(pg !== undefined) { + // Add the new page in so that the locations and page array match up + //this.pages.splice(index, 0, pg); + } else { + pg = -1; + } + + } + return pg; +}; + +EPUBJS.Pagination.prototype.cfiFromPage = function(pg){ + var cfi = -1; + // check that pg is an int + if(typeof pg != "number"){ + pg = parseInt(pg); + } + + // check if the cfi is in the page list + // Pages could be unsorted. + var index = this.pages.indexOf(pg); + if(index != -1) { + cfi = this.locations[index]; + } + // TODO: handle pages not in the list + return cfi; +}; + +EPUBJS.Pagination.prototype.pageFromPercentage = function(percent){ + var pg = Math.round(this.totalPages * percent); + return pg; +}; + +// Returns a value between 0 - 1 corresponding to the location of a page +EPUBJS.Pagination.prototype.percentageFromPage = function(pg){ + var percentage = (pg - this.firstPage) / this.totalPages; + return Math.round(percentage * 1000) / 1000; +}; + +// Returns a value between 0 - 1 corresponding to the location of a cfi +EPUBJS.Pagination.prototype.percentageFromCfi = function(cfi){ + var pg = this.pageFromCfi(cfi); + var percentage = this.percentageFromPage(pg); + return percentage; +}; +EPUBJS.Parser = function(baseUrl){ + this.baseUrl = baseUrl || ''; +}; + +EPUBJS.Parser.prototype.container = function(containerXml){ + //-- + var rootfile, fullpath, folder, encoding; + + if(!containerXml) { + console.error("Container File Not Found"); + return; + } + + rootfile = containerXml.querySelector("rootfile"); + + if(!rootfile) { + console.error("No RootFile Found"); + return; + } + + fullpath = rootfile.getAttribute('full-path'); + folder = EPUBJS.core.uri(fullpath).directory; + encoding = containerXml.xmlEncoding; + + //-- Now that we have the path we can parse the contents + return { + 'packagePath' : fullpath, + 'basePath' : folder, + 'encoding' : encoding + }; +}; + +EPUBJS.Parser.prototype.identifier = function(packageXml){ + var metadataNode; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = packageXml.querySelector("metadata"); + + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + return this.getElementText(metadataNode, "identifier"); +}; + +EPUBJS.Parser.prototype.packageContents = function(packageXml, baseUrl){ + var parse = this; + var metadataNode, manifestNode, spineNode; + var manifest, navPath, tocPath, coverPath; + var spineNodeIndex; + var spine; + var spineIndexByURL; + + if(baseUrl) this.baseUrl = baseUrl; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = packageXml.querySelector("metadata"); + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + manifestNode = packageXml.querySelector("manifest"); + if(!manifestNode) { + console.error("No Manifest Found"); + return; + } + + spineNode = packageXml.querySelector("spine"); + if(!spineNode) { + console.error("No Spine Found"); + return; + } + + manifest = parse.manifest(manifestNode); + navPath = parse.findNavPath(manifestNode); + tocPath = parse.findTocPath(manifestNode, spineNode); + coverPath = parse.findCoverPath(manifestNode); + + spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); + + spine = parse.spine(spineNode, manifest); + + spineIndexByURL = {}; + spine.forEach(function(item){ + spineIndexByURL[item.href] = item.index; + }); + + return { + 'metadata' : parse.metadata(metadataNode), + 'spine' : spine, + 'manifest' : manifest, + 'navPath' : navPath, + 'tocPath' : tocPath, + 'coverPath': coverPath, + 'spineNodeIndex' : spineNodeIndex, + 'spineIndexByURL' : spineIndexByURL + }; +}; + +//-- Find TOC NAV +EPUBJS.Parser.prototype.findNavPath = function(manifestNode){ + // Find item with property 'nav' + // Should catch nav irregardless of order + var node = manifestNode.querySelector("item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']"); + return node ? node.getAttribute('href') : false; +}; + +//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" +EPUBJS.Parser.prototype.findTocPath = function(manifestNode, spineNode){ + var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); + var tocId; + + // If we can't find the toc by media-type then try to look for id of the item in the spine attributes as + // according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2, + // "The item that describes the NCX must be referenced by the spine toc attribute." + if (!node) { + tocId = spineNode.getAttribute("toc"); + if(tocId) { + node = manifestNode.querySelector("item[id='" + tocId + "']"); + } + } + + return node ? node.getAttribute('href') : false; +}; + +//-- Find Cover: +EPUBJS.Parser.prototype.findCoverPath = function(manifestNode){ + var node = manifestNode.querySelector("item[properties='cover-image']"); + return node ? node.getAttribute('href') : false; +}; + +//-- Expanded to match Readium web components +EPUBJS.Parser.prototype.metadata = function(xml){ + var metadata = {}, + p = this; + + metadata.bookTitle = p.getElementText(xml, 'title'); + metadata.creator = p.getElementText(xml, 'creator'); + metadata.description = p.getElementText(xml, 'description'); + + metadata.pubdate = p.getElementText(xml, 'date'); + + metadata.publisher = p.getElementText(xml, 'publisher'); + + metadata.identifier = p.getElementText(xml, "identifier"); + metadata.language = p.getElementText(xml, "language"); + metadata.rights = p.getElementText(xml, "rights"); + + metadata.modified_date = p.querySelectorText(xml, "meta[property='dcterms:modified']"); + metadata.layout = p.querySelectorText(xml, "meta[property='rendition:layout']"); + metadata.orientation = p.querySelectorText(xml, "meta[property='rendition:orientation']"); + metadata.spread = p.querySelectorText(xml, "meta[property='rendition:spread']"); + // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); + + return metadata; +}; + +EPUBJS.Parser.prototype.getElementText = function(xml, tag){ + var found = xml.getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", tag), + el; + + if(!found || found.length === 0) return ''; + + el = found[0]; + + if(el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; + +}; + +EPUBJS.Parser.prototype.querySelectorText = function(xml, q){ + var el = xml.querySelector(q); + + if(el && el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; +}; + +EPUBJS.Parser.prototype.manifest = function(manifestXml){ + var baseUrl = this.baseUrl, + manifest = {}; + + //-- Turn items into an array + var selected = manifestXml.querySelectorAll("item"), + items = Array.prototype.slice.call(selected); + + //-- Create an object with the id as key + items.forEach(function(item){ + var id = item.getAttribute('id'), + href = item.getAttribute('href') || '', + type = item.getAttribute('media-type') || '', + properties = item.getAttribute('properties') || ''; + + manifest[id] = { + 'href' : href, + 'url' : baseUrl + href, //-- Absolute URL for loading with a web worker + 'type' : type, + 'properties' : properties + }; + + }); + + return manifest; + +}; + +EPUBJS.Parser.prototype.spine = function(spineXml, manifest){ + var spine = []; + + var selected = spineXml.getElementsByTagName("itemref"), + items = Array.prototype.slice.call(selected); + + var spineNodeIndex = Array.prototype.indexOf.call(spineXml.parentNode.childNodes, spineXml); + + var epubcfi = new EPUBJS.EpubCFI(); + + //-- Add to array to mantain ordering and cross reference with manifest + items.forEach(function(item, index){ + var Id = item.getAttribute('idref'); + var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id); + var props = item.getAttribute('properties') || ''; + var propArray = props.length ? props.split(' ') : []; + var manifestProps = manifest[Id].properties; + var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : []; + var vert = { + 'id' : Id, + 'linear' : item.getAttribute('linear') || '', + 'properties' : propArray, + 'manifestProperties' : manifestPropArray, + 'href' : manifest[Id].href, + 'url' : manifest[Id].url, + 'index' : index, + 'cfiBase' : cfiBase, + 'cfi' : "epub(" + cfiBase + ")" + }; + spine.push(vert); + }); + + return spine; +}; + +EPUBJS.Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ + var navEl = navHtml.querySelector('nav[*|type="toc"]'), //-- [*|type="toc"] * Doesn't seem to work + idCounter = 0; + + if(!navEl) return []; + + // Implements `> ol > li` + function findListItems(parent){ + var items = []; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('ol' == node.tagName){ + Array.prototype.slice.call(node.childNodes).forEach(function(item){ + if('li' == item.tagName){ + items.push(item); + } + }); + } + }); + + return items; + + } + + // Implements `> a, > span` + function findAnchorOrSpan(parent){ + var item = null; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('a' == node.tagName || 'span' == node.tagName){ + item = node; + } + }); + + return item; + } + + function getTOC(parent){ + var list = [], + nodes = findListItems(parent), + items = Array.prototype.slice.call(nodes), + length = items.length, + node; + + if(length === 0) return false; + + items.forEach(function(item){ + var id = item.getAttribute('id') || false, + content = findAnchorOrSpan(item), + href = content.getAttribute('href') || '', + text = content.textContent || "", + split = href.split("#"), + baseUrl = split[0], + subitems = getTOC(item), + spinePos = spineIndexByURL[baseUrl], + spineItem = bookSpine[spinePos], + cfi = spineItem ? spineItem.cfi : ''; + + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + (idCounter++); + } + } + + item.setAttribute('id', id); // Ensure all elements have an id + list.push({ + "id": id, + "href": href, + "label": text, + "subitems" : subitems, + "parent" : parent ? parent.getAttribute('id') : null, + "cfi" : cfi + }); + + }); + + return list; + } + + return getTOC(navEl); +}; + +EPUBJS.Parser.prototype.toc = function(tocXml, spineIndexByURL, bookSpine){ + var navMap = tocXml.querySelector("navMap"); + if(!navMap) return []; + + function getTOC(parent){ + var list = [], + snapshot = tocXml.evaluate("*[local-name()='navPoint']", parent, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null), + length = snapshot.snapshotLength; + + if(length === 0) return []; + + for ( var i=length-1 ; i >= 0; i-- ) { + var item = snapshot.snapshotItem(i); + + var id = item.getAttribute('id') || false, + content = item.querySelector("content"), + src = content.getAttribute('src'), + navLabel = item.querySelector("navLabel"), + text = navLabel.textContent ? navLabel.textContent : "", + split = src.split("#"), + baseUrl = split[0], + spinePos = spineIndexByURL[baseUrl], + spineItem = bookSpine[spinePos], + subitems = getTOC(item), + cfi = spineItem ? spineItem.cfi : ''; + + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + (idCounter++); + } + } + + list.unshift({ + "id": id, + "href": src, + "label": text, + "spinePos": spinePos, + "subitems" : subitems, + "parent" : parent ? parent.getAttribute('id') : null, + "cfi" : cfi + }); + + } + + return list; + } + + return getTOC(navMap); +}; + +EPUBJS.Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ + var navEl = navHtml.querySelector('nav[*|type="page-list"]'), + idCounter = 0; + + if(!navEl) return []; + + // Implements `> ol > li` + function findListItems(parent){ + var items = []; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('ol' == node.tagName){ + Array.prototype.slice.call(node.childNodes).forEach(function(item){ + if('li' == item.tagName){ + items.push(item); + } + }); + } + }); + + return items; + + } + + // Implements `> a, > span` + function findAnchorOrSpan(parent){ + var item = null; + + Array.prototype.slice.call(parent.childNodes).forEach(function(node){ + if('a' == node.tagName || 'span' == node.tagName){ + item = node; + } + }); + + return item; + } + + function getPages(parent){ + var list = [], + nodes = findListItems(parent), + items = Array.prototype.slice.call(nodes), + length = items.length, + node; + + if(length === 0) return false; + + items.forEach(function(item){ + var id = item.getAttribute('id') || false, + content = findAnchorOrSpan(item), + href = content.getAttribute('href') || '', + text = content.textContent || "", + page = parseInt(text), + isCfi = href.indexOf("epubcfi"), + split, + packageUrl, + cfi; + + if(isCfi != -1) { + split = href.split("#"); + packageUrl = split[0]; + cfi = split.length > 1 ? split[1] : false; + list.push({ + "cfi" : cfi, + "href" : href, + "packageUrl" : packageUrl, + "page" : page + }); + } else { + list.push({ + "href" : href, + "page" : page + }); + } + + }); + + return list; + } + + return getPages(navEl); +}; + +EPUBJS.Render.Iframe = function() { + this.iframe = null; + this.document = null; + this.window = null; + this.docEl = null; + this.bodyEl = null; + + this.leftPos = 0; + this.pageWidth = 0; +}; + +//-- Build up any html needed +EPUBJS.Render.Iframe.prototype.create = function(){ + this.iframe = document.createElement('iframe'); + this.iframe.id = "epubjs-iframe:" + EPUBJS.core.uuid(); + this.iframe.scrolling = "no"; + this.iframe.seamless = "seamless"; + // Back up if seamless isn't supported + this.iframe.style.border = "none"; + + this.iframe.addEventListener("load", this.loaded.bind(this), false); + return this.iframe; +}; + +/** +* Sets the source of the iframe with the given URL string +* Takes: URL string +* Returns: promise with document element +*/ +EPUBJS.Render.Iframe.prototype.load = function(chapter){ + var render = this, + deferred = new RSVP.defer(); + + chapter.url().then(function(url){ + // Reset the scroll position + render.leftPos = 0; + + if(this.window) { + this.unload(); + } + + this.iframe.onload = function(e) { + render.document = render.iframe.contentDocument; + render.docEl = render.document.documentElement; + render.headEl = render.document.head; + render.bodyEl = render.document.body || render.document.querySelector("body"); + render.window = render.iframe.contentWindow; + + render.window.addEventListener("resize", render.resized.bind(render), false); + + //-- Clear Margins + if(render.bodyEl) { + render.bodyEl.style.margin = "0"; + } + + deferred.resolve(render.docEl); + }; + + this.iframe.onerror = function(e) { + //console.error("Error Loading Contents", e); + deferred.reject({ + message : "Error Loading Contents: " + e, + stack : new Error().stack + }); + }; + + this.iframe.contentWindow.location.replace(url); + + }.bind(this)); + + return deferred.promise; +}; + + +EPUBJS.Render.Iframe.prototype.loaded = function(v){ + var url = this.iframe.contentWindow.location.href; + if(url != "about:blank"){ + this.trigger("render:loaded", url); + } +}; + +// Resize the iframe to the given width and height +EPUBJS.Render.Iframe.prototype.resize = function(width, height){ + var iframeBox; + + if(!this.iframe) return; + + this.iframe.height = height; + + if(!isNaN(width) && width % 2 !== 0){ + width += 1; //-- Prevent cutting off edges of text in columns + } + + this.iframe.width = width; + // Get the fractional height and width of the iframe + // Default to orginal if bounding rect is 0 + this.width = this.iframe.getBoundingClientRect().width || width; + this.height = this.iframe.getBoundingClientRect().height || height; +}; + + +EPUBJS.Render.Iframe.prototype.resized = function(e){ + // Get the fractional height and width of the iframe + this.width = this.iframe.getBoundingClientRect().width; + this.height = this.iframe.getBoundingClientRect().height; +}; + +EPUBJS.Render.Iframe.prototype.totalWidth = function(){ + return this.docEl.scrollWidth; +}; + +EPUBJS.Render.Iframe.prototype.totalHeight = function(){ + return this.docEl.scrollHeight; +}; + +EPUBJS.Render.Iframe.prototype.setPageDimensions = function(pageWidth, pageHeight){ + this.pageWidth = pageWidth; + this.pageHeight = pageHeight; + //-- Add a page to the width of the document to account an for odd number of pages + // this.docEl.style.width = this.docEl.scrollWidth + pageWidth + "px"; +}; + +EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){ + // this.bodyEl.style.marginLeft = -leftPos + "px"; + // this.docEl.style.marginLeft = -leftPos + "px"; + // this.docEl.style[EPUBJS.Render.Iframe.transform] = 'translate('+ (-leftPos) + 'px, 0)'; + this.document.defaultView.scrollTo(leftPos, 0); +}; + +EPUBJS.Render.Iframe.prototype.setStyle = function(style, val, prefixed){ + if(prefixed) { + style = EPUBJS.core.prefixed(style); + } + + if(this.bodyEl) this.bodyEl.style[style] = val; +}; + +EPUBJS.Render.Iframe.prototype.removeStyle = function(style){ + + if(this.bodyEl) this.bodyEl.style[style] = ''; + +}; + +EPUBJS.Render.Iframe.prototype.addHeadTag = function(tag, attrs, _doc) { + var doc = _doc || this.document; + var tagEl = doc.createElement(tag); + var headEl = doc.head; + + for(var attr in attrs) { + tagEl.setAttribute(attr, attrs[attr]); + } + + if(headEl) headEl.insertBefore(tagEl, headEl.firstChild); +}; + +EPUBJS.Render.Iframe.prototype.page = function(pg){ + this.leftPos = this.pageWidth * (pg-1); //-- pages start at 1 + this.setLeft(this.leftPos); +}; + +//-- Show the page containing an Element +EPUBJS.Render.Iframe.prototype.getPageNumberByElement = function(el){ + var left, pg; + if(!el) return; + + left = this.leftPos + el.getBoundingClientRect().left; //-- Calculate left offset compaired to scrolled position + + pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 + + return pg; +}; + +//-- Show the page containing an Element +EPUBJS.Render.Iframe.prototype.getPageNumberByRect = function(boundingClientRect){ + var left, pg; + + left = this.leftPos + boundingClientRect.left; //-- Calculate left offset compaired to scrolled position + pg = Math.floor(left / this.pageWidth) + 1; //-- pages start at 1 + + return pg; +}; + +// Return the root element of the content +EPUBJS.Render.Iframe.prototype.getBaseElement = function(){ + return this.bodyEl; +}; + +// Checks if an element is on the screen +EPUBJS.Render.Iframe.prototype.isElementVisible = function(el){ + var rect; + var left; + + if(el && typeof el.getBoundingClientRect === 'function'){ + rect = el.getBoundingClientRect(); + left = rect.left; //+ rect.width; + if( rect.width !== 0 && + rect.height !== 0 && // Element not visible + left >= 0 && + left < this.pageWidth ) { + return true; + } + } + + return false; +}; + + +EPUBJS.Render.Iframe.prototype.scroll = function(bool){ + if(bool) { + this.iframe.scrolling = "yes"; + } else { + this.iframe.scrolling = "no"; + } +}; + +// Cleanup event listeners +EPUBJS.Render.Iframe.prototype.unload = function(){ + this.window.removeEventListener("resize", this.resized); +}; + +//-- Enable binding events to Render +RSVP.EventTarget.mixin(EPUBJS.Render.Iframe.prototype); +EPUBJS.Renderer = function(renderMethod, hidden) { + // Dom events to listen for + this.listenedEvents = ["keydown", "keyup", "keypressed", "mouseup", "mousedown", "click"]; + this.upEvent = "mouseup"; + this.downEvent = "mousedown"; + if('ontouchstart' in document.documentElement) { + this.listenedEvents.push("touchstart", "touchend"); + this.upEvent = "touchend"; + this.downEvent = "touchstart"; + } + /** + * Setup a render method. + * Options are: Iframe + */ + if(renderMethod && typeof(EPUBJS.Render[renderMethod]) != "undefined"){ + this.render = new EPUBJS.Render[renderMethod](); + } else { + console.error("Not a Valid Rendering Method"); + } + + // Listen for load events + this.render.on("render:loaded", this.loaded.bind(this)); + + // Cached for replacement urls from storage + this.caches = {}; + + // Blank Cfi for Parsing + this.epubcfi = new EPUBJS.EpubCFI(); + + this.spreads = true; + this.isForcedSingle = false; + this.resized = _.debounce(this.onResized.bind(this), 100); + + this.layoutSettings = {}; + + this.hidden = hidden || false; + //-- Adds Hook methods to the Book prototype + // Hooks will all return before triggering the callback. + EPUBJS.Hooks.mixin(this); + //-- Get pre-registered hooks for events + this.getHooks("beforeChapterDisplay"); + + //-- Queue up page changes if page map isn't ready + this._q = EPUBJS.core.queue(this); + + this._moving = false; + +}; + +//-- Renderer events for listening +EPUBJS.Renderer.prototype.Events = [ + "renderer:keydown", + "renderer:keyup", + "renderer:keypressed", + "renderer:mouseup", + "renderer:mousedown", + "renderer:click", + "renderer:touchstart", + "renderer:touchend", + "renderer:selected", + "renderer:chapterUnloaded", + "renderer:chapterDisplayed", + "renderer:locationChanged", + "renderer:visibleLocationChanged", + "renderer:resized", + "renderer:spreads" +]; + +/** +* Creates an element to render to. +* Resizes to passed width and height or to the elements size +*/ +EPUBJS.Renderer.prototype.initialize = function(element, width, height){ + this.container = element; + this.element = this.render.create(); + + this.initWidth = width; + this.initHeight = height; + + this.width = width || this.container.clientWidth; + this.height = height || this.container.clientHeight; + + this.container.appendChild(this.element); + + if(width && height){ + this.render.resize(this.width, this.height); + } else { + this.render.resize('100%', '100%'); + } + + document.addEventListener("orientationchange", this.onResized); +}; + +/** +* Display a chapter +* Takes: chapter object, global layout settings +* Returns: Promise with passed Renderer after pages has loaded +*/ +EPUBJS.Renderer.prototype.displayChapter = function(chapter, globalLayout){ + var store = false; + if(this._moving) { + console.error("Rendering In Progress"); + return; + } + this._moving = true; + // Get the url string from the chapter (may be from storage) + return chapter.url(). + then(function(url) { + + // Unload the previous chapter listener + if(this.currentChapter) { + this.currentChapter.unload(); // Remove stored blobs + + if(this.render.window){ + this.render.window.removeEventListener("resize", this.resized); + } + + this.removeEventListeners(); + this.removeSelectionListeners(); + this.trigger("renderer:chapterUnloaded"); + this.contents = null; + this.doc = null; + this.pageMap = null; + } + + this.currentChapter = chapter; + this.chapterPos = 1; + this.currentChapterCfiBase = chapter.cfiBase; + + this.layoutSettings = this.reconcileLayoutSettings(globalLayout, chapter.properties); + return this.load(chapter); + + }.bind(this)); + +}; + +/** +* Loads a url (string) and renders it, +* attaching event listeners and triggering hooks. +* Returns: Promise with the rendered contents. +*/ + +EPUBJS.Renderer.prototype.load = function(url){ + var deferred = new RSVP.defer(); + var loaded; + + // Switch to the required layout method for the settings + this.layoutMethod = this.determineLayout(this.layoutSettings); + this.layout = new EPUBJS.Layout[this.layoutMethod](); + + this.visible(false); + + render = this.render.load(url); + + render.then(function(contents) { + var formated; + this.currentChapter.setDocument(this.render.document); + this.contents = contents; + this.doc = this.render.document; + + // Format the contents using the current layout method + this.formated = this.layout.format(contents, this.render.width, this.render.height, this.gap); + this.render.setPageDimensions(this.formated.pageWidth, this.formated.pageHeight); + + // window.addEventListener("orientationchange", this.onResized.bind(this), false); + if(!this.initWidth && !this.initHeight){ + this.render.window.addEventListener("resize", this.resized, false); + } + + this.addEventListeners(); + this.addSelectionListeners(); + + //-- Trigger registered hooks before displaying + this.beforeDisplay(function(){ + var pages = this.layout.calculatePages(); + var msg = this.currentChapter; + var queued = this._q.length(); + this._moving = false; + + this.updatePages(pages); + + this.visibleRangeCfi = this.getVisibleRangeCfi(); + this.currentLocationCfi = this.visibleRangeCfi.start; + + if(queued === 0) { + this.trigger("renderer:locationChanged", this.currentLocationCfi); + this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); + } + + msg.cfi = this.currentLocationCfi; //TODO: why is this cfi passed to chapterDisplayed + this.trigger("renderer:chapterDisplayed", msg); + + this.visible(true); + + deferred.resolve(this); //-- why does this return the renderer? + }.bind(this)); + + }.bind(this)); + + return deferred.promise; +}; + +EPUBJS.Renderer.prototype.loaded = function(url){ + this.trigger("render:loaded", url); + // var uri = EPUBJS.core.uri(url); + // var relative = uri.path.replace(book.bookUrl, ''); + // console.log(url, uri, relative); +}; + +/** +* Reconciles the current chapters layout properies with +* the global layout properities. +* Takes: global layout settings object, chapter properties string +* Returns: Object with layout properties +*/ +EPUBJS.Renderer.prototype.reconcileLayoutSettings = function(global, chapter){ + var settings = {}; + + //-- Get the global defaults + for (var attr in global) { + if (global.hasOwnProperty(attr)){ + settings[attr] = global[attr]; + } + } + //-- Get the chapter's display type + chapter.forEach(function(prop){ + var rendition = prop.replace("rendition:", ''); + var split = rendition.indexOf("-"); + var property, value; + + if(split != -1){ + property = rendition.slice(0, split); + value = rendition.slice(split+1); + + settings[property] = value; + } + }); + return settings; +}; + +/** +* Uses the settings to determine which Layout Method is needed +* Triggers events based on the method choosen +* Takes: Layout settings object +* Returns: String of appropriate for EPUBJS.Layout function +*/ +EPUBJS.Renderer.prototype.determineLayout = function(settings){ + // Default is layout: reflowable & spread: auto + var spreads = this.determineSpreads(this.minSpreadWidth); + var layoutMethod = spreads ? "ReflowableSpreads" : "Reflowable"; + var scroll = false; + + if(settings.layout === "pre-paginated") { + layoutMethod = "Fixed"; + scroll = true; + spreads = false; + } + + if(settings.layout === "reflowable" && settings.spread === "none") { + layoutMethod = "Reflowable"; + scroll = false; + spreads = false; + } + + if(settings.layout === "reflowable" && settings.spread === "both") { + layoutMethod = "ReflowableSpreads"; + scroll = false; + spreads = true; + } + + this.spreads = spreads; + this.render.scroll(scroll); + this.trigger("renderer:spreads", spreads); + return layoutMethod; +}; + +// Shortcut to trigger the hook before displaying the chapter +EPUBJS.Renderer.prototype.beforeDisplay = function(callback, renderer){ + this.triggerHooks("beforeChapterDisplay", callback, this); +}; + +// Update the renderer with the information passed by the layout +EPUBJS.Renderer.prototype.updatePages = function(layout){ + this.pageMap = this.mapPage(); + // this.displayedPages = layout.displayedPages; + + if (this.spreads) { + this.displayedPages = Math.ceil(this.pageMap.length / 2); + } else { + this.displayedPages = this.pageMap.length; + } + + // this.currentChapter.pages = layout.pageCount; + this.currentChapter.pages = this.pageMap.length; + + this._q.flush(); +}; + +// Apply the layout again and jump back to the previous cfi position +EPUBJS.Renderer.prototype.reformat = function(){ + var renderer = this; + var formated, pages; + if(!this.contents) return; + + spreads = this.determineSpreads(this.minSpreadWidth); + + // Only re-layout if the spreads have switched + if(spreads != this.spreads){ + this.spreads = spreads; + this.layoutMethod = this.determineLayout(this.layoutSettings); + this.layout = new EPUBJS.Layout[this.layoutMethod](); + } + + // Reset pages + this.chapterPos = 1; + this.render.page(1); + + // Give the css styles time to update + // clearTimeout(this.timeoutTillCfi); + // this.timeoutTillCfi = setTimeout(function(){ + + renderer.formated = renderer.layout.format(renderer.contents, renderer.render.width, renderer.render.height, renderer.gap); + renderer.render.setPageDimensions(renderer.formated.pageWidth, renderer.formated.pageHeight); + + pages = renderer.layout.calculatePages(); + renderer.updatePages(pages); + + //-- Go to current page after formating + if(renderer.currentLocationCfi){ + renderer.gotoCfi(renderer.currentLocationCfi); + } + // renderer.timeoutTillCfi = null; + +}; + +// Hide and show the render's container . +EPUBJS.Renderer.prototype.visible = function(bool){ + if(typeof(bool) === "undefined") { + return this.element.style.visibility; + } + + if(bool === true && !this.hidden){ + this.element.style.visibility = "visible"; + }else if(bool === false){ + this.element.style.visibility = "hidden"; + } +}; + +// Remove the render element and clean up listeners +EPUBJS.Renderer.prototype.remove = function() { + if(this.render.window) { + this.render.unload(); + this.render.window.removeEventListener("resize", this.resized); + this.removeEventListeners(); + this.removeSelectionListeners(); + } + + this.container.removeChild(this.element); +}; + +//-- STYLES + +EPUBJS.Renderer.prototype.applyStyles = function(styles) { + for (var style in styles) { + this.render.setStyle(style, styles[style]); + } +}; + +EPUBJS.Renderer.prototype.setStyle = function(style, val, prefixed){ + this.render.setStyle(style, val, prefixed); +}; + +EPUBJS.Renderer.prototype.removeStyle = function(style){ + this.render.removeStyle(style); +}; + +//-- HEAD TAGS +EPUBJS.Renderer.prototype.applyHeadTags = function(headTags) { + for ( var headTag in headTags ) { + this.render.addHeadTag(headTag, headTags[headTag]); + } +}; + +//-- NAVIGATION + +EPUBJS.Renderer.prototype.page = function(pg){ + if(!this.pageMap) { + console.warn("pageMap not set, queuing"); + this._q.enqueue("page", arguments); + return true; + } + + if(pg >= 1 && pg <= this.displayedPages){ + this.chapterPos = pg; + + this.render.page(pg); + this.visibleRangeCfi = this.getVisibleRangeCfi(); + this.currentLocationCfi = this.visibleRangeCfi.start; + this.trigger("renderer:locationChanged", this.currentLocationCfi); + this.trigger("renderer:visibleRangeChanged", this.visibleRangeCfi); + + return true; + } + //-- Return false if page is greater than the total + return false; +}; + +// Short cut to find next page's cfi starting at the last visible element +/* +EPUBJS.Renderer.prototype.nextPage = function(){ + var pg = this.chapterPos + 1; + if(pg <= this.displayedPages){ + this.chapterPos = pg; + + this.render.page(pg); + + this.currentLocationCfi = this.getPageCfi(this.visibileEl); + this.trigger("renderer:locationChanged", this.currentLocationCfi); + + return true; + } + //-- Return false if page is greater than the total + return false; +}; +*/ +EPUBJS.Renderer.prototype.nextPage = function(){ + return this.page(this.chapterPos + 1); +}; + +EPUBJS.Renderer.prototype.prevPage = function(){ + return this.page(this.chapterPos - 1); +}; + +//-- Show the page containing an Element +EPUBJS.Renderer.prototype.pageByElement = function(el){ + var pg; + if(!el) return; + + pg = this.render.getPageNumberByElement(el); + this.page(pg); +}; + +// Jump to the last page of the chapter +EPUBJS.Renderer.prototype.lastPage = function(){ + if(this._moving) { + return this._q.enqueue("lastPage", arguments); + } + + this.page(this.displayedPages); +}; + +// Jump to the first page of the chapter +EPUBJS.Renderer.prototype.firstPage = function(){ + this.page(1); +}; + +//-- Find a section by fragement id +EPUBJS.Renderer.prototype.section = function(fragment){ + var el = this.doc.getElementById(fragment), + left, pg; + + if(el){ + this.pageByElement(el); + } + +}; + +EPUBJS.Renderer.prototype.firstElementisTextNode = function(node) { + var children = node.childNodes; + var leng = children.length; + + if(leng && + children[0] && // First Child + children[0].nodeType === 3 && // This is a textNodes + children[0].textContent.trim().length) { // With non whitespace or return charecters + return true; + } + return false; +}; + +// Walk the node tree from a start element to next visible element +EPUBJS.Renderer.prototype.walk = function(node, x, y) { + var r, children, leng, + startNode = node, + prevNode, + stack = [startNode]; + + var STOP = 10000, ITER=0; + + while(!r && stack.length) { + node = stack.shift(); + if( this.containsPoint(node, x, y) && this.firstElementisTextNode(node)) { + r = node; + } + + if(!r && node && node.childElementCount > 0){ + children = node.children; + if (children && children.length) { + leng = children.length ? children.length : 0; + } else { + return r; + } + for (var i = leng-1; i >= 0; i--) { + if(children[i] != prevNode) stack.unshift(children[i]); + } + } + + if(!r && stack.length === 0 && startNode && startNode.parentNode !== null){ + stack.push(startNode.parentNode); + prevNode = startNode; + startNode = startNode.parentNode; + } + + + ITER++; + if(ITER > STOP) { + console.error("ENDLESS LOOP"); + break; + } + + } + + return r; +}; + +// Checks if an element is on the screen +EPUBJS.Renderer.prototype.containsPoint = function(el, x, y){ + var rect; + var left; + if(el && typeof el.getBoundingClientRect === 'function'){ + rect = el.getBoundingClientRect(); + // console.log(el, rect, x, y); + + if( rect.width !== 0 && + rect.height !== 0 && // Element not visible + rect.left >= x && + x <= rect.left + rect.width) { + return true; + } + } + + return false; +}; + +EPUBJS.Renderer.prototype.textSprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if ( ! /^\s*$/.test(node.data) ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; + +EPUBJS.Renderer.prototype.sprint = function(root, func) { + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT, null, false); + var node; + while ((node = treeWalker.nextNode())) { + func(node); + } + +}; + +EPUBJS.Renderer.prototype.mapPage = function(){ + var renderer = this; + var map = []; + var root = this.render.getBaseElement(); + var page = 1; + var width = this.layout.colWidth + this.layout.gap; + var offset = this.formated.pageWidth * (this.chapterPos-1); + var limit = (width * page) - offset;// (width * page) - offset; + var elLimit = 0; + var prevRange; + var cfi; + var check = function(node) { + var elPos; + var elRange; + var children = Array.prototype.slice.call(node.childNodes); + if (node.nodeType == Node.ELEMENT_NODE) { + // elPos = node.getBoundingClientRect(); + elRange = document.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + + if(!elPos || (elPos.width === 0 && elPos.height === 0)) { + return; + } + + //-- Element starts new Col + if(elPos.left > elLimit) { + children.forEach(function(node){ + if(node.nodeType == Node.TEXT_NODE && + node.textContent.trim().length) { + checkText(node); + } + }); + } + + //-- Element Spans new Col + if(elPos.right > elLimit) { + children.forEach(function(node){ + if(node.nodeType == Node.TEXT_NODE && + node.textContent.trim().length) { + checkText(node); + } + }); + } + } + + }; + var checkText = function(node){ + var ranges = renderer.splitTextNodeIntoWordsRanges(node); + ranges.forEach(function(range){ + var pos = range.getBoundingClientRect(); + + if(!pos || (pos.width === 0 && pos.height === 0)) { + return; + } + if(pos.left + pos.width < limit) { + if(!map[page-1]){ + range.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(range); + // map[page-1].start = cfi; + map.push({ start: cfi, end: null }); + } + } else { + if(prevRange){ + prevRange.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(prevRange); + map[map.length-1].end = cfi; + } + + range.collapse(true); + cfi = renderer.currentChapter.cfiFromRange(range); + map.push({ + start: cfi, + end: null + }); + + page += 1; + limit = (width * page) - offset; + elLimit = limit; + } + + prevRange = range; + }); + + + }; + + this.sprint(root, check); + // this.textSprint(root, checkText); + + if(prevRange){ + prevRange.collapse(true); + + cfi = renderer.currentChapter.cfiFromRange(prevRange); + map[map.length-1].end = cfi; + } + + // Handle empty map + if(!map.length) { + range = this.doc.createRange(); + range.selectNodeContents(root); + range.collapse(true); + + cfi = renderer.currentChapter.cfiFromRange(range); + + map.push({ start: cfi, end: cfi }); + + } + + // clean up + prevRange = null; + ranges = null; + range = null; + root = null; + + return map; +}; + + +EPUBJS.Renderer.prototype.indexOfBreakableChar = function (text, startPosition) { + var whiteCharacters = "\x2D\x20\t\r\n\b\f"; + // '-' \x2D + // ' ' \x20 + + if (! startPosition) { + startPosition = 0; + } + + for (var i = startPosition; i < text.length; i++) { + if (whiteCharacters.indexOf(text.charAt(i)) != -1) { + return i; + } + } + + return -1; +}; + + +EPUBJS.Renderer.prototype.splitTextNodeIntoWordsRanges = function(node){ + var ranges = []; + var text = node.textContent.trim(); + var range; + var rect; + var list; + // jaroslaw.bielski@7bulls.com + // Usage of indexOf() function for space character as word delimiter + // is not sufficient in case of other breakable characters like \r\n- etc + pos = this.indexOfBreakableChar(text); + + if(pos === -1) { + range = this.doc.createRange(); + range.selectNodeContents(node); + return [range]; + } + + range = this.doc.createRange(); + range.setStart(node, 0); + range.setEnd(node, pos); + ranges.push(range); + + // jaroslaw.bielski@7bulls.com + // there was a word miss in case of one letter words + range = this.doc.createRange(); + range.setStart(node, pos+1); + + while ( pos != -1 ) { + + pos = this.indexOfBreakableChar(text, pos + 1); + if(pos > 0) { + + if(range) { + range.setEnd(node, pos); + ranges.push(range); + } + + range = this.doc.createRange(); + range.setStart(node, pos+1); + } + } + + if(range) { + range.setEnd(node, text.length); + ranges.push(range); + } + + return ranges; +}; + +EPUBJS.Renderer.prototype.rangePosition = function(range){ + var rect; + var list; + + list = range.getClientRects(); + + if(list.length) { + rect = list[0]; + return rect; + } + + return null; +}; + +/* +// Get the cfi of the current page +EPUBJS.Renderer.prototype.getPageCfi = function(prevEl){ + var range = this.doc.createRange(); + var position; + // TODO : this might need to take margin / padding into account? + var x = 1;//this.formated.pageWidth/2; + var y = 1;//;this.formated.pageHeight/2; + + range = this.getRange(x, y); + + // var test = this.doc.defaultView.getSelection(); + // var r = this.doc.createRange(); + // test.removeAllRanges(); + // r.setStart(range.startContainer, range.startOffset); + // r.setEnd(range.startContainer, range.startOffset + 1); + // test.addRange(r); + + return this.currentChapter.cfiFromRange(range); +}; +*/ + +// Get the cfi of the current page +EPUBJS.Renderer.prototype.getPageCfi = function(){ + var pg; + if (this.spreads) { + pg = this.chapterPos*2; + startRange = this.pageMap[pg-2]; + } else { + pg = this.chapterPos; + startRange = this.pageMap[pg-1]; + } + return this.pageMap[(this.chapterPos * 2) -1].start; +}; + +EPUBJS.Renderer.prototype.getRange = function(x, y, forceElement){ + var range = this.doc.createRange(); + var position; + forceElement = true; // temp override + if(typeof document.caretPositionFromPoint !== "undefined" && !forceElement){ + position = this.doc.caretPositionFromPoint(x, y); + range.setStart(position.offsetNode, position.offset); + } else if(typeof document.caretRangeFromPoint !== "undefined" && !forceElement){ + range = this.doc.caretRangeFromPoint(x, y); + } else { + this.visibileEl = this.findElementAfter(x, y); + range.setStart(this.visibileEl, 1); + } + + // var test = this.doc.defaultView.getSelection(); + // var r = this.doc.createRange(); + // test.removeAllRanges(); + // r.setStart(range.startContainer, range.startOffset); + // r.setEnd(range.startContainer, range.startOffset + 1); + // test.addRange(r); + return range; +}; + +/* +EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(prevEl){ + var startX = 0; + var startY = 0; + var endX = this.width-1; + var endY = this.height-1; + var startRange = this.getRange(startX, startY); + var endRange = this.getRange(endX, endY); //fix if carret not avail + var startCfi = this.currentChapter.cfiFromRange(startRange); + var endCfi; + if(endRange) { + endCfi = this.currentChapter.cfiFromRange(endRange); + } + + return { + start: startCfi, + end: endCfi || false + }; +}; +*/ + +EPUBJS.Renderer.prototype.pagesInCurrentChapter = function() { + var pgs; + var length; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + length = this.pageMap.length; + + if(this.spreads){ + pgs = Math.ceil(length / 2); + } else { + pgs = length; + } + + return pgs; +}; + +EPUBJS.Renderer.prototype.currentRenderedPage = function(){ + var pg; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + if (this.spreads && this.layout.pageCount > 1) { + pg = this.chapterPos*2; + } else { + pg = this.chapterPos; + } + + return pg; +}; + +EPUBJS.Renderer.prototype.getRenderedPagesLeft = function(){ + var pg; + var lastPage; + var pagesLeft; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + lastPage = this.pageMap.length; + + if (this.spreads) { + pg = this.chapterPos*2; + } else { + pg = this.chapterPos; + } + + pagesLeft = lastPage - pg; + return pagesLeft; + +}; + +EPUBJS.Renderer.prototype.getVisibleRangeCfi = function(){ + var pg; + var startRange, endRange; + + if(!this.pageMap) { + console.warn("page map not loaded"); + return false; + } + + if (this.spreads) { + pg = this.chapterPos*2; + startRange = this.pageMap[pg-2]; + endRange = startRange; + + if(this.layout.pageCount > 1) { + endRange = this.pageMap[pg-1]; + } + } else { + pg = this.chapterPos; + startRange = this.pageMap[pg-1]; + endRange = startRange; + } + + if(!startRange) { + console.warn("page range miss:", pg, this.pageMap); + startRange = this.pageMap[this.pageMap.length-1]; + endRange = startRange; + } + + return { + start: startRange.start, + end: endRange.end + }; +}; + +// Goto a cfi position in the current chapter +EPUBJS.Renderer.prototype.gotoCfi = function(cfi){ + var pg; + var marker; + var range; + + if(this._moving){ + return this._q.enqueue("gotoCfi", arguments); + } + + if(_.isString(cfi)){ + cfi = this.epubcfi.parse(cfi); + } + + if(typeof document.evaluate === 'undefined') { + marker = this.epubcfi.addMarker(cfi, this.doc); + if(marker) { + pg = this.render.getPageNumberByElement(marker); + // Must Clean up Marker before going to page + this.epubcfi.removeMarker(marker, this.doc); + this.page(pg); + } + } else { + range = this.epubcfi.generateRangeFromCfi(cfi, this.doc); + if(range) { + // jaroslaw.bielski@7bulls.com + // It seems that sometimes getBoundingClientRect() returns null for first page CFI in chapter. + // It is always reproductible if few consecutive chapters have only one page. + // NOTE: This is only workaround and the issue needs an deeper investigation. + // NOTE: Observed on Android 4.2.1 using WebView widget as HTML renderer (Asus TF300T). + var rect = range.getBoundingClientRect(); + if (rect) { + pg = this.render.getPageNumberByRect(rect); + + } else { + // Goto first page in chapter + pg = 1; + } + + this.page(pg); + + // Reset the current location cfi to requested cfi + this.currentLocationCfi = cfi.str; + } + } +}; + +// Walk nodes until a visible element is found +EPUBJS.Renderer.prototype.findFirstVisible = function(startEl){ + var el = startEl || this.render.getBaseElement(); + var found; + // kgolunski@7bulls.com + // Looks like an old API usage + // Set x and y as 0 to fullfill walk method API. + found = this.walk(el, 0, 0); + + if(found) { + return found; + }else{ + return startEl; + } + +}; +// TODO: remove me - unsused +EPUBJS.Renderer.prototype.findElementAfter = function(x, y, startEl){ + var el = startEl || this.render.getBaseElement(); + var found; + found = this.walk(el, x, y); + if(found) { + return found; + }else{ + return el; + } + +}; + +/* +EPUBJS.Renderer.prototype.route = function(hash, callback){ + var location = window.location.hash.replace('#/', ''); + if(this.useHash && location.length && location != this.prevLocation){ + this.show(location, callback); + this.prevLocation = location; + return true; + } + return false; +} + +EPUBJS.Renderer.prototype.hideHashChanges = function(){ + this.useHash = false; +} + +*/ + +EPUBJS.Renderer.prototype.resize = function(width, height, setSize){ + var spreads; + + this.width = width; + this.height = height; + + if(setSize !== false) { + this.render.resize(this.width, this.height); + } + + + + if(this.contents){ + this.reformat(); + } + + this.trigger("renderer:resized", { + width: this.width, + height: this.height + }); +}; + +//-- Listeners for events in the frame + +EPUBJS.Renderer.prototype.onResized = function(e) { + var width = this.container.clientWidth; + var height = this.container.clientHeight; + + this.resize(width, height, false); +}; + +EPUBJS.Renderer.prototype.addEventListeners = function(){ + if(!this.render.document) { + return; + } + this.listenedEvents.forEach(function(eventName){ + this.render.document.addEventListener(eventName, this.triggerEvent.bind(this), false); + }, this); + +}; + +EPUBJS.Renderer.prototype.removeEventListeners = function(){ + if(!this.render.document) { + return; + } + this.listenedEvents.forEach(function(eventName){ + this.render.document.removeEventListener(eventName, this.triggerEvent, false); + }, this); + +}; + +// Pass browser events +EPUBJS.Renderer.prototype.triggerEvent = function(e){ + this.trigger("renderer:"+e.type, e); +}; + +EPUBJS.Renderer.prototype.addSelectionListeners = function(){ + this.render.document.addEventListener("selectionchange", this.onSelectionChange.bind(this), false); +}; + +EPUBJS.Renderer.prototype.removeSelectionListeners = function(){ + if(!this.render.document) { + return; + } + this.doc.removeEventListener("selectionchange", this.onSelectionChange, false); +}; + +EPUBJS.Renderer.prototype.onSelectionChange = function(e){ + if (this.selectionEndTimeout) { + clearTimeout(this.selectionEndTimeout); + } + this.selectionEndTimeout = setTimeout(function() { + this.selectedRange = this.render.window.getSelection(); + this.trigger("renderer:selected", this.selectedRange); + }.bind(this), 500); +}; + + +//-- Spreads + +EPUBJS.Renderer.prototype.setMinSpreadWidth = function(width){ + this.minSpreadWidth = width; + this.spreads = this.determineSpreads(width); +}; + +EPUBJS.Renderer.prototype.determineSpreads = function(cutoff){ + if(this.isForcedSingle || !cutoff || this.width < cutoff) { + return false; //-- Single Page + }else{ + return true; //-- Double Page + } +}; + +EPUBJS.Renderer.prototype.forceSingle = function(bool){ + if(bool) { + this.isForcedSingle = true; + // this.spreads = false; + } else { + this.isForcedSingle = false; + // this.spreads = this.determineSpreads(this.minSpreadWidth); + } +}; + +EPUBJS.Renderer.prototype.setGap = function(gap){ + this.gap = gap; //-- False == auto gap +}; + +//-- Content Replacements + +EPUBJS.Renderer.prototype.replace = function(query, func, finished, progress){ + var items = this.contents.querySelectorAll(query), + resources = Array.prototype.slice.call(items), + count = resources.length; + + + if(count === 0) { + finished(false); + return; + } + resources.forEach(function(item){ + var called = false; + var after = function(result, full){ + if(called === false) { + count--; + if(progress) progress(result, full, count); + if(count <= 0 && finished) finished(true); + called = true; + } + }; + + func(item, after); + + }.bind(this)); + +}; + +EPUBJS.Renderer.prototype.replaceWithStored = function(query, attr, func, callback) { + var _oldUrls, + _newUrls = {}, + _store = this.currentChapter.store, + _cache = this.caches[query], + _uri = EPUBJS.core.uri(this.currentChapter.absolute), + _chapterBase = _uri.base, + _attr = attr, + _wait = 2000, + progress = function(url, full, count) { + _newUrls[full] = url; + }, + finished = function(notempty) { + if(callback) callback(); + + _.each(_oldUrls, function(url){ + _store.revokeUrl(url); + }); + + _cache = _newUrls; + }; + + if(!_store) return; + + if(!_cache) _cache = {}; + _oldUrls = _.clone(_cache); + + this.replace(query, function(link, done){ + var src = link.getAttribute(_attr), + full = EPUBJS.core.resolveUrl(_chapterBase, src); + + var replaceUrl = function(url) { + var timeout; + link.onload = function(){ + clearTimeout(timeout); + done(url, full); + }; + + link.onerror = function(e){ + clearTimeout(timeout); + done(url, full); + console.error(e); + }; + + if(query == "image") { + //-- SVG needs this to trigger a load event + link.setAttribute("externalResourcesRequired", "true"); + } + + if(query == "link[href]" && link.getAttribute("rel") !== "stylesheet") { + //-- Only Stylesheet links seem to have a load events, just continue others + done(url, full); + } + + link.setAttribute(_attr, url); + + //-- If elements never fire Load Event, should continue anyways + timeout = setTimeout(function(){ + done(url, full); + }, _wait); + + }; + + if(full in _oldUrls){ + replaceUrl(_oldUrls[full]); + _newUrls[full] = _oldUrls[full]; + delete _oldUrls[full]; + }else{ + func(_store, full, replaceUrl, link); + } + + }, finished, progress); +}; + +//-- Enable binding events to Renderer +RSVP.EventTarget.mixin(EPUBJS.Renderer.prototype); + +var EPUBJS = EPUBJS || {}; +EPUBJS.replace = {}; + +//-- Replaces the relative links within the book to use our internal page changer +EPUBJS.replace.hrefs = function(callback, renderer){ + var book = this; + var replacments = function(link, done){ + var href = link.getAttribute("href"), + isRelative = href.search("://"), + directory, + relative, + location; + + if(isRelative != -1){ + + link.setAttribute("target", "_blank"); + + }else{ + // Links may need to be resolved, such as ../chp1.xhtml + directory = EPUBJS.core.uri(renderer.render.window.location.href).directory; + if(directory) { + relative = EPUBJS.core.resolveUrl(directory, href); + } else { + relative = href; + } + + link.onclick = function(){ + book.goto(relative); + return false; + }; + + } + done(); + + }; + + renderer.replace("a[href]", replacments, callback); + +}; + +EPUBJS.replace.head = function(callback, renderer) { + + renderer.replaceWithStored("link[href]", "href", EPUBJS.replace.links, callback); + +}; + + +//-- Replaces assets src's to point to stored version if browser is offline +EPUBJS.replace.resources = function(callback, renderer){ + //srcs = this.doc.querySelectorAll('[src]'); + renderer.replaceWithStored("[src]", "src", EPUBJS.replace.srcs, callback); + +}; + +EPUBJS.replace.svg = function(callback, renderer) { + + renderer.replaceWithStored("image", "xlink:href", function(_store, full, done){ + _store.getUrl(full).then(done); + }, callback); + +}; + +EPUBJS.replace.srcs = function(_store, full, done){ + + _store.getUrl(full).then(done); + +}; + +//-- Replaces links in head, such as stylesheets - link[href] +EPUBJS.replace.links = function(_store, full, done, link){ + //-- Handle replacing urls in CSS + if(link.getAttribute("rel") === "stylesheet") { + EPUBJS.replace.stylesheets(_store, full).then(function(url, full){ + // done + setTimeout(function(){ + done(url, full); + }, 5); //-- Allow for css to apply before displaying chapter + }); + }else{ + _store.getUrl(full).then(done); + } +}; + +EPUBJS.replace.stylesheets = function(_store, full) { + var deferred = new RSVP.defer(); + + if(!_store) return; + + _store.getText(full).then(function(text){ + var url; + + EPUBJS.replace.cssUrls(_store, full, text).then(function(newText){ + var _URL = window.URL || window.webkitURL || window.mozURL; + + var blob = new Blob([newText], { "type" : "text\/css" }), + url = _URL.createObjectURL(blob); + + deferred.resolve(url); + + }, function(e) { + console.error(e); + }); + + }); + + return deferred.promise; +}; + +EPUBJS.replace.cssUrls = function(_store, base, text){ + var deferred = new RSVP.defer(), + promises = [], + matches = text.match(/url\(\'?\"?([^\'|^\"^\)]*)\'?\"?\)/g); + + if(!_store) return; + + if(!matches){ + deferred.resolve(text); + return deferred.promise; + } + + matches.forEach(function(str){ + var full = EPUBJS.core.resolveUrl(base, str.replace(/url\(|[|\)|\'|\"]/g, '')); + var replaced = _store.getUrl(full).then(function(url){ + text = text.replace(str, 'url("'+url+'")'); + }); + + promises.push(replaced); + }); + + RSVP.all(promises).then(function(){ + deferred.resolve(text); + }); + + return deferred.promise; +}; + + + +EPUBJS.Unarchiver = function(url){ + + this.loadLib(); + this.urlCache = {}; + +}; + +//-- Load the zip lib and set the workerScriptsPath +EPUBJS.Unarchiver.prototype.loadLib = function(callback){ + if(typeof(JSZip) == "undefined") console.error("JSZip lib not loaded"); +}; + +EPUBJS.Unarchiver.prototype.openZip = function(zipUrl, callback){ + var deferred = new RSVP.defer(); + + return EPUBJS.core.request(zipUrl, "binary").then(function(data){ + this.zip = new JSZip(data); + }.bind(this)); +}; + +EPUBJS.Unarchiver.prototype.getXml = function(url, encoding){ + + return this.getText(url, encoding). + then(function(text){ + var parser = new DOMParser(); + return parser.parseFromString(text, "text/xml"); + }); + +}; + +EPUBJS.Unarchiver.prototype.getUrl = function(url, mime){ + var unarchiver = this; + var deferred = new RSVP.defer(); + var decodededUrl = window.decodeURIComponent(url); + var entry = this.zip.file(decodededUrl); + var _URL = window.URL || window.webkitURL || window.mozURL; + var tempUrl; + + if(!entry) { + deferred.reject({ + message : "File not found in the epub: " + url, + stack : new Error().stack + }); + return deferred.promise; + } + + if(url in this.urlCache) { + deferred.resolve(this.urlCache[url]); + return deferred.promise; + } + + blob = new Blob([entry.asUint8Array()], {type : mime || this.zip.getMimeType(entry.name)}); + + tempUrl = _URL.createObjectURL(blob); + deferred.resolve(tempUrl); + unarchiver.urlCache[url] = tempUrl; + + return deferred.promise; +}; + +EPUBJS.Unarchiver.prototype.getText = function(url, encoding){ + var unarchiver = this; + var deferred = new RSVP.defer(); + var decodededUrl = window.decodeURIComponent(url); + var entry = this.zip.file(decodededUrl); + var _URL = window.URL || window.webkitURL || window.mozURL; + + if(!entry) { + console.warn("File not found in the contained epub:", url); + return deferred.promise; + } + + text = entry.asText(); + deferred.resolve(text); + + return deferred.promise; +}; + +EPUBJS.Unarchiver.prototype.revokeUrl = function(url){ + var _URL = window.URL || window.webkitURL || window.mozURL; + var fromCache = unarchiver.urlCache[url]; + if(fromCache) _URL.revokeObjectURL(fromCache); +}; + +EPUBJS.Unarchiver.prototype.failed = function(error){ + console.error(error); +}; + +EPUBJS.Unarchiver.prototype.afterSaved = function(error){ + this.callback(); +}; + +EPUBJS.Unarchiver.prototype.toStorage = function(entries){ + var timeout = 0, + delay = 20, + that = this, + count = entries.length; + + function callback(){ + count--; + if(count === 0) that.afterSaved(); + } + + entries.forEach(function(entry){ + + setTimeout(function(entry){ + that.saveEntryFileToStorage(entry, callback); + }, timeout, entry); + + timeout += delay; + }); + + console.log("time", timeout); + + //entries.forEach(this.saveEntryFileToStorage.bind(this)); +}; + +// EPUBJS.Unarchiver.prototype.saveEntryFileToStorage = function(entry, callback){ +// var that = this; +// entry.getData(new zip.BlobWriter(), function(blob) { +// EPUBJS.storage.save(entry.filename, blob, callback); +// }); +// }; + +//# sourceMappingURL=epub_no_underscore.js.map \ No newline at end of file diff --git a/epub.js/epub_no_underscore.js.map b/epub.js/epub_no_underscore.js.map new file mode 100644 index 0000000..afad7ad --- /dev/null +++ b/epub.js/epub_no_underscore.js.map @@ -0,0 +1,23 @@ +{ + "version": 3, + "file": "epub_no_underscore.js", + "sources": [ + "libs/rsvp/rsvp.js", + "src/base.js", + "src/book.js", + "src/chapter.js", + "src/core.js", + "src/epubcfi.js", + "src/events.js", + "src/hooks.js", + "src/layout.js", + "src/pagination.js", + "src/parser.js", + "src/render_iframe.js", + "src/renderer.js", + "src/replace.js", + "src/unarchiver.js" + ], + "names": [], + "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,Y;ACtoEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACjvCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACjRA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACthBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACtfA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACpEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACnFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC5KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACvFA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;AC5dA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,uD;AC7NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A;ACluCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;;ACtIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A" +} \ No newline at end of file diff --git a/epub.js/font/fontello.eot b/epub.js/font/fontello.eot new file mode 100644 index 0000000000000000000000000000000000000000..f63ffa043ea29008e7f5b161b87c44ce567d15fc GIT binary patch literal 10204 zcmeHNYiwM{b)LEJz5C=oN$qNR$>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SiK~(M}rKpzGP3R7iP8^ zWL?1y(X@jh_$`Vci0f^J`Ou6jd526+CA40oX{J|+h{<-iFAVHHbRp0NWHZ#J=2Pu+;@&f8=-{|>q9Hre1V58cIc zZ%l8FmV0(h+8xtdqMKN9wziuH{$CReXD9S}$nP;c!s4auKpn9VLZ~JXxkVj&u^W-i zZU223&@1{`HPeE^Oz9tJ$Xco;Cnco>jnJlz0}Gad#^Gad#!$aom=P)twW zcJm2_=p7(GY(SlWaz@mE+yx{b(_3$IpJa%^J!3$Od)9y$Yayn$-DaI*h{1ZwfEeq% z0WsEvnBIPy^)y2a)-wjgSQib5u`b1;x>C^jy3zA2eaDe`55GiSAICvVpUS?h;HovF zAxrk_d}#Hm&|n%E@4u>Ya^sdn`?u=o6Jt|)>WQf>iSI|80YkmOP*eu^dx_rqeO>q* K{$I9!LjD)8G->Dn literal 0 HcmV?d00001 diff --git a/epub.js/font/fontello.svg b/epub.js/font/fontello.svg new file mode 100644 index 0000000..2db1398 --- /dev/null +++ b/epub.js/font/fontello.svg @@ -0,0 +1,33 @@ + + + +Copyright (C) 2013 by original authors @ fontello.com + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/epub.js/font/fontello.ttf b/epub.js/font/fontello.ttf new file mode 100644 index 0000000000000000000000000000000000000000..95715f86629cdbe17012ceb0595caaf61c8c15cb GIT binary patch literal 10036 zcmeHNdu*H6b-(v}^W#%|N+wNx5=BW7ACjnNELo;W$#P=JdfE{!$003I4_mKEvgfpR z?Ic^83aOI@MUZ6}S{H3ltl03;?bgK0nga8-H0UE3HZ*98EyIe<8?vr{bX{x2@_zRt zY0F8ItU&)9Wq$XZbI-l!anC*X+>a)d5Mm>j2v4#j6U~Xf#)EHx@-DtdXO?qoZ`N0R zlMvdE?}IaEH#O;dw(DCmOOMX!e_Id< z;hrVL^Xx)CH%kMt7YV7<(BHWLg8UBuRp3*=>lT(b&ppUSlFIXV9A8?U$?dy3@C)Ef zr2=V_C`rfy;o?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tWv|BZMP#Agm(7BQ7IJAbmqdMfO78L@7nhLLGVS8$bm3 z_@A=~GxT8YpD4fyrY)nSyjJtc^GyC}*C&A=`EoH6C#A1<(9*=JX!~tCff|``t(lC) zNhzK?W*}Y}+`Difd}aE88<_cz(VRsQkMVE5^F*E?31HzaQsSS8>n^*?5c57rWxC0r zG`Pipwp*8@Bv#-j)776$HXjL-_E@rj`cUS49=*-k#-5C}W`mxHw%5>R1KL~mPp)i6 zZwjXTGug7D=iCTxx9tnH^(hdFQlOHCExEOcc}``;vA6=6XUpM=6^)$xtlUB5Y{MEq zMU$RQC_4S9&h}%z&dM`1?(yE*?J{+FC5W$RsR~H0WVPqnL(`>mX>|171Wdjw;;wco zxwsWUFRbq)B*pp48Xh8(&@$1Uz^HeSTt1dOHr7N-?}9Virt2=3Ra+YWNbU|sshy0^ zI_cT*_T3#W{rG6EJuO!qbrIeyOgH+?!Wgqtc#Je9m3?;nvMYYasOPp;+Xzp|vBc`_O81RE=_ A2mk;8 literal 0 HcmV?d00001 diff --git a/epub.js/hooks.js b/epub.js/hooks.js new file mode 100644 index 0000000..fad6409 --- /dev/null +++ b/epub.js/hooks.js @@ -0,0 +1,318 @@ +EPUBJS.Hooks.register("beforeChapterDisplay").endnotes = function(callback, renderer){ + + var notes = renderer.contents.querySelectorAll('a[href]'), + items = Array.prototype.slice.call(notes), //[].slice.call() + attr = "epub:type", + type = "noteref", + folder = EPUBJS.core.folder(location.pathname), + cssPath = (folder + EPUBJS.cssPath) || folder, + popups = {}; + + EPUBJS.core.addCss(cssPath + "popup.css", false, renderer.render.document.head); + + + items.forEach(function(item){ + var epubType = item.getAttribute(attr), + href, + id, + el, + pop, + pos, + left, + top, + txt; + + if(epubType != type) return; + + href = item.getAttribute("href"); + id = href.replace("#", ''); + el = renderer.render.document.getElementById(id); + + + item.addEventListener("mouseover", showPop, false); + item.addEventListener("mouseout", hidePop, false); + + function showPop(){ + var poppos, + iheight = renderer.height, + iwidth = renderer.width, + tip, + pop, + maxHeight = 225, + itemRect; + + if(!txt) { + pop = el.cloneNode(true); + txt = pop.querySelector("p"); + } + + // chapter.replaceLinks.bind(this) //TODO:Fred - update? + //-- create a popup with endnote inside of it + if(!popups[id]) { + popups[id] = document.createElement("div"); + popups[id].setAttribute("class", "popup"); + + pop_content = document.createElement("div"); + + popups[id].appendChild(pop_content); + + pop_content.appendChild(txt); + pop_content.setAttribute("class", "pop_content"); + + renderer.render.document.body.appendChild(popups[id]); + + //-- TODO: will these leak memory? - Fred + popups[id].addEventListener("mouseover", onPop, false); + popups[id].addEventListener("mouseout", offPop, false); + + //-- Add hide on page change + // chapter.book.listenUntil("book:pageChanged", "book:chapterDestroy", hidePop); + // chapter.book.listenUntil("book:pageChanged", "book:chapterDestroy", offPop); + renderer.on("renderer:pageChanged", hidePop, this); + renderer.on("renderer:pageChanged", offPop, this); + // chapter.book.on("renderer:chapterDestroy", hidePop, this); + } + + pop = popups[id]; + + + //-- get location of item + itemRect = item.getBoundingClientRect(); + left = itemRect.left; + top = itemRect.top; + + //-- show the popup + pop.classList.add("show"); + + //-- locations of popup + popRect = pop.getBoundingClientRect(); + + //-- position the popup + pop.style.left = left - popRect.width / 2 + "px"; + pop.style.top = top + "px"; + + + //-- Adjust max height + if(maxHeight > iheight / 2.5) { + maxHeight = iheight / 2.5; + pop_content.style.maxHeight = maxHeight + "px"; + } + + //-- switch above / below + if(popRect.height + top >= iheight - 25) { + pop.style.top = top - popRect.height + "px"; + pop.classList.add("above"); + }else{ + pop.classList.remove("above"); + } + + //-- switch left + if(left - popRect.width <= 0) { + pop.style.left = left + "px"; + pop.classList.add("left"); + }else{ + pop.classList.remove("left"); + } + + //-- switch right + if(left + popRect.width / 2 >= iwidth) { + //-- TEMP MOVE: 300 + pop.style.left = left - 300 + "px"; + + popRect = pop.getBoundingClientRect(); + pop.style.left = left - popRect.width + "px"; + //-- switch above / below again + if(popRect.height + top >= iheight - 25) { + pop.style.top = top - popRect.height + "px"; + pop.classList.add("above"); + }else{ + pop.classList.remove("above"); + } + + pop.classList.add("right"); + }else{ + pop.classList.remove("right"); + } + + + } + + function onPop(){ + popups[id].classList.add("on"); + } + + function offPop(){ + popups[id].classList.remove("on"); + } + + function hidePop(){ + setTimeout(function(){ + popups[id].classList.remove("show"); + }, 100); + } + + }); + + + if(callback) callback(); + +} + +EPUBJS.Hooks.register("beforeChapterDisplay").mathml = function(callback, renderer){ + + // check of currentChapter properties contains 'mathml' + if(renderer.currentChapter.manifestProperties.indexOf("mathml") !== -1 ){ + + // Assign callback to be inside iframe window + renderer.iframe.contentWindow.mathmlCallback = callback; + + // add MathJax config script tag to the renderer body + var s = document.createElement("script"); + s.type = 'text/x-mathjax-config'; + s.innerHTML = '\ + MathJax.Hub.Register.StartupHook("End",function () { \ + window.mathmlCallback(); \ + });\ + MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); \ + '; + renderer.doc.body.appendChild(s); + // add MathJax.js to renderer head + EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML", null, renderer.doc.head); + + } else { + if(callback) callback(); + } +} + +EPUBJS.Hooks.register("beforeChapterDisplay").smartimages = function(callback, renderer){ + var images = renderer.contents.querySelectorAll('img'), + items = Array.prototype.slice.call(images), + iheight = renderer.height,//chapter.bodyEl.clientHeight,//chapter.doc.body.getBoundingClientRect().height, + oheight; + + if(renderer.layoutSettings.layout != "reflowable") { + callback(); + return; //-- Only adjust images for reflowable text + } + + items.forEach(function(item){ + + function size() { + var itemRect = item.getBoundingClientRect(), + rectHeight = itemRect.height, + top = itemRect.top, + oHeight = item.getAttribute('data-height'), + height = oHeight || rectHeight, + newHeight, + fontSize = Number(getComputedStyle(item, "").fontSize.match(/(\d*(\.\d*)?)px/)[1]), + fontAdjust = fontSize ? fontSize / 2 : 0; + + iheight = renderer.contents.clientHeight; + if(top < 0) top = 0; + + if(height + top >= iheight) { + + if(top < iheight/2) { + // Remove top and half font-size from height to keep container from overflowing + newHeight = iheight - top - fontAdjust; + item.style.maxHeight = newHeight + "px"; + item.style.width= "auto"; + }else{ + if(height > iheight) { + item.style.maxHeight = iheight + "px"; + item.style.width= "auto"; + itemRect = item.getBoundingClientRect(); + height = itemRect.height; + } + item.style.display = "block"; + item.style["WebkitColumnBreakBefore"] = "always"; + item.style["breakBefore"] = "column"; + + } + + item.setAttribute('data-height', newHeight); + + }else{ + item.style.removeProperty('max-height'); + item.style.removeProperty('margin-top'); + } + } + + item.addEventListener('load', size, false); + + renderer.on("renderer:resized", size); + + renderer.on("renderer:chapterUnloaded", function(){ + item.removeEventListener('load', size); + renderer.off("renderer:resized", size); + }); + + size(); + + }); + + if(callback) callback(); + +} + +EPUBJS.Hooks.register("beforeChapterDisplay").transculsions = function(callback, renderer){ + /* + + */ + + var trans = renderer.contents.querySelectorAll('[transclusion]'), + items = Array.prototype.slice.call(trans); + + items.forEach(function(item){ + var src = item.getAttribute("ref"), + iframe = document.createElement('iframe'), + orginal_width = item.getAttribute("width"), + orginal_height = item.getAttribute("height"), + parent = item.parentNode, + width = orginal_width, + height = orginal_height, + ratio; + + + function size() { + width = orginal_width; + height = orginal_height; + + if(width > chapter.colWidth){ + ratio = chapter.colWidth / width; + + width = chapter.colWidth; + height = height * ratio; + } + + iframe.width = width; + iframe.height = height; + } + + + size(); + + //-- resize event + + + renderer.listenUntil("renderer:resized", "renderer:chapterUnloaded", size); + + iframe.src = src; + + // + parent.replaceChild(iframe, item); + + + }); + + + + + if(callback) callback(); + + +} + +//# sourceMappingURL=hooks.js.map \ No newline at end of file diff --git a/epub.js/hooks.js.map b/epub.js/hooks.js.map new file mode 100644 index 0000000..7ed25d6 --- /dev/null +++ b/epub.js/hooks.js.map @@ -0,0 +1,17 @@ +{ + "version": 3, + "file": "reader.js", + "sources": [ + "reader_src/reader.js", + "reader_src/controllers/bookmarks_controller.js", + "reader_src/controllers/controls_controller.js", + "reader_src/controllers/meta_controller.js", + "reader_src/controllers/notes_controller.js", + "reader_src/controllers/reader_controller.js", + "reader_src/controllers/settings_controller.js", + "reader_src/controllers/sidebar_controller.js", + "reader_src/controllers/toc_controller.js" + ], + "names": [], + "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,gD;ACjUA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;AClEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;AChHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;AC9RA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACxHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;AChCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,E;ACjDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;A" +} \ No newline at end of file diff --git a/epub.js/hooks.min.js b/epub.js/hooks.min.js new file mode 100644 index 0000000..33049a9 --- /dev/null +++ b/epub.js/hooks.min.js @@ -0,0 +1,2 @@ +EPUBJS.Hooks.register("beforeChapterDisplay").endnotes=function(a,b){var c=b.contents.querySelectorAll("a[href]"),d=Array.prototype.slice.call(c),e="epub:type",f="noteref",g=EPUBJS.core.folder(location.pathname),h=g+EPUBJS.cssPath||g,i={};EPUBJS.core.addCss(h+"popup.css",!1,b.render.document.head),d.forEach(function(a){function c(){var c,e,f=b.height,j=b.width,p=225;o||(c=l.cloneNode(!0),o=c.querySelector("p")),i[k]||(i[k]=document.createElement("div"),i[k].setAttribute("class","popup"),pop_content=document.createElement("div"),i[k].appendChild(pop_content),pop_content.appendChild(o),pop_content.setAttribute("class","pop_content"),b.render.document.body.appendChild(i[k]),i[k].addEventListener("mouseover",d,!1),i[k].addEventListener("mouseout",g,!1),b.on("renderer:pageChanged",h,this),b.on("renderer:pageChanged",g,this)),c=i[k],e=a.getBoundingClientRect(),m=e.left,n=e.top,c.classList.add("show"),popRect=c.getBoundingClientRect(),c.style.left=m-popRect.width/2+"px",c.style.top=n+"px",p>f/2.5&&(p=f/2.5,pop_content.style.maxHeight=p+"px"),popRect.height+n>=f-25?(c.style.top=n-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),m-popRect.width<=0?(c.style.left=m+"px",c.classList.add("left")):c.classList.remove("left"),m+popRect.width/2>=j?(c.style.left=m-300+"px",popRect=c.getBoundingClientRect(),c.style.left=m-popRect.width+"px",popRect.height+n>=f-25?(c.style.top=n-popRect.height+"px",c.classList.add("above")):c.classList.remove("above"),c.classList.add("right")):c.classList.remove("right")}function d(){i[k].classList.add("on")}function g(){i[k].classList.remove("on")}function h(){setTimeout(function(){i[k].classList.remove("show")},100)}var j,k,l,m,n,o,p=a.getAttribute(e);p==f&&(j=a.getAttribute("href"),k=j.replace("#",""),l=b.render.document.getElementById(k),a.addEventListener("mouseover",c,!1),a.addEventListener("mouseout",h,!1))}),a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").mathml=function(a,b){if(-1!==b.currentChapter.manifestProperties.indexOf("mathml")){b.iframe.contentWindow.mathmlCallback=a;var c=document.createElement("script");c.type="text/x-mathjax-config",c.innerHTML=' MathJax.Hub.Register.StartupHook("End",function () { window.mathmlCallback(); }); MathJax.Hub.Config({jax: ["input/TeX","input/MathML","output/SVG"],extensions: ["tex2jax.js","mml2jax.js","MathEvents.js"],TeX: {extensions: ["noErrors.js","noUndefined.js","autoload-all.js"]},MathMenu: {showRenderer: false},menuSettings: {zoom: "Click"},messageStyle: "none"}); ',b.doc.body.appendChild(c),EPUBJS.core.addScript("http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",null,b.doc.head)}else a&&a()},EPUBJS.Hooks.register("beforeChapterDisplay").smartimages=function(a,b){var c=b.contents.querySelectorAll("img"),d=Array.prototype.slice.call(c),e=b.height;return"reflowable"!=b.layoutSettings.layout?void a():(d.forEach(function(a){function c(){var c,d=a.getBoundingClientRect(),f=d.height,g=d.top,h=a.getAttribute("data-height"),i=h||f,j=Number(getComputedStyle(a,"").fontSize.match(/(\d*(\.\d*)?)px/)[1]),k=j?j/2:0;e=b.contents.clientHeight,0>g&&(g=0),i+g>=e?(e/2>g?(c=e-g-k,a.style.maxHeight=c+"px",a.style.width="auto"):(i>e&&(a.style.maxHeight=e+"px",a.style.width="auto",d=a.getBoundingClientRect(),i=d.height),a.style.display="block",a.style.WebkitColumnBreakBefore="always",a.style.breakBefore="column"),a.setAttribute("data-height",c)):(a.style.removeProperty("max-height"),a.style.removeProperty("margin-top"))}a.addEventListener("load",c,!1),b.on("renderer:resized",c),b.on("renderer:chapterUnloaded",function(){a.removeEventListener("load",c),b.off("renderer:resized",c)}),c()}),void(a&&a()))},EPUBJS.Hooks.register("beforeChapterDisplay").transculsions=function(a,b){var c=b.contents.querySelectorAll("[transclusion]"),d=Array.prototype.slice.call(c);d.forEach(function(a){function c(){j=g,k=h,j>chapter.colWidth&&(d=chapter.colWidth/j,j=chapter.colWidth,k*=d),f.width=j,f.height=k}var d,e=a.getAttribute("ref"),f=document.createElement("iframe"),g=a.getAttribute("width"),h=a.getAttribute("height"),i=a.parentNode,j=g,k=h;c(),b.listenUntil("renderer:resized","renderer:chapterUnloaded",c),f.src=e,i.replaceChild(f,a)}),a&&a()}; +//# sourceMappingURL=hooks.min.map \ No newline at end of file diff --git a/epub.js/hooks.min.map b/epub.js/hooks.min.map new file mode 100644 index 0000000..783dac9 --- /dev/null +++ b/epub.js/hooks.min.map @@ -0,0 +1 @@ +{"version":3,"file":"hooks.min.js","sources":["hooks.js"],"names":["EPUBJS","Hooks","register","endnotes","callback","renderer","notes","contents","querySelectorAll","items","Array","prototype","slice","call","attr","type","folder","core","location","pathname","cssPath","popups","addCss","render","document","head","forEach","item","showPop","pop","itemRect","iheight","height","iwidth","width","maxHeight","txt","el","cloneNode","querySelector","id","createElement","setAttribute","pop_content","appendChild","body","addEventListener","onPop","offPop","on","hidePop","this","getBoundingClientRect","left","top","classList","add","popRect","style","remove","setTimeout","href","epubType","getAttribute","replace","getElementById","mathml","currentChapter","manifestProperties","indexOf","iframe","contentWindow","mathmlCallback","s","innerHTML","doc","addScript","smartimages","images","layoutSettings","layout","size","newHeight","rectHeight","oHeight","fontSize","Number","getComputedStyle","match","fontAdjust","clientHeight","display","removeProperty","removeEventListener","off","transculsions","trans","orginal_width","orginal_height","chapter","colWidth","ratio","src","parent","parentNode","listenUntil","replaceChild"],"mappings":"AAAAA,OAAOC,MAAMC,SAAS,wBAAwBC,SAAW,SAASC,EAAUC,GAE1E,GAAIC,GAAQD,EAASE,SAASC,iBAAiB,WAC9CC,EAAQC,MAAMC,UAAUC,MAAMC,KAAKP,GACnCQ,EAAO,YACPC,EAAO,UACPC,EAAShB,OAAOiB,KAAKD,OAAOE,SAASC,UACrCC,EAAWJ,EAAShB,OAAOoB,SAAYJ,EACvCK,IAEDrB,QAAOiB,KAAKK,OAAOF,EAAU,aAAa,EAAOf,EAASkB,OAAOC,SAASC,MAG1EhB,EAAMiB,QAAQ,SAASC,GAqBtB,QAASC,KACR,GAICC,GAEAC,EALAC,EAAU1B,EAAS2B,OACnBC,EAAS5B,EAAS6B,MAGlBC,EAAY,GAGTC,KACHP,EAAMQ,EAAGC,WAAU,GACnBF,EAAMP,EAAIU,cAAc,MAKrBlB,EAAOmB,KACVnB,EAAOmB,GAAMhB,SAASiB,cAAc,OACpCpB,EAAOmB,GAAIE,aAAa,QAAS,SAEjCC,YAAcnB,SAASiB,cAAc,OAErCpB,EAAOmB,GAAII,YAAYD,aAEvBA,YAAYC,YAAYR,GACxBO,YAAYD,aAAa,QAAS,eAElCrC,EAASkB,OAAOC,SAASqB,KAAKD,YAAYv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EAAgBtE,EAAKoC,aAAa,SAClCmC,EAAiBvE,EAAKoC,aAAa,UACnCwC,EAAS5E,EAAK6E,WACdtE,EAAQ+D,EACRjE,EAASkE,CAoBVjB,KAKA5E,EAASoG,YAAY,mBAAoB,2BAA4BxB,GAErEX,EAAOgC,IAAMA,EAGbC,EAAOG,aAAapC,EAAQ3C,KAQ1BvB,GAAUA"} \ No newline at end of file diff --git a/epub.js/hooks/extensions/highlight.js b/epub.js/hooks/extensions/highlight.js new file mode 100644 index 0000000..1dd1c67 --- /dev/null +++ b/epub.js/hooks/extensions/highlight.js @@ -0,0 +1,14 @@ +EPUBJS.Hooks.register("beforeChapterDisplay").highlight = function(callback, renderer){ + + // EPUBJS.core.addScript("js/libs/jquery.highlight.js", null, renderer.doc.head); + + var s = document.createElement("style"); + s.innerHTML =".highlight { background: yellow; font-weight: normal; }"; + + renderer.render.document.head.appendChild(s); + + if(callback) callback(); + +} + + diff --git a/epub.js/libs/fileStorage.min.js b/epub.js/libs/fileStorage.min.js new file mode 100644 index 0000000..6fc082b --- /dev/null +++ b/epub.js/libs/fileStorage.min.js @@ -0,0 +1,3 @@ +/*! fileStorage - v0.1.0 - 2013-03-28 */var fileStorage = fileStorage || {}; +fileStorage.core=fileStorage.core||{},fileStorage.core.dataURLToBlob=function(e){var t=";base64,";if(e.indexOf(t)==-1){var n=e.split(","),r=n[0].split(":")[1],i=n[1];return new Blob([i],{type:r})}var n=e.split(t),r=n[0].split(":")[1],i=window.atob(n[1]),s=i.length,o=new Uint8Array(s);for(var u=0;u=y&&0===e[y];y++);for(z=y,y>A&&(A=y),x=B;0!==x&&0===e[x];x--);for(v=x,A>x&&(A=x),n[0]=A,H=1<y;y++,H<<=1)if((H-=e[y])<0)return m;if((H-=e[x])<0)return m;for(e[x]+=H,h[1]=y=0,D=1,G=2;0!==--x;)h[G]=y+=e[D],G++,D++;x=0,D=0;do 0!==(y=a[b+D])&&(s[h[y]++]=x),D++;while(++x=z;z++)for(t=e[z];0!==t--;){for(;z>F+A;){if(w++,F+=A,I=v-F,I=I>A?A:I,(u=1<<(y=z-F))>t+1&&(u-=t+1,G=z,I>y))for(;++yq)return m;g[w]=E=r[0],r[0]+=I,0!==w?(h[w]=x,f[0]=y,f[1]=A,y=x>>>F-A,f[2]=E-g[w-1]-y,p.set(f,3*(g[w-1]+y))):l[0]=E}for(f[1]=z-F,D>=c?f[0]=192:s[D]>>F;I>y;y+=u)p.set(f,3*(E+y));for(y=1<>>=1)x^=y;for(x^=y,C=(1<b;b++)d[b]=0;for(b=0;B+1>b;b++)e[b]=0;for(b=0;3>b;b++)f[b]=0;g.set(e.subarray(0,B),0),h.set(e.subarray(0,B+1),0)}var c,d,e,f,g,h,j=this;j.inflate_trees_bits=function(e,f,g,h,i){var j;return b(19),c[0]=0,j=a(e,0,19,19,null,null,g,f,h,c,d),j==m?i.msg="oversubscribed dynamic bit lengths tree":(j==o||0===f[0])&&(i.msg="incomplete dynamic bit lengths tree",j=m),j},j.inflate_trees_dynamic=function(e,f,g,h,j,k,l,p,q){var r;return b(288),c[0]=0,r=a(g,0,e,257,x,y,k,h,p,c,d),r!=i||0===h[0]?(r==m?q.msg="oversubscribed literal/length tree":r!=n&&(q.msg="incomplete literal/length tree",r=m),r):(b(288),r=a(g,e,f,0,z,A,l,j,p,c,d),r!=i||0===j[0]&&e>257?(r==m?q.msg="oversubscribed distance tree":r==o?(q.msg="incomplete distance tree",r=m):r!=n&&(q.msg="empty distance tree with lengths",r=m),r):i)}}function c(){function a(a,b,c,d,e,f,g,h){var k,l,n,o,q,r,s,t,u,v,w,x,y,z,A,B;s=h.next_in_index,t=h.avail_in,q=g.bitb,r=g.bitk,u=g.write,v=ur;)t--,q|=(255&h.read_byte(s++))<>=l[B+1],r-=l[B+1],0!==(16&o)){for(o&=15,y=l[B+2]+(q&p[o]),q>>=o,r-=o;15>r;)t--,q|=(255&h.read_byte(s++))<>=l[B+1],r-=l[B+1],0!==(16&o)){for(o&=15;o>r;)t--,q|=(255&h.read_byte(s++))<>=o,r-=o,v-=y,u>=z)A=u-z,u-A>0&&2>u-A?(g.window[u++]=g.window[A++],g.window[u++]=g.window[A++],y-=2):(g.window.set(g.window.subarray(A,A+2),u),u+=2,A+=2,y-=2);else{A=u-z;do A+=g.end;while(0>A);if(o=g.end-A,y>o){if(y-=o,u-A>0&&o>u-A){do g.window[u++]=g.window[A++];while(0!==--o)}else g.window.set(g.window.subarray(A,A+o),u),u+=o,A+=o,o=0;A=0}}if(u-A>0&&y>u-A){do g.window[u++]=g.window[A++];while(0!==--y)}else g.window.set(g.window.subarray(A,A+y),u),u+=y,A+=y,y=0;break}if(0!==(64&o))return h.msg="invalid distance code",y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,m;k+=l[B+2],k+=q&p[o],B=3*(n+k),o=l[B]}break}if(0!==(64&o))return 0!==(32&o)?(y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,j):(h.msg="invalid literal/length code",y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,m);if(k+=l[B+2],k+=q&p[o],B=3*(n+k),0===(o=l[B])){q>>=l[B+1],r-=l[B+1],g.window[u++]=l[B+2],v--;break}}else q>>=l[B+1],r-=l[B+1],g.window[u++]=l[B+2],v--}while(v>=258&&t>=10);return y=h.avail_in-t,y=y>r>>3?r>>3:y,t+=y,s-=y,r-=y<<3,g.bitb=q,g.bitk=r,h.avail_in=t,h.total_in+=s-h.next_in_index,h.next_in_index=s,g.write=u,i}var b,c,d,e,f=this,g=0,h=0,k=0,n=0,o=0,q=0,r=0,s=0,t=0,u=0;f.init=function(a,f,g,h,i,j){b=C,r=a,s=f,d=g,t=h,e=i,u=j,c=null},f.proc=function(f,v,w){var x,y,z,A,B,M,N,O=0,P=0,Q=0;for(Q=v.next_in_index,A=v.avail_in,O=f.bitb,P=f.bitk,B=f.write,M=B=258&&A>=10&&(f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,w=a(r,s,d,t,e,u,f,v),Q=v.next_in_index,A=v.avail_in,O=f.bitb,P=f.bitk,B=f.write,M=BP;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>>=c[y+1],P-=c[y+1],z=c[y],0===z){n=c[y+2],b=I;break}if(0!==(16&z)){o=15&z,g=c[y+2],b=E;break}if(0===(64&z)){k=z,h=y/3+c[y+2];break}if(0!==(32&z)){b=J;break}return b=L,v.msg="invalid literal/length code",w=m,f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);case E:for(x=o;x>P;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>=x,P-=x,k=s,c=e,h=u,b=F;case F:for(x=k;x>P;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>=c[y+1],P-=c[y+1],z=c[y],0!==(16&z)){o=15&z,q=c[y+2],b=G;break}if(0===(64&z)){k=z,h=y/3+c[y+2];break}return b=L,v.msg="invalid distance code",w=m,f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);case G:for(x=o;x>P;){if(0===A)return f.bitb=O,f.bitk=P,v.avail_in=A,v.total_in+=Q-v.next_in_index,v.next_in_index=Q,f.write=B,f.inflate_flush(v,w);w=i,A--,O|=(255&v.read_byte(Q++))<>=x,P-=x,b=H;case H:for(N=B-q;0>N;)N+=f.end;for(;0!==g;){if(0===M&&(B==f.end&&0!==f.read&&(B=0,M=B7&&(P-=8,A++,Q--),f.write=B,w=f.inflate_flush(v,w),B=f.write,M=Ba.avail_out&&(c=a.avail_out),0!==c&&b==o&&(b=i),a.avail_out-=c,a.total_out+=c,a.next_out.set(f.window.subarray(e,e+c),d),d+=c,e+=c,e==f.end&&(e=0,f.write==f.end&&(f.write=0),c=f.write-e,c>a.avail_out&&(c=a.avail_out),0!==c&&b==o&&(b=i),a.avail_out-=c,a.total_out+=c,a.next_out.set(f.window.subarray(e,e+c),d),d+=c,e+=c),a.next_out_index=d,f.read=e,b},f.proc=function(a,c){var d,o,q,w,y,z,A,B;for(w=a.next_in_index,y=a.avail_in,o=f.bitb,q=f.bitk,z=f.write,A=zq;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>1){case 0:o>>>=3,q-=3,d=7&q,o>>>=d,q-=d,g=O;break;case 1:var C=[],D=[],E=[[]],F=[[]];b.inflate_trees_fixed(C,D,E,F),t.init(C[0],D[0],E[0],0,F[0],0),o>>>=3,q-=3,g=T;break;case 2:o>>>=3,q-=3,g=Q;break;case 3:return o>>>=3,q-=3,g=W,a.msg="invalid block type",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c)}break;case O:for(;32>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>16&65535)!=(65535&o))return g=W,a.msg="invalid stored block lengths",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);h=65535&o,o=q=0,g=0!==h?P:0!==u?U:N;break;case P:if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);if(0===A&&(z==f.end&&0!==f.read&&(z=0,A=zy&&(d=y),d>A&&(d=A),f.window.set(a.read_buf(w,d),z),w+=d,y-=d,z+=d,A-=d,0!==(h-=d))break;g=0!==u?U:N;break;case Q:for(;14>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<29||(d>>5&31)>29)return g=W,a.msg="too many length or distance symbols",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);if(d=258+(31&d)+(d>>5&31),!e||e.lengthB;B++)e[B]=0;o>>>=14,q-=14,n=0,g=R;case R:for(;4+(k>>>10)>n;){for(;3>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>=3,q-=3}for(;19>n;)e[M[n++]]=0;if(r[0]=7,d=x.inflate_trees_bits(e,r,s,v,a),d!=i)return c=d,c==m&&(e=null,g=W),f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);n=0,g=S;case S:for(;;){if(d=k,!(258+(31&d)+(d>>5&31)>n))break;var G,H;for(d=r[0];d>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<H)o>>>=d,q-=d,e[n++]=H;else{for(B=18==H?7:H-14,G=18==H?11:3;d+B>q;){if(0===y)return f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);c=i,y--,o|=(255&a.read_byte(w++))<>>=d,q-=d,G+=o&p[B],o>>>=B,q-=B,B=n,d=k,B+G>258+(31&d)+(d>>5&31)||16==H&&1>B)return e=null,g=W,a.msg="invalid bit length repeat",c=m,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);H=16==H?e[B-1]:0;do e[B++]=H;while(0!==--G);n=B}}s[0]=-1;var I=[],J=[],K=[],L=[];if(I[0]=9,J[0]=6,d=k,d=x.inflate_trees_dynamic(257+(31&d),1+(d>>5&31),e,I,J,K,L,v,a),d!=i)return d==m&&(e=null,g=W),c=d,f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,f.inflate_flush(a,c);t.init(I[0],J[0],v,K[0],v,L[0]),g=T;case T:if(f.bitb=o,f.bitk=q,a.avail_in=y,a.total_in+=w-a.next_in_index,a.next_in_index=w,f.write=z,(c=t.proc(f,a,c))!=j)return f.inflate_flush(a,c);if(c=i,t.free(a),w=a.next_in_index,y=a.avail_in,o=f.bitb,q=f.bitk,z=f.write,A=ze||e>15?(b.inflateEnd(c),l):(b.wbits=e,c.istate.blocks=new d(c,1<>4)+8>a.istate.wbits){a.istate.mode=gb,a.msg="invalid window size",a.istate.marker=5;break}a.istate.mode=$;case $:if(0===a.avail_in)return c;if(c=b,a.avail_in--,a.total_in++,d=255&a.read_byte(a.next_in_index++),((a.istate.method<<8)+d)%31!==0){a.istate.mode=gb,a.msg="incorrect header check",a.istate.marker=5;break}if(0===(d&X)){a.istate.mode=eb;break}a.istate.mode=_;case _:if(0===a.avail_in)return c;c=b,a.avail_in--,a.total_in++,a.istate.need=(255&a.read_byte(a.next_in_index++))<<24&4278190080,a.istate.mode=ab;case ab:if(0===a.avail_in)return c;c=b,a.avail_in--,a.total_in++,a.istate.need+=(255&a.read_byte(a.next_in_index++))<<16&16711680,a.istate.mode=bb;case bb:if(0===a.avail_in)return c;c=b,a.avail_in--,a.total_in++,a.istate.need+=(255&a.read_byte(a.next_in_index++))<<8&65280,a.istate.mode=cb;case cb:return 0===a.avail_in?c:(c=b,a.avail_in--,a.total_in++,a.istate.need+=255&a.read_byte(a.next_in_index++),a.istate.mode=db,k);case db:return a.istate.mode=gb,a.msg="need dictionary",a.istate.marker=0,l;case eb:if(c=a.istate.blocks.proc(a,c),c==m){a.istate.mode=gb,a.istate.marker=0;break}if(c==i&&(c=b),c!=j)return c;c=b,a.istate.blocks.reset(a,a.istate.was),a.istate.mode=fb;case fb:return j;case gb:return m;default:return l}},b.inflateSetDictionary=function(a,b,c){var d=0,e=c;return a&&a.istate&&a.istate.mode==db?(e>=1<e;)b.read_byte(d)==hb[e]?e++:e=0!==b.read_byte(d)?0:4-e,d++,c--;return b.total_in+=d-b.next_in_index,b.next_in_index=d,b.avail_in=c,b.istate.marker=e,4!=e?m:(f=b.total_in,g=b.total_out,a(b),b.total_in=f,b.total_out=g,b.istate.mode=eb,i)},b.inflateSyncPoint=function(a){return a&&a.istate&&a.istate.blocks?a.istate.blocks.sync_point():l}}function f(){}function g(){var a=this,b=new f,c=512,d=r,e=new Uint8Array(c),g=!1;b.inflateInit(),b.next_out=e,a.append=function(a,f){var h,k,l=[],m=0,n=0,p=0;if(0!==a.length){b.next_in_index=0,b.next_in=a,b.avail_in=a.length;do{if(b.next_out_index=0,b.avail_out=c,0!==b.avail_in||g||(b.next_in_index=0,g=!0),h=b.inflate(d),g&&h==o)return-1;if(h!=i&&h!=j)throw"inflating: "+b.msg;if((g||h==j)&&b.avail_in==a.length)return-1;b.next_out_index&&l.push(b.next_out_index==c?new Uint8Array(e):new Uint8Array(e.subarray(0,b.next_out_index))),p+=b.next_out_index,f&&b.next_in_index>0&&b.next_in_index!=m&&(f(b.next_in_index),m=b.next_in_index)}while(b.avail_in>0||0===b.avail_out);return k=new Uint8Array(p),l.forEach(function(a){k.set(a,n),n+=a.length}),k}},a.flush=function(){b.inflateEnd()}}var h=15,i=0,j=1,k=2,l=-2,m=-3,n=-4,o=-5,p=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535],q=1440,r=0,s=4,t=9,u=5,v=[96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,192,80,7,10,0,8,96,0,8,32,0,9,160,0,8,0,0,8,128,0,8,64,0,9,224,80,7,6,0,8,88,0,8,24,0,9,144,83,7,59,0,8,120,0,8,56,0,9,208,81,7,17,0,8,104,0,8,40,0,9,176,0,8,8,0,8,136,0,8,72,0,9,240,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,200,81,7,13,0,8,100,0,8,36,0,9,168,0,8,4,0,8,132,0,8,68,0,9,232,80,7,8,0,8,92,0,8,28,0,9,152,84,7,83,0,8,124,0,8,60,0,9,216,82,7,23,0,8,108,0,8,44,0,9,184,0,8,12,0,8,140,0,8,76,0,9,248,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,196,81,7,11,0,8,98,0,8,34,0,9,164,0,8,2,0,8,130,0,8,66,0,9,228,80,7,7,0,8,90,0,8,26,0,9,148,84,7,67,0,8,122,0,8,58,0,9,212,82,7,19,0,8,106,0,8,42,0,9,180,0,8,10,0,8,138,0,8,74,0,9,244,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,204,81,7,15,0,8,102,0,8,38,0,9,172,0,8,6,0,8,134,0,8,70,0,9,236,80,7,9,0,8,94,0,8,30,0,9,156,84,7,99,0,8,126,0,8,62,0,9,220,82,7,27,0,8,110,0,8,46,0,9,188,0,8,14,0,8,142,0,8,78,0,9,252,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,194,80,7,10,0,8,97,0,8,33,0,9,162,0,8,1,0,8,129,0,8,65,0,9,226,80,7,6,0,8,89,0,8,25,0,9,146,83,7,59,0,8,121,0,8,57,0,9,210,81,7,17,0,8,105,0,8,41,0,9,178,0,8,9,0,8,137,0,8,73,0,9,242,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,202,81,7,13,0,8,101,0,8,37,0,9,170,0,8,5,0,8,133,0,8,69,0,9,234,80,7,8,0,8,93,0,8,29,0,9,154,84,7,83,0,8,125,0,8,61,0,9,218,82,7,23,0,8,109,0,8,45,0,9,186,0,8,13,0,8,141,0,8,77,0,9,250,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,198,81,7,11,0,8,99,0,8,35,0,9,166,0,8,3,0,8,131,0,8,67,0,9,230,80,7,7,0,8,91,0,8,27,0,9,150,84,7,67,0,8,123,0,8,59,0,9,214,82,7,19,0,8,107,0,8,43,0,9,182,0,8,11,0,8,139,0,8,75,0,9,246,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,206,81,7,15,0,8,103,0,8,39,0,9,174,0,8,7,0,8,135,0,8,71,0,9,238,80,7,9,0,8,95,0,8,31,0,9,158,84,7,99,0,8,127,0,8,63,0,9,222,82,7,27,0,8,111,0,8,47,0,9,190,0,8,15,0,8,143,0,8,79,0,9,254,96,7,256,0,8,80,0,8,16,84,8,115,82,7,31,0,8,112,0,8,48,0,9,193,80,7,10,0,8,96,0,8,32,0,9,161,0,8,0,0,8,128,0,8,64,0,9,225,80,7,6,0,8,88,0,8,24,0,9,145,83,7,59,0,8,120,0,8,56,0,9,209,81,7,17,0,8,104,0,8,40,0,9,177,0,8,8,0,8,136,0,8,72,0,9,241,80,7,4,0,8,84,0,8,20,85,8,227,83,7,43,0,8,116,0,8,52,0,9,201,81,7,13,0,8,100,0,8,36,0,9,169,0,8,4,0,8,132,0,8,68,0,9,233,80,7,8,0,8,92,0,8,28,0,9,153,84,7,83,0,8,124,0,8,60,0,9,217,82,7,23,0,8,108,0,8,44,0,9,185,0,8,12,0,8,140,0,8,76,0,9,249,80,7,3,0,8,82,0,8,18,85,8,163,83,7,35,0,8,114,0,8,50,0,9,197,81,7,11,0,8,98,0,8,34,0,9,165,0,8,2,0,8,130,0,8,66,0,9,229,80,7,7,0,8,90,0,8,26,0,9,149,84,7,67,0,8,122,0,8,58,0,9,213,82,7,19,0,8,106,0,8,42,0,9,181,0,8,10,0,8,138,0,8,74,0,9,245,80,7,5,0,8,86,0,8,22,192,8,0,83,7,51,0,8,118,0,8,54,0,9,205,81,7,15,0,8,102,0,8,38,0,9,173,0,8,6,0,8,134,0,8,70,0,9,237,80,7,9,0,8,94,0,8,30,0,9,157,84,7,99,0,8,126,0,8,62,0,9,221,82,7,27,0,8,110,0,8,46,0,9,189,0,8,14,0,8,142,0,8,78,0,9,253,96,7,256,0,8,81,0,8,17,85,8,131,82,7,31,0,8,113,0,8,49,0,9,195,80,7,10,0,8,97,0,8,33,0,9,163,0,8,1,0,8,129,0,8,65,0,9,227,80,7,6,0,8,89,0,8,25,0,9,147,83,7,59,0,8,121,0,8,57,0,9,211,81,7,17,0,8,105,0,8,41,0,9,179,0,8,9,0,8,137,0,8,73,0,9,243,80,7,4,0,8,85,0,8,21,80,8,258,83,7,43,0,8,117,0,8,53,0,9,203,81,7,13,0,8,101,0,8,37,0,9,171,0,8,5,0,8,133,0,8,69,0,9,235,80,7,8,0,8,93,0,8,29,0,9,155,84,7,83,0,8,125,0,8,61,0,9,219,82,7,23,0,8,109,0,8,45,0,9,187,0,8,13,0,8,141,0,8,77,0,9,251,80,7,3,0,8,83,0,8,19,85,8,195,83,7,35,0,8,115,0,8,51,0,9,199,81,7,11,0,8,99,0,8,35,0,9,167,0,8,3,0,8,131,0,8,67,0,9,231,80,7,7,0,8,91,0,8,27,0,9,151,84,7,67,0,8,123,0,8,59,0,9,215,82,7,19,0,8,107,0,8,43,0,9,183,0,8,11,0,8,139,0,8,75,0,9,247,80,7,5,0,8,87,0,8,23,192,8,0,83,7,51,0,8,119,0,8,55,0,9,207,81,7,15,0,8,103,0,8,39,0,9,175,0,8,7,0,8,135,0,8,71,0,9,239,80,7,9,0,8,95,0,8,31,0,9,159,84,7,99,0,8,127,0,8,63,0,9,223,82,7,27,0,8,111,0,8,47,0,9,191,0,8,15,0,8,143,0,8,79,0,9,255],w=[80,5,1,87,5,257,83,5,17,91,5,4097,81,5,5,89,5,1025,85,5,65,93,5,16385,80,5,3,88,5,513,84,5,33,92,5,8193,82,5,9,90,5,2049,86,5,129,192,5,24577,80,5,2,87,5,385,83,5,25,91,5,6145,81,5,7,89,5,1537,85,5,97,93,5,24577,80,5,4,88,5,769,84,5,49,92,5,12289,82,5,13,90,5,3073,86,5,193,192,5,24577],x=[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,0,0],y=[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,112,112],z=[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],A=[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],B=15;b.inflate_trees_fixed=function(a,b,c,d){return a[0]=t,b[0]=u,c[0]=v,d[0]=w,i};var C=0,D=1,E=2,F=3,G=4,H=5,I=6,J=7,K=8,L=9,M=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],N=0,O=1,P=2,Q=3,R=4,S=5,T=6,U=7,V=8,W=9,X=32,Y=8,Z=0,$=1,_=2,ab=3,bb=4,cb=5,db=6,eb=7,fb=12,gb=13,hb=[0,0,255,255];f.prototype={inflateInit:function(a){var b=this;return b.istate=new e,a||(a=h),b.istate.inflateInit(b,a)},inflate:function(a){var b=this;return b.istate?b.istate.inflate(b,a):l},inflateEnd:function(){var a=this;if(!a.istate)return l;var b=a.istate.inflateEnd(a);return a.istate=null,b},inflateSync:function(){var a=this;return a.istate?a.istate.inflateSync(a):l},inflateSetDictionary:function(a,b){var c=this;return c.istate?c.istate.inflateSetDictionary(c,a,b):l},read_byte:function(a){var b=this;return b.next_in.subarray(a,a+1)[0]},read_buf:function(a,b){var c=this;return c.next_in.subarray(a,a+b)}};var ib;a.zip?a.zip.Inflater=g:(ib=new g,a.addEventListener("message",function(b){var c=b.data;c.append&&a.postMessage({onappend:!0,data:ib.append(c.data,function(b){a.postMessage({progress:!0,current:b})})}),c.flush&&(ib.flush(),a.postMessage({onflush:!0}))},!1))}(this); +//# sourceMappingURL=inflate.map \ No newline at end of file diff --git a/epub.js/libs/inflate.map b/epub.js/libs/inflate.map new file mode 100644 index 0000000..dc48317 --- /dev/null +++ b/epub.js/libs/inflate.map @@ -0,0 +1 @@ +{"version":3,"file":"inflate.js","sources":["../../libs/zip/inflate.js"],"names":["obj","InfTree","huft_build","b","bindex","n","s","d","e","t","m","hp","hn","v","a","f","g","h","i","j","k","l","mask","p","q","w","xp","y","z","c","Z_OK","BMAX","Z_DATA_ERROR","x","u","MANY","r","set","Z_BUF_ERROR","initWorkArea","vsize","Int32Array","length","subarray","that","this","inflate_trees_bits","bb","tb","result","msg","inflate_trees_dynamic","nl","nd","bl","bd","tl","td","cplens","cplext","Z_MEM_ERROR","cpdist","cpdext","InfCodes","inflate_fast","tl_index","td_index","tp","tp_index","ml","md","tp_index_t_3","next_in_index","avail_in","bitb","bitk","write","read","end","inflate_mask","read_byte","window","total_in","Z_STREAM_END","mode","tree","ltree","dtree","len","tree_index","need","lit","get","dist","lbits","dbits","ltree_index","dtree_index","init","START","proc","tindex","WASH","BADCODE","LEN","inflate_flush","LIT","LENEXT","DIST","DISTEXT","COPY","END","Z_STREAM_ERROR","free","InfBlocks","blens","TYPE","left","table","index","codes","last","hufts","check","inftree","Uint8Array","reset","CODES","next_out_index","avail_out","total_out","next_out","LENS","inflate_trees_fixed","TABLE","BADBLOCKS","STORED","DRY","read_buf","BTREE","border","DTREE","bl_","bd_","tl_","td_","DONELOCKS","set_dictionary","start","sync_point","Inflate","inflateReset","istate","BLOCKS","blocks","method","was","marker","wbits","inflateEnd","inflateInit","inflate","next_in","Z_FINISH","METHOD","Z_DEFLATED","BAD","FLAG","PRESET_DICT","DICT4","DICT3","DICT2","DICT1","DICT0","Z_NEED_DICT","DONE","inflateSetDictionary","dictionary","dictLength","inflateSync","mark","inflateSyncPoint","ZStream","Inflater","bufsize","flush","Z_NO_FLUSH","buf","nomoreinput","append","data","onprogress","err","array","buffers","lastIndex","bufferIndex","bufferSize","push","forEach","chunk","MAX_BITS","fixed_bl","fixed_bd","fixed_tl","fixed_td","prototype","bits","ret","size","inflater","zip","addEventListener","event","message","postMessage","onappend","current","progress","onflush"],"mappings":"CAmCA,SAAUA,GAqFT,QAASC,KAUR,QAASC,GAAWC,EAEpBC,EAAQC,EACRC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,GAWC,GAAIC,GACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,CAIJL,GAAI,EACJL,EAAIb,CACJ,GACCwB,GAAE1B,EAAEC,EAASmB,MACbA,IACAL,UACc,IAANA,EAET,IAAIW,EAAE,IAAMxB,EAGX,MAFAI,GAAE,GAAK,GACPC,EAAE,GAAK,EACAoB,CAKR,KADAT,EAAIX,EAAE,GACDS,EAAI,EAAQY,GAALZ,GACE,IAATU,EAAEV,GADgBA,KAOvB,IAJAC,EAAID,EACIA,EAAJE,IACHA,EAAIF,GAEAD,EAAIa,EAAY,IAANb,GACD,IAATW,EAAEX,GADiBA,KAWxB,IAPAF,EAAIE,EACAG,EAAIH,IACPG,EAAIH,GAELR,EAAE,GA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DV,SAAW,SAASU,EAAO6D,GAC1B,GAAIrK,GAAOC,IACX,OAAOD,GAAKsH,QAAQvH,SAASyG,EAAOA,EAAQ6D,IA6D9C,IAAIC,GAEAlN,GAAImN,IACPnN,EAAImN,IAAI5B,SAAWA,GAEnB2B,GAAW,GAAI3B,GACfvL,EAAIoN,iBAAiB,UAAW,SAASC,GACxC,GAAIC,GAAUD,EAAMvB,IAEhBwB,GAAQzB,QACX7L,EAAIuN,aACHC,UAAW,EACX1B,KAAOoB,GAASrB,OAAOyB,EAAQxB,KAAM,SAAS2B,GAC7CzN,EAAIuN,aACHG,UAAW,EACXD,QAAUA,QAIVH,EAAQ7B,QACXyB,GAASzB,QACTzL,EAAIuN,aACHI,SAAU,OAGV,KAGF9K"} \ No newline at end of file diff --git a/epub.js/libs/jquery-2.1.0.min.js b/epub.js/libs/jquery-2.1.0.min.js new file mode 100644 index 0000000..cbe6abe --- /dev/null +++ b/epub.js/libs/jquery-2.1.0.min.js @@ -0,0 +1,4 @@ +/*! jQuery v2.1.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */ +!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m=a.document,n="2.1.0",o=function(a,b){return new o.fn.init(a,b)},p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};o.fn=o.prototype={jquery:n,constructor:o,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=o.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return o.each(this,a,b)},map:function(a){return this.pushStack(o.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},o.extend=o.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||o.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(o.isPlainObject(d)||(e=o.isArray(d)))?(e?(e=!1,f=c&&o.isArray(c)?c:[]):f=c&&o.isPlainObject(c)?c:{},g[b]=o.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},o.extend({expando:"jQuery"+(n+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===o.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isPlainObject:function(a){if("object"!==o.type(a)||a.nodeType||o.isWindow(a))return!1;try{if(a.constructor&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(b){return!1}return!0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=o.trim(a),a&&(1===a.indexOf("use strict")?(b=m.createElement("script"),b.text=a,m.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":k.call(a)},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?o.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:g.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(c=a[b],b=a,a=c),o.isFunction(a)?(e=d.call(arguments,2),f=function(){return a.apply(b||this,e.concat(d.call(arguments)))},f.guid=a.guid=a.guid||o.guid++,f):void 0},now:Date.now,support:l}),o.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=o.type(a);return"function"===c||o.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="
",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);o.find=t,o.expr=t.selectors,o.expr[":"]=o.expr.pseudos,o.unique=t.uniqueSort,o.text=t.getText,o.isXMLDoc=t.isXML,o.contains=t.contains;var u=o.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(o.isFunction(b))return o.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return o.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return o.filter(b,a,c);b=o.filter(b,a)}return o.grep(a,function(a){return g.call(b,a)>=0!==c})}o.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?o.find.matchesSelector(d,a)?[d]:[]:o.find.matches(a,o.grep(b,function(a){return 1===a.nodeType}))},o.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(o(a).filter(function(){for(b=0;c>b;b++)if(o.contains(e[b],this))return!0}));for(b=0;c>b;b++)o.find(a,e[b],d);return d=this.pushStack(c>1?o.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?o(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=o.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof o?b[0]:b,o.merge(this,o.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:m,!0)),v.test(c[1])&&o.isPlainObject(b))for(c in b)o.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=m.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=m,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):o.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(o):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),o.makeArray(a,this))};A.prototype=o.fn,y=o(m);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};o.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&o(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),o.fn.extend({has:function(a){var b=o(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(o.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?o(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&o.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?o.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(o(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(o.unique(o.merge(this.get(),o(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}o.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return o.dir(a,"parentNode")},parentsUntil:function(a,b,c){return o.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return o.dir(a,"nextSibling")},prevAll:function(a){return o.dir(a,"previousSibling")},nextUntil:function(a,b,c){return o.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return o.dir(a,"previousSibling",c)},siblings:function(a){return o.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return o.sibling(a.firstChild)},contents:function(a){return a.contentDocument||o.merge([],a.childNodes)}},function(a,b){o.fn[a]=function(c,d){var e=o.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=o.filter(d,e)),this.length>1&&(C[a]||o.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return o.each(a.match(E)||[],function(a,c){b[c]=!0}),b}o.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):o.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){o.each(b,function(b,c){var d=o.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&o.each(arguments,function(a,b){var c;while((c=o.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?o.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},o.extend({Deferred:function(a){var b=[["resolve","done",o.Callbacks("once memory"),"resolved"],["reject","fail",o.Callbacks("once memory"),"rejected"],["notify","progress",o.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return o.Deferred(function(c){o.each(b,function(b,f){var g=o.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&o.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?o.extend(a,d):d}},e={};return d.pipe=d.then,o.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&o.isFunction(a.promise)?e:0,g=1===f?a:o.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&o.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;o.fn.ready=function(a){return o.ready.promise().done(a),this},o.extend({isReady:!1,readyWait:1,holdReady:function(a){a?o.readyWait++:o.ready(!0)},ready:function(a){(a===!0?--o.readyWait:o.isReady)||(o.isReady=!0,a!==!0&&--o.readyWait>0||(H.resolveWith(m,[o]),o.fn.trigger&&o(m).trigger("ready").off("ready")))}});function I(){m.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),o.ready()}o.ready.promise=function(b){return H||(H=o.Deferred(),"complete"===m.readyState?setTimeout(o.ready):(m.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},o.ready.promise();var J=o.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===o.type(c)){e=!0;for(h in c)o.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,o.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(o(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};o.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=o.expando+Math.random()}K.uid=1,K.accepts=o.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,o.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(o.isEmptyObject(f))o.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,o.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{o.isArray(b)?d=b.concat(b.map(o.camelCase)):(e=o.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!o.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?o.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}o.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c)},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),o.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length; +while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=o.camelCase(d.slice(5)),P(f,d,e[d]));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=o.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),o.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||o.isArray(c)?d=L.access(a,b,o.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=o.queue(a,b),d=c.length,e=c.shift(),f=o._queueHooks(a,b),g=function(){o.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:o.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),o.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";l.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return m.activeElement}catch(a){}}o.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=o.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof o!==U&&o.event.triggered!==b.type?o.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n&&(l=o.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=o.event.special[n]||{},k=o.extend({type:n,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&o.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(n,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),o.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],n=q=h[1],p=(h[2]||"").split(".").sort(),n){l=o.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||o.removeEvent(a,n,r.handle),delete i[n])}else for(n in i)o.event.remove(a,n+b[j],c,d,!0);o.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,p=[d||m],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||m,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+o.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[o.expando]?b:new o.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:o.makeArray(c,[b]),n=o.event.special[q]||{},e||!n.trigger||n.trigger.apply(d,c)!==!1)){if(!e&&!n.noBubble&&!o.isWindow(d)){for(i=n.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||m)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:n.bindType||q,l=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),l&&l.apply(g,c),l=k&&g[k],l&&l.apply&&o.acceptData(g)&&(b.result=l.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||n._default&&n._default.apply(p.pop(),c)!==!1||!o.acceptData(d)||k&&o.isFunction(d[q])&&!o.isWindow(d)&&(h=d[k],h&&(d[k]=null),o.event.triggered=q,d[q](),o.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=o.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=o.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=o.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((o.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?o(e,this).index(i)>=0:o.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return o.nodeName(a,"table")&&o.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)o.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=o.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&o.nodeName(a,b)?o.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}o.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=o.contains(a.ownerDocument,a);if(!(l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||o.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,n=a.length;n>m;m++)if(e=a[m],e||0===e)if("object"===o.type(e))o.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;o.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===o.inArray(e,d))&&(i=o.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f,g,h=o.event.special,i=0;void 0!==(c=a[i]);i++){if(o.acceptData(c)&&(f=c[L.expando],f&&(b=L.cache[f]))){if(d=Object.keys(b.events||{}),d.length)for(g=0;void 0!==(e=d[g]);g++)h[e]?o.event.remove(c,e):o.removeEvent(c,e,b.handle);L.cache[f]&&delete L.cache[f]}delete M.cache[c[M.expando]]}}}),o.fn.extend({text:function(a){return J(this,function(a){return void 0===a?o.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?o.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||o.cleanData(ob(c)),c.parentNode&&(b&&o.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(o.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return o.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(o.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,o.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,n=k-1,p=a[0],q=o.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(c=o.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=o.map(ob(c,"script"),kb),g=f.length;k>j;j++)h=c,j!==n&&(h=o.clone(h,!0,!0),g&&o.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,o.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&o.contains(i,h)&&(h.src?o._evalUrl&&o._evalUrl(h.src):o.globalEval(h.textContent.replace(hb,"")))}return this}}),o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){o.fn[a]=function(a){for(var c,d=[],e=o(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),o(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d=o(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:o.css(d[0],"display");return d.detach(),e}function tb(a){var b=m,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||o("