From 730b06f32b0f162b0a47124d9a0538ef8f7608e8 Mon Sep 17 00:00:00 2001 From: Fred Chasen Date: Mon, 24 Oct 2016 16:42:59 +0200 Subject: [PATCH] Move views and helpers into managers --- .gitignore | 3 +- dist/epub.js | 5684 +++++++++++++-------------- dist/epub.js.map | 2 +- src/epub.js | 4 +- src/{ => managers/helpers}/stage.js | 2 +- src/{ => managers/helpers}/views.js | 0 src/managers/single.js | 14 +- src/{ => managers}/views/iframe.js | 6 +- src/{ => managers}/views/inline.js | 6 +- src/rendition.js | 12 +- 10 files changed, 2867 insertions(+), 2866 deletions(-) rename src/{ => managers/helpers}/stage.js (99%) rename src/{ => managers/helpers}/views.js (100%) rename src/{ => managers}/views/iframe.js (99%) rename src/{ => managers}/views/inline.js (98%) diff --git a/.gitignore b/.gitignore index 0de481a..51cf65b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ node_modules/ components node_modules -bower_components \ No newline at end of file +bower_components +books diff --git a/dist/epub.js b/dist/epub.js index 65d3572..620bdac 100644 --- a/dist/epub.js +++ b/dist/epub.js @@ -5775,7 +5775,7 @@ RSVP.on('rejected', function(event){ console.error(event.detail.message, event.detail.stack); }); -},{"./core":10,"./epubcfi":11,"./locations":14,"./navigation":18,"./parser":19,"./rendition":21,"./request":23,"./spine":25,"./unarchive":27,"rsvp":5,"urijs":7}],9:[function(require,module,exports){ +},{"./core":10,"./epubcfi":11,"./locations":14,"./navigation":21,"./parser":22,"./rendition":24,"./request":26,"./spine":28,"./unarchive":29,"rsvp":5,"urijs":7}],9:[function(require,module,exports){ var RSVP = require('rsvp'); var core = require('./core'); var EpubCFI = require('./epubcfi'); @@ -6441,7 +6441,7 @@ RSVP.EventTarget.mixin(Contents.prototype); module.exports = Contents; -},{"./core":10,"./epubcfi":11,"./mapping":17,"rsvp":5}],10:[function(require,module,exports){ +},{"./core":10,"./epubcfi":11,"./mapping":20,"rsvp":5}],10:[function(require,module,exports){ var RSVP = require('rsvp'); var base64 = require('base64-js'); @@ -8332,7 +8332,7 @@ RSVP.EventTarget.mixin(Locations.prototype); module.exports = Locations; -},{"./core":10,"./epubcfi":11,"./queue":20,"rsvp":5}],15:[function(require,module,exports){ +},{"./core":10,"./epubcfi":11,"./queue":23,"rsvp":5}],15:[function(require,module,exports){ var RSVP = require('rsvp'); var core = require('../core'); var SingleViewManager = require('./single'); @@ -9014,15 +9014,417 @@ ContinuousViewManager.prototype.updateFlow = function(flow){ }; module.exports = ContinuousViewManager; -},{"../core":10,"./single":16,"rsvp":5}],16:[function(require,module,exports){ +},{"../core":10,"./single":18,"rsvp":5}],16:[function(require,module,exports){ +var core = require('../../core'); + +function Stage(_options) { + this.settings = _options || {}; + this.id = "epubjs-container-" + core.uuid(); + + this.container = this.create(this.settings); + + if(this.settings.hidden) { + this.wrapper = this.wrap(this.container); + } + +} + +/** +* Creates an element to render to. +* Resizes to passed width and height or to the elements size +*/ +Stage.prototype.create = function(options){ + var height = options.height;// !== false ? options.height : "100%"; + var width = options.width;// !== false ? options.width : "100%"; + var overflow = options.overflow || false; + var axis = options.axis || "vertical"; + + if(options.height && core.isNumber(options.height)) { + height = options.height + "px"; + } + + if(options.width && core.isNumber(options.width)) { + width = options.width + "px"; + } + + // Create new container element + container = document.createElement("div"); + + container.id = this.id; + container.classList.add("epub-container"); + + // Style Element + // container.style.fontSize = "0"; + container.style.wordSpacing = "0"; + container.style.lineHeight = "0"; + container.style.verticalAlign = "top"; + + if(axis === "horizontal") { + container.style.whiteSpace = "nowrap"; + } + + if(width){ + container.style.width = width; + } + + if(height){ + container.style.height = height; + } + + if (overflow) { + container.style.overflow = overflow; + } + + return container; +}; + +Stage.wrap = function(container) { + var wrapper = document.createElement("div"); + + wrapper.style.visibility = "hidden"; + wrapper.style.overflow = "hidden"; + wrapper.style.width = "0"; + wrapper.style.height = "0"; + + wrapper.appendChild(container); + return wrapper; +}; + + +Stage.prototype.getElement = function(_element){ + var element; + + if(core.isElement(_element)) { + element = _element; + } else if (typeof _element === "string") { + element = document.getElementById(_element); + } + + if(!element){ + console.error("Not an Element"); + return; + } + + return element; +}; + +Stage.prototype.attachTo = function(what){ + + var element = this.getElement(what); + var base; + + if(!element){ + return; + } + + if(this.settings.hidden) { + base = this.wrapper; + } else { + base = this.container; + } + + element.appendChild(base); + + this.element = element; + + return element; + +}; + +Stage.prototype.getContainer = function() { + return this.container; +}; + +Stage.prototype.onResize = function(func){ + // Only listen to window for resize event if width and height are not fixed. + // This applies if it is set to a percent or auto. + if(!core.isNumber(this.settings.width) || + !core.isNumber(this.settings.height) ) { + window.addEventListener("resize", func, false); + } + +}; + +Stage.prototype.size = function(width, height){ + var bounds; + // var width = _width || this.settings.width; + // var height = _height || this.settings.height; + + // If width or height are set to false, inherit them from containing element + if(width === null) { + bounds = this.element.getBoundingClientRect(); + + if(bounds.width) { + width = bounds.width; + this.container.style.width = bounds.width + "px"; + } + } + + if(height === null) { + bounds = bounds || this.element.getBoundingClientRect(); + + if(bounds.height) { + height = bounds.height; + this.container.style.height = bounds.height + "px"; + } + + } + + if(!core.isNumber(width)) { + bounds = this.container.getBoundingClientRect(); + width = bounds.width; + //height = bounds.height; + } + + if(!core.isNumber(height)) { + bounds = bounds || this.container.getBoundingClientRect(); + //width = bounds.width; + height = bounds.height; + } + + + this.containerStyles = window.getComputedStyle(this.container); + + this.containerPadding = { + left: parseFloat(this.containerStyles["padding-left"]) || 0, + right: parseFloat(this.containerStyles["padding-right"]) || 0, + top: parseFloat(this.containerStyles["padding-top"]) || 0, + bottom: parseFloat(this.containerStyles["padding-bottom"]) || 0 + }; + + return { + width: width - + this.containerPadding.left - + this.containerPadding.right, + height: height - + this.containerPadding.top - + this.containerPadding.bottom + }; + +}; + +Stage.prototype.bounds = function(){ + + if(!this.container) { + return core.windowBounds(); + } else { + return this.container.getBoundingClientRect(); + } + +} + +Stage.prototype.getSheet = function(){ + var style = document.createElement("style"); + + // WebKit hack --> https://davidwalsh.name/add-rules-stylesheets + style.appendChild(document.createTextNode("")); + + document.head.appendChild(style); + + return style.sheet; +} + +Stage.prototype.addStyleRules = function(selector, rulesArray){ + var scope = "#" + this.id + " "; + var rules = ""; + + if(!this.sheet){ + this.sheet = this.getSheet(); + } + + rulesArray.forEach(function(set) { + for (var prop in set) { + if(set.hasOwnProperty(prop)) { + rules += prop + ":" + set[prop] + ";"; + } + } + }) + + this.sheet.insertRule(scope + selector + " {" + rules + "}", 0); +} + + + +module.exports = Stage; + +},{"../../core":10}],17:[function(require,module,exports){ +function Views(container) { + this.container = container; + this._views = []; + this.length = 0; + this.hidden = false; +}; + +Views.prototype.all = function() { + return this._views; +}; + +Views.prototype.first = function() { + return this._views[0]; +}; + +Views.prototype.last = function() { + return this._views[this._views.length-1]; +}; + +Views.prototype.indexOf = function(view) { + return this._views.indexOf(view); +}; + +Views.prototype.slice = function() { + return this._views.slice.apply(this._views, arguments); +}; + +Views.prototype.get = function(i) { + return this._views[i]; +}; + +Views.prototype.append = function(view){ + this._views.push(view); + if(this.container){ + this.container.appendChild(view.element); + } + this.length++; + return view; +}; + +Views.prototype.prepend = function(view){ + this._views.unshift(view); + if(this.container){ + this.container.insertBefore(view.element, this.container.firstChild); + } + this.length++; + return view; +}; + +Views.prototype.insert = function(view, index) { + this._views.splice(index, 0, view); + + if(this.container){ + if(index < this.container.children.length){ + this.container.insertBefore(view.element, this.container.children[index]); + } else { + this.container.appendChild(view.element); + } + } + + this.length++; + return view; +}; + +Views.prototype.remove = function(view) { + var index = this._views.indexOf(view); + + if(index > -1) { + this._views.splice(index, 1); + } + + + this.destroy(view); + + this.length--; +}; + +Views.prototype.destroy = function(view) { + view.off("resized"); + + if(view.displayed){ + view.destroy(); + } + + if(this.container){ + this.container.removeChild(view.element); + } + view = null; +}; + +// Iterators + +Views.prototype.each = function() { + return this._views.forEach.apply(this._views, arguments); +}; + +Views.prototype.clear = function(){ + // Remove all views + var view; + var len = this.length; + + if(!this.length) return; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + this.destroy(view); + } + + this._views = []; + this.length = 0; +}; + +Views.prototype.find = function(section){ + + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if(view.displayed && view.section.index == section.index) { + return view; + } + } + +}; + +Views.prototype.displayed = function(){ + var displayed = []; + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if(view.displayed){ + displayed.push(view); + } + } + return displayed; +}; + +Views.prototype.show = function(){ + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if(view.displayed){ + view.show(); + } + } + this.hidden = false; +}; + +Views.prototype.hide = function(){ + var view; + var len = this.length; + + for (var i = 0; i < len; i++) { + view = this._views[i]; + if(view.displayed){ + view.hide(); + } + } + this.hidden = true; +}; + +module.exports = Views; + +},{}],18:[function(require,module,exports){ var RSVP = require('rsvp'); var core = require('../core'); -var Stage = require('../stage'); -var Views = require('../views'); var EpubCFI = require('../epubcfi'); // var Layout = require('../layout'); var Mapping = require('../mapping'); var Queue = require('../queue'); +var Stage = require('./helpers/stage'); +var Views = require('./helpers/views'); function SingleViewManager(options) { @@ -9106,6 +9508,16 @@ SingleViewManager.prototype.destroy = function(){ // this.views.each(function(view){ // view.destroy(); // }); + + /* + + clearTimeout(this.trimTimeout); + if(this.settings.hidden) { + this.element.removeChild(this.wrapper); + } else { + this.element.removeChild(this.container); + } + */ }; SingleViewManager.prototype.onResized = function(e) { @@ -9550,2839 +9962,11 @@ SingleViewManager.prototype.updateFlow = function(flow){ module.exports = SingleViewManager; -},{"../core":10,"../epubcfi":11,"../mapping":17,"../queue":20,"../stage":26,"../views":28,"rsvp":5}],17:[function(require,module,exports){ -var EpubCFI = require('./epubcfi'); - -function Mapping(layout){ - this.layout = layout; -}; - -Mapping.prototype.section = function(view) { - var ranges = this.findRanges(view); - var map = this.rangeListToCfiList(view.section.cfiBase, ranges); - - return map; -}; - -Mapping.prototype.page = function(contents, cfiBase, start, end) { - var root = contents && contents.document ? contents.document.body : false; - - if (!root) { - return; - } - - return this.rangePairToCfiPair(cfiBase, { - start: this.findStart(root, start, end), - end: this.findEnd(root, start, end) - }); -}; - -Mapping.prototype.walk = function(root, func) { - //var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false); - var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { - acceptNode: function (node) { - if ( node.data.trim().length > 0 ) { - return NodeFilter.FILTER_ACCEPT; - } else { - return NodeFilter.FILTER_REJECT; - } - } - }, false); - var node; - var result; - while ((node = treeWalker.nextNode())) { - result = func(node); - if(result) break; - } - - return result; -}; - -Mapping.prototype.findRanges = function(view){ - var columns = []; - var scrollWidth = view.contents.scrollWidth(); - var count = this.layout.count(scrollWidth); - var column = this.layout.column; - var gap = this.layout.gap; - var start, end; - - for (var i = 0; i < count.pages; i++) { - start = (column + gap) * i; - end = (column * (i+1)) + (gap * i); - columns.push({ - start: this.findStart(view.document.body, start, end), - end: this.findEnd(view.document.body, start, end) - }); - } - - return columns; -}; - -Mapping.prototype.findStart = function(root, start, end){ - var stack = [root]; - var $el; - var found; - var $prev = root; - while (stack.length) { - - $el = stack.shift(); - - found = this.walk($el, function(node){ - var left, right; - var elPos; - var elRange; - - - if(node.nodeType == Node.TEXT_NODE){ - elRange = document.createRange(); - elRange.selectNodeContents(node); - elPos = elRange.getBoundingClientRect(); - } else { - elPos = node.getBoundingClientRect(); - } - - left = elPos.left; - right = elPos.right; - - if( left >= start && left <= end ) { - return node; - } else if (right > start) { - return node; - } else { - $prev = node; - stack.push(node); - } - - }); - - if(found) { - return this.findTextStartRange(found, start, end); - } - - } - - // Return last element - return this.findTextStartRange($prev, start, end); -}; - -Mapping.prototype.findEnd = function(root, start, end){ - var stack = [root]; - var $el; - var $prev = root; - var found; - - while (stack.length) { - - $el = stack.shift(); - - found = this.walk($el, function(node){ - - var left, right; - var elPos; - var elRange; - - - if(node.nodeType == Node.TEXT_NODE){ - elRange = document.createRange(); - elRange.selectNodeContents(node); - elPos = elRange.getBoundingClientRect(); - } else { - elPos = node.getBoundingClientRect(); - } - - left = elPos.left; - right = elPos.right; - - if(left > end && $prev) { - return $prev; - } else if(right > end) { - return node; - } else { - $prev = node; - stack.push(node); - } - - }); - - - if(found){ - return this.findTextEndRange(found, start, end); - } - - } - - // end of chapter - return this.findTextEndRange($prev, start, end); -}; - - -Mapping.prototype.findTextStartRange = function(node, start, end){ - var ranges = this.splitTextNodeIntoRanges(node); - var prev; - var range; - var pos; - - for (var i = 0; i < ranges.length; i++) { - range = ranges[i]; - - pos = range.getBoundingClientRect(); - - if( pos.left >= start ) { - return range; - } - - prev = range; - - } - - return ranges[0]; -}; - -Mapping.prototype.findTextEndRange = function(node, start, end){ - var ranges = this.splitTextNodeIntoRanges(node); - var prev; - var range; - var pos; - - for (var i = 0; i < ranges.length; i++) { - range = ranges[i]; - - pos = range.getBoundingClientRect(); - - if(pos.left > end && prev) { - return prev; - } else if(pos.right > end) { - return range; - } - - prev = range; - - } - - // Ends before limit - return ranges[ranges.length-1]; - -}; - -Mapping.prototype.splitTextNodeIntoRanges = function(node, _splitter){ - var ranges = []; - var textContent = node.textContent || ""; - var text = textContent.trim(); - var range; - var rect; - var list; - var doc = node.ownerDocument; - var splitter = _splitter || " "; - - pos = text.indexOf(splitter); - - if(pos === -1 || node.nodeType != Node.TEXT_NODE) { - range = doc.createRange(); - range.selectNodeContents(node); - return [range]; - } - - range = doc.createRange(); - range.setStart(node, 0); - range.setEnd(node, pos); - ranges.push(range); - range = false; - - while ( pos != -1 ) { - - pos = text.indexOf(splitter, pos + 1); - if(pos > 0) { - - if(range) { - range.setEnd(node, pos); - ranges.push(range); - } - - range = doc.createRange(); - range.setStart(node, pos+1); - } - } - - if(range) { - range.setEnd(node, text.length); - ranges.push(range); - } - - return ranges; -}; - - - -Mapping.prototype.rangePairToCfiPair = function(cfiBase, rangePair){ - - var startRange = rangePair.start; - var endRange = rangePair.end; - - startRange.collapse(true); - endRange.collapse(true); - - // startCfi = section.cfiFromRange(startRange); - // endCfi = section.cfiFromRange(endRange); - startCfi = new EpubCFI(startRange, cfiBase).toString(); - endCfi = new EpubCFI(endRange, cfiBase).toString(); - - return { - start: startCfi, - end: endCfi - }; - -}; - -Mapping.prototype.rangeListToCfiList = function(cfiBase, columns){ - var map = []; - var rangePair, cifPair; - - for (var i = 0; i < columns.length; i++) { - cifPair = this.rangePairToCfiPair(cfiBase, columns[i]); - - map.push(cifPair); - - } - - return map; -}; - -module.exports = Mapping; - -},{"./epubcfi":11}],18:[function(require,module,exports){ -var core = require('./core'); -var Parser = require('./parser'); +},{"../core":10,"../epubcfi":11,"../mapping":20,"../queue":23,"./helpers/stage":16,"./helpers/views":17,"rsvp":5}],19:[function(require,module,exports){ var RSVP = require('rsvp'); -var URI = require('urijs'); - -function Navigation(_package, _request){ - var navigation = this; - var parse = new Parser(); - var request = _request || require('./request'); - - this.package = _package; - this.toc = []; - this.tocByHref = {}; - this.tocById = {}; - - if(_package.navPath) { - this.navUrl = URI(_package.navPath).absoluteTo(_package.baseUrl).toString(); - this.nav = {}; - - this.nav.load = function(_request){ - var loading = new RSVP.defer(); - var loaded = loading.promise; - - request(navigation.navUrl, 'xml').then(function(xml){ - navigation.toc = parse.nav(xml); - navigation.loaded(navigation.toc); - loading.resolve(navigation.toc); - }); - - return loaded; - }; - - } - - if(_package.ncxPath) { - this.ncxUrl = URI(_package.ncxPath).absoluteTo(_package.baseUrl).toString(); - this.ncx = {}; - - this.ncx.load = function(_request){ - var loading = new RSVP.defer(); - var loaded = loading.promise; - - request(navigation.ncxUrl, 'xml').then(function(xml){ - navigation.toc = parse.toc(xml); - navigation.loaded(navigation.toc); - loading.resolve(navigation.toc); - }); - - return loaded; - }; - - } -}; - -// Load the navigation -Navigation.prototype.load = function(_request) { - var request = _request || require('./request'); - var loading, loaded; - - if(this.nav) { - loading = this.nav.load(); - } else if(this.ncx) { - loading = this.ncx.load(); - } else { - loaded = new RSVP.defer(); - loaded.resolve([]); - loading = loaded.promise; - } - - return loading; - -}; - -Navigation.prototype.loaded = function(toc) { - var item; - - for (var i = 0; i < toc.length; i++) { - item = toc[i]; - this.tocByHref[item.href] = i; - this.tocById[item.id] = i; - } - -}; - -// Get an item from the navigation -Navigation.prototype.get = function(target) { - var index; - - if(!target) { - return this.toc; - } - - if(target.indexOf("#") === 0) { - index = this.tocById[target.substring(1)]; - } else if(target in this.tocByHref){ - index = this.tocByHref[target]; - } - - return this.toc[index]; -}; - -module.exports = Navigation; - -},{"./core":10,"./parser":19,"./request":23,"rsvp":5,"urijs":7}],19:[function(require,module,exports){ -var URI = require('urijs'); -var core = require('./core'); -var EpubCFI = require('./epubcfi'); - - -function Parser(){}; - -Parser.prototype.container = function(containerXml){ - //-- - var rootfile, fullpath, folder, encoding; - - if(!containerXml) { - console.error("Container File Not Found"); - return; - } - - rootfile = core.qs(containerXml, "rootfile"); - - if(!rootfile) { - console.error("No RootFile Found"); - return; - } - - fullpath = rootfile.getAttribute('full-path'); - folder = URI(fullpath).directory(); - encoding = containerXml.xmlEncoding; - - //-- Now that we have the path we can parse the contents - return { - 'packagePath' : fullpath, - 'basePath' : folder, - 'encoding' : encoding - }; -}; - -Parser.prototype.identifier = function(packageXml){ - var metadataNode; - - if(!packageXml) { - console.error("Package File Not Found"); - return; - } - - metadataNode = core.qs(packageXml, "metadata"); - - if(!metadataNode) { - console.error("No Metadata Found"); - return; - } - - return this.getElementText(metadataNode, "identifier"); -}; - -Parser.prototype.packageContents = function(packageXml){ - var parse = this; - var metadataNode, manifestNode, spineNode; - var manifest, navPath, ncxPath, coverPath; - var spineNodeIndex; - var spine; - var spineIndexByURL; - var metadata; - - if(!packageXml) { - console.error("Package File Not Found"); - return; - } - - metadataNode = core.qs(packageXml, "metadata"); - if(!metadataNode) { - console.error("No Metadata Found"); - return; - } - - manifestNode = core.qs(packageXml, "manifest"); - if(!manifestNode) { - console.error("No Manifest Found"); - return; - } - - spineNode = core.qs(packageXml, "spine"); - if(!spineNode) { - console.error("No Spine Found"); - return; - } - - manifest = parse.manifest(manifestNode); - navPath = parse.findNavPath(manifestNode); - ncxPath = parse.findNcxPath(manifestNode, spineNode); - coverPath = parse.findCoverPath(packageXml); - - spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); - - spine = parse.spine(spineNode, manifest); - - metadata = parse.metadata(metadataNode); - - metadata.direction = spineNode.getAttribute("page-progression-direction"); - - return { - 'metadata' : metadata, - 'spine' : spine, - 'manifest' : manifest, - 'navPath' : navPath, - 'ncxPath' : ncxPath, - 'coverPath': coverPath, - 'spineNodeIndex' : spineNodeIndex - }; -}; - -//-- Find TOC NAV -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 ']"); - var node = core.qsp(manifestNode, "item", {"properties":"nav"}); - return node ? node.getAttribute('href') : false; -}; - -//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" -Parser.prototype.findNcxPath = function(manifestNode, spineNode){ - // var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); - var node = core.qsp(manifestNode, "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 + "']"); - node = manifestNode.getElementById(tocId); - } - } - - return node ? node.getAttribute('href') : false; -}; - -//-- Expanded to match Readium web components -Parser.prototype.metadata = function(xml){ - var metadata = {}, - p = this; - - metadata.title = 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.getPropertyText(xml, 'dcterms:modified'); - - metadata.layout = p.getPropertyText(xml, "rendition:layout"); - metadata.orientation = p.getPropertyText(xml, 'rendition:orientation'); - metadata.flow = p.getPropertyText(xml, 'rendition:flow'); - metadata.viewport = p.getPropertyText(xml, 'rendition:viewport'); - // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); - - return metadata; -}; - -//-- Find Cover: -//-- Fallback for Epub 2.0 -Parser.prototype.findCoverPath = function(packageXml){ - var pkg = core.qs(packageXml, "package"); - var epubVersion = pkg.getAttribute('version'); - - if (epubVersion === '2.0') { - var metaCover = core.qsp(packageXml, 'meta', {'name':'cover'}); - if (metaCover) { - var coverId = metaCover.getAttribute('content'); - // var cover = packageXml.querySelector("item[id='" + coverId + "']"); - var cover = packageXml.getElementById(coverId); - return cover ? cover.getAttribute('href') : false; - } - else { - return false; - } - } - else { - // var node = packageXml.querySelector("item[properties='cover-image']"); - var node = core.qsp(packageXml, 'item', {'properties':'cover-image'}); - return node ? node.getAttribute('href') : false; - } -}; - -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 ''; - -}; - -Parser.prototype.getPropertyText = function(xml, property){ - var el = core.qsp(xml, "meta", {"property":property}); - - if(el && el.childNodes.length){ - return el.childNodes[0].nodeValue; - } - - return ''; -}; - -Parser.prototype.querySelectorText = function(xml, q){ - var el = xml.querySelector(q); - - if(el && el.childNodes.length){ - return el.childNodes[0].nodeValue; - } - - return ''; -}; - -Parser.prototype.manifest = function(manifestXml){ - var manifest = {}; - - //-- Turn items into an array - // var selected = manifestXml.querySelectorAll("item"); - var selected = core.qsa(manifestXml, "item"); - var 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' : href, - 'type' : type, - 'properties' : properties.length ? properties.split(' ') : [] - }; - - }); - - return manifest; - -}; - -Parser.prototype.spine = function(spineXml, manifest){ - var spine = []; - - var selected = spineXml.getElementsByTagName("itemref"), - items = Array.prototype.slice.call(selected); - - var epubcfi = new EpubCFI(); - - //-- Add to array to mantain ordering and cross reference with manifest - items.forEach(function(item, index){ - var idref = 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 itemref = { - 'idref' : idref, - 'linear' : item.getAttribute('linear') || '', - 'properties' : propArray, - // 'href' : manifest[Id].href, - // 'url' : manifest[Id].url, - 'index' : index - // 'cfiBase' : cfiBase - }; - spine.push(itemref); - }); - - return spine; -}; - -Parser.prototype.querySelectorByType = function(html, element, type){ - var query; - if (typeof html.querySelector != "undefined") { - query = html.querySelector(element+'[*|type="'+type+'"]'); - } - // Handle IE not supporting namespaced epub:type in querySelector - if(!query || query.length === 0) { - query = core.qsa(html, element); - for (var i = 0; i < query.length; i++) { - if(query[i].getAttributeNS("http://www.idpf.org/2007/ops", "type") === type) { - return query[i]; - } - } - } else { - return query; - } -}; - -Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ - var navElement = this.querySelectorByType(navHtml, "nav", "toc"); - // var navItems = navElement ? navElement.querySelectorAll("ol li") : []; - var navItems = navElement ? core.qsa(navElement, "li") : []; - var length = navItems.length; - var i; - var toc = {}; - var list = []; - var item, parent; - - if(!navItems || length === 0) return list; - - for (i = 0; i < length; ++i) { - item = this.navItem(navItems[i], spineIndexByURL, bookSpine); - toc[item.id] = item; - if(!item.parent) { - list.push(item); - } else { - parent = toc[item.parent]; - parent.subitems.push(item); - } - } - - return list; -}; - -Parser.prototype.navItem = function(item, spineIndexByURL, bookSpine){ - var id = item.getAttribute('id') || false, - // content = item.querySelector("a, span"), - content = core.qs(item, "a"), - src = content.getAttribute('href') || '', - text = content.textContent || "", - // split = src.split("#"), - // baseUrl = split[0], - // spinePos = spineIndexByURL[baseUrl], - // spineItem = bookSpine[spinePos], - subitems = [], - parentNode = item.parentNode, - parent; - // cfi = spineItem ? spineItem.cfi : ''; - - if(parentNode && parentNode.nodeName === "navPoint") { - parent = parentNode.getAttribute('id'); - } - - /* - if(!id) { - if(spinePos) { - spineItem = bookSpine[spinePos]; - id = spineItem.id; - cfi = spineItem.cfi; - } else { - id = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid(); - item.setAttribute('id', id); - } - } - */ - - return { - "id": id, - "href": src, - "label": text, - "subitems" : subitems, - "parent" : parent - }; -}; - -Parser.prototype.ncx = function(tocXml, spineIndexByURL, bookSpine){ - // var navPoints = tocXml.querySelectorAll("navMap navPoint"); - var navPoints = core.qsa(tocXml, "navPoint"); - var length = navPoints.length; - var i; - var toc = {}; - var list = []; - var item, parent; - - if(!navPoints || length === 0) return list; - - for (i = 0; i < length; ++i) { - item = this.ncxItem(navPoints[i], spineIndexByURL, bookSpine); - toc[item.id] = item; - if(!item.parent) { - list.push(item); - } else { - parent = toc[item.parent]; - parent.subitems.push(item); - } - } - - return list; -}; - -Parser.prototype.ncxItem = function(item, spineIndexByURL, bookSpine){ - var id = item.getAttribute('id') || false, - // content = item.querySelector("content"), - content = core.qs(item, "content"), - src = content.getAttribute('src'), - // navLabel = item.querySelector("navLabel"), - navLabel = core.qs(item, "navLabel"), - text = navLabel.textContent ? navLabel.textContent : "", - // split = src.split("#"), - // baseUrl = split[0], - // spinePos = spineIndexByURL[baseUrl], - // spineItem = bookSpine[spinePos], - subitems = [], - parentNode = item.parentNode, - parent; - // cfi = spineItem ? spineItem.cfi : ''; - - if(parentNode && parentNode.nodeName === "navPoint") { - parent = parentNode.getAttribute('id'); - } - - /* - if(!id) { - if(spinePos) { - spineItem = bookSpine[spinePos]; - id = spineItem.id; - cfi = spineItem.cfi; - } else { - id = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid(); - item.setAttribute('id', id); - } - } - */ - - return { - "id": id, - "href": src, - "label": text, - "subitems" : subitems, - "parent" : parent - }; -}; - -Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ - var navElement = this.querySelectorByType(navHtml, "nav", "page-list"); - // var navItems = navElement ? navElement.querySelectorAll("ol li") : []; - var navItems = navElement ? core.qsa(navElement, "li") : []; - var length = navItems.length; - var i; - var toc = {}; - var list = []; - var item; - - if(!navItems || length === 0) return list; - - for (i = 0; i < length; ++i) { - item = this.pageListItem(navItems[i], spineIndexByURL, bookSpine); - list.push(item); - } - - return list; -}; - -Parser.prototype.pageListItem = function(item, spineIndexByURL, bookSpine){ - var id = item.getAttribute('id') || false, - // content = item.querySelector("a"), - content = core.qs(item, "a"), - 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; - return { - "cfi" : cfi, - "href" : href, - "packageUrl" : packageUrl, - "page" : page - }; - } else { - return { - "href" : href, - "page" : page - }; - } -}; - -module.exports = Parser; - -},{"./core":10,"./epubcfi":11,"urijs":7}],20:[function(require,module,exports){ -var RSVP = require('rsvp'); -var core = require('./core'); - -function Queue(_context){ - this._q = []; - this.context = _context; - this.tick = core.requestAnimationFrame; - this.running = false; - this.paused = false; -}; - -// Add an item to the queue -Queue.prototype.enqueue = function() { - var deferred, promise; - var queued; - var task = [].shift.call(arguments); - var args = arguments; - - // Handle single args without context - // if(args && !Array.isArray(args)) { - // args = [args]; - // } - if(!task) { - return console.error("No Task Provided"); - } - - if(typeof task === "function"){ - - deferred = new RSVP.defer(); - promise = deferred.promise; - - queued = { - "task" : task, - "args" : args, - //"context" : context, - "deferred" : deferred, - "promise" : promise - }; - - } else { - // Task is a promise - queued = { - "promise" : task - }; - - } - - this._q.push(queued); - - // Wait to start queue flush - if (this.paused == false && !this.running) { - // setTimeout(this.flush.bind(this), 0); - // this.tick.call(window, this.run.bind(this)); - this.run(); - } - - return queued.promise; -}; - -// Run one item -Queue.prototype.dequeue = function(){ - var inwait, task, result; - - if(this._q.length) { - inwait = this._q.shift(); - task = inwait.task; - if(task){ - // console.log(task) - - result = task.apply(this.context, inwait.args); - - if(result && typeof result["then"] === "function") { - // Task is a function that returns a promise - return result.then(function(){ - inwait.deferred.resolve.apply(this.context, arguments); - }.bind(this)); - } else { - // Task resolves immediately - inwait.deferred.resolve.apply(this.context, result); - return inwait.promise; - } - - - - } else if(inwait.promise) { - // Task is a promise - return inwait.promise; - } - - } else { - inwait = new RSVP.defer(); - inwait.deferred.resolve(); - return inwait.promise; - } - -}; - -// Run All Immediately -Queue.prototype.dump = function(){ - while(this._q.length) { - this.dequeue(); - } -}; - -// Run all sequentially, at convince - -Queue.prototype.run = function(){ - - if(!this.running){ - this.running = true; - this.defered = new RSVP.defer(); - } - - this.tick.call(window, function() { - - if(this._q.length) { - - this.dequeue() - .then(function(){ - this.run(); - }.bind(this)); - - } else { - this.defered.resolve(); - this.running = undefined; - } - - }.bind(this)); - - // Unpause - if(this.paused == true) { - this.paused = false; - } - - return this.defered.promise; -}; - -// Flush all, as quickly as possible -Queue.prototype.flush = function(){ - - if(this.running){ - return this.running; - } - - if(this._q.length) { - this.running = this.dequeue() - .then(function(){ - this.running = undefined; - return this.flush(); - }.bind(this)); - - return this.running; - } - -}; - -// Clear all items in wait -Queue.prototype.clear = function(){ - this._q = []; - this.running = false; -}; - -Queue.prototype.length = function(){ - return this._q.length; -}; - -Queue.prototype.pause = function(){ - this.paused = true; -}; - -// Create a new task from a callback -function Task(task, args, context){ - - return function(){ - var toApply = arguments || []; - - return new RSVP.Promise(function(resolve, reject) { - var callback = function(value){ - resolve(value); - }; - // Add the callback to the arguments list - toApply.push(callback); - - // Apply all arguments to the functions - task.apply(this, toApply); - - }.bind(this)); - - }; - -}; - -module.exports = Queue; - -},{"./core":10,"rsvp":5}],21:[function(require,module,exports){ -var RSVP = require('rsvp'); -var URI = require('urijs'); -var core = require('./core'); -var replace = require('./replacements'); -var Hook = require('./hook'); -var EpubCFI = require('./epubcfi'); -var Queue = require('./queue'); -// var View = require('./view'); -var Views = require('./views'); -var Layout = require('./layout'); -var Mapping = require('./mapping'); - -function Rendition(book, options) { - - this.settings = core.extend(this.settings || {}, { - width: null, - height: null, - ignoreClass: '', - manager: "single", - view: "iframe", - flow: null, - layout: null, - spread: null, - minSpreadWidth: 800, //-- overridden by spread: none (never) / both (always), - useBase64: true - }); - - core.extend(this.settings, options); - - this.viewSettings = { - ignoreClass: this.settings.ignoreClass - }; - - this.book = book; - - this.views = null; - - //-- Adds Hook methods to the Rendition prototype - this.hooks = {}; - this.hooks.display = new Hook(this); - this.hooks.serialize = new Hook(this); - this.hooks.content = new Hook(this); - this.hooks.layout = new Hook(this); - this.hooks.render = new Hook(this); - this.hooks.show = new Hook(this); - - this.hooks.content.register(replace.links.bind(this)); - this.hooks.content.register(this.passViewEvents.bind(this)); - - // this.hooks.display.register(this.afterDisplay.bind(this)); - - this.epubcfi = new EpubCFI(); - - this.q = new Queue(this); - - this.q.enqueue(this.book.opened); - - // Block the queue until rendering is started - // this.starting = new RSVP.defer(); - // this.started = this.starting.promise; - this.q.enqueue(this.start); - - if(this.book.unarchived) { - this.q.enqueue(this.replacements.bind(this)); - } - -}; - -Rendition.prototype.setManager = function(manager) { - this.manager = manager; -}; - -Rendition.prototype.requireManager = function(manager) { - var viewManager; - - // If manager is a string, try to load from register managers, - // or require included managers directly - if (typeof manager === "string") { - // Use global or require - viewManager = typeof ePub != "undefined" ? ePub.ViewManagers[manager] : undefined; //require('./managers/'+manager); - } else { - // otherwise, assume we were passed a function - viewManager = manager - } - - return viewManager; -}; - -Rendition.prototype.requireView = function(view) { - var View; - - if (typeof view == "string") { - View = typeof ePub != "undefined" ? ePub.Views[view] : undefined; //require('./views/'+view); - } else { - // otherwise, assume we were passed a function - View = view - } - - return View; -}; - -Rendition.prototype.start = function(){ - - if(!this.manager) { - this.ViewManager = this.requireManager(this.settings.manager); - this.View = this.requireView(this.settings.view); - - this.manager = new this.ViewManager({ - view: this.View, - queue: this.q, - request: this.book.request, - settings: this.settings - }); - } - - // Parse metadata to get layout props - this.settings.globalLayoutProperties = this.determineLayoutProperties(this.book.package.metadata); - - this.flow(this.settings.globalLayoutProperties.flow); - - this.layout(this.settings.globalLayoutProperties); - - // Listen for displayed views - this.manager.on("added", this.afterDisplayed.bind(this)); - - // Listen for resizing - this.manager.on("resized", this.onResized.bind(this)); - - // Listen for scroll changes - this.manager.on("scroll", this.reportLocation.bind(this)); - - - this.on('displayed', this.reportLocation.bind(this)); - - // Trigger that rendering has started - this.trigger("started"); - - // Start processing queue - // this.starting.resolve(); -}; - -// Call to attach the container to an element in the dom -// Container must be attached before rendering can begin -Rendition.prototype.attachTo = function(element){ - - return this.q.enqueue(function () { - - // Start rendering - this.manager.render(element, { - "width" : this.settings.width, - "height" : this.settings.height - }); - - // Trigger Attached - this.trigger("attached"); - - }.bind(this)); - -}; - -Rendition.prototype.display = function(target){ - - // if (!this.book.spine.spineItems.length > 0) { - // Book isn't open yet - // return this.q.enqueue(this.display, target); - // } - - return this.q.enqueue(this._display, target); - -}; - -Rendition.prototype._display = function(target){ - var isCfiString = this.epubcfi.isCfiString(target); - var displaying = new RSVP.defer(); - var displayed = displaying.promise; - var section; - var moveTo; - - section = this.book.spine.get(target); - - if(!section){ - displaying.reject(new Error("No Section Found")); - return displayed; - } - - // Trim the target fragment - // removing the chapter - if(!isCfiString && typeof target === "string" && - target.indexOf("#") > -1) { - moveTo = target.substring(target.indexOf("#")+1); - } - - if (isCfiString) { - moveTo = target; - } - - return this.manager.display(section, moveTo) - .then(function(){ - this.trigger("displayed", section); - }.bind(this)); - -}; - -/* -Rendition.prototype.render = function(view, show) { - - // view.onLayout = this.layout.format.bind(this.layout); - view.create(); - - // Fit to size of the container, apply padding - this.manager.resizeView(view); - - // Render Chain - return view.section.render(this.book.request) - .then(function(contents){ - return view.load(contents); - }.bind(this)) - .then(function(doc){ - return this.hooks.content.trigger(view, this); - }.bind(this)) - .then(function(){ - this.layout.format(view.contents); - return this.hooks.layout.trigger(view, this); - }.bind(this)) - .then(function(){ - return view.display(); - }.bind(this)) - .then(function(){ - return this.hooks.render.trigger(view, this); - }.bind(this)) - .then(function(){ - if(show !== false) { - this.q.enqueue(function(view){ - view.show(); - }, view); - } - // this.map = new Map(view, this.layout); - this.hooks.show.trigger(view, this); - this.trigger("rendered", view.section); - - }.bind(this)) - .catch(function(e){ - this.trigger("loaderror", e); - }.bind(this)); - -}; -*/ - -Rendition.prototype.afterDisplayed = function(view){ - this.hooks.content.trigger(view, this); - this.trigger("rendered", view.section); - this.reportLocation(); -}; - -Rendition.prototype.onResized = function(size){ - - if(this.location) { - this.display(this.location.start); - } - - this.trigger("resized", { - width: size.width, - height: size.height - }); - -}; - -Rendition.prototype.moveTo = function(offset){ - this.manager.moveTo(offset); -}; - -Rendition.prototype.next = function(){ - return this.q.enqueue(this.manager.next.bind(this.manager)) - .then(this.reportLocation.bind(this)); -}; - -Rendition.prototype.prev = function(){ - return this.q.enqueue(this.manager.prev.bind(this.manager)) - .then(this.reportLocation.bind(this)); -}; - -//-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering -Rendition.prototype.determineLayoutProperties = function(metadata){ - var settings; - var layout = this.settings.layout || metadata.layout || "reflowable"; - var spread = this.settings.spread || metadata.spread || "auto"; - var orientation = this.settings.orientation || metadata.orientation || "auto"; - var flow = this.settings.flow || metadata.flow || "auto"; - var viewport = metadata.viewport || ""; - var minSpreadWidth = this.settings.minSpreadWidth || metadata.minSpreadWidth || 800; - - if (this.settings.width >= 0 && this.settings.height >= 0) { - viewport = "width="+this.settings.width+", height="+this.settings.height+""; - } - - settings = { - layout : layout, - spread : spread, - orientation : orientation, - flow : flow, - viewport : viewport, - minSpreadWidth : minSpreadWidth - }; - - return settings; -}; - -// Rendition.prototype.applyLayoutProperties = function(){ -// var settings = this.determineLayoutProperties(this.book.package.metadata); -// -// this.flow(settings.flow); -// -// this.layout(settings); -// }; - -// paginated | scrolled -// (scrolled-continuous vs scrolled-doc are handled by different view managers) -Rendition.prototype.flow = function(_flow){ - var flow; - if (_flow === "scrolled-doc" || _flow === "scrolled-continuous") { - flow = "scrolled"; - } - - if (_flow === "auto" || _flow === "paginated") { - flow = "paginated"; - } - - if (this._layout) { - this._layout.flow(flow); - } - - if (this.manager) { - this.manager.updateFlow(flow); - } -}; - -// reflowable | pre-paginated -Rendition.prototype.layout = function(settings){ - if (settings) { - this._layout = new Layout(settings); - this._layout.spread(settings.spread, this.settings.minSpreadWidth); - - this.mapping = new Mapping(this._layout); - } - - if (this.manager && this._layout) { - this.manager.applyLayout(this._layout); - } - - return this._layout; -}; - -// none | auto (TODO: implement landscape, portrait, both) -Rendition.prototype.spread = function(spread, min){ - - this._layout.spread(spread, min); - - if (this.manager.isRendered()) { - this.manager.updateLayout(); - } -}; - - -Rendition.prototype.reportLocation = function(){ - return this.q.enqueue(function(){ - var location = this.manager.currentLocation(); - if (location && location.then && typeof location.then === 'function') { - location.then(function(result) { - this.location = result; - this.trigger("locationChanged", this.location); - }.bind(this)); - } else if (location) { - this.location = location; - this.trigger("locationChanged", this.location); - } - - }.bind(this)); -}; - - -Rendition.prototype.destroy = function(){ - // Clear the queue - this.q.clear(); - - this.views.clear(); - - clearTimeout(this.trimTimeout); - if(this.settings.hidden) { - this.element.removeChild(this.wrapper); - } else { - this.element.removeChild(this.container); - } - -}; - -Rendition.prototype.passViewEvents = function(view){ - view.contents.listenedEvents.forEach(function(e){ - view.on(e, this.triggerViewEvent.bind(this)); - }.bind(this)); - - view.on("selected", this.triggerSelectedEvent.bind(this)); -}; - -Rendition.prototype.triggerViewEvent = function(e){ - this.trigger(e.type, e); -}; - -Rendition.prototype.triggerSelectedEvent = function(cfirange){ - this.trigger("selected", cfirange); -}; - -Rendition.prototype.replacements = function(){ - // Wait for loading - // return this.q.enqueue(function () { - // Get thes books manifest - var manifest = this.book.package.manifest; - var manifestArray = Object.keys(manifest). - map(function (key){ - return manifest[key]; - }); - - // Exclude HTML - var items = manifestArray. - filter(function (item){ - if (item.type != "application/xhtml+xml" && - item.type != "text/html") { - return true; - } - }); - - // Only CSS - var css = items. - filter(function (item){ - if (item.type === "text/css") { - return true; - } - }); - - // Css Urls - var cssUrls = css.map(function(item) { - return item.href; - }); - - // All Assets Urls - var urls = items. - map(function(item) { - return item.href; - }.bind(this)); - - // Create blob urls for all the assets - var processing = urls. - map(function(url) { - var absolute = URI(url).absoluteTo(this.book.baseUrl).toString(); - // Full url from archive base - return this.book.unarchived.createUrl(absolute, {"base64": this.settings.useBase64}); - }.bind(this)); - - var replacementUrls; - - // After all the urls are created - return RSVP.all(processing) - .then(function(_replacementUrls) { - var replaced = []; - - replacementUrls = _replacementUrls; - - // Replace Asset Urls in the text of all css files - cssUrls.forEach(function(href) { - replaced.push(this.replaceCss(href, urls, replacementUrls)); - }.bind(this)); - - return RSVP.all(replaced); - - }.bind(this)) - .then(function () { - // Replace Asset Urls in chapters - // by registering a hook after the sections contents has been serialized - this.book.spine.hooks.serialize.register(function(output, section) { - - this.replaceAssets(section, urls, replacementUrls); - - }.bind(this)); - - }.bind(this)) - .catch(function(reason){ - console.error(reason); - }); - // }.bind(this)); -}; - -Rendition.prototype.replaceCss = function(href, urls, replacementUrls){ - var newUrl; - var indexInUrls; - - // Find the absolute url of the css file - var fileUri = URI(href); - var absolute = fileUri.absoluteTo(this.book.baseUrl).toString(); - // Get the text of the css file from the archive - var textResponse = this.book.unarchived.getText(absolute); - // Get asset links relative to css file - var relUrls = urls. - map(function(assetHref) { - var assetUri = URI(assetHref).absoluteTo(this.book.baseUrl); - var relative = assetUri.relativeTo(absolute).toString(); - return relative; - }.bind(this)); - - return textResponse.then(function (text) { - // Replacements in the css text - text = replace.substitute(text, relUrls, replacementUrls); - - // Get the new url - if (this.settings.useBase64) { - newUrl = core.createBase64Url(text, 'text/css'); - } else { - newUrl = core.createBlobUrl(text, 'text/css'); - } - - // switch the url in the replacementUrls - indexInUrls = urls.indexOf(href); - if (indexInUrls > -1) { - replacementUrls[indexInUrls] = newUrl; - } - - return new RSVP.Promise(function(resolve, reject){ - resolve(urls, replacementUrls); - }); - - }.bind(this)); - -}; - -Rendition.prototype.replaceAssets = function(section, urls, replacementUrls){ - var fileUri = URI(section.url); - // Get Urls relative to current sections - var relUrls = urls. - map(function(href) { - var assetUri = URI(href).absoluteTo(this.book.baseUrl); - var relative = assetUri.relativeTo(fileUri).toString(); - return relative; - }.bind(this)); - - - section.output = replace.substitute(section.output, relUrls, replacementUrls); -}; - -Rendition.prototype.range = function(_cfi, ignoreClass){ - var cfi = new EpubCFI(_cfi); - var found = this.visible().filter(function (view) { - if(cfi.spinePos === view.index) return true; - }); - - // Should only every return 1 item - if (found.length) { - return found[0].range(cfi, ignoreClass); - } -}; - -Rendition.prototype.adjustImages = function(view) { - - view.addStylesheetRules([ - ["img", - ["max-width", (view.layout.spreadWidth) + "px"], - ["max-height", (view.layout.height) + "px"] - ] - ]); - return new RSVP.Promise(function(resolve, reject){ - // Wait to apply - setTimeout(function() { - resolve(); - }, 1); - }); -}; - -//-- Enable binding events to Renderer -RSVP.EventTarget.mixin(Rendition.prototype); - -module.exports = Rendition; - -},{"./core":10,"./epubcfi":11,"./hook":12,"./layout":13,"./mapping":17,"./queue":20,"./replacements":22,"./views":28,"rsvp":5,"urijs":7}],22:[function(require,module,exports){ -var URI = require('urijs'); -var core = require('./core'); - -function base(doc, section){ - var base; - var head; - - if(!doc){ - return; - } - - // head = doc.querySelector("head"); - // base = head.querySelector("base"); - head = core.qs(doc, "head"); - base = core.qs(head, "base"); - - if(!base) { - base = doc.createElement("base"); - head.insertBefore(base, head.firstChild); - } - - base.setAttribute("href", section.url); -} - -function canonical(doc, section){ - var head; - var link; - var url = section.url; // window.location.origin + window.location.pathname + "?loc=" + encodeURIComponent(section.url); - - if(!doc){ - return; - } - - head = core.qs(doc, "head"); - link = core.qs(head, "link[rel='canonical']"); - - if (link) { - link.setAttribute("href", url); - } else { - link = doc.createElement("link"); - link.setAttribute("rel", "canonical"); - link.setAttribute("href", url); - head.appendChild(link); - } -} - -function links(view, renderer) { - - var links = view.document.querySelectorAll("a[href]"); - var replaceLinks = function(link){ - var href = link.getAttribute("href"); - - if(href.indexOf("mailto:") === 0){ - return; - } - - var linkUri = URI(href); - var absolute = linkUri.absoluteTo(view.section.url); - var relative = absolute.relativeTo(this.book.baseUrl).toString(); - - if(linkUri.protocol()){ - - link.setAttribute("target", "_blank"); - - }else{ - /* - if(baseDirectory) { - // We must ensure that the file:// protocol is preserved for - // local file links, as in certain contexts (such as under - // Titanium), file links without the file:// protocol will not - // work - if (baseUri.protocol === "file") { - relative = core.resolveUrl(baseUri.base, href); - } else { - relative = core.resolveUrl(baseDirectory, href); - } - } else { - relative = href; - } - */ - - if(linkUri.fragment()) { - // do nothing with fragment yet - } else { - link.onclick = function(){ - renderer.display(relative); - return false; - }; - } - - } - }.bind(this); - - for (var i = 0; i < links.length; i++) { - replaceLinks(links[i]); - } - - -}; - -function substitute(content, urls, replacements) { - urls.forEach(function(url, i){ - if (url && replacements[i]) { - content = content.replace(new RegExp(url, 'g'), replacements[i]); - } - }); - return content; -} -module.exports = { - 'base': base, - 'canonical' : canonical, - 'links': links, - 'substitute': substitute -}; - -},{"./core":10,"urijs":7}],23:[function(require,module,exports){ -var RSVP = require('rsvp'); -var URI = require('urijs'); -var core = require('./core'); - -function request(url, type, withCredentials, headers) { - var supportsURL = (typeof window != "undefined") ? window.URL : false; // TODO: fallback for url if window isn't defined - var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; - var uri; - - 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; - - var header; - - 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.onreadystatechange = handler; - xhr.onerror = err; - - xhr.open("GET", url, true); - - for(header in headers) { - xhr.setRequestHeader(header, headers[header]); - } - - if(type == "json") { - xhr.setRequestHeader("Accept", "application/json"); - } - - // If type isn't set, determine it from the file extension - if(!type) { - uri = URI(url); - type = uri.suffix(); - } - - if(type == 'blob'){ - xhr.responseType = BLOB_RESPONSE; - } - - - if(core.isXml(type)) { - // xhr.responseType = "document"; - xhr.overrideMimeType('text/xml'); // for OPF parsing - } - - if(type == 'xhtml') { - // xhr.responseType = "document"; - } - - if(type == 'html' || type == 'htm') { - // xhr.responseType = "document"; - } - - if(type == "binary") { - xhr.responseType = "arraybuffer"; - } - - xhr.send(); - - function err(e) { - console.error(e); - deferred.reject(e); - } - - function handler() { - if (this.readyState === XMLHttpRequest.DONE) { - - if (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls - var r; - - if (!this.response && !this.responseXML) { - deferred.reject({ - status: this.status, - message : "Empty Response", - stack : new Error().stack - }); - return deferred.promise; - } - - if (this.status === 403) { - deferred.reject({ - status: this.status, - response: this.response, - message : "Forbidden", - stack : new Error().stack - }); - return deferred.promise; - } - - if((this.responseType == '' || this.responseType == 'document') - && this.responseXML){ - r = this.responseXML; - } else - if(core.isXml(type)){ - // xhr.overrideMimeType('text/xml'); // for OPF parsing - // If this.responseXML wasn't set, try to parse using a DOMParser from text - r = core.parse(this.response, "text/xml"); - }else - if(type == 'xhtml'){ - r = core.parse(this.response, "application/xhtml+xml"); - }else - if(type == 'html' || type == 'htm'){ - r = core.parse(this.response, "text/html"); - }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({ - status: this.status, - message : this.response, - stack : new Error().stack - }); - - } - } - } - - return deferred.promise; -}; - -module.exports = request; - -},{"./core":10,"rsvp":5,"urijs":7}],24:[function(require,module,exports){ -var RSVP = require('rsvp'); -var URI = require('urijs'); -var core = require('./core'); -var EpubCFI = require('./epubcfi'); -var Hook = require('./hook'); - -function Section(item, hooks){ - this.idref = item.idref; - this.linear = item.linear; - this.properties = item.properties; - this.index = item.index; - this.href = item.href; - this.url = item.url; - this.next = item.next; - this.prev = item.prev; - - this.cfiBase = item.cfiBase; - - if (hooks) { - this.hooks = hooks; - } else { - this.hooks = {}; - this.hooks.serialize = new Hook(this); - this.hooks.content = new Hook(this); - } - -}; - - -Section.prototype.load = function(_request){ - var request = _request || this.request || require('./request'); - var loading = new RSVP.defer(); - var loaded = loading.promise; - - if(this.contents) { - loading.resolve(this.contents); - } else { - request(this.url) - .then(function(xml){ - var base; - var directory = URI(this.url).directory(); - - this.document = xml; - this.contents = xml.documentElement; - - return this.hooks.content.trigger(this.document, this); - }.bind(this)) - .then(function(){ - loading.resolve(this.contents); - }.bind(this)) - .catch(function(error){ - loading.reject(error); - }); - } - - return loaded; -}; - -Section.prototype.base = function(_document){ - var task = new RSVP.defer(); - var base = _document.createElement("base"); // TODO: check if exists - var head; - console.log(window.location.origin + "/" +this.url); - - base.setAttribute("href", window.location.origin + "/" +this.url); - - if(_document) { - head = _document.querySelector("head"); - } - if(head) { - head.insertBefore(base, head.firstChild); - task.resolve(); - } else { - task.reject(new Error("No head to insert into")); - } - - - return task.promise; -}; - -Section.prototype.beforeSectionLoad = function(){ - // Stub for a hook - replace me for now -}; - -Section.prototype.render = function(_request){ - var rendering = new RSVP.defer(); - var rendered = rendering.promise; - this.output; // TODO: better way to return this from hooks? - - this.load(_request). - then(function(contents){ - var serializer; - - if (typeof XMLSerializer === "undefined") { - XMLSerializer = require('xmldom').XMLSerializer; - } - serializer = new XMLSerializer(); - this.output = serializer.serializeToString(contents); - return this.output; - }.bind(this)). - then(function(){ - return this.hooks.serialize.trigger(this.output, this); - }.bind(this)). - then(function(){ - rendering.resolve(this.output); - }.bind(this)) - .catch(function(error){ - rendering.reject(error); - }); - - return rendered; -}; - -Section.prototype.find = function(_query){ - -}; - -/** -* Reconciles the current chapters layout properies with -* the global layout properities. -* Takes: global layout settings object, chapter properties string -* Returns: Object with layout properties -*/ -Section.prototype.reconcileLayoutSettings = function(global){ - //-- Get the global defaults - var settings = { - layout : global.layout, - spread : global.spread, - orientation : global.orientation - }; - - //-- Get the chapter's display type - this.properties.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; -}; - -Section.prototype.cfiFromRange = function(_range) { - return new EpubCFI(_range, this.cfiBase).toString(); -}; - -Section.prototype.cfiFromElement = function(el) { - return new EpubCFI(el, this.cfiBase).toString(); -}; - -module.exports = Section; - -},{"./core":10,"./epubcfi":11,"./hook":12,"./request":23,"rsvp":5,"urijs":7,"xmldom":"xmldom"}],25:[function(require,module,exports){ -var RSVP = require('rsvp'); -var core = require('./core'); -var EpubCFI = require('./epubcfi'); -var Hook = require('./hook'); -var Section = require('./section'); -var replacements = require('./replacements'); - -function Spine(_request){ - this.request = _request; - this.spineItems = []; - this.spineByHref = {}; - this.spineById = {}; - - this.hooks = {}; - this.hooks.serialize = new Hook(); - this.hooks.content = new Hook(); - - // Register replacements - this.hooks.content.register(replacements.base); - this.hooks.content.register(replacements.canonical); - - this.epubcfi = new EpubCFI(); - - this.loaded = false; -}; - -Spine.prototype.load = function(_package) { - - this.items = _package.spine; - this.manifest = _package.manifest; - this.spineNodeIndex = _package.spineNodeIndex; - this.baseUrl = _package.baseUrl || ''; - this.length = this.items.length; - - this.items.forEach(function(item, index){ - var href, url; - var manifestItem = this.manifest[item.idref]; - var spineItem; - - item.cfiBase = this.epubcfi.generateChapterComponent(this.spineNodeIndex, item.index, item.idref); - - if(manifestItem) { - item.href = manifestItem.href; - item.url = this.baseUrl + item.href; - - if(manifestItem.properties.length){ - item.properties.push.apply(item.properties, manifestItem.properties); - } - } - - // if(index > 0) { - item.prev = function(){ return this.get(index-1); }.bind(this); - // } - - // if(index+1 < this.items.length) { - item.next = function(){ return this.get(index+1); }.bind(this); - // } - - spineItem = new Section(item, this.hooks); - - this.append(spineItem); - - - }.bind(this)); - - this.loaded = true; -}; - -// book.spine.get(); -// book.spine.get(1); -// book.spine.get("chap1.html"); -// book.spine.get("#id1234"); -Spine.prototype.get = function(target) { - var index = 0; - - if(this.epubcfi.isCfiString(target)) { - cfi = new EpubCFI(target); - index = cfi.spinePos; - } else if(target && (typeof target === "number" || isNaN(target) === false)){ - index = target; - } else if(target && target.indexOf("#") === 0) { - index = this.spineById[target.substring(1)]; - } else if(target) { - // Remove fragments - target = target.split("#")[0]; - index = this.spineByHref[target]; - } - - return this.spineItems[index] || null; -}; - -Spine.prototype.append = function(section) { - var index = this.spineItems.length; - section.index = index; - - this.spineItems.push(section); - - this.spineByHref[section.href] = index; - this.spineById[section.idref] = index; - - return index; -}; - -Spine.prototype.prepend = function(section) { - var index = this.spineItems.unshift(section); - this.spineByHref[section.href] = 0; - this.spineById[section.idref] = 0; - - // Re-index - this.spineItems.forEach(function(item, index){ - item.index = index; - }); - - return 0; -}; - -Spine.prototype.insert = function(section, index) { - -}; - -Spine.prototype.remove = function(section) { - var index = this.spineItems.indexOf(section); - - if(index > -1) { - delete this.spineByHref[section.href]; - delete this.spineById[section.idref]; - - return this.spineItems.splice(index, 1); - } -}; - -Spine.prototype.each = function() { - return this.spineItems.forEach.apply(this.spineItems, arguments); -}; - -module.exports = Spine; - -},{"./core":10,"./epubcfi":11,"./hook":12,"./replacements":22,"./section":24,"rsvp":5}],26:[function(require,module,exports){ -var core = require('./core'); - -function Stage(_options) { - this.settings = _options || {}; - this.id = "epubjs-container-" + core.uuid(); - - this.container = this.create(this.settings); - - if(this.settings.hidden) { - this.wrapper = this.wrap(this.container); - } - -} - -/** -* Creates an element to render to. -* Resizes to passed width and height or to the elements size -*/ -Stage.prototype.create = function(options){ - var height = options.height;// !== false ? options.height : "100%"; - var width = options.width;// !== false ? options.width : "100%"; - var overflow = options.overflow || false; - var axis = options.axis || "vertical"; - - if(options.height && core.isNumber(options.height)) { - height = options.height + "px"; - } - - if(options.width && core.isNumber(options.width)) { - width = options.width + "px"; - } - - // Create new container element - container = document.createElement("div"); - - container.id = this.id; - container.classList.add("epub-container"); - - // Style Element - // container.style.fontSize = "0"; - container.style.wordSpacing = "0"; - container.style.lineHeight = "0"; - container.style.verticalAlign = "top"; - - if(axis === "horizontal") { - container.style.whiteSpace = "nowrap"; - } - - if(width){ - container.style.width = width; - } - - if(height){ - container.style.height = height; - } - - if (overflow) { - container.style.overflow = overflow; - } - - return container; -}; - -Stage.wrap = function(container) { - var wrapper = document.createElement("div"); - - wrapper.style.visibility = "hidden"; - wrapper.style.overflow = "hidden"; - wrapper.style.width = "0"; - wrapper.style.height = "0"; - - wrapper.appendChild(container); - return wrapper; -}; - - -Stage.prototype.getElement = function(_element){ - var element; - - if(core.isElement(_element)) { - element = _element; - } else if (typeof _element === "string") { - element = document.getElementById(_element); - } - - if(!element){ - console.error("Not an Element"); - return; - } - - return element; -}; - -Stage.prototype.attachTo = function(what){ - - var element = this.getElement(what); - var base; - - if(!element){ - return; - } - - if(this.settings.hidden) { - base = this.wrapper; - } else { - base = this.container; - } - - element.appendChild(base); - - this.element = element; - - return element; - -}; - -Stage.prototype.getContainer = function() { - return this.container; -}; - -Stage.prototype.onResize = function(func){ - // Only listen to window for resize event if width and height are not fixed. - // This applies if it is set to a percent or auto. - if(!core.isNumber(this.settings.width) || - !core.isNumber(this.settings.height) ) { - window.addEventListener("resize", func, false); - } - -}; - -Stage.prototype.size = function(width, height){ - var bounds; - // var width = _width || this.settings.width; - // var height = _height || this.settings.height; - - // If width or height are set to false, inherit them from containing element - if(width === null) { - bounds = this.element.getBoundingClientRect(); - - if(bounds.width) { - width = bounds.width; - this.container.style.width = bounds.width + "px"; - } - } - - if(height === null) { - bounds = bounds || this.element.getBoundingClientRect(); - - if(bounds.height) { - height = bounds.height; - this.container.style.height = bounds.height + "px"; - } - - } - - if(!core.isNumber(width)) { - bounds = this.container.getBoundingClientRect(); - width = bounds.width; - //height = bounds.height; - } - - if(!core.isNumber(height)) { - bounds = bounds || this.container.getBoundingClientRect(); - //width = bounds.width; - height = bounds.height; - } - - - this.containerStyles = window.getComputedStyle(this.container); - - this.containerPadding = { - left: parseFloat(this.containerStyles["padding-left"]) || 0, - right: parseFloat(this.containerStyles["padding-right"]) || 0, - top: parseFloat(this.containerStyles["padding-top"]) || 0, - bottom: parseFloat(this.containerStyles["padding-bottom"]) || 0 - }; - - return { - width: width - - this.containerPadding.left - - this.containerPadding.right, - height: height - - this.containerPadding.top - - this.containerPadding.bottom - }; - -}; - -Stage.prototype.bounds = function(){ - - if(!this.container) { - return core.windowBounds(); - } else { - return this.container.getBoundingClientRect(); - } - -} - -Stage.prototype.getSheet = function(){ - var style = document.createElement("style"); - - // WebKit hack --> https://davidwalsh.name/add-rules-stylesheets - style.appendChild(document.createTextNode("")); - - document.head.appendChild(style); - - return style.sheet; -} - -Stage.prototype.addStyleRules = function(selector, rulesArray){ - var scope = "#" + this.id + " "; - var rules = ""; - - if(!this.sheet){ - this.sheet = this.getSheet(); - } - - rulesArray.forEach(function(set) { - for (var prop in set) { - if(set.hasOwnProperty(prop)) { - rules += prop + ":" + set[prop] + ";"; - } - } - }) - - this.sheet.insertRule(scope + selector + " {" + rules + "}", 0); -} - - - -module.exports = Stage; - -},{"./core":10}],27:[function(require,module,exports){ -var RSVP = require('rsvp'); -var URI = require('urijs'); -var core = require('./core'); -var request = require('./request'); -var mime = require('../libs/mime/mime'); - -function Unarchive() { - - this.checkRequirements(); - this.urlCache = {}; - -} - -Unarchive.prototype.checkRequirements = function(callback){ - try { - if (typeof JSZip !== 'undefined') { - this.zip = new JSZip(); - } else { - JSZip = require('jszip'); - this.zip = new JSZip(); - } - } catch (e) { - console.error("JSZip lib not loaded"); - } -}; - -Unarchive.prototype.open = function(zipUrl, isBase64){ - if (zipUrl instanceof ArrayBuffer || isBase64) { - return this.zip.loadAsync(zipUrl, {"base64": isBase64}); - } else { - return request(zipUrl, "binary") - .then(function(data){ - return this.zip.loadAsync(data); - }.bind(this)); - } -}; - -Unarchive.prototype.request = function(url, type){ - var deferred = new RSVP.defer(); - var response; - var r; - - // If type isn't set, determine it from the file extension - if(!type) { - uri = URI(url); - type = uri.suffix(); - } - - if(type == 'blob'){ - response = this.getBlob(url); - } else { - response = this.getText(url); - } - - if (response) { - response.then(function (r) { - result = this.handleResponse(r, type); - deferred.resolve(result); - }.bind(this)); - } else { - deferred.reject({ - message : "File not found in the epub: " + url, - stack : new Error().stack - }); - } - return deferred.promise; -}; - -Unarchive.prototype.handleResponse = function(response, type){ - var r; - - if(type == "json") { - r = JSON.parse(response); - } - else - if(core.isXml(type)) { - r = core.parse(response, "text/xml"); - } - else - if(type == 'xhtml') { - r = core.parse(response, "application/xhtml+xml"); - } - else - if(type == 'html' || type == 'htm') { - r = core.parse(response, "text/html"); - } else { - r = response; - } - - return r; -}; - -Unarchive.prototype.getBlob = function(url, _mimeType){ - var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash - var entry = this.zip.file(decodededUrl); - var mimeType; - - if(entry) { - mimeType = _mimeType || mime.lookup(entry.name); - return entry.async("uint8array").then(function(uint8array) { - return new Blob([uint8array], {type : mimeType}); - }); - } -}; - -Unarchive.prototype.getText = function(url, encoding){ - var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash - var entry = this.zip.file(decodededUrl); - - if(entry) { - return entry.async("string").then(function(text) { - return text; - }); - } -}; - -Unarchive.prototype.getBase64 = function(url, _mimeType){ - var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash - var entry = this.zip.file(decodededUrl); - var mimeType; - - if(entry) { - mimeType = _mimeType || mime.lookup(entry.name); - return entry.async("base64").then(function(data) { - return "data:" + mimeType + ";base64," + data; - }); - } -}; - -Unarchive.prototype.createUrl = function(url, options){ - var deferred = new RSVP.defer(); - var _URL = window.URL || window.webkitURL || window.mozURL; - var tempUrl; - var blob; - var response; - var useBase64 = options && options.base64; - - if(url in this.urlCache) { - deferred.resolve(this.urlCache[url]); - return deferred.promise; - } - - if (useBase64) { - response = this.getBase64(url); - - if (response) { - response.then(function(tempUrl) { - - this.urlCache[url] = tempUrl; - deferred.resolve(tempUrl); - - }.bind(this)); - - } - - } else { - - response = this.getBlob(url); - - if (response) { - response.then(function(blob) { - - tempUrl = _URL.createObjectURL(blob); - this.urlCache[url] = tempUrl; - deferred.resolve(tempUrl); - - }.bind(this)); - - } - } - - - if (!response) { - deferred.reject({ - message : "File not found in the epub: " + url, - stack : new Error().stack - }); - } - - return deferred.promise; -}; - -Unarchive.prototype.revokeUrl = function(url){ - var _URL = window.URL || window.webkitURL || window.mozURL; - var fromCache = this.urlCache[url]; - if(fromCache) _URL.revokeObjectURL(fromCache); -}; - -module.exports = Unarchive; - -},{"../libs/mime/mime":1,"./core":10,"./request":23,"jszip":"jszip","rsvp":5,"urijs":7}],28:[function(require,module,exports){ -function Views(container) { - this.container = container; - this._views = []; - this.length = 0; - this.hidden = false; -}; - -Views.prototype.all = function() { - return this._views; -}; - -Views.prototype.first = function() { - return this._views[0]; -}; - -Views.prototype.last = function() { - return this._views[this._views.length-1]; -}; - -Views.prototype.indexOf = function(view) { - return this._views.indexOf(view); -}; - -Views.prototype.slice = function() { - return this._views.slice.apply(this._views, arguments); -}; - -Views.prototype.get = function(i) { - return this._views[i]; -}; - -Views.prototype.append = function(view){ - this._views.push(view); - if(this.container){ - this.container.appendChild(view.element); - } - this.length++; - return view; -}; - -Views.prototype.prepend = function(view){ - this._views.unshift(view); - if(this.container){ - this.container.insertBefore(view.element, this.container.firstChild); - } - this.length++; - return view; -}; - -Views.prototype.insert = function(view, index) { - this._views.splice(index, 0, view); - - if(this.container){ - if(index < this.container.children.length){ - this.container.insertBefore(view.element, this.container.children[index]); - } else { - this.container.appendChild(view.element); - } - } - - this.length++; - return view; -}; - -Views.prototype.remove = function(view) { - var index = this._views.indexOf(view); - - if(index > -1) { - this._views.splice(index, 1); - } - - - this.destroy(view); - - this.length--; -}; - -Views.prototype.destroy = function(view) { - view.off("resized"); - - if(view.displayed){ - view.destroy(); - } - - if(this.container){ - this.container.removeChild(view.element); - } - view = null; -}; - -// Iterators - -Views.prototype.each = function() { - return this._views.forEach.apply(this._views, arguments); -}; - -Views.prototype.clear = function(){ - // Remove all views - var view; - var len = this.length; - - if(!this.length) return; - - for (var i = 0; i < len; i++) { - view = this._views[i]; - this.destroy(view); - } - - this._views = []; - this.length = 0; -}; - -Views.prototype.find = function(section){ - - var view; - var len = this.length; - - for (var i = 0; i < len; i++) { - view = this._views[i]; - if(view.displayed && view.section.index == section.index) { - return view; - } - } - -}; - -Views.prototype.displayed = function(){ - var displayed = []; - var view; - var len = this.length; - - for (var i = 0; i < len; i++) { - view = this._views[i]; - if(view.displayed){ - displayed.push(view); - } - } - return displayed; -}; - -Views.prototype.show = function(){ - var view; - var len = this.length; - - for (var i = 0; i < len; i++) { - view = this._views[i]; - if(view.displayed){ - view.show(); - } - } - this.hidden = false; -}; - -Views.prototype.hide = function(){ - var view; - var len = this.length; - - for (var i = 0; i < len; i++) { - view = this._views[i]; - if(view.displayed){ - view.hide(); - } - } - this.hidden = true; -}; - -module.exports = Views; - -},{}],29:[function(require,module,exports){ -var RSVP = require('rsvp'); -var core = require('../core'); -var EpubCFI = require('../epubcfi'); -var Contents = require('../contents'); +var core = require('../../core'); +var EpubCFI = require('../../epubcfi'); +var Contents = require('../../contents'); function IframeView(section, options) { this.settings = core.extend({ @@ -12954,7 +10538,2423 @@ RSVP.EventTarget.mixin(IframeView.prototype); module.exports = IframeView; -},{"../contents":9,"../core":10,"../epubcfi":11,"rsvp":5}],"epub":[function(require,module,exports){ +},{"../../contents":9,"../../core":10,"../../epubcfi":11,"rsvp":5}],20:[function(require,module,exports){ +var EpubCFI = require('./epubcfi'); + +function Mapping(layout){ + this.layout = layout; +}; + +Mapping.prototype.section = function(view) { + var ranges = this.findRanges(view); + var map = this.rangeListToCfiList(view.section.cfiBase, ranges); + + return map; +}; + +Mapping.prototype.page = function(contents, cfiBase, start, end) { + var root = contents && contents.document ? contents.document.body : false; + + if (!root) { + return; + } + + return this.rangePairToCfiPair(cfiBase, { + start: this.findStart(root, start, end), + end: this.findEnd(root, start, end) + }); +}; + +Mapping.prototype.walk = function(root, func) { + //var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false); + var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { + acceptNode: function (node) { + if ( node.data.trim().length > 0 ) { + return NodeFilter.FILTER_ACCEPT; + } else { + return NodeFilter.FILTER_REJECT; + } + } + }, false); + var node; + var result; + while ((node = treeWalker.nextNode())) { + result = func(node); + if(result) break; + } + + return result; +}; + +Mapping.prototype.findRanges = function(view){ + var columns = []; + var scrollWidth = view.contents.scrollWidth(); + var count = this.layout.count(scrollWidth); + var column = this.layout.column; + var gap = this.layout.gap; + var start, end; + + for (var i = 0; i < count.pages; i++) { + start = (column + gap) * i; + end = (column * (i+1)) + (gap * i); + columns.push({ + start: this.findStart(view.document.body, start, end), + end: this.findEnd(view.document.body, start, end) + }); + } + + return columns; +}; + +Mapping.prototype.findStart = function(root, start, end){ + var stack = [root]; + var $el; + var found; + var $prev = root; + while (stack.length) { + + $el = stack.shift(); + + found = this.walk($el, function(node){ + var left, right; + var elPos; + var elRange; + + + if(node.nodeType == Node.TEXT_NODE){ + elRange = document.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + } else { + elPos = node.getBoundingClientRect(); + } + + left = elPos.left; + right = elPos.right; + + if( left >= start && left <= end ) { + return node; + } else if (right > start) { + return node; + } else { + $prev = node; + stack.push(node); + } + + }); + + if(found) { + return this.findTextStartRange(found, start, end); + } + + } + + // Return last element + return this.findTextStartRange($prev, start, end); +}; + +Mapping.prototype.findEnd = function(root, start, end){ + var stack = [root]; + var $el; + var $prev = root; + var found; + + while (stack.length) { + + $el = stack.shift(); + + found = this.walk($el, function(node){ + + var left, right; + var elPos; + var elRange; + + + if(node.nodeType == Node.TEXT_NODE){ + elRange = document.createRange(); + elRange.selectNodeContents(node); + elPos = elRange.getBoundingClientRect(); + } else { + elPos = node.getBoundingClientRect(); + } + + left = elPos.left; + right = elPos.right; + + if(left > end && $prev) { + return $prev; + } else if(right > end) { + return node; + } else { + $prev = node; + stack.push(node); + } + + }); + + + if(found){ + return this.findTextEndRange(found, start, end); + } + + } + + // end of chapter + return this.findTextEndRange($prev, start, end); +}; + + +Mapping.prototype.findTextStartRange = function(node, start, end){ + var ranges = this.splitTextNodeIntoRanges(node); + var prev; + var range; + var pos; + + for (var i = 0; i < ranges.length; i++) { + range = ranges[i]; + + pos = range.getBoundingClientRect(); + + if( pos.left >= start ) { + return range; + } + + prev = range; + + } + + return ranges[0]; +}; + +Mapping.prototype.findTextEndRange = function(node, start, end){ + var ranges = this.splitTextNodeIntoRanges(node); + var prev; + var range; + var pos; + + for (var i = 0; i < ranges.length; i++) { + range = ranges[i]; + + pos = range.getBoundingClientRect(); + + if(pos.left > end && prev) { + return prev; + } else if(pos.right > end) { + return range; + } + + prev = range; + + } + + // Ends before limit + return ranges[ranges.length-1]; + +}; + +Mapping.prototype.splitTextNodeIntoRanges = function(node, _splitter){ + var ranges = []; + var textContent = node.textContent || ""; + var text = textContent.trim(); + var range; + var rect; + var list; + var doc = node.ownerDocument; + var splitter = _splitter || " "; + + pos = text.indexOf(splitter); + + if(pos === -1 || node.nodeType != Node.TEXT_NODE) { + range = doc.createRange(); + range.selectNodeContents(node); + return [range]; + } + + range = doc.createRange(); + range.setStart(node, 0); + range.setEnd(node, pos); + ranges.push(range); + range = false; + + while ( pos != -1 ) { + + pos = text.indexOf(splitter, pos + 1); + if(pos > 0) { + + if(range) { + range.setEnd(node, pos); + ranges.push(range); + } + + range = doc.createRange(); + range.setStart(node, pos+1); + } + } + + if(range) { + range.setEnd(node, text.length); + ranges.push(range); + } + + return ranges; +}; + + + +Mapping.prototype.rangePairToCfiPair = function(cfiBase, rangePair){ + + var startRange = rangePair.start; + var endRange = rangePair.end; + + startRange.collapse(true); + endRange.collapse(true); + + // startCfi = section.cfiFromRange(startRange); + // endCfi = section.cfiFromRange(endRange); + startCfi = new EpubCFI(startRange, cfiBase).toString(); + endCfi = new EpubCFI(endRange, cfiBase).toString(); + + return { + start: startCfi, + end: endCfi + }; + +}; + +Mapping.prototype.rangeListToCfiList = function(cfiBase, columns){ + var map = []; + var rangePair, cifPair; + + for (var i = 0; i < columns.length; i++) { + cifPair = this.rangePairToCfiPair(cfiBase, columns[i]); + + map.push(cifPair); + + } + + return map; +}; + +module.exports = Mapping; + +},{"./epubcfi":11}],21:[function(require,module,exports){ +var core = require('./core'); +var Parser = require('./parser'); +var RSVP = require('rsvp'); +var URI = require('urijs'); + +function Navigation(_package, _request){ + var navigation = this; + var parse = new Parser(); + var request = _request || require('./request'); + + this.package = _package; + this.toc = []; + this.tocByHref = {}; + this.tocById = {}; + + if(_package.navPath) { + this.navUrl = URI(_package.navPath).absoluteTo(_package.baseUrl).toString(); + this.nav = {}; + + this.nav.load = function(_request){ + var loading = new RSVP.defer(); + var loaded = loading.promise; + + request(navigation.navUrl, 'xml').then(function(xml){ + navigation.toc = parse.nav(xml); + navigation.loaded(navigation.toc); + loading.resolve(navigation.toc); + }); + + return loaded; + }; + + } + + if(_package.ncxPath) { + this.ncxUrl = URI(_package.ncxPath).absoluteTo(_package.baseUrl).toString(); + this.ncx = {}; + + this.ncx.load = function(_request){ + var loading = new RSVP.defer(); + var loaded = loading.promise; + + request(navigation.ncxUrl, 'xml').then(function(xml){ + navigation.toc = parse.toc(xml); + navigation.loaded(navigation.toc); + loading.resolve(navigation.toc); + }); + + return loaded; + }; + + } +}; + +// Load the navigation +Navigation.prototype.load = function(_request) { + var request = _request || require('./request'); + var loading, loaded; + + if(this.nav) { + loading = this.nav.load(); + } else if(this.ncx) { + loading = this.ncx.load(); + } else { + loaded = new RSVP.defer(); + loaded.resolve([]); + loading = loaded.promise; + } + + return loading; + +}; + +Navigation.prototype.loaded = function(toc) { + var item; + + for (var i = 0; i < toc.length; i++) { + item = toc[i]; + this.tocByHref[item.href] = i; + this.tocById[item.id] = i; + } + +}; + +// Get an item from the navigation +Navigation.prototype.get = function(target) { + var index; + + if(!target) { + return this.toc; + } + + if(target.indexOf("#") === 0) { + index = this.tocById[target.substring(1)]; + } else if(target in this.tocByHref){ + index = this.tocByHref[target]; + } + + return this.toc[index]; +}; + +module.exports = Navigation; + +},{"./core":10,"./parser":22,"./request":26,"rsvp":5,"urijs":7}],22:[function(require,module,exports){ +var URI = require('urijs'); +var core = require('./core'); +var EpubCFI = require('./epubcfi'); + + +function Parser(){}; + +Parser.prototype.container = function(containerXml){ + //-- + var rootfile, fullpath, folder, encoding; + + if(!containerXml) { + console.error("Container File Not Found"); + return; + } + + rootfile = core.qs(containerXml, "rootfile"); + + if(!rootfile) { + console.error("No RootFile Found"); + return; + } + + fullpath = rootfile.getAttribute('full-path'); + folder = URI(fullpath).directory(); + encoding = containerXml.xmlEncoding; + + //-- Now that we have the path we can parse the contents + return { + 'packagePath' : fullpath, + 'basePath' : folder, + 'encoding' : encoding + }; +}; + +Parser.prototype.identifier = function(packageXml){ + var metadataNode; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = core.qs(packageXml, "metadata"); + + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + return this.getElementText(metadataNode, "identifier"); +}; + +Parser.prototype.packageContents = function(packageXml){ + var parse = this; + var metadataNode, manifestNode, spineNode; + var manifest, navPath, ncxPath, coverPath; + var spineNodeIndex; + var spine; + var spineIndexByURL; + var metadata; + + if(!packageXml) { + console.error("Package File Not Found"); + return; + } + + metadataNode = core.qs(packageXml, "metadata"); + if(!metadataNode) { + console.error("No Metadata Found"); + return; + } + + manifestNode = core.qs(packageXml, "manifest"); + if(!manifestNode) { + console.error("No Manifest Found"); + return; + } + + spineNode = core.qs(packageXml, "spine"); + if(!spineNode) { + console.error("No Spine Found"); + return; + } + + manifest = parse.manifest(manifestNode); + navPath = parse.findNavPath(manifestNode); + ncxPath = parse.findNcxPath(manifestNode, spineNode); + coverPath = parse.findCoverPath(packageXml); + + spineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode); + + spine = parse.spine(spineNode, manifest); + + metadata = parse.metadata(metadataNode); + + metadata.direction = spineNode.getAttribute("page-progression-direction"); + + return { + 'metadata' : metadata, + 'spine' : spine, + 'manifest' : manifest, + 'navPath' : navPath, + 'ncxPath' : ncxPath, + 'coverPath': coverPath, + 'spineNodeIndex' : spineNodeIndex + }; +}; + +//-- Find TOC NAV +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 ']"); + var node = core.qsp(manifestNode, "item", {"properties":"nav"}); + return node ? node.getAttribute('href') : false; +}; + +//-- Find TOC NCX: media-type="application/x-dtbncx+xml" href="toc.ncx" +Parser.prototype.findNcxPath = function(manifestNode, spineNode){ + // var node = manifestNode.querySelector("item[media-type='application/x-dtbncx+xml']"); + var node = core.qsp(manifestNode, "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 + "']"); + node = manifestNode.getElementById(tocId); + } + } + + return node ? node.getAttribute('href') : false; +}; + +//-- Expanded to match Readium web components +Parser.prototype.metadata = function(xml){ + var metadata = {}, + p = this; + + metadata.title = 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.getPropertyText(xml, 'dcterms:modified'); + + metadata.layout = p.getPropertyText(xml, "rendition:layout"); + metadata.orientation = p.getPropertyText(xml, 'rendition:orientation'); + metadata.flow = p.getPropertyText(xml, 'rendition:flow'); + metadata.viewport = p.getPropertyText(xml, 'rendition:viewport'); + // metadata.page_prog_dir = packageXml.querySelector("spine").getAttribute("page-progression-direction"); + + return metadata; +}; + +//-- Find Cover: +//-- Fallback for Epub 2.0 +Parser.prototype.findCoverPath = function(packageXml){ + var pkg = core.qs(packageXml, "package"); + var epubVersion = pkg.getAttribute('version'); + + if (epubVersion === '2.0') { + var metaCover = core.qsp(packageXml, 'meta', {'name':'cover'}); + if (metaCover) { + var coverId = metaCover.getAttribute('content'); + // var cover = packageXml.querySelector("item[id='" + coverId + "']"); + var cover = packageXml.getElementById(coverId); + return cover ? cover.getAttribute('href') : false; + } + else { + return false; + } + } + else { + // var node = packageXml.querySelector("item[properties='cover-image']"); + var node = core.qsp(packageXml, 'item', {'properties':'cover-image'}); + return node ? node.getAttribute('href') : false; + } +}; + +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 ''; + +}; + +Parser.prototype.getPropertyText = function(xml, property){ + var el = core.qsp(xml, "meta", {"property":property}); + + if(el && el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; +}; + +Parser.prototype.querySelectorText = function(xml, q){ + var el = xml.querySelector(q); + + if(el && el.childNodes.length){ + return el.childNodes[0].nodeValue; + } + + return ''; +}; + +Parser.prototype.manifest = function(manifestXml){ + var manifest = {}; + + //-- Turn items into an array + // var selected = manifestXml.querySelectorAll("item"); + var selected = core.qsa(manifestXml, "item"); + var 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' : href, + 'type' : type, + 'properties' : properties.length ? properties.split(' ') : [] + }; + + }); + + return manifest; + +}; + +Parser.prototype.spine = function(spineXml, manifest){ + var spine = []; + + var selected = spineXml.getElementsByTagName("itemref"), + items = Array.prototype.slice.call(selected); + + var epubcfi = new EpubCFI(); + + //-- Add to array to mantain ordering and cross reference with manifest + items.forEach(function(item, index){ + var idref = 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 itemref = { + 'idref' : idref, + 'linear' : item.getAttribute('linear') || '', + 'properties' : propArray, + // 'href' : manifest[Id].href, + // 'url' : manifest[Id].url, + 'index' : index + // 'cfiBase' : cfiBase + }; + spine.push(itemref); + }); + + return spine; +}; + +Parser.prototype.querySelectorByType = function(html, element, type){ + var query; + if (typeof html.querySelector != "undefined") { + query = html.querySelector(element+'[*|type="'+type+'"]'); + } + // Handle IE not supporting namespaced epub:type in querySelector + if(!query || query.length === 0) { + query = core.qsa(html, element); + for (var i = 0; i < query.length; i++) { + if(query[i].getAttributeNS("http://www.idpf.org/2007/ops", "type") === type) { + return query[i]; + } + } + } else { + return query; + } +}; + +Parser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){ + var navElement = this.querySelectorByType(navHtml, "nav", "toc"); + // var navItems = navElement ? navElement.querySelectorAll("ol li") : []; + var navItems = navElement ? core.qsa(navElement, "li") : []; + var length = navItems.length; + var i; + var toc = {}; + var list = []; + var item, parent; + + if(!navItems || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.navItem(navItems[i], spineIndexByURL, bookSpine); + toc[item.id] = item; + if(!item.parent) { + list.push(item); + } else { + parent = toc[item.parent]; + parent.subitems.push(item); + } + } + + return list; +}; + +Parser.prototype.navItem = function(item, spineIndexByURL, bookSpine){ + var id = item.getAttribute('id') || false, + // content = item.querySelector("a, span"), + content = core.qs(item, "a"), + src = content.getAttribute('href') || '', + text = content.textContent || "", + // split = src.split("#"), + // baseUrl = split[0], + // spinePos = spineIndexByURL[baseUrl], + // spineItem = bookSpine[spinePos], + subitems = [], + parentNode = item.parentNode, + parent; + // cfi = spineItem ? spineItem.cfi : ''; + + if(parentNode && parentNode.nodeName === "navPoint") { + parent = parentNode.getAttribute('id'); + } + + /* + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid(); + item.setAttribute('id', id); + } + } + */ + + return { + "id": id, + "href": src, + "label": text, + "subitems" : subitems, + "parent" : parent + }; +}; + +Parser.prototype.ncx = function(tocXml, spineIndexByURL, bookSpine){ + // var navPoints = tocXml.querySelectorAll("navMap navPoint"); + var navPoints = core.qsa(tocXml, "navPoint"); + var length = navPoints.length; + var i; + var toc = {}; + var list = []; + var item, parent; + + if(!navPoints || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.ncxItem(navPoints[i], spineIndexByURL, bookSpine); + toc[item.id] = item; + if(!item.parent) { + list.push(item); + } else { + parent = toc[item.parent]; + parent.subitems.push(item); + } + } + + return list; +}; + +Parser.prototype.ncxItem = function(item, spineIndexByURL, bookSpine){ + var id = item.getAttribute('id') || false, + // content = item.querySelector("content"), + content = core.qs(item, "content"), + src = content.getAttribute('src'), + // navLabel = item.querySelector("navLabel"), + navLabel = core.qs(item, "navLabel"), + text = navLabel.textContent ? navLabel.textContent : "", + // split = src.split("#"), + // baseUrl = split[0], + // spinePos = spineIndexByURL[baseUrl], + // spineItem = bookSpine[spinePos], + subitems = [], + parentNode = item.parentNode, + parent; + // cfi = spineItem ? spineItem.cfi : ''; + + if(parentNode && parentNode.nodeName === "navPoint") { + parent = parentNode.getAttribute('id'); + } + + /* + if(!id) { + if(spinePos) { + spineItem = bookSpine[spinePos]; + id = spineItem.id; + cfi = spineItem.cfi; + } else { + id = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid(); + item.setAttribute('id', id); + } + } + */ + + return { + "id": id, + "href": src, + "label": text, + "subitems" : subitems, + "parent" : parent + }; +}; + +Parser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){ + var navElement = this.querySelectorByType(navHtml, "nav", "page-list"); + // var navItems = navElement ? navElement.querySelectorAll("ol li") : []; + var navItems = navElement ? core.qsa(navElement, "li") : []; + var length = navItems.length; + var i; + var toc = {}; + var list = []; + var item; + + if(!navItems || length === 0) return list; + + for (i = 0; i < length; ++i) { + item = this.pageListItem(navItems[i], spineIndexByURL, bookSpine); + list.push(item); + } + + return list; +}; + +Parser.prototype.pageListItem = function(item, spineIndexByURL, bookSpine){ + var id = item.getAttribute('id') || false, + // content = item.querySelector("a"), + content = core.qs(item, "a"), + 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; + return { + "cfi" : cfi, + "href" : href, + "packageUrl" : packageUrl, + "page" : page + }; + } else { + return { + "href" : href, + "page" : page + }; + } +}; + +module.exports = Parser; + +},{"./core":10,"./epubcfi":11,"urijs":7}],23:[function(require,module,exports){ +var RSVP = require('rsvp'); +var core = require('./core'); + +function Queue(_context){ + this._q = []; + this.context = _context; + this.tick = core.requestAnimationFrame; + this.running = false; + this.paused = false; +}; + +// Add an item to the queue +Queue.prototype.enqueue = function() { + var deferred, promise; + var queued; + var task = [].shift.call(arguments); + var args = arguments; + + // Handle single args without context + // if(args && !Array.isArray(args)) { + // args = [args]; + // } + if(!task) { + return console.error("No Task Provided"); + } + + if(typeof task === "function"){ + + deferred = new RSVP.defer(); + promise = deferred.promise; + + queued = { + "task" : task, + "args" : args, + //"context" : context, + "deferred" : deferred, + "promise" : promise + }; + + } else { + // Task is a promise + queued = { + "promise" : task + }; + + } + + this._q.push(queued); + + // Wait to start queue flush + if (this.paused == false && !this.running) { + // setTimeout(this.flush.bind(this), 0); + // this.tick.call(window, this.run.bind(this)); + this.run(); + } + + return queued.promise; +}; + +// Run one item +Queue.prototype.dequeue = function(){ + var inwait, task, result; + + if(this._q.length) { + inwait = this._q.shift(); + task = inwait.task; + if(task){ + // console.log(task) + + result = task.apply(this.context, inwait.args); + + if(result && typeof result["then"] === "function") { + // Task is a function that returns a promise + return result.then(function(){ + inwait.deferred.resolve.apply(this.context, arguments); + }.bind(this)); + } else { + // Task resolves immediately + inwait.deferred.resolve.apply(this.context, result); + return inwait.promise; + } + + + + } else if(inwait.promise) { + // Task is a promise + return inwait.promise; + } + + } else { + inwait = new RSVP.defer(); + inwait.deferred.resolve(); + return inwait.promise; + } + +}; + +// Run All Immediately +Queue.prototype.dump = function(){ + while(this._q.length) { + this.dequeue(); + } +}; + +// Run all sequentially, at convince + +Queue.prototype.run = function(){ + + if(!this.running){ + this.running = true; + this.defered = new RSVP.defer(); + } + + this.tick.call(window, function() { + + if(this._q.length) { + + this.dequeue() + .then(function(){ + this.run(); + }.bind(this)); + + } else { + this.defered.resolve(); + this.running = undefined; + } + + }.bind(this)); + + // Unpause + if(this.paused == true) { + this.paused = false; + } + + return this.defered.promise; +}; + +// Flush all, as quickly as possible +Queue.prototype.flush = function(){ + + if(this.running){ + return this.running; + } + + if(this._q.length) { + this.running = this.dequeue() + .then(function(){ + this.running = undefined; + return this.flush(); + }.bind(this)); + + return this.running; + } + +}; + +// Clear all items in wait +Queue.prototype.clear = function(){ + this._q = []; + this.running = false; +}; + +Queue.prototype.length = function(){ + return this._q.length; +}; + +Queue.prototype.pause = function(){ + this.paused = true; +}; + +// Create a new task from a callback +function Task(task, args, context){ + + return function(){ + var toApply = arguments || []; + + return new RSVP.Promise(function(resolve, reject) { + var callback = function(value){ + resolve(value); + }; + // Add the callback to the arguments list + toApply.push(callback); + + // Apply all arguments to the functions + task.apply(this, toApply); + + }.bind(this)); + + }; + +}; + +module.exports = Queue; + +},{"./core":10,"rsvp":5}],24:[function(require,module,exports){ +var RSVP = require('rsvp'); +var URI = require('urijs'); +var core = require('./core'); +var replace = require('./replacements'); +var Hook = require('./hook'); +var EpubCFI = require('./epubcfi'); +var Queue = require('./queue'); +var Layout = require('./layout'); +var Mapping = require('./mapping'); + +function Rendition(book, options) { + + this.settings = core.extend(this.settings || {}, { + width: null, + height: null, + ignoreClass: '', + manager: "single", + view: "iframe", + flow: null, + layout: null, + spread: null, + minSpreadWidth: 800, //-- overridden by spread: none (never) / both (always), + useBase64: true + }); + + core.extend(this.settings, options); + + this.viewSettings = { + ignoreClass: this.settings.ignoreClass + }; + + this.book = book; + + this.views = null; + + //-- Adds Hook methods to the Rendition prototype + this.hooks = {}; + this.hooks.display = new Hook(this); + this.hooks.serialize = new Hook(this); + this.hooks.content = new Hook(this); + this.hooks.layout = new Hook(this); + this.hooks.render = new Hook(this); + this.hooks.show = new Hook(this); + + this.hooks.content.register(replace.links.bind(this)); + this.hooks.content.register(this.passViewEvents.bind(this)); + + // this.hooks.display.register(this.afterDisplay.bind(this)); + + this.epubcfi = new EpubCFI(); + + this.q = new Queue(this); + + this.q.enqueue(this.book.opened); + + // Block the queue until rendering is started + // this.starting = new RSVP.defer(); + // this.started = this.starting.promise; + this.q.enqueue(this.start); + + if(this.book.unarchived) { + this.q.enqueue(this.replacements.bind(this)); + } + +}; + +Rendition.prototype.setManager = function(manager) { + this.manager = manager; +}; + +Rendition.prototype.requireManager = function(manager) { + var viewManager; + + // If manager is a string, try to load from register managers, + // or require included managers directly + if (typeof manager === "string") { + // Use global or require + viewManager = typeof ePub != "undefined" ? ePub.ViewManagers[manager] : undefined; //require('./managers/'+manager); + } else { + // otherwise, assume we were passed a function + viewManager = manager + } + + return viewManager; +}; + +Rendition.prototype.requireView = function(view) { + var View; + + if (typeof view == "string") { + View = typeof ePub != "undefined" ? ePub.Views[view] : undefined; //require('./views/'+view); + } else { + // otherwise, assume we were passed a function + View = view + } + + return View; +}; + +Rendition.prototype.start = function(){ + + if(!this.manager) { + this.ViewManager = this.requireManager(this.settings.manager); + this.View = this.requireView(this.settings.view); + + this.manager = new this.ViewManager({ + view: this.View, + queue: this.q, + request: this.book.request, + settings: this.settings + }); + } + + // Parse metadata to get layout props + this.settings.globalLayoutProperties = this.determineLayoutProperties(this.book.package.metadata); + + this.flow(this.settings.globalLayoutProperties.flow); + + this.layout(this.settings.globalLayoutProperties); + + // Listen for displayed views + this.manager.on("added", this.afterDisplayed.bind(this)); + + // Listen for resizing + this.manager.on("resized", this.onResized.bind(this)); + + // Listen for scroll changes + this.manager.on("scroll", this.reportLocation.bind(this)); + + + this.on('displayed', this.reportLocation.bind(this)); + + // Trigger that rendering has started + this.trigger("started"); + + // Start processing queue + // this.starting.resolve(); +}; + +// Call to attach the container to an element in the dom +// Container must be attached before rendering can begin +Rendition.prototype.attachTo = function(element){ + + return this.q.enqueue(function () { + + // Start rendering + this.manager.render(element, { + "width" : this.settings.width, + "height" : this.settings.height + }); + + // Trigger Attached + this.trigger("attached"); + + }.bind(this)); + +}; + +Rendition.prototype.display = function(target){ + + // if (!this.book.spine.spineItems.length > 0) { + // Book isn't open yet + // return this.q.enqueue(this.display, target); + // } + + return this.q.enqueue(this._display, target); + +}; + +Rendition.prototype._display = function(target){ + var isCfiString = this.epubcfi.isCfiString(target); + var displaying = new RSVP.defer(); + var displayed = displaying.promise; + var section; + var moveTo; + + section = this.book.spine.get(target); + + if(!section){ + displaying.reject(new Error("No Section Found")); + return displayed; + } + + // Trim the target fragment + // removing the chapter + if(!isCfiString && typeof target === "string" && + target.indexOf("#") > -1) { + moveTo = target.substring(target.indexOf("#")+1); + } + + if (isCfiString) { + moveTo = target; + } + + return this.manager.display(section, moveTo) + .then(function(){ + this.trigger("displayed", section); + }.bind(this)); + +}; + +/* +Rendition.prototype.render = function(view, show) { + + // view.onLayout = this.layout.format.bind(this.layout); + view.create(); + + // Fit to size of the container, apply padding + this.manager.resizeView(view); + + // Render Chain + return view.section.render(this.book.request) + .then(function(contents){ + return view.load(contents); + }.bind(this)) + .then(function(doc){ + return this.hooks.content.trigger(view, this); + }.bind(this)) + .then(function(){ + this.layout.format(view.contents); + return this.hooks.layout.trigger(view, this); + }.bind(this)) + .then(function(){ + return view.display(); + }.bind(this)) + .then(function(){ + return this.hooks.render.trigger(view, this); + }.bind(this)) + .then(function(){ + if(show !== false) { + this.q.enqueue(function(view){ + view.show(); + }, view); + } + // this.map = new Map(view, this.layout); + this.hooks.show.trigger(view, this); + this.trigger("rendered", view.section); + + }.bind(this)) + .catch(function(e){ + this.trigger("loaderror", e); + }.bind(this)); + +}; +*/ + +Rendition.prototype.afterDisplayed = function(view){ + this.hooks.content.trigger(view, this); + this.trigger("rendered", view.section); + this.reportLocation(); +}; + +Rendition.prototype.onResized = function(size){ + + if(this.location) { + this.display(this.location.start); + } + + this.trigger("resized", { + width: size.width, + height: size.height + }); + +}; + +Rendition.prototype.moveTo = function(offset){ + this.manager.moveTo(offset); +}; + +Rendition.prototype.next = function(){ + return this.q.enqueue(this.manager.next.bind(this.manager)) + .then(this.reportLocation.bind(this)); +}; + +Rendition.prototype.prev = function(){ + return this.q.enqueue(this.manager.prev.bind(this.manager)) + .then(this.reportLocation.bind(this)); +}; + +//-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering +Rendition.prototype.determineLayoutProperties = function(metadata){ + var settings; + var layout = this.settings.layout || metadata.layout || "reflowable"; + var spread = this.settings.spread || metadata.spread || "auto"; + var orientation = this.settings.orientation || metadata.orientation || "auto"; + var flow = this.settings.flow || metadata.flow || "auto"; + var viewport = metadata.viewport || ""; + var minSpreadWidth = this.settings.minSpreadWidth || metadata.minSpreadWidth || 800; + + if (this.settings.width >= 0 && this.settings.height >= 0) { + viewport = "width="+this.settings.width+", height="+this.settings.height+""; + } + + settings = { + layout : layout, + spread : spread, + orientation : orientation, + flow : flow, + viewport : viewport, + minSpreadWidth : minSpreadWidth + }; + + return settings; +}; + +// Rendition.prototype.applyLayoutProperties = function(){ +// var settings = this.determineLayoutProperties(this.book.package.metadata); +// +// this.flow(settings.flow); +// +// this.layout(settings); +// }; + +// paginated | scrolled +// (scrolled-continuous vs scrolled-doc are handled by different view managers) +Rendition.prototype.flow = function(_flow){ + var flow; + if (_flow === "scrolled-doc" || _flow === "scrolled-continuous") { + flow = "scrolled"; + } + + if (_flow === "auto" || _flow === "paginated") { + flow = "paginated"; + } + + if (this._layout) { + this._layout.flow(flow); + } + + if (this.manager) { + this.manager.updateFlow(flow); + } +}; + +// reflowable | pre-paginated +Rendition.prototype.layout = function(settings){ + if (settings) { + this._layout = new Layout(settings); + this._layout.spread(settings.spread, this.settings.minSpreadWidth); + + this.mapping = new Mapping(this._layout); + } + + if (this.manager && this._layout) { + this.manager.applyLayout(this._layout); + } + + return this._layout; +}; + +// none | auto (TODO: implement landscape, portrait, both) +Rendition.prototype.spread = function(spread, min){ + + this._layout.spread(spread, min); + + if (this.manager.isRendered()) { + this.manager.updateLayout(); + } +}; + + +Rendition.prototype.reportLocation = function(){ + return this.q.enqueue(function(){ + var location = this.manager.currentLocation(); + if (location && location.then && typeof location.then === 'function') { + location.then(function(result) { + this.location = result; + this.trigger("locationChanged", this.location); + }.bind(this)); + } else if (location) { + this.location = location; + this.trigger("locationChanged", this.location); + } + + }.bind(this)); +}; + + +Rendition.prototype.destroy = function(){ + // Clear the queue + this.q.clear(); + + this.manager.destroy(); +}; + +Rendition.prototype.passViewEvents = function(view){ + view.contents.listenedEvents.forEach(function(e){ + view.on(e, this.triggerViewEvent.bind(this)); + }.bind(this)); + + view.on("selected", this.triggerSelectedEvent.bind(this)); +}; + +Rendition.prototype.triggerViewEvent = function(e){ + this.trigger(e.type, e); +}; + +Rendition.prototype.triggerSelectedEvent = function(cfirange){ + this.trigger("selected", cfirange); +}; + +Rendition.prototype.replacements = function(){ + // Wait for loading + // return this.q.enqueue(function () { + // Get thes books manifest + var manifest = this.book.package.manifest; + var manifestArray = Object.keys(manifest). + map(function (key){ + return manifest[key]; + }); + + // Exclude HTML + var items = manifestArray. + filter(function (item){ + if (item.type != "application/xhtml+xml" && + item.type != "text/html") { + return true; + } + }); + + // Only CSS + var css = items. + filter(function (item){ + if (item.type === "text/css") { + return true; + } + }); + + // Css Urls + var cssUrls = css.map(function(item) { + return item.href; + }); + + // All Assets Urls + var urls = items. + map(function(item) { + return item.href; + }.bind(this)); + + // Create blob urls for all the assets + var processing = urls. + map(function(url) { + var absolute = URI(url).absoluteTo(this.book.baseUrl).toString(); + // Full url from archive base + return this.book.unarchived.createUrl(absolute, {"base64": this.settings.useBase64}); + }.bind(this)); + + var replacementUrls; + + // After all the urls are created + return RSVP.all(processing) + .then(function(_replacementUrls) { + var replaced = []; + + replacementUrls = _replacementUrls; + + // Replace Asset Urls in the text of all css files + cssUrls.forEach(function(href) { + replaced.push(this.replaceCss(href, urls, replacementUrls)); + }.bind(this)); + + return RSVP.all(replaced); + + }.bind(this)) + .then(function () { + // Replace Asset Urls in chapters + // by registering a hook after the sections contents has been serialized + this.book.spine.hooks.serialize.register(function(output, section) { + + this.replaceAssets(section, urls, replacementUrls); + + }.bind(this)); + + }.bind(this)) + .catch(function(reason){ + console.error(reason); + }); + // }.bind(this)); +}; + +Rendition.prototype.replaceCss = function(href, urls, replacementUrls){ + var newUrl; + var indexInUrls; + + // Find the absolute url of the css file + var fileUri = URI(href); + var absolute = fileUri.absoluteTo(this.book.baseUrl).toString(); + // Get the text of the css file from the archive + var textResponse = this.book.unarchived.getText(absolute); + // Get asset links relative to css file + var relUrls = urls. + map(function(assetHref) { + var assetUri = URI(assetHref).absoluteTo(this.book.baseUrl); + var relative = assetUri.relativeTo(absolute).toString(); + return relative; + }.bind(this)); + + return textResponse.then(function (text) { + // Replacements in the css text + text = replace.substitute(text, relUrls, replacementUrls); + + // Get the new url + if (this.settings.useBase64) { + newUrl = core.createBase64Url(text, 'text/css'); + } else { + newUrl = core.createBlobUrl(text, 'text/css'); + } + + // switch the url in the replacementUrls + indexInUrls = urls.indexOf(href); + if (indexInUrls > -1) { + replacementUrls[indexInUrls] = newUrl; + } + + return new RSVP.Promise(function(resolve, reject){ + resolve(urls, replacementUrls); + }); + + }.bind(this)); + +}; + +Rendition.prototype.replaceAssets = function(section, urls, replacementUrls){ + var fileUri = URI(section.url); + // Get Urls relative to current sections + var relUrls = urls. + map(function(href) { + var assetUri = URI(href).absoluteTo(this.book.baseUrl); + var relative = assetUri.relativeTo(fileUri).toString(); + return relative; + }.bind(this)); + + + section.output = replace.substitute(section.output, relUrls, replacementUrls); +}; + +Rendition.prototype.range = function(_cfi, ignoreClass){ + var cfi = new EpubCFI(_cfi); + var found = this.visible().filter(function (view) { + if(cfi.spinePos === view.index) return true; + }); + + // Should only every return 1 item + if (found.length) { + return found[0].range(cfi, ignoreClass); + } +}; + +Rendition.prototype.adjustImages = function(view) { + + view.addStylesheetRules([ + ["img", + ["max-width", (view.layout.spreadWidth) + "px"], + ["max-height", (view.layout.height) + "px"] + ] + ]); + return new RSVP.Promise(function(resolve, reject){ + // Wait to apply + setTimeout(function() { + resolve(); + }, 1); + }); +}; + +//-- Enable binding events to Renderer +RSVP.EventTarget.mixin(Rendition.prototype); + +module.exports = Rendition; + +},{"./core":10,"./epubcfi":11,"./hook":12,"./layout":13,"./mapping":20,"./queue":23,"./replacements":25,"rsvp":5,"urijs":7}],25:[function(require,module,exports){ +var URI = require('urijs'); +var core = require('./core'); + +function base(doc, section){ + var base; + var head; + + if(!doc){ + return; + } + + // head = doc.querySelector("head"); + // base = head.querySelector("base"); + head = core.qs(doc, "head"); + base = core.qs(head, "base"); + + if(!base) { + base = doc.createElement("base"); + head.insertBefore(base, head.firstChild); + } + + base.setAttribute("href", section.url); +} + +function canonical(doc, section){ + var head; + var link; + var url = section.url; // window.location.origin + window.location.pathname + "?loc=" + encodeURIComponent(section.url); + + if(!doc){ + return; + } + + head = core.qs(doc, "head"); + link = core.qs(head, "link[rel='canonical']"); + + if (link) { + link.setAttribute("href", url); + } else { + link = doc.createElement("link"); + link.setAttribute("rel", "canonical"); + link.setAttribute("href", url); + head.appendChild(link); + } +} + +function links(view, renderer) { + + var links = view.document.querySelectorAll("a[href]"); + var replaceLinks = function(link){ + var href = link.getAttribute("href"); + + if(href.indexOf("mailto:") === 0){ + return; + } + + var linkUri = URI(href); + var absolute = linkUri.absoluteTo(view.section.url); + var relative = absolute.relativeTo(this.book.baseUrl).toString(); + + if(linkUri.protocol()){ + + link.setAttribute("target", "_blank"); + + }else{ + /* + if(baseDirectory) { + // We must ensure that the file:// protocol is preserved for + // local file links, as in certain contexts (such as under + // Titanium), file links without the file:// protocol will not + // work + if (baseUri.protocol === "file") { + relative = core.resolveUrl(baseUri.base, href); + } else { + relative = core.resolveUrl(baseDirectory, href); + } + } else { + relative = href; + } + */ + + if(linkUri.fragment()) { + // do nothing with fragment yet + } else { + link.onclick = function(){ + renderer.display(relative); + return false; + }; + } + + } + }.bind(this); + + for (var i = 0; i < links.length; i++) { + replaceLinks(links[i]); + } + + +}; + +function substitute(content, urls, replacements) { + urls.forEach(function(url, i){ + if (url && replacements[i]) { + content = content.replace(new RegExp(url, 'g'), replacements[i]); + } + }); + return content; +} +module.exports = { + 'base': base, + 'canonical' : canonical, + 'links': links, + 'substitute': substitute +}; + +},{"./core":10,"urijs":7}],26:[function(require,module,exports){ +var RSVP = require('rsvp'); +var URI = require('urijs'); +var core = require('./core'); + +function request(url, type, withCredentials, headers) { + var supportsURL = (typeof window != "undefined") ? window.URL : false; // TODO: fallback for url if window isn't defined + var BLOB_RESPONSE = supportsURL ? "blob" : "arraybuffer"; + var uri; + + 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; + + var header; + + 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.onreadystatechange = handler; + xhr.onerror = err; + + xhr.open("GET", url, true); + + for(header in headers) { + xhr.setRequestHeader(header, headers[header]); + } + + if(type == "json") { + xhr.setRequestHeader("Accept", "application/json"); + } + + // If type isn't set, determine it from the file extension + if(!type) { + uri = URI(url); + type = uri.suffix(); + } + + if(type == 'blob'){ + xhr.responseType = BLOB_RESPONSE; + } + + + if(core.isXml(type)) { + // xhr.responseType = "document"; + xhr.overrideMimeType('text/xml'); // for OPF parsing + } + + if(type == 'xhtml') { + // xhr.responseType = "document"; + } + + if(type == 'html' || type == 'htm') { + // xhr.responseType = "document"; + } + + if(type == "binary") { + xhr.responseType = "arraybuffer"; + } + + xhr.send(); + + function err(e) { + console.error(e); + deferred.reject(e); + } + + function handler() { + if (this.readyState === XMLHttpRequest.DONE) { + + if (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls + var r; + + if (!this.response && !this.responseXML) { + deferred.reject({ + status: this.status, + message : "Empty Response", + stack : new Error().stack + }); + return deferred.promise; + } + + if (this.status === 403) { + deferred.reject({ + status: this.status, + response: this.response, + message : "Forbidden", + stack : new Error().stack + }); + return deferred.promise; + } + + if((this.responseType == '' || this.responseType == 'document') + && this.responseXML){ + r = this.responseXML; + } else + if(core.isXml(type)){ + // xhr.overrideMimeType('text/xml'); // for OPF parsing + // If this.responseXML wasn't set, try to parse using a DOMParser from text + r = core.parse(this.response, "text/xml"); + }else + if(type == 'xhtml'){ + r = core.parse(this.response, "application/xhtml+xml"); + }else + if(type == 'html' || type == 'htm'){ + r = core.parse(this.response, "text/html"); + }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({ + status: this.status, + message : this.response, + stack : new Error().stack + }); + + } + } + } + + return deferred.promise; +}; + +module.exports = request; + +},{"./core":10,"rsvp":5,"urijs":7}],27:[function(require,module,exports){ +var RSVP = require('rsvp'); +var URI = require('urijs'); +var core = require('./core'); +var EpubCFI = require('./epubcfi'); +var Hook = require('./hook'); + +function Section(item, hooks){ + this.idref = item.idref; + this.linear = item.linear; + this.properties = item.properties; + this.index = item.index; + this.href = item.href; + this.url = item.url; + this.next = item.next; + this.prev = item.prev; + + this.cfiBase = item.cfiBase; + + if (hooks) { + this.hooks = hooks; + } else { + this.hooks = {}; + this.hooks.serialize = new Hook(this); + this.hooks.content = new Hook(this); + } + +}; + + +Section.prototype.load = function(_request){ + var request = _request || this.request || require('./request'); + var loading = new RSVP.defer(); + var loaded = loading.promise; + + if(this.contents) { + loading.resolve(this.contents); + } else { + request(this.url) + .then(function(xml){ + var base; + var directory = URI(this.url).directory(); + + this.document = xml; + this.contents = xml.documentElement; + + return this.hooks.content.trigger(this.document, this); + }.bind(this)) + .then(function(){ + loading.resolve(this.contents); + }.bind(this)) + .catch(function(error){ + loading.reject(error); + }); + } + + return loaded; +}; + +Section.prototype.base = function(_document){ + var task = new RSVP.defer(); + var base = _document.createElement("base"); // TODO: check if exists + var head; + console.log(window.location.origin + "/" +this.url); + + base.setAttribute("href", window.location.origin + "/" +this.url); + + if(_document) { + head = _document.querySelector("head"); + } + if(head) { + head.insertBefore(base, head.firstChild); + task.resolve(); + } else { + task.reject(new Error("No head to insert into")); + } + + + return task.promise; +}; + +Section.prototype.beforeSectionLoad = function(){ + // Stub for a hook - replace me for now +}; + +Section.prototype.render = function(_request){ + var rendering = new RSVP.defer(); + var rendered = rendering.promise; + this.output; // TODO: better way to return this from hooks? + + this.load(_request). + then(function(contents){ + var serializer; + + if (typeof XMLSerializer === "undefined") { + XMLSerializer = require('xmldom').XMLSerializer; + } + serializer = new XMLSerializer(); + this.output = serializer.serializeToString(contents); + return this.output; + }.bind(this)). + then(function(){ + return this.hooks.serialize.trigger(this.output, this); + }.bind(this)). + then(function(){ + rendering.resolve(this.output); + }.bind(this)) + .catch(function(error){ + rendering.reject(error); + }); + + return rendered; +}; + +Section.prototype.find = function(_query){ + +}; + +/** +* Reconciles the current chapters layout properies with +* the global layout properities. +* Takes: global layout settings object, chapter properties string +* Returns: Object with layout properties +*/ +Section.prototype.reconcileLayoutSettings = function(global){ + //-- Get the global defaults + var settings = { + layout : global.layout, + spread : global.spread, + orientation : global.orientation + }; + + //-- Get the chapter's display type + this.properties.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; +}; + +Section.prototype.cfiFromRange = function(_range) { + return new EpubCFI(_range, this.cfiBase).toString(); +}; + +Section.prototype.cfiFromElement = function(el) { + return new EpubCFI(el, this.cfiBase).toString(); +}; + +module.exports = Section; + +},{"./core":10,"./epubcfi":11,"./hook":12,"./request":26,"rsvp":5,"urijs":7,"xmldom":"xmldom"}],28:[function(require,module,exports){ +var RSVP = require('rsvp'); +var core = require('./core'); +var EpubCFI = require('./epubcfi'); +var Hook = require('./hook'); +var Section = require('./section'); +var replacements = require('./replacements'); + +function Spine(_request){ + this.request = _request; + this.spineItems = []; + this.spineByHref = {}; + this.spineById = {}; + + this.hooks = {}; + this.hooks.serialize = new Hook(); + this.hooks.content = new Hook(); + + // Register replacements + this.hooks.content.register(replacements.base); + this.hooks.content.register(replacements.canonical); + + this.epubcfi = new EpubCFI(); + + this.loaded = false; +}; + +Spine.prototype.load = function(_package) { + + this.items = _package.spine; + this.manifest = _package.manifest; + this.spineNodeIndex = _package.spineNodeIndex; + this.baseUrl = _package.baseUrl || ''; + this.length = this.items.length; + + this.items.forEach(function(item, index){ + var href, url; + var manifestItem = this.manifest[item.idref]; + var spineItem; + + item.cfiBase = this.epubcfi.generateChapterComponent(this.spineNodeIndex, item.index, item.idref); + + if(manifestItem) { + item.href = manifestItem.href; + item.url = this.baseUrl + item.href; + + if(manifestItem.properties.length){ + item.properties.push.apply(item.properties, manifestItem.properties); + } + } + + // if(index > 0) { + item.prev = function(){ return this.get(index-1); }.bind(this); + // } + + // if(index+1 < this.items.length) { + item.next = function(){ return this.get(index+1); }.bind(this); + // } + + spineItem = new Section(item, this.hooks); + + this.append(spineItem); + + + }.bind(this)); + + this.loaded = true; +}; + +// book.spine.get(); +// book.spine.get(1); +// book.spine.get("chap1.html"); +// book.spine.get("#id1234"); +Spine.prototype.get = function(target) { + var index = 0; + + if(this.epubcfi.isCfiString(target)) { + cfi = new EpubCFI(target); + index = cfi.spinePos; + } else if(target && (typeof target === "number" || isNaN(target) === false)){ + index = target; + } else if(target && target.indexOf("#") === 0) { + index = this.spineById[target.substring(1)]; + } else if(target) { + // Remove fragments + target = target.split("#")[0]; + index = this.spineByHref[target]; + } + + return this.spineItems[index] || null; +}; + +Spine.prototype.append = function(section) { + var index = this.spineItems.length; + section.index = index; + + this.spineItems.push(section); + + this.spineByHref[section.href] = index; + this.spineById[section.idref] = index; + + return index; +}; + +Spine.prototype.prepend = function(section) { + var index = this.spineItems.unshift(section); + this.spineByHref[section.href] = 0; + this.spineById[section.idref] = 0; + + // Re-index + this.spineItems.forEach(function(item, index){ + item.index = index; + }); + + return 0; +}; + +Spine.prototype.insert = function(section, index) { + +}; + +Spine.prototype.remove = function(section) { + var index = this.spineItems.indexOf(section); + + if(index > -1) { + delete this.spineByHref[section.href]; + delete this.spineById[section.idref]; + + return this.spineItems.splice(index, 1); + } +}; + +Spine.prototype.each = function() { + return this.spineItems.forEach.apply(this.spineItems, arguments); +}; + +module.exports = Spine; + +},{"./core":10,"./epubcfi":11,"./hook":12,"./replacements":25,"./section":27,"rsvp":5}],29:[function(require,module,exports){ +var RSVP = require('rsvp'); +var URI = require('urijs'); +var core = require('./core'); +var request = require('./request'); +var mime = require('../libs/mime/mime'); + +function Unarchive() { + + this.checkRequirements(); + this.urlCache = {}; + +} + +Unarchive.prototype.checkRequirements = function(callback){ + try { + if (typeof JSZip !== 'undefined') { + this.zip = new JSZip(); + } else { + JSZip = require('jszip'); + this.zip = new JSZip(); + } + } catch (e) { + console.error("JSZip lib not loaded"); + } +}; + +Unarchive.prototype.open = function(zipUrl, isBase64){ + if (zipUrl instanceof ArrayBuffer || isBase64) { + return this.zip.loadAsync(zipUrl, {"base64": isBase64}); + } else { + return request(zipUrl, "binary") + .then(function(data){ + return this.zip.loadAsync(data); + }.bind(this)); + } +}; + +Unarchive.prototype.request = function(url, type){ + var deferred = new RSVP.defer(); + var response; + var r; + + // If type isn't set, determine it from the file extension + if(!type) { + uri = URI(url); + type = uri.suffix(); + } + + if(type == 'blob'){ + response = this.getBlob(url); + } else { + response = this.getText(url); + } + + if (response) { + response.then(function (r) { + result = this.handleResponse(r, type); + deferred.resolve(result); + }.bind(this)); + } else { + deferred.reject({ + message : "File not found in the epub: " + url, + stack : new Error().stack + }); + } + return deferred.promise; +}; + +Unarchive.prototype.handleResponse = function(response, type){ + var r; + + if(type == "json") { + r = JSON.parse(response); + } + else + if(core.isXml(type)) { + r = core.parse(response, "text/xml"); + } + else + if(type == 'xhtml') { + r = core.parse(response, "application/xhtml+xml"); + } + else + if(type == 'html' || type == 'htm') { + r = core.parse(response, "text/html"); + } else { + r = response; + } + + return r; +}; + +Unarchive.prototype.getBlob = function(url, _mimeType){ + var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash + var entry = this.zip.file(decodededUrl); + var mimeType; + + if(entry) { + mimeType = _mimeType || mime.lookup(entry.name); + return entry.async("uint8array").then(function(uint8array) { + return new Blob([uint8array], {type : mimeType}); + }); + } +}; + +Unarchive.prototype.getText = function(url, encoding){ + var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash + var entry = this.zip.file(decodededUrl); + + if(entry) { + return entry.async("string").then(function(text) { + return text; + }); + } +}; + +Unarchive.prototype.getBase64 = function(url, _mimeType){ + var decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash + var entry = this.zip.file(decodededUrl); + var mimeType; + + if(entry) { + mimeType = _mimeType || mime.lookup(entry.name); + return entry.async("base64").then(function(data) { + return "data:" + mimeType + ";base64," + data; + }); + } +}; + +Unarchive.prototype.createUrl = function(url, options){ + var deferred = new RSVP.defer(); + var _URL = window.URL || window.webkitURL || window.mozURL; + var tempUrl; + var blob; + var response; + var useBase64 = options && options.base64; + + if(url in this.urlCache) { + deferred.resolve(this.urlCache[url]); + return deferred.promise; + } + + if (useBase64) { + response = this.getBase64(url); + + if (response) { + response.then(function(tempUrl) { + + this.urlCache[url] = tempUrl; + deferred.resolve(tempUrl); + + }.bind(this)); + + } + + } else { + + response = this.getBlob(url); + + if (response) { + response.then(function(blob) { + + tempUrl = _URL.createObjectURL(blob); + this.urlCache[url] = tempUrl; + deferred.resolve(tempUrl); + + }.bind(this)); + + } + } + + + if (!response) { + deferred.reject({ + message : "File not found in the epub: " + url, + stack : new Error().stack + }); + } + + return deferred.promise; +}; + +Unarchive.prototype.revokeUrl = function(url){ + var _URL = window.URL || window.webkitURL || window.mozURL; + var fromCache = this.urlCache[url]; + if(fromCache) _URL.revokeObjectURL(fromCache); +}; + +module.exports = Unarchive; + +},{"../libs/mime/mime":1,"./core":10,"./request":26,"jszip":"jszip","rsvp":5,"urijs":7}],"epub":[function(require,module,exports){ var Book = require('./book'); var EpubCFI = require('./epubcfi'); var Rendition = require('./rendition'); @@ -12984,8 +12984,8 @@ ePub.register = { }; // Default Views -ePub.register.view("iframe", require('./views/iframe')); -// ePub.register.view("inline", require('./views/inline')); +ePub.register.view("iframe", require('./managers/views/iframe')); +// ePub.register.view("inline", require('./managers/views/inline')); // Default View Managers ePub.register.manager("single", require('./managers/single')); @@ -12993,7 +12993,7 @@ ePub.register.manager("continuous", require('./managers/continuous')); module.exports = ePub; -},{"./book":8,"./contents":9,"./epubcfi":11,"./managers/continuous":15,"./managers/single":16,"./rendition":21,"./views/iframe":29,"rsvp":5}]},{},["epub"])("epub") +},{"./book":8,"./contents":9,"./epubcfi":11,"./managers/continuous":15,"./managers/single":18,"./managers/views/iframe":19,"./rendition":24,"rsvp":5}]},{},["epub"])("epub") }); diff --git a/dist/epub.js.map b/dist/epub.js.map index cad394c..a684969 100644 --- a/dist/epub.js.map +++ b/dist/epub.js.map @@ -1 +1 @@ -{"version":3,"sources":["node_modules/browser-pack/_prelude.js","libs/mime/mime.js","node_modules/base64-js/index.js","node_modules/browserify/lib/_empty.js","node_modules/process/browser.js","node_modules/rsvp/dist/rsvp.js","node_modules/urijs/src/SecondLevelDomains.js","node_modules/urijs/src/URI.js","src/book.js","src/contents.js","src/core.js","src/epubcfi.js","src/hook.js","src/layout.js","src/locations.js","src/managers/continuous.js","src/managers/single.js","src/mapping.js","src/navigation.js","src/parser.js","src/queue.js","src/rendition.js","src/replacements.js","src/request.js","src/section.js","src/spine.js","src/stage.js","src/unarchive.js","src/views.js","src/views/iframe.js","src/epub.js"],"names":[],"mappings":"AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACh8EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClqEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC16BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxqBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;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;;ACzSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClkBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9jBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"epub.js","sourceRoot":"/source/","sourcesContent":["(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n}\n\nfunction byteLength (b64) {\n // base64 is 4/3 + up to two characters of the original data\n return b64.length * 3 / 4 - placeHoldersCount(b64)\n}\n\nfunction toByteArray (b64) {\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n placeHolders = placeHoldersCount(b64)\n\n arr = new Arr(len * 3 / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n","","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/*!\n * @overview RSVP - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2016 Yehuda Katz, Tom Dale, Stefan Penner and contributors\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE\n * @version 3.3.2\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (factory((global.RSVP = global.RSVP || {})));\n}(this, (function (exports) { 'use strict';\n\nfunction indexOf(callbacks, callback) {\n for (var i = 0, l = callbacks.length; i < l; i++) {\n if (callbacks[i] === callback) {\n return i;\n }\n }\n\n return -1;\n}\n\nfunction callbacksFor(object) {\n var callbacks = object._promiseCallbacks;\n\n if (!callbacks) {\n callbacks = object._promiseCallbacks = {};\n }\n\n return callbacks;\n}\n\n/**\n @class RSVP.EventTarget\n*/\nvar EventTarget = {\n\n /**\n `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For\n Example:\n ```javascript\n let object = {};\n RSVP.EventTarget.mixin(object);\n object.on('finished', function(event) {\n // handle event\n });\n object.trigger('finished', { detail: value });\n ```\n `EventTarget.mixin` also works with prototypes:\n ```javascript\n let Person = function() {};\n RSVP.EventTarget.mixin(Person.prototype);\n let yehuda = new Person();\n let tom = new Person();\n yehuda.on('poke', function(event) {\n console.log('Yehuda says OW');\n });\n tom.on('poke', function(event) {\n console.log('Tom says OW');\n });\n yehuda.trigger('poke');\n tom.trigger('poke');\n ```\n @method mixin\n @for RSVP.EventTarget\n @private\n @param {Object} object object to extend with EventTarget methods\n */\n mixin: function mixin(object) {\n object['on'] = this['on'];\n object['off'] = this['off'];\n object['trigger'] = this['trigger'];\n object._promiseCallbacks = undefined;\n return object;\n },\n\n /**\n Registers a callback to be executed when `eventName` is triggered\n ```javascript\n object.on('event', function(eventInfo){\n // handle the event\n });\n object.trigger('event');\n ```\n @method on\n @for RSVP.EventTarget\n @private\n @param {String} eventName name of the event to listen for\n @param {Function} callback function to be called when the event is triggered.\n */\n on: function on(eventName, callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function');\n }\n\n var allCallbacks = callbacksFor(this),\n callbacks = undefined;\n\n callbacks = allCallbacks[eventName];\n\n if (!callbacks) {\n callbacks = allCallbacks[eventName] = [];\n }\n\n if (indexOf(callbacks, callback) === -1) {\n callbacks.push(callback);\n }\n },\n\n /**\n You can use `off` to stop firing a particular callback for an event:\n ```javascript\n function doStuff() { // do stuff! }\n object.on('stuff', doStuff);\n object.trigger('stuff'); // doStuff will be called\n // Unregister ONLY the doStuff callback\n object.off('stuff', doStuff);\n object.trigger('stuff'); // doStuff will NOT be called\n ```\n If you don't pass a `callback` argument to `off`, ALL callbacks for the\n event will not be executed when the event fires. For example:\n ```javascript\n let callback1 = function(){};\n let callback2 = function(){};\n object.on('stuff', callback1);\n object.on('stuff', callback2);\n object.trigger('stuff'); // callback1 and callback2 will be executed.\n object.off('stuff');\n object.trigger('stuff'); // callback1 and callback2 will not be executed!\n ```\n @method off\n @for RSVP.EventTarget\n @private\n @param {String} eventName event to stop listening to\n @param {Function} callback optional argument. If given, only the function\n given will be removed from the event's callback queue. If no `callback`\n argument is given, all callbacks will be removed from the event's callback\n queue.\n */\n off: function off(eventName, callback) {\n var allCallbacks = callbacksFor(this),\n callbacks = undefined,\n index = undefined;\n\n if (!callback) {\n allCallbacks[eventName] = [];\n return;\n }\n\n callbacks = allCallbacks[eventName];\n\n index = indexOf(callbacks, callback);\n\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n },\n\n /**\n Use `trigger` to fire custom events. For example:\n ```javascript\n object.on('foo', function(){\n console.log('foo event happened!');\n });\n object.trigger('foo');\n // 'foo event happened!' logged to the console\n ```\n You can also pass a value as a second argument to `trigger` that will be\n passed as an argument to all event listeners for the event:\n ```javascript\n object.on('foo', function(value){\n console.log(value.name);\n });\n object.trigger('foo', { name: 'bar' });\n // 'bar' logged to the console\n ```\n @method trigger\n @for RSVP.EventTarget\n @private\n @param {String} eventName name of the event to be triggered\n @param {*} options optional value to be passed to any event handlers for\n the given `eventName`\n */\n trigger: function trigger(eventName, options, label) {\n var allCallbacks = callbacksFor(this),\n callbacks = undefined,\n callback = undefined;\n\n if (callbacks = allCallbacks[eventName]) {\n // Don't cache the callbacks.length since it may grow\n for (var i = 0; i < callbacks.length; i++) {\n callback = callbacks[i];\n\n callback(options, label);\n }\n }\n }\n};\n\nvar config = {\n instrument: false\n};\n\nEventTarget['mixin'](config);\n\nfunction configure(name, value) {\n if (name === 'onerror') {\n // handle for legacy users that expect the actual\n // error to be passed to their function added via\n // `RSVP.configure('onerror', someFunctionHere);`\n config['on']('error', value);\n return;\n }\n\n if (arguments.length === 2) {\n config[name] = value;\n } else {\n return config[name];\n }\n}\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nfunction isMaybeThenable(x) {\n return typeof x === 'object' && x !== null;\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\n// Date.now is not available in browsers < IE9\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility\nvar now = Date.now || function () {\n return new Date().getTime();\n};\n\nfunction F() {}\n\nvar o_create = Object.create || function (o) {\n if (arguments.length > 1) {\n throw new Error('Second argument not supported');\n }\n if (typeof o !== 'object') {\n throw new TypeError('Argument must be an object');\n }\n F.prototype = o;\n return new F();\n};\n\nvar queue = [];\n\nfunction scheduleFlush() {\n setTimeout(function () {\n for (var i = 0; i < queue.length; i++) {\n var entry = queue[i];\n\n var payload = entry.payload;\n\n payload.guid = payload.key + payload.id;\n payload.childGuid = payload.key + payload.childId;\n if (payload.error) {\n payload.stack = payload.error.stack;\n }\n\n config['trigger'](entry.name, entry.payload);\n }\n queue.length = 0;\n }, 50);\n}\nfunction instrument(eventName, promise, child) {\n if (1 === queue.push({\n name: eventName,\n payload: {\n key: promise._guidKey,\n id: promise._id,\n eventName: eventName,\n detail: promise._result,\n childId: child && child._id,\n label: promise._label,\n timeStamp: now(),\n error: config[\"instrument-with-stack\"] ? new Error(promise._label) : null\n } })) {\n scheduleFlush();\n }\n}\n\n/**\n `RSVP.Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new RSVP.Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = RSVP.Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {*} object value that the returned promise will be resolved with\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve$1(object, label) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop, label);\n resolve(promise, object);\n return promise;\n}\n\nfunction withOwnPromise() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n config.async(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n resolve(promise, value, undefined);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n thenable._onError = null;\n reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n if (thenable !== value) {\n resolve(promise, value, undefined);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && promise.constructor.resolve === resolve$1) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n reject(promise, GET_THEN_ERROR.error);\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction resolve(promise, value) {\n if (promise === value) {\n fulfill(promise, value);\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onError) {\n promise._onError(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length === 0) {\n if (config.instrument) {\n instrument('fulfilled', promise);\n }\n } else {\n config.async(publish, promise);\n }\n}\n\nfunction reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n config.async(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var subscribers = parent._subscribers;\n var length = subscribers.length;\n\n parent._onError = null;\n\n subscribers[length] = child;\n subscribers[length + FULFILLED] = onFulfillment;\n subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n config.async(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (config.instrument) {\n instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);\n }\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n reject(promise, withOwnPromise());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n resolve(promise, value);\n } else if (failed) {\n reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n var resolved = false;\n try {\n resolver(function (value) {\n if (resolved) {\n return;\n }\n resolved = true;\n resolve(promise, value);\n }, function (reason) {\n if (resolved) {\n return;\n }\n resolved = true;\n reject(promise, reason);\n });\n } catch (e) {\n reject(promise, e);\n }\n}\n\nfunction then(onFulfillment, onRejection, label) {\n var _arguments = arguments;\n\n var parent = this;\n var state = parent._state;\n\n if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {\n config.instrument && instrument('chained', parent, parent);\n return parent;\n }\n\n parent._onError = null;\n\n var child = new parent.constructor(noop, label);\n var result = parent._result;\n\n config.instrument && instrument('chained', parent, child);\n\n if (state) {\n (function () {\n var callback = _arguments[state - 1];\n config.async(function () {\n return invokeCallback(state, child, callback, result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\nfunction makeSettledResult(state, position, value) {\n if (state === FULFILLED) {\n return {\n state: 'fulfilled',\n value: value\n };\n } else {\n return {\n state: 'rejected',\n reason: value\n };\n }\n}\n\nfunction Enumerator(Constructor, input, abortOnReject, label) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop, label);\n this._abortOnReject = abortOnReject;\n\n if (this._validateInput(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._init();\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n reject(this.promise, this._validationError());\n }\n}\n\nEnumerator.prototype._validateInput = function (input) {\n return isArray(input);\n};\n\nEnumerator.prototype._validationError = function () {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._init = function () {\n this._result = new Array(this.length);\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var promise = this.promise;\n var input = this._input;\n\n for (var i = 0; promise._state === PENDING && i < length; i++) {\n this._eachEntry(input[i], i);\n }\n};\n\nEnumerator.prototype._settleMaybeThenable = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve = c.resolve;\n\n if (resolve === resolve$1) {\n var then$$ = getThen(entry);\n\n if (then$$ === then && entry._state !== PENDING) {\n entry._onError = null;\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof then$$ !== 'function') {\n this._remaining--;\n this._result[i] = this._makeResult(FULFILLED, i, entry);\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, then$$);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve) {\n return resolve(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve(entry), i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n if (isMaybeThenable(entry)) {\n this._settleMaybeThenable(entry, i);\n } else {\n this._remaining--;\n this._result[i] = this._makeResult(FULFILLED, i, entry);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (this._abortOnReject && state === REJECTED) {\n reject(promise, value);\n } else {\n this._result[i] = this._makeResult(state, i, value);\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._makeResult = function (state, i, value) {\n return value;\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `RSVP.Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `RSVP.all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error(\"2\"));\n let promise3 = RSVP.reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries, label) {\n return new Enumerator(this, entries, true, /* abort on reject */label).promise;\n}\n\n/**\n `RSVP.Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n RSVP.Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `RSVP.Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n RSVP.Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n RSVP.Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} entries array of promises to observe\n @param {String} label optional string for describing the promise returned.\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries, label) {\n /*jshint validthis:true */\n var Constructor = this;\n\n var promise = new Constructor(noop, label);\n\n if (!isArray(entries)) {\n reject(promise, new TypeError('You must pass an array to race.'));\n return promise;\n }\n\n for (var i = 0; promise._state === PENDING && i < entries.length; i++) {\n subscribe(Constructor.resolve(entries[i]), undefined, function (value) {\n return resolve(promise, value);\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n\n return promise;\n}\n\n/**\n `RSVP.Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new RSVP.Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = RSVP.Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {*} reason value that the returned promise will be rejected with.\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject$1(reason, label) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop, label);\n reject(promise, reason);\n return promise;\n}\n\nvar guidKey = 'rsvp_' + now() + '-';\nvar counter = 0;\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise’s eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class RSVP.Promise\n @param {function} resolver\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver, label) {\n this._id = counter++;\n this._label = label;\n this._state = undefined;\n this._result = undefined;\n this._subscribers = [];\n\n config.instrument && instrument('created', this);\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.cast = resolve$1; // deprecated\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve$1;\nPromise.reject = reject$1;\n\nPromise.prototype = {\n constructor: Promise,\n\n _guidKey: guidKey,\n\n _onError: function _onError(reason) {\n var promise = this;\n config.after(function () {\n if (promise._onError) {\n config['trigger']('error', reason, promise._label);\n }\n });\n },\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we\\'re unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we\\'re unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfillment\n @param {Function} onRejection\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn\\'t find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection, label) {\n return this.then(undefined, onRejection, label);\n },\n\n /**\n `finally` will be invoked regardless of the promise's fate just as native\n try/catch/finally behaves\n \n Synchronous example:\n \n ```js\n findAuthor() {\n if (Math.random() > 0.5) {\n throw new Error();\n }\n return new Author();\n }\n \n try {\n return findAuthor(); // succeed or fail\n } catch(error) {\n return findOtherAuther();\n } finally {\n // always runs\n // doesn't affect the return value\n }\n ```\n \n Asynchronous example:\n \n ```js\n findAuthor().catch(function(reason){\n return findOtherAuther();\n }).finally(function(){\n // author was either found, or not\n });\n ```\n \n @method finally\n @param {Function} callback\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n 'finally': function _finally(callback, label) {\n var promise = this;\n var constructor = promise.constructor;\n\n return promise.then(function (value) {\n return constructor.resolve(callback()).then(function () {\n return value;\n });\n }, function (reason) {\n return constructor.resolve(callback()).then(function () {\n throw reason;\n });\n }, label);\n }\n};\n\nfunction Result() {\n this.value = undefined;\n}\n\nvar ERROR = new Result();\nvar GET_THEN_ERROR$1 = new Result();\n\nfunction getThen$1(obj) {\n try {\n return obj.then;\n } catch (error) {\n ERROR.value = error;\n return ERROR;\n }\n}\n\nfunction tryApply(f, s, a) {\n try {\n f.apply(s, a);\n } catch (error) {\n ERROR.value = error;\n return ERROR;\n }\n}\n\nfunction makeObject(_, argumentNames) {\n var obj = {};\n var length = _.length;\n var args = new Array(length);\n\n for (var x = 0; x < length; x++) {\n args[x] = _[x];\n }\n\n for (var i = 0; i < argumentNames.length; i++) {\n var _name = argumentNames[i];\n obj[_name] = args[i + 1];\n }\n\n return obj;\n}\n\nfunction arrayResult(_) {\n var length = _.length;\n var args = new Array(length - 1);\n\n for (var i = 1; i < length; i++) {\n args[i - 1] = _[i];\n }\n\n return args;\n}\n\nfunction wrapThenable(_then, promise) {\n return {\n then: function then(onFulFillment, onRejection) {\n return _then.call(promise, onFulFillment, onRejection);\n }\n };\n}\n\n/**\n `RSVP.denodeify` takes a 'node-style' function and returns a function that\n will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the\n browser when you'd prefer to use promises over using callbacks. For example,\n `denodeify` transforms the following:\n\n ```javascript\n let fs = require('fs');\n\n fs.readFile('myfile.txt', function(err, data){\n if (err) return handleError(err);\n handleData(data);\n });\n ```\n\n into:\n\n ```javascript\n let fs = require('fs');\n let readFile = RSVP.denodeify(fs.readFile);\n\n readFile('myfile.txt').then(handleData, handleError);\n ```\n\n If the node function has multiple success parameters, then `denodeify`\n just returns the first one:\n\n ```javascript\n let request = RSVP.denodeify(require('request'));\n\n request('http://example.com').then(function(res) {\n // ...\n });\n ```\n\n However, if you need all success parameters, setting `denodeify`'s\n second parameter to `true` causes it to return all success parameters\n as an array:\n\n ```javascript\n let request = RSVP.denodeify(require('request'), true);\n\n request('http://example.com').then(function(result) {\n // result[0] -> res\n // result[1] -> body\n });\n ```\n\n Or if you pass it an array with names it returns the parameters as a hash:\n\n ```javascript\n let request = RSVP.denodeify(require('request'), ['res', 'body']);\n\n request('http://example.com').then(function(result) {\n // result.res\n // result.body\n });\n ```\n\n Sometimes you need to retain the `this`:\n\n ```javascript\n let app = require('express')();\n let render = RSVP.denodeify(app.render.bind(app));\n ```\n\n The denodified function inherits from the original function. It works in all\n environments, except IE 10 and below. Consequently all properties of the original\n function are available to you. However, any properties you change on the\n denodeified function won't be changed on the original function. Example:\n\n ```javascript\n let request = RSVP.denodeify(require('request')),\n cookieJar = request.jar(); // <- Inheritance is used here\n\n request('http://example.com', {jar: cookieJar}).then(function(res) {\n // cookieJar.cookies holds now the cookies returned by example.com\n });\n ```\n\n Using `denodeify` makes it easier to compose asynchronous operations instead\n of using callbacks. For example, instead of:\n\n ```javascript\n let fs = require('fs');\n\n fs.readFile('myfile.txt', function(err, data){\n if (err) { ... } // Handle error\n fs.writeFile('myfile2.txt', data, function(err){\n if (err) { ... } // Handle error\n console.log('done')\n });\n });\n ```\n\n you can chain the operations together using `then` from the returned promise:\n\n ```javascript\n let fs = require('fs');\n let readFile = RSVP.denodeify(fs.readFile);\n let writeFile = RSVP.denodeify(fs.writeFile);\n\n readFile('myfile.txt').then(function(data){\n return writeFile('myfile2.txt', data);\n }).then(function(){\n console.log('done')\n }).catch(function(error){\n // Handle error\n });\n ```\n\n @method denodeify\n @static\n @for RSVP\n @param {Function} nodeFunc a 'node-style' function that takes a callback as\n its last argument. The callback expects an error to be passed as its first\n argument (if an error occurred, otherwise null), and the value from the\n operation as its second argument ('function(err, value){ }').\n @param {Boolean|Array} [options] An optional paramter that if set\n to `true` causes the promise to fulfill with the callback's success arguments\n as an array. This is useful if the node function has multiple success\n paramters. If you set this paramter to an array with names, the promise will\n fulfill with a hash with these names as keys and the success parameters as\n values.\n @return {Function} a function that wraps `nodeFunc` to return an\n `RSVP.Promise`\n @static\n*/\nfunction denodeify(nodeFunc, options) {\n var fn = function fn() {\n var self = this;\n var l = arguments.length;\n var args = new Array(l + 1);\n var promiseInput = false;\n\n for (var i = 0; i < l; ++i) {\n var arg = arguments[i];\n\n if (!promiseInput) {\n // TODO: clean this up\n promiseInput = needsPromiseInput(arg);\n if (promiseInput === GET_THEN_ERROR$1) {\n var p = new Promise(noop);\n reject(p, GET_THEN_ERROR$1.value);\n return p;\n } else if (promiseInput && promiseInput !== true) {\n arg = wrapThenable(promiseInput, arg);\n }\n }\n args[i] = arg;\n }\n\n var promise = new Promise(noop);\n\n args[l] = function (err, val) {\n if (err) reject(promise, err);else if (options === undefined) resolve(promise, val);else if (options === true) resolve(promise, arrayResult(arguments));else if (isArray(options)) resolve(promise, makeObject(arguments, options));else resolve(promise, val);\n };\n\n if (promiseInput) {\n return handlePromiseInput(promise, args, nodeFunc, self);\n } else {\n return handleValueInput(promise, args, nodeFunc, self);\n }\n };\n\n fn.__proto__ = nodeFunc;\n\n return fn;\n}\n\nfunction handleValueInput(promise, args, nodeFunc, self) {\n var result = tryApply(nodeFunc, self, args);\n if (result === ERROR) {\n reject(promise, result.value);\n }\n return promise;\n}\n\nfunction handlePromiseInput(promise, args, nodeFunc, self) {\n return Promise.all(args).then(function (args) {\n var result = tryApply(nodeFunc, self, args);\n if (result === ERROR) {\n reject(promise, result.value);\n }\n return promise;\n });\n}\n\nfunction needsPromiseInput(arg) {\n if (arg && typeof arg === 'object') {\n if (arg.constructor === Promise) {\n return true;\n } else {\n return getThen$1(arg);\n }\n } else {\n return false;\n }\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.all`.\n\n @method all\n @static\n @for RSVP\n @param {Array} array Array of promises.\n @param {String} label An optional label. This is useful\n for tooling.\n*/\nfunction all$1(array, label) {\n return Promise.all(array, label);\n}\n\nfunction AllSettled(Constructor, entries, label) {\n this._superConstructor(Constructor, entries, false, /* don't abort on reject */label);\n}\n\nAllSettled.prototype = o_create(Enumerator.prototype);\nAllSettled.prototype._superConstructor = Enumerator;\nAllSettled.prototype._makeResult = makeSettledResult;\nAllSettled.prototype._validationError = function () {\n return new Error('allSettled must be called with an array');\n};\n\n/**\n `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing\n a fail-fast method, it waits until all the promises have returned and\n shows you all the results. This is useful if you want to handle multiple\n promises' failure states together as a set.\n\n Returns a promise that is fulfilled when all the given promises have been\n settled. The return promise is fulfilled with an array of the states of\n the promises passed into the `promises` array argument.\n\n Each state object will either indicate fulfillment or rejection, and\n provide the corresponding value or reason. The states will take one of\n the following formats:\n\n ```javascript\n { state: 'fulfilled', value: value }\n or\n { state: 'rejected', reason: reason }\n ```\n\n Example:\n\n ```javascript\n let promise1 = RSVP.Promise.resolve(1);\n let promise2 = RSVP.Promise.reject(new Error('2'));\n let promise3 = RSVP.Promise.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.allSettled(promises).then(function(array){\n // array == [\n // { state: 'fulfilled', value: 1 },\n // { state: 'rejected', reason: Error },\n // { state: 'rejected', reason: Error }\n // ]\n // Note that for the second item, reason.message will be '2', and for the\n // third item, reason.message will be '3'.\n }, function(error) {\n // Not run. (This block would only be called if allSettled had failed,\n // for instance if passed an incorrect argument type.)\n });\n ```\n\n @method allSettled\n @static\n @for RSVP\n @param {Array} entries\n @param {String} label - optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled with an array of the settled\n states of the constituent promises.\n*/\nfunction allSettled(entries, label) {\n return new AllSettled(Promise, entries, label).promise;\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.race`.\n\n @method race\n @static\n @for RSVP\n @param {Array} array Array of promises.\n @param {String} label An optional label. This is useful\n for tooling.\n */\nfunction race$1(array, label) {\n return Promise.race(array, label);\n}\n\nfunction PromiseHash(Constructor, object, label) {\n this._superConstructor(Constructor, object, true, label);\n}\n\nPromiseHash.prototype = o_create(Enumerator.prototype);\nPromiseHash.prototype._superConstructor = Enumerator;\nPromiseHash.prototype._init = function () {\n this._result = {};\n};\n\nPromiseHash.prototype._validateInput = function (input) {\n return input && typeof input === 'object';\n};\n\nPromiseHash.prototype._validationError = function () {\n return new Error('Promise.hash must be called with an object');\n};\n\nPromiseHash.prototype._enumerate = function () {\n var enumerator = this;\n var promise = enumerator.promise;\n var input = enumerator._input;\n var results = [];\n\n for (var key in input) {\n if (promise._state === PENDING && Object.prototype.hasOwnProperty.call(input, key)) {\n results.push({\n position: key,\n entry: input[key]\n });\n }\n }\n\n var length = results.length;\n enumerator._remaining = length;\n var result = undefined;\n\n for (var i = 0; promise._state === PENDING && i < length; i++) {\n result = results[i];\n enumerator._eachEntry(result.entry, result.position);\n }\n};\n\n/**\n `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array\n for its `promises` argument.\n\n Returns a promise that is fulfilled when all the given promises have been\n fulfilled, or rejected if any of them become rejected. The returned promise\n is fulfilled with a hash that has the same key names as the `promises` object\n argument. If any of the values in the object are not promises, they will\n simply be copied over to the fulfilled object.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.resolve(1),\n yourPromise: RSVP.resolve(2),\n theirPromise: RSVP.resolve(3),\n notAPromise: 4\n };\n\n RSVP.hash(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: 1,\n // yourPromise: 2,\n // theirPromise: 3,\n // notAPromise: 4\n // }\n });\n ````\n\n If any of the `promises` given to `RSVP.hash` are rejected, the first promise\n that is rejected will be given as the reason to the rejection handler.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.resolve(1),\n rejectedPromise: RSVP.reject(new Error('rejectedPromise')),\n anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')),\n };\n\n RSVP.hash(promises).then(function(hash){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === 'rejectedPromise'\n });\n ```\n\n An important note: `RSVP.hash` is intended for plain JavaScript objects that\n are just a set of keys and values. `RSVP.hash` will NOT preserve prototype\n chains.\n\n Example:\n\n ```javascript\n function MyConstructor(){\n this.example = RSVP.resolve('Example');\n }\n\n MyConstructor.prototype = {\n protoProperty: RSVP.resolve('Proto Property')\n };\n\n let myObject = new MyConstructor();\n\n RSVP.hash(myObject).then(function(hash){\n // protoProperty will not be present, instead you will just have an\n // object that looks like:\n // {\n // example: 'Example'\n // }\n //\n // hash.hasOwnProperty('protoProperty'); // false\n // 'undefined' === typeof hash.protoProperty\n });\n ```\n\n @method hash\n @static\n @for RSVP\n @param {Object} object\n @param {String} label optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all properties of `promises`\n have been fulfilled, or rejected if any of them become rejected.\n*/\nfunction hash(object, label) {\n return new PromiseHash(Promise, object, label).promise;\n}\n\nfunction HashSettled(Constructor, object, label) {\n this._superConstructor(Constructor, object, false, label);\n}\n\nHashSettled.prototype = o_create(PromiseHash.prototype);\nHashSettled.prototype._superConstructor = Enumerator;\nHashSettled.prototype._makeResult = makeSettledResult;\n\nHashSettled.prototype._validationError = function () {\n return new Error('hashSettled must be called with an object');\n};\n\n/**\n `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object\n instead of an array for its `promises` argument.\n\n Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method,\n but like `RSVP.allSettled`, `hashSettled` waits until all the\n constituent promises have returned and then shows you all the results\n with their states and values/reasons. This is useful if you want to\n handle multiple promises' failure states together as a set.\n\n Returns a promise that is fulfilled when all the given promises have been\n settled, or rejected if the passed parameters are invalid.\n\n The returned promise is fulfilled with a hash that has the same key names as\n the `promises` object argument. If any of the values in the object are not\n promises, they will be copied over to the fulfilled object and marked with state\n 'fulfilled'.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.Promise.resolve(1),\n yourPromise: RSVP.Promise.resolve(2),\n theirPromise: RSVP.Promise.resolve(3),\n notAPromise: 4\n };\n\n RSVP.hashSettled(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: { state: 'fulfilled', value: 1 },\n // yourPromise: { state: 'fulfilled', value: 2 },\n // theirPromise: { state: 'fulfilled', value: 3 },\n // notAPromise: { state: 'fulfilled', value: 4 }\n // }\n });\n ```\n\n If any of the `promises` given to `RSVP.hash` are rejected, the state will\n be set to 'rejected' and the reason for rejection provided.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.Promise.resolve(1),\n rejectedPromise: RSVP.Promise.reject(new Error('rejection')),\n anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')),\n };\n\n RSVP.hashSettled(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: { state: 'fulfilled', value: 1 },\n // rejectedPromise: { state: 'rejected', reason: Error },\n // anotherRejectedPromise: { state: 'rejected', reason: Error },\n // }\n // Note that for rejectedPromise, reason.message == 'rejection',\n // and for anotherRejectedPromise, reason.message == 'more rejection'.\n });\n ```\n\n An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that\n are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype\n chains.\n\n Example:\n\n ```javascript\n function MyConstructor(){\n this.example = RSVP.Promise.resolve('Example');\n }\n\n MyConstructor.prototype = {\n protoProperty: RSVP.Promise.resolve('Proto Property')\n };\n\n let myObject = new MyConstructor();\n\n RSVP.hashSettled(myObject).then(function(hash){\n // protoProperty will not be present, instead you will just have an\n // object that looks like:\n // {\n // example: { state: 'fulfilled', value: 'Example' }\n // }\n //\n // hash.hasOwnProperty('protoProperty'); // false\n // 'undefined' === typeof hash.protoProperty\n });\n ```\n\n @method hashSettled\n @for RSVP\n @param {Object} object\n @param {String} label optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when when all properties of `promises`\n have been settled.\n @static\n*/\nfunction hashSettled(object, label) {\n return new HashSettled(Promise, object, label).promise;\n}\n\nfunction rethrow(reason) {\n setTimeout(function () {\n throw reason;\n });\n throw reason;\n}\n\n/**\n `RSVP.defer` returns an object similar to jQuery's `$.Deferred`.\n `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s\n interface. New code should use the `RSVP.Promise` constructor instead.\n\n The object returned from `RSVP.defer` is a plain object with three properties:\n\n * promise - an `RSVP.Promise`.\n * reject - a function that causes the `promise` property on this object to\n become rejected\n * resolve - a function that causes the `promise` property on this object to\n become fulfilled.\n\n Example:\n\n ```javascript\n let deferred = RSVP.defer();\n\n deferred.resolve(\"Success!\");\n\n deferred.promise.then(function(value){\n // value here is \"Success!\"\n });\n ```\n\n @method defer\n @static\n @for RSVP\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Object}\n */\nfunction defer(label) {\n var deferred = { resolve: undefined, reject: undefined };\n\n deferred.promise = new Promise(function (resolve, reject) {\n deferred.resolve = resolve;\n deferred.reject = reject;\n }, label);\n\n return deferred;\n}\n\n/**\n `RSVP.map` is similar to JavaScript's native `map` method, except that it\n waits for all promises to become fulfilled before running the `mapFn` on\n each item in given to `promises`. `RSVP.map` returns a promise that will\n become fulfilled with the result of running `mapFn` on the values the promises\n become fulfilled with.\n\n For example:\n\n ```javascript\n\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n let mapFn = function(item){\n return item + 1;\n };\n\n RSVP.map(promises, mapFn).then(function(result){\n // result is [ 2, 3, 4 ]\n });\n ```\n\n If any of the `promises` given to `RSVP.map` are rejected, the first promise\n that is rejected will be given as an argument to the returned promise's\n rejection handler. For example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error('2'));\n let promise3 = RSVP.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n let mapFn = function(item){\n return item + 1;\n };\n\n RSVP.map(promises, mapFn).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === '2'\n });\n ```\n\n `RSVP.map` will also wait if a promise is returned from `mapFn`. For example,\n say you want to get all comments from a set of blog posts, but you need\n the blog posts first because they contain a url to those comments.\n\n ```javscript\n\n let mapFn = function(blogPost){\n // getComments does some ajax and returns an RSVP.Promise that is fulfilled\n // with some comments data\n return getComments(blogPost.comments_url);\n };\n\n // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled\n // with some blog post data\n RSVP.map(getBlogPosts(), mapFn).then(function(comments){\n // comments is the result of asking the server for the comments\n // of all blog posts returned from getBlogPosts()\n });\n ```\n\n @method map\n @static\n @for RSVP\n @param {Array} promises\n @param {Function} mapFn function to be called on each fulfilled promise.\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled with the result of calling\n `mapFn` on each fulfilled promise or value when they become fulfilled.\n The promise will be rejected if any of the given `promises` become rejected.\n @static\n*/\nfunction map(promises, mapFn, label) {\n return Promise.all(promises, label).then(function (values) {\n if (!isFunction(mapFn)) {\n throw new TypeError(\"You must pass a function as map's second argument.\");\n }\n\n var length = values.length;\n var results = new Array(length);\n\n for (var i = 0; i < length; i++) {\n results[i] = mapFn(values[i]);\n }\n\n return Promise.all(results, label);\n });\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.resolve`.\n\n @method resolve\n @static\n @for RSVP\n @param {*} value value that the returned promise will be resolved with\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve$2(value, label) {\n return Promise.resolve(value, label);\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.reject`.\n\n @method reject\n @static\n @for RSVP\n @param {*} reason value that the returned promise will be rejected with.\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject$2(reason, label) {\n return Promise.reject(reason, label);\n}\n\n/**\n `RSVP.filter` is similar to JavaScript's native `filter` method, except that it\n waits for all promises to become fulfilled before running the `filterFn` on\n each item in given to `promises`. `RSVP.filter` returns a promise that will\n become fulfilled with the result of running `filterFn` on the values the\n promises become fulfilled with.\n\n For example:\n\n ```javascript\n\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n\n let promises = [promise1, promise2, promise3];\n\n let filterFn = function(item){\n return item > 1;\n };\n\n RSVP.filter(promises, filterFn).then(function(result){\n // result is [ 2, 3 ]\n });\n ```\n\n If any of the `promises` given to `RSVP.filter` are rejected, the first promise\n that is rejected will be given as an argument to the returned promise's\n rejection handler. For example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error('2'));\n let promise3 = RSVP.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n let filterFn = function(item){\n return item > 1;\n };\n\n RSVP.filter(promises, filterFn).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === '2'\n });\n ```\n\n `RSVP.filter` will also wait for any promises returned from `filterFn`.\n For instance, you may want to fetch a list of users then return a subset\n of those users based on some asynchronous operation:\n\n ```javascript\n\n let alice = { name: 'alice' };\n let bob = { name: 'bob' };\n let users = [ alice, bob ];\n\n let promises = users.map(function(user){\n return RSVP.resolve(user);\n });\n\n let filterFn = function(user){\n // Here, Alice has permissions to create a blog post, but Bob does not.\n return getPrivilegesForUser(user).then(function(privs){\n return privs.can_create_blog_post === true;\n });\n };\n RSVP.filter(promises, filterFn).then(function(users){\n // true, because the server told us only Alice can create a blog post.\n users.length === 1;\n // false, because Alice is the only user present in `users`\n users[0] === bob;\n });\n ```\n\n @method filter\n @static\n @for RSVP\n @param {Array} promises\n @param {Function} filterFn - function to be called on each resolved value to\n filter the final results.\n @param {String} label optional string describing the promise. Useful for\n tooling.\n @return {Promise}\n*/\n\nfunction resolveAll(promises, label) {\n return Promise.all(promises, label);\n}\n\nfunction resolveSingle(promise, label) {\n return Promise.resolve(promise, label).then(function (promises) {\n return resolveAll(promises, label);\n });\n}\nfunction filter(promises, filterFn, label) {\n var promise = isArray(promises) ? resolveAll(promises, label) : resolveSingle(promises, label);\n return promise.then(function (values) {\n if (!isFunction(filterFn)) {\n throw new TypeError(\"You must pass a function as filter's second argument.\");\n }\n\n var length = values.length;\n var filtered = new Array(length);\n\n for (var i = 0; i < length; i++) {\n filtered[i] = filterFn(values[i]);\n }\n\n return resolveAll(filtered, label).then(function (filtered) {\n var results = new Array(length);\n var newLength = 0;\n\n for (var i = 0; i < length; i++) {\n if (filtered[i]) {\n results[newLength] = values[i];\n newLength++;\n }\n }\n\n results.length = newLength;\n\n return results;\n });\n });\n}\n\nvar len = 0;\nvar vertxNext = undefined;\nfunction asap(callback, arg) {\n queue$1[len] = callback;\n queue$1[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 1, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n scheduleFlush$1();\n }\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n var nextTick = process.nextTick;\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // setImmediate should be used instead instead\n var version = process.versions.node.match(/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/);\n if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {\n nextTick = setImmediate;\n }\n return function () {\n return nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n return function () {\n return vertxNext(flush);\n };\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n return node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n return function () {\n return setTimeout(flush, 1);\n };\n}\n\nvar queue$1 = new Array(1000);\n\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue$1[i];\n var arg = queue$1[i + 1];\n\n callback(arg);\n\n queue$1[i] = undefined;\n queue$1[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertex() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush$1 = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush$1 = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush$1 = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush$1 = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush$1 = attemptVertex();\n} else {\n scheduleFlush$1 = useSetTimeout();\n}\n\nvar platform = undefined;\n\n/* global self */\nif (typeof self === 'object') {\n platform = self;\n\n /* global global */\n} else if (typeof global === 'object') {\n platform = global;\n } else {\n throw new Error('no global: `self` or `global` found');\n }\n\nvar _async$filter;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n// defaults\n\n// the default export here is for backwards compat:\n// https://github.com/tildeio/rsvp.js/issues/434\nconfig.async = asap;\nconfig.after = function (cb) {\n return setTimeout(cb, 0);\n};\nvar cast = resolve$2;\n\nvar async = function async(callback, arg) {\n return config.async(callback, arg);\n};\n\nfunction on() {\n config['on'].apply(config, arguments);\n}\n\nfunction off() {\n config['off'].apply(config, arguments);\n}\n\n// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`\nif (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {\n var callbacks = window['__PROMISE_INSTRUMENTATION__'];\n configure('instrument', true);\n for (var eventName in callbacks) {\n if (callbacks.hasOwnProperty(eventName)) {\n on(eventName, callbacks[eventName]);\n }\n }\n}var rsvp = (_async$filter = {\n cast: cast,\n Promise: Promise,\n EventTarget: EventTarget,\n all: all$1,\n allSettled: allSettled,\n race: race$1,\n hash: hash,\n hashSettled: hashSettled,\n rethrow: rethrow,\n defer: defer,\n denodeify: denodeify,\n configure: configure,\n on: on,\n off: off,\n resolve: resolve$2,\n reject: reject$2,\n map: map\n}, _defineProperty(_async$filter, 'async', async), _defineProperty(_async$filter, 'filter', // babel seems to error if async isn't a computed prop here...\nfilter), _async$filter);\n\nexports['default'] = rsvp;\nexports.cast = cast;\nexports.Promise = Promise;\nexports.EventTarget = EventTarget;\nexports.all = all$1;\nexports.allSettled = allSettled;\nexports.race = race$1;\nexports.hash = hash;\nexports.hashSettled = hashSettled;\nexports.rethrow = rethrow;\nexports.defer = defer;\nexports.denodeify = denodeify;\nexports.configure = configure;\nexports.on = on;\nexports.off = off;\nexports.resolve = resolve$2;\nexports.reject = reject$2;\nexports.map = map;\nexports.async = async;\nexports.filter = filter;\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n})));\n//# sourceMappingURL=rsvp.map","/*!\n * URI.js - Mutating URLs\n * Second Level Domain (SLD) Support\n *\n * Version: 1.18.1\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof exports === 'object') {\n // Node\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(factory);\n } else {\n // Browser globals (root is window)\n root.SecondLevelDomains = factory(root);\n }\n}(this, function (root) {\n 'use strict';\n\n // save current SecondLevelDomains variable, if any\n var _SecondLevelDomains = root && root.SecondLevelDomains;\n\n var SLD = {\n // list of known Second Level Domains\n // converted list of SLDs from https://github.com/gavingmiller/second-level-domains\n // ----\n // publicsuffix.org is more current and actually used by a couple of browsers internally.\n // downside is it also contains domains like \"dyndns.org\" - which is fine for the security\n // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js\n // ----\n list: {\n 'ac':' com gov mil net org ',\n 'ae':' ac co gov mil name net org pro sch ',\n 'af':' com edu gov net org ',\n 'al':' com edu gov mil net org ',\n 'ao':' co ed gv it og pb ',\n 'ar':' com edu gob gov int mil net org tur ',\n 'at':' ac co gv or ',\n 'au':' asn com csiro edu gov id net org ',\n 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',\n 'bb':' biz co com edu gov info net org store tv ',\n 'bh':' biz cc com edu gov info net org ',\n 'bn':' com edu gov net org ',\n 'bo':' com edu gob gov int mil net org tv ',\n 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',\n 'bs':' com edu gov net org ',\n 'bz':' du et om ov rg ',\n 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',\n 'ck':' biz co edu gen gov info net org ',\n 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',\n 'co':' com edu gov mil net nom org ',\n 'cr':' ac c co ed fi go or sa ',\n 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',\n 'do':' art com edu gob gov mil net org sld web ',\n 'dz':' art asso com edu gov net org pol ',\n 'ec':' com edu fin gov info med mil net org pro ',\n 'eg':' com edu eun gov mil name net org sci ',\n 'er':' com edu gov ind mil net org rochest w ',\n 'es':' com edu gob nom org ',\n 'et':' biz com edu gov info name net org ',\n 'fj':' ac biz com info mil name net org pro ',\n 'fk':' ac co gov net nom org ',\n 'fr':' asso com f gouv nom prd presse tm ',\n 'gg':' co net org ',\n 'gh':' com edu gov mil org ',\n 'gn':' ac com gov net org ',\n 'gr':' com edu gov mil net org ',\n 'gt':' com edu gob ind mil net org ',\n 'gu':' com edu gov net org ',\n 'hk':' com edu gov idv net org ',\n 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',\n 'id':' ac co go mil net or sch web ',\n 'il':' ac co gov idf k12 muni net org ',\n 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',\n 'iq':' com edu gov i mil net org ',\n 'ir':' ac co dnssec gov i id net org sch ',\n 'it':' edu gov ',\n 'je':' co net org ',\n 'jo':' com edu gov mil name net org sch ',\n 'jp':' ac ad co ed go gr lg ne or ',\n 'ke':' ac co go info me mobi ne or sc ',\n 'kh':' com edu gov mil net org per ',\n 'ki':' biz com de edu gov info mob net org tel ',\n 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',\n 'kn':' edu gov net org ',\n 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',\n 'kw':' com edu gov net org ',\n 'ky':' com edu gov net org ',\n 'kz':' com edu gov mil net org ',\n 'lb':' com edu gov net org ',\n 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',\n 'lr':' com edu gov net org ',\n 'lv':' asn com conf edu gov id mil net org ',\n 'ly':' com edu gov id med net org plc sch ',\n 'ma':' ac co gov m net org press ',\n 'mc':' asso tm ',\n 'me':' ac co edu gov its net org priv ',\n 'mg':' com edu gov mil nom org prd tm ',\n 'mk':' com edu gov inf name net org pro ',\n 'ml':' com edu gov net org presse ',\n 'mn':' edu gov org ',\n 'mo':' com edu gov net org ',\n 'mt':' com edu gov net org ',\n 'mv':' aero biz com coop edu gov info int mil museum name net org pro ',\n 'mw':' ac co com coop edu gov int museum net org ',\n 'mx':' com edu gob net org ',\n 'my':' com edu gov mil name net org sch ',\n 'nf':' arts com firm info net other per rec store web ',\n 'ng':' biz com edu gov mil mobi name net org sch ',\n 'ni':' ac co com edu gob mil net nom org ',\n 'np':' com edu gov mil net org ',\n 'nr':' biz com edu gov info net org ',\n 'om':' ac biz co com edu gov med mil museum net org pro sch ',\n 'pe':' com edu gob mil net nom org sld ',\n 'ph':' com edu gov i mil net ngo org ',\n 'pk':' biz com edu fam gob gok gon gop gos gov net org web ',\n 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',\n 'pr':' ac biz com edu est gov info isla name net org pro prof ',\n 'ps':' com edu gov net org plo sec ',\n 'pw':' belau co ed go ne or ',\n 'ro':' arts com firm info nom nt org rec store tm www ',\n 'rs':' ac co edu gov in org ',\n 'sb':' com edu gov net org ',\n 'sc':' com edu gov net org ',\n 'sh':' co com edu gov net nom org ',\n 'sl':' com edu gov net org ',\n 'st':' co com consulado edu embaixada gov mil net org principe saotome store ',\n 'sv':' com edu gob org red ',\n 'sz':' ac co org ',\n 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',\n 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',\n 'tw':' club com ebiz edu game gov idv mil net org ',\n 'mu':' ac co com gov net or org ',\n 'mz':' ac co edu gov org ',\n 'na':' co com ',\n 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',\n 'pa':' abo ac com edu gob ing med net nom org sld ',\n 'pt':' com edu gov int net nome org publ ',\n 'py':' com edu gov mil net org ',\n 'qa':' com edu gov mil net org ',\n 're':' asso com nom ',\n 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',\n 'rw':' ac co com edu gouv gov int mil net ',\n 'sa':' com edu gov med net org pub sch ',\n 'sd':' com edu gov info med net org tv ',\n 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',\n 'sg':' com edu gov idn net org per ',\n 'sn':' art com edu gouv org perso univ ',\n 'sy':' com edu gov mil net news org ',\n 'th':' ac co go in mi net or ',\n 'tj':' ac biz co com edu go gov info int mil name net nic org test web ',\n 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',\n 'tz':' ac co go ne or ',\n 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',\n 'ug':' ac co go ne or org sc ',\n 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',\n 'us':' dni fed isa kids nsn ',\n 'uy':' com edu gub mil net org ',\n 've':' co com edu gob info mil net org web ',\n 'vi':' co com k12 net org ',\n 'vn':' ac biz com edu gov health info int name net org pro ',\n 'ye':' co com gov ltd me net org plc ',\n 'yu':' ac co edu gov org ',\n 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',\n 'zm':' ac co com edu gov net org sch '\n },\n // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost\n // in both performance and memory footprint. No initialization required.\n // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4\n // Following methods use lastIndexOf() rather than array.split() in order\n // to avoid any memory allocations.\n has: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return false;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {\n return false;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return false;\n }\n return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;\n },\n is: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return false;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset >= 0) {\n return false;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return false;\n }\n return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;\n },\n get: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return null;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {\n return null;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return null;\n }\n if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {\n return null;\n }\n return domain.slice(sldOffset+1);\n },\n noConflict: function(){\n if (root.SecondLevelDomains === this) {\n root.SecondLevelDomains = _SecondLevelDomains;\n }\n return this;\n }\n };\n\n return SLD;\n}));\n","/*!\n * URI.js - Mutating URLs\n *\n * Version: 1.18.1\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof exports === 'object') {\n // Node\n module.exports = factory(require('./punycode'), require('./IPv6'), require('./SecondLevelDomains'));\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(['./punycode', './IPv6', './SecondLevelDomains'], factory);\n } else {\n // Browser globals (root is window)\n root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);\n }\n}(this, function (punycode, IPv6, SLD, root) {\n 'use strict';\n /*global location, escape, unescape */\n // FIXME: v2.0.0 renamce non-camelCase properties to uppercase\n /*jshint camelcase: false */\n\n // save current URI variable, if any\n var _URI = root && root.URI;\n\n function URI(url, base) {\n var _urlSupplied = arguments.length >= 1;\n var _baseSupplied = arguments.length >= 2;\n\n // Allow instantiation without the 'new' keyword\n if (!(this instanceof URI)) {\n if (_urlSupplied) {\n if (_baseSupplied) {\n return new URI(url, base);\n }\n\n return new URI(url);\n }\n\n return new URI();\n }\n\n if (url === undefined) {\n if (_urlSupplied) {\n throw new TypeError('undefined is not a valid argument for URI');\n }\n\n if (typeof location !== 'undefined') {\n url = location.href + '';\n } else {\n url = '';\n }\n }\n\n this.href(url);\n\n // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor\n if (base !== undefined) {\n return this.absoluteTo(base);\n }\n\n return this;\n }\n\n URI.version = '1.18.1';\n\n var p = URI.prototype;\n var hasOwn = Object.prototype.hasOwnProperty;\n\n function escapeRegEx(string) {\n // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963\n return string.replace(/([.*+?^=!:${}()|[\\]\\/\\\\])/g, '\\\\$1');\n }\n\n function getType(value) {\n // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value\n if (value === undefined) {\n return 'Undefined';\n }\n\n return String(Object.prototype.toString.call(value)).slice(8, -1);\n }\n\n function isArray(obj) {\n return getType(obj) === 'Array';\n }\n\n function filterArrayValues(data, value) {\n var lookup = {};\n var i, length;\n\n if (getType(value) === 'RegExp') {\n lookup = null;\n } else if (isArray(value)) {\n for (i = 0, length = value.length; i < length; i++) {\n lookup[value[i]] = true;\n }\n } else {\n lookup[value] = true;\n }\n\n for (i = 0, length = data.length; i < length; i++) {\n /*jshint laxbreak: true */\n var _match = lookup && lookup[data[i]] !== undefined\n || !lookup && value.test(data[i]);\n /*jshint laxbreak: false */\n if (_match) {\n data.splice(i, 1);\n length--;\n i--;\n }\n }\n\n return data;\n }\n\n function arrayContains(list, value) {\n var i, length;\n\n // value may be string, number, array, regexp\n if (isArray(value)) {\n // Note: this can be optimized to O(n) (instead of current O(m * n))\n for (i = 0, length = value.length; i < length; i++) {\n if (!arrayContains(list, value[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n var _type = getType(value);\n for (i = 0, length = list.length; i < length; i++) {\n if (_type === 'RegExp') {\n if (typeof list[i] === 'string' && list[i].match(value)) {\n return true;\n }\n } else if (list[i] === value) {\n return true;\n }\n }\n\n return false;\n }\n\n function arraysEqual(one, two) {\n if (!isArray(one) || !isArray(two)) {\n return false;\n }\n\n // arrays can't be equal if they have different amount of content\n if (one.length !== two.length) {\n return false;\n }\n\n one.sort();\n two.sort();\n\n for (var i = 0, l = one.length; i < l; i++) {\n if (one[i] !== two[i]) {\n return false;\n }\n }\n\n return true;\n }\n\n function trimSlashes(text) {\n var trim_expression = /^\\/+|\\/+$/g;\n return text.replace(trim_expression, '');\n }\n\n URI._parts = function() {\n return {\n protocol: null,\n username: null,\n password: null,\n hostname: null,\n urn: null,\n port: null,\n path: null,\n query: null,\n fragment: null,\n // state\n duplicateQueryParameters: URI.duplicateQueryParameters,\n escapeQuerySpace: URI.escapeQuerySpace\n };\n };\n // state: allow duplicate query parameters (a=1&a=1)\n URI.duplicateQueryParameters = false;\n // state: replaces + with %20 (space in query strings)\n URI.escapeQuerySpace = true;\n // static properties\n URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;\n URI.idn_expression = /[^a-z0-9\\.-]/i;\n URI.punycode_expression = /(xn--)/i;\n // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?\n URI.ip4_expression = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n // credits to Rich Brown\n // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096\n // specification: http://www.ietf.org/rfc/rfc4291.txt\n URI.ip6_expression = /^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$/;\n // expression used is \"gruber revised\" (@gruber v2) determined to be the\n // best solution in a regex-golf we did a couple of ages ago at\n // * http://mathiasbynens.be/demo/url-regex\n // * http://rodneyrehm.de/t/url-regex.html\n URI.find_uri_expression = /\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))/ig;\n URI.findUri = {\n // valid \"scheme://\" or \"www.\"\n start: /\\b(?:([a-z][a-z0-9.+-]*:\\/\\/)|www\\.)/gi,\n // everything up to the next whitespace\n end: /[\\s\\r\\n]|$/,\n // trim trailing punctuation captured by end RegExp\n trim: /[`!()\\[\\]{};:'\".,<>?«»“”„‘’]+$/\n };\n // http://www.iana.org/assignments/uri-schemes.html\n // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports\n URI.defaultPorts = {\n http: '80',\n https: '443',\n ftp: '21',\n gopher: '70',\n ws: '80',\n wss: '443'\n };\n // allowed hostname characters according to RFC 3986\n // ALPHA DIGIT \"-\" \".\" \"_\" \"~\" \"!\" \"$\" \"&\" \"'\" \"(\" \")\" \"*\" \"+\" \",\" \";\" \"=\" %encoded\n // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . -\n URI.invalid_hostname_characters = /[^a-zA-Z0-9\\.-]/;\n // map DOM Elements to their URI attribute\n URI.domAttributes = {\n 'a': 'href',\n 'blockquote': 'cite',\n 'link': 'href',\n 'base': 'href',\n 'script': 'src',\n 'form': 'action',\n 'img': 'src',\n 'area': 'href',\n 'iframe': 'src',\n 'embed': 'src',\n 'source': 'src',\n 'track': 'src',\n 'input': 'src', // but only if type=\"image\"\n 'audio': 'src',\n 'video': 'src'\n };\n URI.getDomAttribute = function(node) {\n if (!node || !node.nodeName) {\n return undefined;\n }\n\n var nodeName = node.nodeName.toLowerCase();\n // should only expose src for type=\"image\"\n if (nodeName === 'input' && node.type !== 'image') {\n return undefined;\n }\n\n return URI.domAttributes[nodeName];\n };\n\n function escapeForDumbFirefox36(value) {\n // https://github.com/medialize/URI.js/issues/91\n return escape(value);\n }\n\n // encoding / decoding according to RFC3986\n function strictEncodeURIComponent(string) {\n // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent\n return encodeURIComponent(string)\n .replace(/[!'()*]/g, escapeForDumbFirefox36)\n .replace(/\\*/g, '%2A');\n }\n URI.encode = strictEncodeURIComponent;\n URI.decode = decodeURIComponent;\n URI.iso8859 = function() {\n URI.encode = escape;\n URI.decode = unescape;\n };\n URI.unicode = function() {\n URI.encode = strictEncodeURIComponent;\n URI.decode = decodeURIComponent;\n };\n URI.characters = {\n pathname: {\n encode: {\n // RFC3986 2.1: For consistency, URI producers and normalizers should\n // use uppercase hexadecimal digits for all percent-encodings.\n expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,\n map: {\n // -._~!'()*\n '%24': '$',\n '%26': '&',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '=',\n '%3A': ':',\n '%40': '@'\n }\n },\n decode: {\n expression: /[\\/\\?#]/g,\n map: {\n '/': '%2F',\n '?': '%3F',\n '#': '%23'\n }\n }\n },\n reserved: {\n encode: {\n // RFC3986 2.1: For consistency, URI producers and normalizers should\n // use uppercase hexadecimal digits for all percent-encodings.\n expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,\n map: {\n // gen-delims\n '%3A': ':',\n '%2F': '/',\n '%3F': '?',\n '%23': '#',\n '%5B': '[',\n '%5D': ']',\n '%40': '@',\n // sub-delims\n '%21': '!',\n '%24': '$',\n '%26': '&',\n '%27': '\\'',\n '%28': '(',\n '%29': ')',\n '%2A': '*',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '='\n }\n }\n },\n urnpath: {\n // The characters under `encode` are the characters called out by RFC 2141 as being acceptable\n // for usage in a URN. RFC2141 also calls out \"-\", \".\", and \"_\" as acceptable characters, but\n // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also\n // note that the colon character is not featured in the encoding map; this is because URI.js\n // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it\n // should not appear unencoded in a segment itself.\n // See also the note above about RFC3986 and capitalalized hex digits.\n encode: {\n expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,\n map: {\n '%21': '!',\n '%24': '$',\n '%27': '\\'',\n '%28': '(',\n '%29': ')',\n '%2A': '*',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '=',\n '%40': '@'\n }\n },\n // These characters are the characters called out by RFC2141 as \"reserved\" characters that\n // should never appear in a URN, plus the colon character (see note above).\n decode: {\n expression: /[\\/\\?#:]/g,\n map: {\n '/': '%2F',\n '?': '%3F',\n '#': '%23',\n ':': '%3A'\n }\n }\n }\n };\n URI.encodeQuery = function(string, escapeQuerySpace) {\n var escaped = URI.encode(string + '');\n if (escapeQuerySpace === undefined) {\n escapeQuerySpace = URI.escapeQuerySpace;\n }\n\n return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;\n };\n URI.decodeQuery = function(string, escapeQuerySpace) {\n string += '';\n if (escapeQuerySpace === undefined) {\n escapeQuerySpace = URI.escapeQuerySpace;\n }\n\n try {\n return URI.decode(escapeQuerySpace ? string.replace(/\\+/g, '%20') : string);\n } catch(e) {\n // we're not going to mess with weird encodings,\n // give up and return the undecoded original string\n // see https://github.com/medialize/URI.js/issues/87\n // see https://github.com/medialize/URI.js/issues/92\n return string;\n }\n };\n // generate encode/decode path functions\n var _parts = {'encode':'encode', 'decode':'decode'};\n var _part;\n var generateAccessor = function(_group, _part) {\n return function(string) {\n try {\n return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {\n return URI.characters[_group][_part].map[c];\n });\n } catch (e) {\n // we're not going to mess with weird encodings,\n // give up and return the undecoded original string\n // see https://github.com/medialize/URI.js/issues/87\n // see https://github.com/medialize/URI.js/issues/92\n return string;\n }\n };\n };\n\n for (_part in _parts) {\n URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);\n URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);\n }\n\n var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {\n return function(string) {\n // Why pass in names of functions, rather than the function objects themselves? The\n // definitions of some functions (but in particular, URI.decode) will occasionally change due\n // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure\n // that the functions we use here are \"fresh\".\n var actualCodingFunc;\n if (!_innerCodingFuncName) {\n actualCodingFunc = URI[_codingFuncName];\n } else {\n actualCodingFunc = function(string) {\n return URI[_codingFuncName](URI[_innerCodingFuncName](string));\n };\n }\n\n var segments = (string + '').split(_sep);\n\n for (var i = 0, length = segments.length; i < length; i++) {\n segments[i] = actualCodingFunc(segments[i]);\n }\n\n return segments.join(_sep);\n };\n };\n\n // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.\n URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');\n URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');\n URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');\n URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');\n\n URI.encodeReserved = generateAccessor('reserved', 'encode');\n\n URI.parse = function(string, parts) {\n var pos;\n if (!parts) {\n parts = {};\n }\n // [protocol\"://\"[username[\":\"password]\"@\"]hostname[\":\"port]\"/\"?][path][\"?\"querystring][\"#\"fragment]\n\n // extract fragment\n pos = string.indexOf('#');\n if (pos > -1) {\n // escaping?\n parts.fragment = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // extract query\n pos = string.indexOf('?');\n if (pos > -1) {\n // escaping?\n parts.query = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // extract protocol\n if (string.substring(0, 2) === '//') {\n // relative-scheme\n parts.protocol = null;\n string = string.substring(2);\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n pos = string.indexOf(':');\n if (pos > -1) {\n parts.protocol = string.substring(0, pos) || null;\n if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {\n // : may be within the path\n parts.protocol = undefined;\n } else if (string.substring(pos + 1, pos + 3) === '//') {\n string = string.substring(pos + 3);\n\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n string = string.substring(pos + 1);\n parts.urn = true;\n }\n }\n }\n\n // what's left must be the path\n parts.path = string;\n\n // and we're done\n return parts;\n };\n URI.parseHost = function(string, parts) {\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n // https://github.com/medialize/URI.js/pull/233\n string = string.replace(/\\\\/g, '/');\n\n // extract host:port\n var pos = string.indexOf('/');\n var bracketPos;\n var t;\n\n if (pos === -1) {\n pos = string.length;\n }\n\n if (string.charAt(0) === '[') {\n // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6\n // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts\n // IPv6+port in the format [2001:db8::1]:80 (for the time being)\n bracketPos = string.indexOf(']');\n parts.hostname = string.substring(1, bracketPos) || null;\n parts.port = string.substring(bracketPos + 2, pos) || null;\n if (parts.port === '/') {\n parts.port = null;\n }\n } else {\n var firstColon = string.indexOf(':');\n var firstSlash = string.indexOf('/');\n var nextColon = string.indexOf(':', firstColon + 1);\n if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {\n // IPv6 host contains multiple colons - but no port\n // this notation is actually not allowed by RFC 3986, but we're a liberal parser\n parts.hostname = string.substring(0, pos) || null;\n parts.port = null;\n } else {\n t = string.substring(0, pos).split(':');\n parts.hostname = t[0] || null;\n parts.port = t[1] || null;\n }\n }\n\n if (parts.hostname && string.substring(pos).charAt(0) !== '/') {\n pos++;\n string = '/' + string;\n }\n\n return string.substring(pos) || '/';\n };\n URI.parseAuthority = function(string, parts) {\n string = URI.parseUserinfo(string, parts);\n return URI.parseHost(string, parts);\n };\n URI.parseUserinfo = function(string, parts) {\n // extract username:password\n var firstSlash = string.indexOf('/');\n var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);\n var t;\n\n // authority@ must come before /path\n if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {\n t = string.substring(0, pos).split(':');\n parts.username = t[0] ? URI.decode(t[0]) : null;\n t.shift();\n parts.password = t[0] ? URI.decode(t.join(':')) : null;\n string = string.substring(pos + 1);\n } else {\n parts.username = null;\n parts.password = null;\n }\n\n return string;\n };\n URI.parseQuery = function(string, escapeQuerySpace) {\n if (!string) {\n return {};\n }\n\n // throw out the funky business - \"?\"[name\"=\"value\"&\"]+\n string = string.replace(/&+/g, '&').replace(/^\\?*&*|&+$/g, '');\n\n if (!string) {\n return {};\n }\n\n var items = {};\n var splits = string.split('&');\n var length = splits.length;\n var v, name, value;\n\n for (var i = 0; i < length; i++) {\n v = splits[i].split('=');\n name = URI.decodeQuery(v.shift(), escapeQuerySpace);\n // no \"=\" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters\n value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;\n\n if (hasOwn.call(items, name)) {\n if (typeof items[name] === 'string' || items[name] === null) {\n items[name] = [items[name]];\n }\n\n items[name].push(value);\n } else {\n items[name] = value;\n }\n }\n\n return items;\n };\n\n URI.build = function(parts) {\n var t = '';\n\n if (parts.protocol) {\n t += parts.protocol + ':';\n }\n\n if (!parts.urn && (t || parts.hostname)) {\n t += '//';\n }\n\n t += (URI.buildAuthority(parts) || '');\n\n if (typeof parts.path === 'string') {\n if (parts.path.charAt(0) !== '/' && typeof parts.hostname === 'string') {\n t += '/';\n }\n\n t += parts.path;\n }\n\n if (typeof parts.query === 'string' && parts.query) {\n t += '?' + parts.query;\n }\n\n if (typeof parts.fragment === 'string' && parts.fragment) {\n t += '#' + parts.fragment;\n }\n return t;\n };\n URI.buildHost = function(parts) {\n var t = '';\n\n if (!parts.hostname) {\n return '';\n } else if (URI.ip6_expression.test(parts.hostname)) {\n t += '[' + parts.hostname + ']';\n } else {\n t += parts.hostname;\n }\n\n if (parts.port) {\n t += ':' + parts.port;\n }\n\n return t;\n };\n URI.buildAuthority = function(parts) {\n return URI.buildUserinfo(parts) + URI.buildHost(parts);\n };\n URI.buildUserinfo = function(parts) {\n var t = '';\n\n if (parts.username) {\n t += URI.encode(parts.username);\n }\n\n if (parts.password) {\n t += ':' + URI.encode(parts.password);\n }\n\n if (t) {\n t += '@';\n }\n\n return t;\n };\n URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {\n // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html\n // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed\n // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!\n // URI.js treats the query string as being application/x-www-form-urlencoded\n // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type\n\n var t = '';\n var unique, key, i, length;\n for (key in data) {\n if (hasOwn.call(data, key) && key) {\n if (isArray(data[key])) {\n unique = {};\n for (i = 0, length = data[key].length; i < length; i++) {\n if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {\n t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);\n if (duplicateQueryParameters !== true) {\n unique[data[key][i] + ''] = true;\n }\n }\n }\n } else if (data[key] !== undefined) {\n t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);\n }\n }\n }\n\n return t.substring(1);\n };\n URI.buildQueryParameter = function(name, value, escapeQuerySpace) {\n // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded\n // don't append \"=\" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization\n return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');\n };\n\n URI.addQuery = function(data, name, value) {\n if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n URI.addQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n if (data[name] === undefined) {\n data[name] = value;\n return;\n } else if (typeof data[name] === 'string') {\n data[name] = [data[name]];\n }\n\n if (!isArray(value)) {\n value = [value];\n }\n\n data[name] = (data[name] || []).concat(value);\n } else {\n throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');\n }\n };\n URI.removeQuery = function(data, name, value) {\n var i, length, key;\n\n if (isArray(name)) {\n for (i = 0, length = name.length; i < length; i++) {\n data[name[i]] = undefined;\n }\n } else if (getType(name) === 'RegExp') {\n for (key in data) {\n if (name.test(key)) {\n data[key] = undefined;\n }\n }\n } else if (typeof name === 'object') {\n for (key in name) {\n if (hasOwn.call(name, key)) {\n URI.removeQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n if (value !== undefined) {\n if (getType(value) === 'RegExp') {\n if (!isArray(data[name]) && value.test(data[name])) {\n data[name] = undefined;\n } else {\n data[name] = filterArrayValues(data[name], value);\n }\n } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {\n data[name] = undefined;\n } else if (isArray(data[name])) {\n data[name] = filterArrayValues(data[name], value);\n }\n } else {\n data[name] = undefined;\n }\n } else {\n throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');\n }\n };\n URI.hasQuery = function(data, name, value, withinArray) {\n switch (getType(name)) {\n case 'String':\n // Nothing to do here\n break;\n\n case 'RegExp':\n for (var key in data) {\n if (hasOwn.call(data, key)) {\n if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {\n return true;\n }\n }\n }\n\n return false;\n\n case 'Object':\n for (var _key in name) {\n if (hasOwn.call(name, _key)) {\n if (!URI.hasQuery(data, _key, name[_key])) {\n return false;\n }\n }\n }\n\n return true;\n\n default:\n throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');\n }\n\n switch (getType(value)) {\n case 'Undefined':\n // true if exists (but may be empty)\n return name in data; // data[name] !== undefined;\n\n case 'Boolean':\n // true if exists and non-empty\n var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);\n return value === _booly;\n\n case 'Function':\n // allow complex comparison\n return !!value(data[name], name, data);\n\n case 'Array':\n if (!isArray(data[name])) {\n return false;\n }\n\n var op = withinArray ? arrayContains : arraysEqual;\n return op(data[name], value);\n\n case 'RegExp':\n if (!isArray(data[name])) {\n return Boolean(data[name] && data[name].match(value));\n }\n\n if (!withinArray) {\n return false;\n }\n\n return arrayContains(data[name], value);\n\n case 'Number':\n value = String(value);\n /* falls through */\n case 'String':\n if (!isArray(data[name])) {\n return data[name] === value;\n }\n\n if (!withinArray) {\n return false;\n }\n\n return arrayContains(data[name], value);\n\n default:\n throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');\n }\n };\n\n\n URI.joinPaths = function() {\n var input = [];\n var segments = [];\n var nonEmptySegments = 0;\n\n for (var i = 0; i < arguments.length; i++) {\n var url = new URI(arguments[i]);\n input.push(url);\n var _segments = url.segment();\n for (var s = 0; s < _segments.length; s++) {\n if (typeof _segments[s] === 'string') {\n segments.push(_segments[s]);\n }\n\n if (_segments[s]) {\n nonEmptySegments++;\n }\n }\n }\n\n if (!segments.length || !nonEmptySegments) {\n return new URI('');\n }\n\n var uri = new URI('').segment(segments);\n\n if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {\n uri.path('/' + uri.path());\n }\n\n return uri.normalize();\n };\n\n URI.commonPath = function(one, two) {\n var length = Math.min(one.length, two.length);\n var pos;\n\n // find first non-matching character\n for (pos = 0; pos < length; pos++) {\n if (one.charAt(pos) !== two.charAt(pos)) {\n pos--;\n break;\n }\n }\n\n if (pos < 1) {\n return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';\n }\n\n // revert to last /\n if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {\n pos = one.substring(0, pos).lastIndexOf('/');\n }\n\n return one.substring(0, pos + 1);\n };\n\n URI.withinString = function(string, callback, options) {\n options || (options = {});\n var _start = options.start || URI.findUri.start;\n var _end = options.end || URI.findUri.end;\n var _trim = options.trim || URI.findUri.trim;\n var _attributeOpen = /[a-z0-9-]=[\"']?$/i;\n\n _start.lastIndex = 0;\n while (true) {\n var match = _start.exec(string);\n if (!match) {\n break;\n }\n\n var start = match.index;\n if (options.ignoreHtml) {\n // attribut(e=[\"']?$)\n var attributeOpen = string.slice(Math.max(start - 3, 0), start);\n if (attributeOpen && _attributeOpen.test(attributeOpen)) {\n continue;\n }\n }\n\n var end = start + string.slice(start).search(_end);\n var slice = string.slice(start, end).replace(_trim, '');\n if (options.ignore && options.ignore.test(slice)) {\n continue;\n }\n\n end = start + slice.length;\n var result = callback(slice, start, end, string);\n string = string.slice(0, start) + result + string.slice(end);\n _start.lastIndex = start + result.length;\n }\n\n _start.lastIndex = 0;\n return string;\n };\n\n URI.ensureValidHostname = function(v) {\n // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)\n // they are not part of DNS and therefore ignored by URI.js\n\n if (v.match(URI.invalid_hostname_characters)) {\n // test punycode\n if (!punycode) {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-] and Punycode.js is not available');\n }\n\n if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n }\n };\n\n // noConflict\n URI.noConflict = function(removeAll) {\n if (removeAll) {\n var unconflicted = {\n URI: this.noConflict()\n };\n\n if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {\n unconflicted.URITemplate = root.URITemplate.noConflict();\n }\n\n if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {\n unconflicted.IPv6 = root.IPv6.noConflict();\n }\n\n if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {\n unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();\n }\n\n return unconflicted;\n } else if (root.URI === this) {\n root.URI = _URI;\n }\n\n return this;\n };\n\n p.build = function(deferBuild) {\n if (deferBuild === true) {\n this._deferred_build = true;\n } else if (deferBuild === undefined || this._deferred_build) {\n this._string = URI.build(this._parts);\n this._deferred_build = false;\n }\n\n return this;\n };\n\n p.clone = function() {\n return new URI(this);\n };\n\n p.valueOf = p.toString = function() {\n return this.build(false)._string;\n };\n\n\n function generateSimpleAccessor(_part){\n return function(v, build) {\n if (v === undefined) {\n return this._parts[_part] || '';\n } else {\n this._parts[_part] = v || null;\n this.build(!build);\n return this;\n }\n };\n }\n\n function generatePrefixAccessor(_part, _key){\n return function(v, build) {\n if (v === undefined) {\n return this._parts[_part] || '';\n } else {\n if (v !== null) {\n v = v + '';\n if (v.charAt(0) === _key) {\n v = v.substring(1);\n }\n }\n\n this._parts[_part] = v;\n this.build(!build);\n return this;\n }\n };\n }\n\n p.protocol = generateSimpleAccessor('protocol');\n p.username = generateSimpleAccessor('username');\n p.password = generateSimpleAccessor('password');\n p.hostname = generateSimpleAccessor('hostname');\n p.port = generateSimpleAccessor('port');\n p.query = generatePrefixAccessor('query', '?');\n p.fragment = generatePrefixAccessor('fragment', '#');\n\n p.search = function(v, build) {\n var t = this.query(v, build);\n return typeof t === 'string' && t.length ? ('?' + t) : t;\n };\n p.hash = function(v, build) {\n var t = this.fragment(v, build);\n return typeof t === 'string' && t.length ? ('#' + t) : t;\n };\n\n p.pathname = function(v, build) {\n if (v === undefined || v === true) {\n var res = this._parts.path || (this._parts.hostname ? '/' : '');\n return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;\n } else {\n if (this._parts.urn) {\n this._parts.path = v ? URI.recodeUrnPath(v) : '';\n } else {\n this._parts.path = v ? URI.recodePath(v) : '/';\n }\n this.build(!build);\n return this;\n }\n };\n p.path = p.pathname;\n p.href = function(href, build) {\n var key;\n\n if (href === undefined) {\n return this.toString();\n }\n\n this._string = '';\n this._parts = URI._parts();\n\n var _URI = href instanceof URI;\n var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);\n if (href.nodeName) {\n var attribute = URI.getDomAttribute(href);\n href = href[attribute] || '';\n _object = false;\n }\n\n // window.location is reported to be an object, but it's not the sort\n // of object we're looking for:\n // * location.protocol ends with a colon\n // * location.query != object.search\n // * location.hash != object.fragment\n // simply serializing the unknown object should do the trick\n // (for location, not for everything...)\n if (!_URI && _object && href.pathname !== undefined) {\n href = href.toString();\n }\n\n if (typeof href === 'string' || href instanceof String) {\n this._parts = URI.parse(String(href), this._parts);\n } else if (_URI || _object) {\n var src = _URI ? href._parts : href;\n for (key in src) {\n if (hasOwn.call(this._parts, key)) {\n this._parts[key] = src[key];\n }\n }\n } else {\n throw new TypeError('invalid input');\n }\n\n this.build(!build);\n return this;\n };\n\n // identification accessors\n p.is = function(what) {\n var ip = false;\n var ip4 = false;\n var ip6 = false;\n var name = false;\n var sld = false;\n var idn = false;\n var punycode = false;\n var relative = !this._parts.urn;\n\n if (this._parts.hostname) {\n relative = false;\n ip4 = URI.ip4_expression.test(this._parts.hostname);\n ip6 = URI.ip6_expression.test(this._parts.hostname);\n ip = ip4 || ip6;\n name = !ip;\n sld = name && SLD && SLD.has(this._parts.hostname);\n idn = name && URI.idn_expression.test(this._parts.hostname);\n punycode = name && URI.punycode_expression.test(this._parts.hostname);\n }\n\n switch (what.toLowerCase()) {\n case 'relative':\n return relative;\n\n case 'absolute':\n return !relative;\n\n // hostname identification\n case 'domain':\n case 'name':\n return name;\n\n case 'sld':\n return sld;\n\n case 'ip':\n return ip;\n\n case 'ip4':\n case 'ipv4':\n case 'inet4':\n return ip4;\n\n case 'ip6':\n case 'ipv6':\n case 'inet6':\n return ip6;\n\n case 'idn':\n return idn;\n\n case 'url':\n return !this._parts.urn;\n\n case 'urn':\n return !!this._parts.urn;\n\n case 'punycode':\n return punycode;\n }\n\n return null;\n };\n\n // component specific input validation\n var _protocol = p.protocol;\n var _port = p.port;\n var _hostname = p.hostname;\n\n p.protocol = function(v, build) {\n if (v !== undefined) {\n if (v) {\n // accept trailing ://\n v = v.replace(/:(\\/\\/)?$/, '');\n\n if (!v.match(URI.protocol_expression)) {\n throw new TypeError('Protocol \"' + v + '\" contains characters other than [A-Z0-9.+-] or doesn\\'t start with [A-Z]');\n }\n }\n }\n return _protocol.call(this, v, build);\n };\n p.scheme = p.protocol;\n p.port = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v !== undefined) {\n if (v === 0) {\n v = null;\n }\n\n if (v) {\n v += '';\n if (v.charAt(0) === ':') {\n v = v.substring(1);\n }\n\n if (v.match(/[^0-9]/)) {\n throw new TypeError('Port \"' + v + '\" contains characters other than [0-9]');\n }\n }\n }\n return _port.call(this, v, build);\n };\n p.hostname = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v !== undefined) {\n var x = {};\n var res = URI.parseHost(v, x);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n v = x.hostname;\n }\n return _hostname.call(this, v, build);\n };\n\n // compound accessors\n p.origin = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n var protocol = this.protocol();\n var authority = this.authority();\n if (!authority) {\n return '';\n }\n\n return (protocol ? protocol + '://' : '') + this.authority();\n } else {\n var origin = URI(v);\n this\n .protocol(origin.protocol())\n .authority(origin.authority())\n .build(!build);\n return this;\n }\n };\n p.host = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n return this._parts.hostname ? URI.buildHost(this._parts) : '';\n } else {\n var res = URI.parseHost(v, this._parts);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n this.build(!build);\n return this;\n }\n };\n p.authority = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n return this._parts.hostname ? URI.buildAuthority(this._parts) : '';\n } else {\n var res = URI.parseAuthority(v, this._parts);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n this.build(!build);\n return this;\n }\n };\n p.userinfo = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n var t = URI.buildUserinfo(this._parts);\n return t ? t.substring(0, t.length -1) : t;\n } else {\n if (v[v.length-1] !== '@') {\n v += '@';\n }\n\n URI.parseUserinfo(v, this._parts);\n this.build(!build);\n return this;\n }\n };\n p.resource = function(v, build) {\n var parts;\n\n if (v === undefined) {\n return this.path() + this.search() + this.hash();\n }\n\n parts = URI.parse(v);\n this._parts.path = parts.path;\n this._parts.query = parts.query;\n this._parts.fragment = parts.fragment;\n this.build(!build);\n return this;\n };\n\n // fraction accessors\n p.subdomain = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n // convenience, return \"www\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n // grab domain and add another segment\n var end = this._parts.hostname.length - this.domain().length - 1;\n return this._parts.hostname.substring(0, end) || '';\n } else {\n var e = this._parts.hostname.length - this.domain().length;\n var sub = this._parts.hostname.substring(0, e);\n var replace = new RegExp('^' + escapeRegEx(sub));\n\n if (v && v.charAt(v.length - 1) !== '.') {\n v += '.';\n }\n\n if (v) {\n URI.ensureValidHostname(v);\n }\n\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n this.build(!build);\n return this;\n }\n };\n p.domain = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v === 'boolean') {\n build = v;\n v = undefined;\n }\n\n // convenience, return \"example.org\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n // if hostname consists of 1 or 2 segments, it must be the domain\n var t = this._parts.hostname.match(/\\./g);\n if (t && t.length < 2) {\n return this._parts.hostname;\n }\n\n // grab tld and add another segment\n var end = this._parts.hostname.length - this.tld(build).length - 1;\n end = this._parts.hostname.lastIndexOf('.', end -1) + 1;\n return this._parts.hostname.substring(end) || '';\n } else {\n if (!v) {\n throw new TypeError('cannot set domain empty');\n }\n\n URI.ensureValidHostname(v);\n\n if (!this._parts.hostname || this.is('IP')) {\n this._parts.hostname = v;\n } else {\n var replace = new RegExp(escapeRegEx(this.domain()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.tld = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v === 'boolean') {\n build = v;\n v = undefined;\n }\n\n // return \"org\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n var pos = this._parts.hostname.lastIndexOf('.');\n var tld = this._parts.hostname.substring(pos + 1);\n\n if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {\n return SLD.get(this._parts.hostname) || tld;\n }\n\n return tld;\n } else {\n var replace;\n\n if (!v) {\n throw new TypeError('cannot set TLD empty');\n } else if (v.match(/[^a-zA-Z0-9-]/)) {\n if (SLD && SLD.is(v)) {\n replace = new RegExp(escapeRegEx(this.tld()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n } else {\n throw new TypeError('TLD \"' + v + '\" contains characters other than [A-Z0-9]');\n }\n } else if (!this._parts.hostname || this.is('IP')) {\n throw new ReferenceError('cannot set TLD on non-domain host');\n } else {\n replace = new RegExp(escapeRegEx(this.tld()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.directory = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path && !this._parts.hostname) {\n return '';\n }\n\n if (this._parts.path === '/') {\n return '/';\n }\n\n var end = this._parts.path.length - this.filename().length - 1;\n var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');\n\n return v ? URI.decodePath(res) : res;\n\n } else {\n var e = this._parts.path.length - this.filename().length;\n var directory = this._parts.path.substring(0, e);\n var replace = new RegExp('^' + escapeRegEx(directory));\n\n // fully qualifier directories begin with a slash\n if (!this.is('relative')) {\n if (!v) {\n v = '/';\n }\n\n if (v.charAt(0) !== '/') {\n v = '/' + v;\n }\n }\n\n // directories always end with a slash\n if (v && v.charAt(v.length - 1) !== '/') {\n v += '/';\n }\n\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n this.build(!build);\n return this;\n }\n };\n p.filename = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path || this._parts.path === '/') {\n return '';\n }\n\n var pos = this._parts.path.lastIndexOf('/');\n var res = this._parts.path.substring(pos+1);\n\n return v ? URI.decodePathSegment(res) : res;\n } else {\n var mutatedDirectory = false;\n\n if (v.charAt(0) === '/') {\n v = v.substring(1);\n }\n\n if (v.match(/\\.?\\//)) {\n mutatedDirectory = true;\n }\n\n var replace = new RegExp(escapeRegEx(this.filename()) + '$');\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n\n if (mutatedDirectory) {\n this.normalizePath(build);\n } else {\n this.build(!build);\n }\n\n return this;\n }\n };\n p.suffix = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path || this._parts.path === '/') {\n return '';\n }\n\n var filename = this.filename();\n var pos = filename.lastIndexOf('.');\n var s, res;\n\n if (pos === -1) {\n return '';\n }\n\n // suffix may only contain alnum characters (yup, I made this up.)\n s = filename.substring(pos+1);\n res = (/^[a-z0-9%]+$/i).test(s) ? s : '';\n return v ? URI.decodePathSegment(res) : res;\n } else {\n if (v.charAt(0) === '.') {\n v = v.substring(1);\n }\n\n var suffix = this.suffix();\n var replace;\n\n if (!suffix) {\n if (!v) {\n return this;\n }\n\n this._parts.path += '.' + URI.recodePath(v);\n } else if (!v) {\n replace = new RegExp(escapeRegEx('.' + suffix) + '$');\n } else {\n replace = new RegExp(escapeRegEx(suffix) + '$');\n }\n\n if (replace) {\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.segment = function(segment, v, build) {\n var separator = this._parts.urn ? ':' : '/';\n var path = this.path();\n var absolute = path.substring(0, 1) === '/';\n var segments = path.split(separator);\n\n if (segment !== undefined && typeof segment !== 'number') {\n build = v;\n v = segment;\n segment = undefined;\n }\n\n if (segment !== undefined && typeof segment !== 'number') {\n throw new Error('Bad segment \"' + segment + '\", must be 0-based integer');\n }\n\n if (absolute) {\n segments.shift();\n }\n\n if (segment < 0) {\n // allow negative indexes to address from the end\n segment = Math.max(segments.length + segment, 0);\n }\n\n if (v === undefined) {\n /*jshint laxbreak: true */\n return segment === undefined\n ? segments\n : segments[segment];\n /*jshint laxbreak: false */\n } else if (segment === null || segments[segment] === undefined) {\n if (isArray(v)) {\n segments = [];\n // collapse empty elements within array\n for (var i=0, l=v.length; i < l; i++) {\n if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {\n continue;\n }\n\n if (segments.length && !segments[segments.length -1].length) {\n segments.pop();\n }\n\n segments.push(trimSlashes(v[i]));\n }\n } else if (v || typeof v === 'string') {\n v = trimSlashes(v);\n if (segments[segments.length -1] === '') {\n // empty trailing elements have to be overwritten\n // to prevent results such as /foo//bar\n segments[segments.length -1] = v;\n } else {\n segments.push(v);\n }\n }\n } else {\n if (v) {\n segments[segment] = trimSlashes(v);\n } else {\n segments.splice(segment, 1);\n }\n }\n\n if (absolute) {\n segments.unshift('');\n }\n\n return this.path(segments.join(separator), build);\n };\n p.segmentCoded = function(segment, v, build) {\n var segments, i, l;\n\n if (typeof segment !== 'number') {\n build = v;\n v = segment;\n segment = undefined;\n }\n\n if (v === undefined) {\n segments = this.segment(segment, v, build);\n if (!isArray(segments)) {\n segments = segments !== undefined ? URI.decode(segments) : undefined;\n } else {\n for (i = 0, l = segments.length; i < l; i++) {\n segments[i] = URI.decode(segments[i]);\n }\n }\n\n return segments;\n }\n\n if (!isArray(v)) {\n v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;\n } else {\n for (i = 0, l = v.length; i < l; i++) {\n v[i] = URI.encode(v[i]);\n }\n }\n\n return this.segment(segment, v, build);\n };\n\n // mutating query string\n var q = p.query;\n p.query = function(v, build) {\n if (v === true) {\n return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n } else if (typeof v === 'function') {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n var result = v.call(this, data);\n this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n this.build(!build);\n return this;\n } else if (v !== undefined && typeof v !== 'string') {\n this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n this.build(!build);\n return this;\n } else {\n return q.call(this, v, build);\n }\n };\n p.setQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n\n if (typeof name === 'string' || name instanceof String) {\n data[name] = value !== undefined ? value : null;\n } else if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n data[key] = name[key];\n }\n }\n } else {\n throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');\n }\n\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.addQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n URI.addQuery(data, name, value === undefined ? null : value);\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.removeQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n URI.removeQuery(data, name, value);\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.hasQuery = function(name, value, withinArray) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n return URI.hasQuery(data, name, value, withinArray);\n };\n p.setSearch = p.setQuery;\n p.addSearch = p.addQuery;\n p.removeSearch = p.removeQuery;\n p.hasSearch = p.hasQuery;\n\n // sanitizing URLs\n p.normalize = function() {\n if (this._parts.urn) {\n return this\n .normalizeProtocol(false)\n .normalizePath(false)\n .normalizeQuery(false)\n .normalizeFragment(false)\n .build();\n }\n\n return this\n .normalizeProtocol(false)\n .normalizeHostname(false)\n .normalizePort(false)\n .normalizePath(false)\n .normalizeQuery(false)\n .normalizeFragment(false)\n .build();\n };\n p.normalizeProtocol = function(build) {\n if (typeof this._parts.protocol === 'string') {\n this._parts.protocol = this._parts.protocol.toLowerCase();\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeHostname = function(build) {\n if (this._parts.hostname) {\n if (this.is('IDN') && punycode) {\n this._parts.hostname = punycode.toASCII(this._parts.hostname);\n } else if (this.is('IPv6') && IPv6) {\n this._parts.hostname = IPv6.best(this._parts.hostname);\n }\n\n this._parts.hostname = this._parts.hostname.toLowerCase();\n this.build(!build);\n }\n\n return this;\n };\n p.normalizePort = function(build) {\n // remove port of it's the protocol's default\n if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {\n this._parts.port = null;\n this.build(!build);\n }\n\n return this;\n };\n p.normalizePath = function(build) {\n var _path = this._parts.path;\n if (!_path) {\n return this;\n }\n\n if (this._parts.urn) {\n this._parts.path = URI.recodeUrnPath(this._parts.path);\n this.build(!build);\n return this;\n }\n\n if (this._parts.path === '/') {\n return this;\n }\n\n _path = URI.recodePath(_path);\n\n var _was_relative;\n var _leadingParents = '';\n var _parent, _pos;\n\n // handle relative paths\n if (_path.charAt(0) !== '/') {\n _was_relative = true;\n _path = '/' + _path;\n }\n\n // handle relative files (as opposed to directories)\n if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {\n _path += '/';\n }\n\n // resolve simples\n _path = _path\n .replace(/(\\/(\\.\\/)+)|(\\/\\.$)/g, '/')\n .replace(/\\/{2,}/g, '/');\n\n // remember leading parents\n if (_was_relative) {\n _leadingParents = _path.substring(1).match(/^(\\.\\.\\/)+/) || '';\n if (_leadingParents) {\n _leadingParents = _leadingParents[0];\n }\n }\n\n // resolve parents\n while (true) {\n _parent = _path.search(/\\/\\.\\.(\\/|$)/);\n if (_parent === -1) {\n // no more ../ to resolve\n break;\n } else if (_parent === 0) {\n // top level cannot be relative, skip it\n _path = _path.substring(3);\n continue;\n }\n\n _pos = _path.substring(0, _parent).lastIndexOf('/');\n if (_pos === -1) {\n _pos = _parent;\n }\n _path = _path.substring(0, _pos) + _path.substring(_parent + 3);\n }\n\n // revert to relative\n if (_was_relative && this.is('relative')) {\n _path = _leadingParents + _path.substring(1);\n }\n\n this._parts.path = _path;\n this.build(!build);\n return this;\n };\n p.normalizePathname = p.normalizePath;\n p.normalizeQuery = function(build) {\n if (typeof this._parts.query === 'string') {\n if (!this._parts.query.length) {\n this._parts.query = null;\n } else {\n this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));\n }\n\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeFragment = function(build) {\n if (!this._parts.fragment) {\n this._parts.fragment = null;\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeSearch = p.normalizeQuery;\n p.normalizeHash = p.normalizeFragment;\n\n p.iso8859 = function() {\n // expect unicode input, iso8859 output\n var e = URI.encode;\n var d = URI.decode;\n\n URI.encode = escape;\n URI.decode = decodeURIComponent;\n try {\n this.normalize();\n } finally {\n URI.encode = e;\n URI.decode = d;\n }\n return this;\n };\n\n p.unicode = function() {\n // expect iso8859 input, unicode output\n var e = URI.encode;\n var d = URI.decode;\n\n URI.encode = strictEncodeURIComponent;\n URI.decode = unescape;\n try {\n this.normalize();\n } finally {\n URI.encode = e;\n URI.decode = d;\n }\n return this;\n };\n\n p.readable = function() {\n var uri = this.clone();\n // removing username, password, because they shouldn't be displayed according to RFC 3986\n uri.username('').password('').normalize();\n var t = '';\n if (uri._parts.protocol) {\n t += uri._parts.protocol + '://';\n }\n\n if (uri._parts.hostname) {\n if (uri.is('punycode') && punycode) {\n t += punycode.toUnicode(uri._parts.hostname);\n if (uri._parts.port) {\n t += ':' + uri._parts.port;\n }\n } else {\n t += uri.host();\n }\n }\n\n if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {\n t += '/';\n }\n\n t += uri.path(true);\n if (uri._parts.query) {\n var q = '';\n for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {\n var kv = (qp[i] || '').split('=');\n q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)\n .replace(/&/g, '%26');\n\n if (kv[1] !== undefined) {\n q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)\n .replace(/&/g, '%26');\n }\n }\n t += '?' + q.substring(1);\n }\n\n t += URI.decodeQuery(uri.hash(), true);\n return t;\n };\n\n // resolving relative and absolute URLs\n p.absoluteTo = function(base) {\n var resolved = this.clone();\n var properties = ['protocol', 'username', 'password', 'hostname', 'port'];\n var basedir, i, p;\n\n if (this._parts.urn) {\n throw new Error('URNs do not have any generally defined hierarchical components');\n }\n\n if (!(base instanceof URI)) {\n base = new URI(base);\n }\n\n if (!resolved._parts.protocol) {\n resolved._parts.protocol = base._parts.protocol;\n }\n\n if (this._parts.hostname) {\n return resolved;\n }\n\n for (i = 0; (p = properties[i]); i++) {\n resolved._parts[p] = base._parts[p];\n }\n\n if (!resolved._parts.path) {\n resolved._parts.path = base._parts.path;\n if (!resolved._parts.query) {\n resolved._parts.query = base._parts.query;\n }\n } else if (resolved._parts.path.substring(-2) === '..') {\n resolved._parts.path += '/';\n }\n\n if (resolved.path().charAt(0) !== '/') {\n basedir = base.directory();\n basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';\n resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;\n resolved.normalizePath();\n }\n\n resolved.build();\n return resolved;\n };\n p.relativeTo = function(base) {\n var relative = this.clone().normalize();\n var relativeParts, baseParts, common, relativePath, basePath;\n\n if (relative._parts.urn) {\n throw new Error('URNs do not have any generally defined hierarchical components');\n }\n\n base = new URI(base).normalize();\n relativeParts = relative._parts;\n baseParts = base._parts;\n relativePath = relative.path();\n basePath = base.path();\n\n if (relativePath.charAt(0) !== '/') {\n throw new Error('URI is already relative');\n }\n\n if (basePath.charAt(0) !== '/') {\n throw new Error('Cannot calculate a URI relative to another relative URI');\n }\n\n if (relativeParts.protocol === baseParts.protocol) {\n relativeParts.protocol = null;\n }\n\n if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {\n return relative.build();\n }\n\n if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {\n return relative.build();\n }\n\n if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {\n relativeParts.hostname = null;\n relativeParts.port = null;\n } else {\n return relative.build();\n }\n\n if (relativePath === basePath) {\n relativeParts.path = '';\n return relative.build();\n }\n\n // determine common sub path\n common = URI.commonPath(relativePath, basePath);\n\n // If the paths have nothing in common, return a relative URL with the absolute path.\n if (!common) {\n return relative.build();\n }\n\n var parents = baseParts.path\n .substring(common.length)\n .replace(/[^\\/]*$/, '')\n .replace(/.*?\\//g, '../');\n\n relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';\n\n return relative.build();\n };\n\n // comparing URIs\n p.equals = function(uri) {\n var one = this.clone();\n var two = new URI(uri);\n var one_map = {};\n var two_map = {};\n var checked = {};\n var one_query, two_query, key;\n\n one.normalize();\n two.normalize();\n\n // exact match\n if (one.toString() === two.toString()) {\n return true;\n }\n\n // extract query string\n one_query = one.query();\n two_query = two.query();\n one.query('');\n two.query('');\n\n // definitely not equal if not even non-query parts match\n if (one.toString() !== two.toString()) {\n return false;\n }\n\n // query parameters have the same length, even if they're permuted\n if (one_query.length !== two_query.length) {\n return false;\n }\n\n one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);\n two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);\n\n for (key in one_map) {\n if (hasOwn.call(one_map, key)) {\n if (!isArray(one_map[key])) {\n if (one_map[key] !== two_map[key]) {\n return false;\n }\n } else if (!arraysEqual(one_map[key], two_map[key])) {\n return false;\n }\n\n checked[key] = true;\n }\n }\n\n for (key in two_map) {\n if (hasOwn.call(two_map, key)) {\n if (!checked[key]) {\n // two contains a parameter not present in one\n return false;\n }\n }\n }\n\n return true;\n };\n\n // state\n p.duplicateQueryParameters = function(v) {\n this._parts.duplicateQueryParameters = !!v;\n return this;\n };\n\n p.escapeQuerySpace = function(v) {\n this._parts.escapeQuerySpace = !!v;\n return this;\n };\n\n return URI;\n}));\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar Spine = require('./spine');\nvar Locations = require('./locations');\nvar Parser = require('./parser');\nvar Navigation = require('./navigation');\nvar Rendition = require('./rendition');\nvar Unarchive = require('./unarchive');\nvar request = require('./request');\nvar EpubCFI = require('./epubcfi');\n\nfunction Book(_url, options){\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\trequestMethod: this.requestMethod\n\t});\n\n\tcore.extend(this.settings, options);\n\n\n\t// Promises\n\tthis.opening = new RSVP.defer();\n\tthis.opened = this.opening.promise;\n\tthis.isOpen = false;\n\n\tthis.url = undefined;\n\n\tthis.loading = {\n\t\tmanifest: new RSVP.defer(),\n\t\tspine: new RSVP.defer(),\n\t\tmetadata: new RSVP.defer(),\n\t\tcover: new RSVP.defer(),\n\t\tnavigation: new RSVP.defer(),\n\t\tpageList: new RSVP.defer()\n\t};\n\n\tthis.loaded = {\n\t\tmanifest: this.loading.manifest.promise,\n\t\tspine: this.loading.spine.promise,\n\t\tmetadata: this.loading.metadata.promise,\n\t\tcover: this.loading.cover.promise,\n\t\tnavigation: this.loading.navigation.promise,\n\t\tpageList: this.loading.pageList.promise\n\t};\n\n\tthis.ready = RSVP.hash(this.loaded);\n\n\t// Queue for methods used before opening\n\tthis.isRendered = false;\n\t// this._q = core.queue(this);\n\n\tthis.request = this.settings.requestMethod.bind(this);\n\n\tthis.spine = new Spine(this.request);\n\tthis.locations = new Locations(this.spine, this.request);\n\n\tif(_url) {\n\t\tthis.open(_url).catch(function (error) {\n\t\t\tvar err = new Error(\"Cannot load book at \"+ _url );\n\t\t\tconsole.error(err);\n\n\t\t\tthis.trigger(\"loadFailed\", error);\n\t\t}.bind(this));\n\t}\n};\n\nBook.prototype.open = function(_url, options){\n\tvar uri;\n\tvar parse = new Parser();\n\tvar epubPackage;\n\tvar epubContainer;\n\tvar book = this;\n\tvar containerPath = \"META-INF/container.xml\";\n\tvar location;\n\tvar absoluteUri;\n\tvar isArrayBuffer = false;\n\tvar isBase64 = options && options.base64;\n\n\tif(!_url) {\n\t\tthis.opening.resolve(this);\n\t\treturn this.opened;\n\t}\n\n\t// Reuse parsed url or create a new uri object\n\t// if(typeof(_url) === \"object\") {\n\t// uri = _url;\n\t// } else {\n\t// uri = core.uri(_url);\n\t// }\n\tif (_url instanceof ArrayBuffer || isBase64) {\n\t\tisArrayBuffer = true;\n\t\tthis.url = '/';\n\t} else {\n\t\turi = URI(_url);\n\t}\n\n\tif (window && window.location && uri) {\n\t\tabsoluteUri = uri.absoluteTo(window.location.href);\n\t\tthis.url = absoluteUri.toString();\n\t} else if (window && window.location) {\n\t\tthis.url = window.location.href;\n\t} else {\n\t\tthis.url = _url;\n\t}\n\n\t// Find path to the Container\n\tif(uri && uri.suffix() === \"opf\") {\n\t\t// Direct link to package, no container\n\t\tthis.packageUrl = _url;\n\t\tthis.containerUrl = '';\n\n\t\tif(uri.origin()) {\n\t\t\tthis.baseUrl = uri.origin() + \"/\" + uri.directory() + \"/\";\n\t\t} else if(absoluteUri){\n\t\t\tthis.baseUrl = absoluteUri.origin();\n\t\t\tthis.baseUrl += absoluteUri.directory() + \"/\";\n\t\t} else {\n\t\t\tthis.baseUrl = uri.directory() + \"/\";\n\t\t}\n\n\t\tepubPackage = this.request(this.packageUrl)\n\t\t\t.catch(function(error) {\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\n\t} else if(isArrayBuffer || isBase64 || this.isArchivedUrl(uri)) {\n\t\t// Book is archived\n\t\tthis.url = '/';\n\t\tthis.containerUrl = URI(containerPath).absoluteTo(this.url).toString();\n\n\t\tepubContainer = this.unarchive(_url, isBase64).\n\t\t\tthen(function() {\n\t\t\t\treturn this.request(this.containerUrl);\n\t\t\t}.bind(this))\n\t\t\t.catch(function(error) {\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\t}\n\t// Find the path to the Package from the container\n\telse if (!uri.suffix()) {\n\n\t\tthis.containerUrl = this.url + containerPath;\n\n\t\tepubContainer = this.request(this.containerUrl)\n\t\t\t.catch(function(error) {\n\t\t\t\t// handle errors in loading container\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\t}\n\n\tif (epubContainer) {\n\t\tepubPackage = epubContainer.\n\t\t\tthen(function(containerXml){\n\t\t\t\treturn parse.container(containerXml); // Container has path to content\n\t\t\t}).\n\t\t\tthen(function(paths){\n\t\t\t\tvar packageUri = URI(paths.packagePath);\n\t\t\t\tvar absPackageUri = packageUri.absoluteTo(book.url);\n\t\t\t\tvar absWindowUri;\n\n\t\t\t\tbook.packageUrl = absPackageUri.toString();\n\t\t\t\tbook.encoding = paths.encoding;\n\n\t\t\t\t// Set Url relative to the content\n\t\t\t\tif(absPackageUri.origin()) {\n\t\t\t\t\tbook.baseUrl = absPackageUri.origin() + absPackageUri.directory() + \"/\";\n\t\t\t\t} else {\n\t\t\t\t\tif(packageUri.directory()) {\n\t\t\t\t\t\tbook.baseUrl = \"/\" + packageUri.directory() + \"/\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbook.baseUrl = \"/\"\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn book.request(book.packageUrl);\n\t\t\t}).catch(function(error) {\n\t\t\t\t// handle errors in either of the two requests\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\t}\n\n\tepubPackage.then(function(packageXml) {\n\n\t\tif (!packageXml) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Get package information from epub opf\n\t\tbook.unpack(packageXml);\n\n\t\t// Resolve promises\n\t\tbook.loading.manifest.resolve(book.package.manifest);\n\t\tbook.loading.metadata.resolve(book.package.metadata);\n\t\tbook.loading.spine.resolve(book.spine);\n\t\tbook.loading.cover.resolve(book.cover);\n\n\t\tbook.isOpen = true;\n\n\t\t// Clear queue of any waiting book request\n\n\t\t// Resolve book opened promise\n\t\tbook.opening.resolve(book);\n\n\t}).catch(function(error) {\n\t\t// handle errors in parsing the book\n\t\t// console.error(error.message, error.stack);\n\t\tbook.opening.reject(error);\n\t});\n\n\treturn this.opened;\n};\n\nBook.prototype.unpack = function(packageXml){\n\tvar book = this,\n\t\t\tparse = new Parser();\n\n\tbook.package = parse.packageContents(packageXml); // Extract info from contents\n\tif(!book.package) {\n\t\treturn;\n\t}\n\n\tbook.package.baseUrl = book.baseUrl; // Provides a url base for resolving paths\n\n\tthis.spine.load(book.package);\n\n\tbook.navigation = new Navigation(book.package, this.request);\n\tbook.navigation.load().then(function(toc){\n\t\tbook.toc = toc;\n\t\tbook.loading.navigation.resolve(book.toc);\n\t});\n\n\t// //-- Set Global Layout setting based on metadata\n\t// MOVE TO RENDER\n\t// book.globalLayoutProperties = book.parseLayoutProperties(book.package.metadata);\n\n\tbook.cover = URI(book.package.coverPath).absoluteTo(book.baseUrl).toString();\n};\n\n// Alias for book.spine.get\nBook.prototype.section = function(target) {\n\treturn this.spine.get(target);\n};\n\n// Sugar to render a book\nBook.prototype.renderTo = function(element, options) {\n\t// var renderMethod = (options && options.method) ?\n\t// options.method :\n\t// \"single\";\n\n\tthis.rendition = new Rendition(this, options);\n\tthis.rendition.attachTo(element);\n\n\treturn this.rendition;\n};\n\nBook.prototype.requestMethod = function(_url) {\n\t// Switch request methods\n\tif(this.unarchived) {\n\t\treturn this.unarchived.request(_url);\n\t} else {\n\t\treturn request(_url, null, this.requestCredentials, this.requestHeaders);\n\t}\n\n};\n\nBook.prototype.setRequestCredentials = function(_credentials) {\n\tthis.requestCredentials = _credentials;\n};\n\nBook.prototype.setRequestHeaders = function(_headers) {\n\tthis.requestHeaders = _headers;\n};\n\nBook.prototype.unarchive = function(bookUrl, isBase64){\n\tthis.unarchived = new Unarchive();\n\treturn this.unarchived.open(bookUrl, isBase64);\n};\n\n//-- Checks if url has a .epub or .zip extension, or is ArrayBuffer (of zip/epub)\nBook.prototype.isArchivedUrl = function(bookUrl){\n\tvar uri;\n\tvar extension;\n\n\tif (bookUrl instanceof ArrayBuffer) {\n\t\treturn true;\n\t}\n\n\t// Reuse parsed url or create a new uri object\n\t// if(typeof(bookUrl) === \"object\") {\n\t// uri = bookUrl;\n\t// } else {\n\t// uri = core.uri(bookUrl);\n\t// }\n\turi = URI(bookUrl);\n\textension = uri.suffix();\n\n\tif(extension && (extension == \"epub\" || extension == \"zip\")){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n//-- Returns the cover\nBook.prototype.coverUrl = function(){\n\tvar retrieved = this.loaded.cover.\n\t\tthen(function(url) {\n\t\t\tif(this.unarchived) {\n\t\t\t\treturn this.unarchived.createUrl(this.cover);\n\t\t\t}else{\n\t\t\t\treturn this.cover;\n\t\t\t}\n\t\t}.bind(this));\n\n\n\n\treturn retrieved;\n};\n\nBook.prototype.range = function(cfiRange) {\n\tvar cfi = new EpubCFI(cfiRange);\n\tvar item = this.spine.get(cfi.spinePos);\n\n\treturn item.load().then(function (contents) {\n\t\tvar range = cfi.toRange(item.document);\n\t\treturn range;\n\t})\n};\n\nmodule.exports = Book;\n\n//-- Enable binding events to book\nRSVP.EventTarget.mixin(Book.prototype);\n\n//-- Handle RSVP Errors\nRSVP.on('error', function(event) {\n\tconsole.error(event);\n});\n\nRSVP.configure('instrument', false); //-- true | will logging out all RSVP rejections\n// RSVP.on('created', listener);\n// RSVP.on('chained', listener);\n// RSVP.on('fulfilled', listener);\nRSVP.on('rejected', function(event){\n\tconsole.error(event.detail.message, event.detail.stack);\n});\n","var RSVP = require('rsvp');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\nvar Mapping = require('./mapping');\n\n\nfunction Contents(doc, content, cfiBase) {\n\t// Blank Cfi for Parsing\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.document = doc;\n\tthis.documentElement = this.document.documentElement;\n\tthis.content = content || this.document.body;\n\tthis.window = this.document.defaultView;\n\t// Dom events to listen for\n\tthis.listenedEvents = [\"keydown\", \"keyup\", \"keypressed\", \"mouseup\", \"mousedown\", \"click\", \"touchend\", \"touchstart\"];\n\n\tthis._size = {\n\t\twidth: 0,\n\t\theight: 0\n\t}\n\n\tthis.cfiBase = cfiBase || \"\";\n\n\tthis.listeners();\n};\n\nContents.prototype.width = function(w) {\n\t// var frame = this.documentElement;\n\tvar frame = this.content;\n\n\tif (w && core.isNumber(w)) {\n\t\tw = w + \"px\";\n\t}\n\n\tif (w) {\n\t\tframe.style.width = w;\n\t\t// this.content.style.width = w;\n\t}\n\n\treturn this.window.getComputedStyle(frame)['width'];\n\n\n};\n\nContents.prototype.height = function(h) {\n\t// var frame = this.documentElement;\n\tvar frame = this.content;\n\n\tif (h && core.isNumber(h)) {\n\t\th = h + \"px\";\n\t}\n\n\tif (h) {\n\t\tframe.style.height = h;\n\t\t// this.content.style.height = h;\n\t}\n\n\treturn this.window.getComputedStyle(frame)['height'];\n\n};\n\nContents.prototype.contentWidth = function(w) {\n\n\tvar content = this.content || this.document.body;\n\n\tif (w && core.isNumber(w)) {\n\t\tw = w + \"px\";\n\t}\n\n\tif (w) {\n\t\tcontent.style.width = w;\n\t}\n\n\treturn this.window.getComputedStyle(content)['width'];\n\n\n};\n\nContents.prototype.contentHeight = function(h) {\n\n\tvar content = this.content || this.document.body;\n\n\tif (h && core.isNumber(h)) {\n\t\th = h + \"px\";\n\t}\n\n\tif (h) {\n\t\tcontent.style.height = h;\n\t}\n\n\treturn this.window.getComputedStyle(content)['height'];\n\n};\n\nContents.prototype.textWidth = function() {\n\tvar width;\n\tvar range = this.document.createRange();\n\tvar content = this.content || this.document.body;\n\n\t// Select the contents of frame\n\trange.selectNodeContents(content);\n\n\t// get the width of the text content\n\twidth = range.getBoundingClientRect().width;\n\n\treturn width;\n\n};\n\nContents.prototype.textHeight = function() {\n\tvar height;\n\tvar range = this.document.createRange();\n\tvar content = this.content || this.document.body;\n\n\trange.selectNodeContents(content);\n\n\theight = range.getBoundingClientRect().height;\n\n\treturn height;\n};\n\nContents.prototype.scrollWidth = function() {\n\tvar width = this.documentElement.scrollWidth;\n\n\treturn width;\n};\n\nContents.prototype.scrollHeight = function() {\n\tvar height = this.documentElement.scrollHeight;\n\n\treturn height;\n};\n\nContents.prototype.overflow = function(overflow) {\n\n\tif (overflow) {\n\t\tthis.documentElement.style.overflow = overflow;\n\t}\n\n\treturn this.window.getComputedStyle(this.documentElement)['overflow'];\n};\n\nContents.prototype.overflowX = function(overflow) {\n\n\tif (overflow) {\n\t\tthis.documentElement.style.overflowX = overflow;\n\t}\n\n\treturn this.window.getComputedStyle(this.documentElement)['overflowX'];\n};\n\nContents.prototype.overflowY = function(overflow) {\n\n\tif (overflow) {\n\t\tthis.documentElement.style.overflowY = overflow;\n\t}\n\n\treturn this.window.getComputedStyle(this.documentElement)['overflowY'];\n};\n\nContents.prototype.css = function(property, value) {\n\tvar content = this.content || this.document.body;\n\n\tif (value) {\n\t\tcontent.style[property] = value;\n\t}\n\n\treturn this.window.getComputedStyle(content)[property];\n};\n\nContents.prototype.viewport = function(options) {\n\tvar width, height, scale, scalable;\n\tvar $viewport = this.document.querySelector(\"meta[name='viewport']\");\n\tvar newContent = '';\n\n\t/**\n\t* check for the viewport size\n\t* \n\t*/\n\tif($viewport && $viewport.hasAttribute(\"content\")) {\n\t\tcontent = $viewport.getAttribute(\"content\");\n\t\tcontents = content.split(/\\s*,\\s*/);\n\t\tif(contents[0]){\n\t\t\twidth = contents[0].replace(\"width=\", '').trim();\n\t\t}\n\t\tif(contents[1]){\n\t\t\theight = contents[1].replace(\"height=\", '').trim();\n\t\t}\n\t\tif(contents[2]){\n\t\t\tscale = contents[2].replace(\"initial-scale=\", '').trim();\n\t\t}\n\t\tif(contents[3]){\n\t\t\tscalable = contents[3].replace(\"user-scalable=\", '').trim();\n\t\t}\n\t}\n\n\tif (options) {\n\n\t\tnewContent += \"width=\" + (options.width || width);\n\t\tnewContent += \", height=\" + (options.height || height);\n\t\tif (options.scale || scale) {\n\t\t\tnewContent += \", initial-scale=\" + (options.scale || scale);\n\t\t}\n\t\tif (options.scalable || scalable) {\n\t\t\tnewContent += \", user-scalable=\" + (options.scalable || scalable);\n\t\t}\n\n\t\tif (!$viewport) {\n\t\t\t$viewport = this.document.createElement(\"meta\");\n\t\t\t$viewport.setAttribute(\"name\", \"viewport\");\n\t\t\tthis.document.querySelector('head').appendChild($viewport);\n\t\t}\n\n\t\t$viewport.setAttribute(\"content\", newContent);\n\t}\n\n\n\treturn {\n\t\twidth: parseInt(width),\n\t\theight: parseInt(height)\n\t};\n};\n\n\n// Contents.prototype.layout = function(layoutFunc) {\n//\n// this.iframe.style.display = \"inline-block\";\n//\n// // Reset Body Styles\n// this.content.style.margin = \"0\";\n// //this.document.body.style.display = \"inline-block\";\n// //this.document.documentElement.style.width = \"auto\";\n//\n// if(layoutFunc){\n// layoutFunc(this);\n// }\n//\n// this.onLayout(this);\n//\n// };\n//\n// Contents.prototype.onLayout = function(view) {\n// // stub\n// };\n\nContents.prototype.expand = function() {\n\tthis.trigger(\"expand\");\n};\n\nContents.prototype.listeners = function() {\n\n\tthis.imageLoadListeners();\n\n\tthis.mediaQueryListeners();\n\n\t// this.fontLoadListeners();\n\n\tthis.addEventListeners();\n\n\tthis.addSelectionListeners();\n\n\tthis.resizeListeners();\n\n};\n\nContents.prototype.removeListeners = function() {\n\n\tthis.removeEventListeners();\n\n\tthis.removeSelectionListeners();\n};\n\nContents.prototype.resizeListeners = function() {\n\tvar width, height;\n\t// Test size again\n\tclearTimeout(this.expanding);\n\n\twidth = this.scrollWidth();\n\theight = this.scrollHeight();\n\n\tif (width != this._size.width || height != this._size.height) {\n\n\t\tthis._size = {\n\t\t\twidth: width,\n\t\t\theight: height\n\t\t}\n\n\t\tthis.trigger(\"resize\", this._size);\n\t}\n\n\tthis.expanding = setTimeout(this.resizeListeners.bind(this), 350);\n};\n\n//https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js\nContents.prototype.mediaQueryListeners = function() {\n\t\tvar sheets = this.document.styleSheets;\n\t\tvar mediaChangeHandler = function(m){\n\t\t\tif(m.matches && !this._expanding) {\n\t\t\t\tsetTimeout(this.expand.bind(this), 1);\n\t\t\t\t// this.expand();\n\t\t\t}\n\t\t}.bind(this);\n\n\t\tfor (var i = 0; i < sheets.length; i += 1) {\n\t\t\t\tvar rules = sheets[i].cssRules;\n\t\t\t\tif(!rules) return; // Stylesheets changed\n\t\t\t\tfor (var j = 0; j < rules.length; j += 1) {\n\t\t\t\t\t\t//if (rules[j].constructor === CSSMediaRule) {\n\t\t\t\t\t\tif(rules[j].media){\n\t\t\t\t\t\t\t\tvar mql = this.window.matchMedia(rules[j].media.mediaText);\n\t\t\t\t\t\t\t\tmql.addListener(mediaChangeHandler);\n\t\t\t\t\t\t\t\t//mql.onchange = mediaChangeHandler;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n};\n\nContents.prototype.observe = function(target) {\n\tvar renderer = this;\n\n\t// create an observer instance\n\tvar observer = new MutationObserver(function(mutations) {\n\t\tif(renderer._expanding) {\n\t\t\trenderer.expand();\n\t\t}\n\t\t// mutations.forEach(function(mutation) {\n\t\t// console.log(mutation);\n\t\t// });\n\t});\n\n\t// configuration of the observer:\n\tvar config = { attributes: true, childList: true, characterData: true, subtree: true };\n\n\t// pass in the target node, as well as the observer options\n\tobserver.observe(target, config);\n\n\treturn observer;\n};\n\nContents.prototype.imageLoadListeners = function(target) {\n\tvar images = this.document.querySelectorAll(\"img\");\n\tvar img;\n\tfor (var i = 0; i < images.length; i++) {\n\t\timg = images[i];\n\n\t\tif (typeof img.naturalWidth !== \"undefined\" &&\n\t\t\t\timg.naturalWidth === 0) {\n\t\t\timg.onload = this.expand.bind(this);\n\t\t}\n\t}\n};\n\nContents.prototype.fontLoadListeners = function(target) {\n\tif (!this.document || !this.document.fonts) {\n\t\treturn;\n\t}\n\n\tthis.document.fonts.ready.then(function () {\n\t\tthis.expand();\n\t}.bind(this));\n\n};\n\nContents.prototype.root = function() {\n\tif(!this.document) return null;\n\treturn this.document.documentElement;\n};\n\nContents.prototype.locationOf = function(target, ignoreClass) {\n\tvar position;\n\tvar targetPos = {\"left\": 0, \"top\": 0};\n\n\tif(!this.document) return;\n\n\tif(this.epubcfi.isCfiString(target)) {\n\t\trange = new EpubCFI(target).toRange(this.document, ignoreClass);\n\n\t\tif(range) {\n\t\t\tif (range.startContainer.nodeType === Node.ELEMENT_NODE) {\n\t\t\t\tposition = range.startContainer.getBoundingClientRect();\n\t\t\t\ttargetPos.left = position.left;\n\t\t\t\ttargetPos.top = position.top;\n\t\t\t} else {\n\t\t\t\tposition = range.getBoundingClientRect();\n\t\t\t\ttargetPos.left = position.left;\n\t\t\t\ttargetPos.top = position.top;\n\t\t\t}\n\t\t}\n\n\t} else if(typeof target === \"string\" &&\n\t\ttarget.indexOf(\"#\") > -1) {\n\n\t\tid = target.substring(target.indexOf(\"#\")+1);\n\t\tel = this.document.getElementById(id);\n\n\t\tif(el) {\n\t\t\tposition = el.getBoundingClientRect();\n\t\t\ttargetPos.left = position.left;\n\t\t\ttargetPos.top = position.top;\n\t\t}\n\t}\n\n\treturn targetPos;\n};\n\nContents.prototype.addStylesheet = function(src) {\n\treturn new RSVP.Promise(function(resolve, reject){\n\t\tvar $stylesheet;\n\t\tvar ready = false;\n\n\t\tif(!this.document) {\n\t\t\tresolve(false);\n\t\t\treturn;\n\t\t}\n\n\t\t$stylesheet = this.document.createElement('link');\n\t\t$stylesheet.type = 'text/css';\n\t\t$stylesheet.rel = \"stylesheet\";\n\t\t$stylesheet.href = src;\n\t\t$stylesheet.onload = $stylesheet.onreadystatechange = function() {\n\t\t\tif ( !ready && (!this.readyState || this.readyState == 'complete') ) {\n\t\t\t\tready = true;\n\t\t\t\t// Let apply\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tresolve(true);\n\t\t\t\t}, 1);\n\t\t\t}\n\t\t};\n\n\t\tthis.document.head.appendChild($stylesheet);\n\n\t}.bind(this));\n};\n\n// https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule\nContents.prototype.addStylesheetRules = function(rules) {\n\tvar styleEl;\n\tvar styleSheet;\n\n\tif(!this.document) return;\n\n\tstyleEl = this.document.createElement('style');\n\n\t// Append style element to head\n\tthis.document.head.appendChild(styleEl);\n\n\t// Grab style sheet\n\tstyleSheet = styleEl.sheet;\n\n\tfor (var i = 0, rl = rules.length; i < rl; i++) {\n\t\tvar j = 1, rule = rules[i], selector = rules[i][0], propStr = '';\n\t\t// If the second argument of a rule is an array of arrays, correct our variables.\n\t\tif (Object.prototype.toString.call(rule[1][0]) === '[object Array]') {\n\t\t\trule = rule[1];\n\t\t\tj = 0;\n\t\t}\n\n\t\tfor (var pl = rule.length; j < pl; j++) {\n\t\t\tvar prop = rule[j];\n\t\t\tpropStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\\n';\n\t\t}\n\n\t\t// Insert CSS Rule\n\t\tstyleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);\n\t}\n};\n\nContents.prototype.addScript = function(src) {\n\n\treturn new RSVP.Promise(function(resolve, reject){\n\t\tvar $script;\n\t\tvar ready = false;\n\n\t\tif(!this.document) {\n\t\t\tresolve(false);\n\t\t\treturn;\n\t\t}\n\n\t\t$script = this.document.createElement('script');\n\t\t$script.type = 'text/javascript';\n\t\t$script.async = true;\n\t\t$script.src = src;\n\t\t$script.onload = $script.onreadystatechange = function() {\n\t\t\tif ( !ready && (!this.readyState || this.readyState == 'complete') ) {\n\t\t\t\tready = true;\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tresolve(true);\n\t\t\t\t}, 1);\n\t\t\t}\n\t\t};\n\n\t\tthis.document.head.appendChild($script);\n\n\t}.bind(this));\n};\n\nContents.prototype.addEventListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.listenedEvents.forEach(function(eventName){\n\t\tthis.document.addEventListener(eventName, this.triggerEvent.bind(this), false);\n\t}, this);\n\n};\n\nContents.prototype.removeEventListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.listenedEvents.forEach(function(eventName){\n\t\tthis.document.removeEventListener(eventName, this.triggerEvent, false);\n\t}, this);\n\n};\n\n// Pass browser events\nContents.prototype.triggerEvent = function(e){\n\tthis.trigger(e.type, e);\n};\n\nContents.prototype.addSelectionListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.document.addEventListener(\"selectionchange\", this.onSelectionChange.bind(this), false);\n};\n\nContents.prototype.removeSelectionListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.document.removeEventListener(\"selectionchange\", this.onSelectionChange, false);\n};\n\nContents.prototype.onSelectionChange = function(e){\n\tif (this.selectionEndTimeout) {\n\t\tclearTimeout(this.selectionEndTimeout);\n\t}\n\tthis.selectionEndTimeout = setTimeout(function() {\n\t\tvar selection = this.window.getSelection();\n\t\tthis.triggerSelectedEvent(selection);\n\t}.bind(this), 500);\n};\n\nContents.prototype.triggerSelectedEvent = function(selection){\n\tvar range, cfirange;\n\n\tif (selection && selection.rangeCount > 0) {\n\t\trange = selection.getRangeAt(0);\n\t\tif(!range.collapsed) {\n\t\t\t// cfirange = this.section.cfiFromRange(range);\n\t\t\tcfirange = new EpubCFI(range, this.cfiBase).toString();\n\t\t\tthis.trigger(\"selected\", cfirange);\n\t\t\tthis.trigger(\"selectedRange\", range);\n\t\t}\n\t}\n};\n\nContents.prototype.range = function(_cfi, ignoreClass){\n\tvar cfi = new EpubCFI(_cfi);\n\treturn cfi.toRange(this.document, ignoreClass);\n};\n\nContents.prototype.map = function(layout){\n\tvar map = new Mapping(layout);\n\treturn map.section();\n};\n\nContents.prototype.size = function(width, height){\n\n\tif (width >= 0) {\n\t\tthis.width(width);\n\t}\n\n\tif (height >= 0) {\n\t\tthis.height(height);\n\t}\n\n\tthis.css(\"margin\", \"0\");\n\tthis.css(\"boxSizing\", \"border-box\");\n\n};\n\nContents.prototype.columns = function(width, height, columnWidth, gap){\n\tvar COLUMN_AXIS = core.prefixed('columnAxis');\n\tvar COLUMN_GAP = core.prefixed('columnGap');\n\tvar COLUMN_WIDTH = core.prefixed('columnWidth');\n\tvar COLUMN_FILL = core.prefixed('columnFill');\n\tvar textWidth;\n\n\tthis.width(width);\n\tthis.height(height);\n\n\t// Deal with Mobile trying to scale to viewport\n\tthis.viewport({ width: width, height: height, scale: 1.0 });\n\n\t// this.overflowY(\"hidden\");\n\tthis.css(\"overflowY\", \"hidden\");\n\tthis.css(\"margin\", \"0\");\n\tthis.css(\"boxSizing\", \"border-box\");\n\tthis.css(\"maxWidth\", \"inherit\");\n\n\tthis.css(COLUMN_AXIS, \"horizontal\");\n\tthis.css(COLUMN_FILL, \"auto\");\n\n\tthis.css(COLUMN_GAP, gap+\"px\");\n\tthis.css(COLUMN_WIDTH, columnWidth+\"px\");\n};\n\nContents.prototype.scale = function(scale, offsetX, offsetY){\n\tvar scale = \"scale(\" + scale + \")\";\n\tvar translate = '';\n\t// this.css(\"position\", \"absolute\"));\n\tthis.css(\"transformOrigin\", \"top left\");\n\n\tif (offsetX >= 0 || offsetY >= 0) {\n\t\ttranslate = \" translate(\" + (offsetX || 0 )+ \"px, \" + (offsetY || 0 )+ \"px )\";\n\t}\n\n\tthis.css(\"transform\", scale + translate);\n};\n\nContents.prototype.fit = function(width, height){\n\tvar viewport = this.viewport();\n\tvar widthScale = width / viewport.width;\n\tvar heightScale = height / viewport.height;\n\tvar scale = widthScale < heightScale ? widthScale : heightScale;\n\n\tvar offsetY = (height - (viewport.height * scale)) / 2;\n\n\tthis.width(width);\n\tthis.height(height);\n\tthis.overflow(\"hidden\");\n\n\t// Deal with Mobile trying to scale to viewport\n\tthis.viewport({ scale: 1.0 });\n\n\t// Scale to the correct size\n\tthis.scale(scale, 0, offsetY);\n\n\tthis.css(\"backgroundColor\", \"transparent\");\n};\n\nContents.prototype.mapPage = function(cfiBase, start, end) {\n\tvar mapping = new Mapping();\n\n\treturn mapping.page(this, cfiBase, start, end);\n};\n\nContents.prototype.destroy = function() {\n\t// Stop observing\n\tif(this.observer) {\n\t\tthis.observer.disconnect();\n\t}\n\n\tthis.removeListeners();\n\n};\n\nRSVP.EventTarget.mixin(Contents.prototype);\n\nmodule.exports = Contents;\n","var RSVP = require('rsvp');\nvar base64 = require('base64-js');\n\nvar requestAnimationFrame = (typeof window != 'undefined') ? (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame) : false;\n/*\n//-- Parse the different parts of a url, returning a object\nfunction uri(url){\n\tvar uri = {\n\t\t\t\tprotocol : '',\n\t\t\t\thost : '',\n\t\t\t\tpath : '',\n\t\t\t\torigin : '',\n\t\t\t\tdirectory : '',\n\t\t\t\tbase : '',\n\t\t\t\tfilename : '',\n\t\t\t\textension : '',\n\t\t\t\tfragment : '',\n\t\t\t\thref : url\n\t\t\t},\n\t\t\tdoubleSlash = url.indexOf('://'),\n\t\t\tsearch = url.indexOf('?'),\n\t\t\tfragment = url.indexOf(\"#\"),\n\t\t\twithoutProtocol,\n\t\t\tdot,\n\t\t\tfirstSlash;\n\n\tif(fragment != -1) {\n\t\turi.fragment = url.slice(fragment + 1);\n\t\turl = url.slice(0, fragment);\n\t}\n\n\tif(search != -1) {\n\t\turi.search = url.slice(search + 1);\n\t\turl = url.slice(0, search);\n\t\thref = url;\n\t}\n\n\tif(doubleSlash != -1) {\n\t\turi.protocol = url.slice(0, doubleSlash);\n\t\twithoutProtocol = url.slice(doubleSlash+3);\n\t\tfirstSlash = withoutProtocol.indexOf('/');\n\n\t\tif(firstSlash === -1) {\n\t\t\turi.host = uri.path;\n\t\t\turi.path = \"\";\n\t\t} else {\n\t\t\turi.host = withoutProtocol.slice(0, firstSlash);\n\t\t\turi.path = withoutProtocol.slice(firstSlash);\n\t\t}\n\n\n\t\turi.origin = uri.protocol + \"://\" + uri.host;\n\n\t\turi.directory = folder(uri.path);\n\n\t\turi.base = uri.origin + uri.directory;\n\t\t// return origin;\n\t} else {\n\t\turi.path = url;\n\t\turi.directory = folder(url);\n\t\turi.base = uri.directory;\n\t}\n\n\t//-- Filename\n\turi.filename = url.replace(uri.base, '');\n\tdot = uri.filename.lastIndexOf('.');\n\tif(dot != -1) {\n\t\turi.extension = uri.filename.slice(dot+1);\n\t}\n\treturn uri;\n};\n\n//-- Parse out the folder, will return everything before the last slash\nfunction folder(url){\n\n\tvar lastSlash = url.lastIndexOf('/');\n\n\tif(lastSlash == -1) var folder = '';\n\n\tfolder = url.slice(0, lastSlash + 1);\n\n\treturn folder;\n\n};\n*/\nfunction isElement(obj) {\n\t\treturn !!(obj && obj.nodeType == 1);\n};\n\n// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\nfunction uuid() {\n\tvar d = new Date().getTime();\n\tvar uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n\t\t\tvar r = (d + Math.random()*16)%16 | 0;\n\t\t\td = Math.floor(d/16);\n\t\t\treturn (c=='x' ? r : (r&0x7|0x8)).toString(16);\n\t});\n\treturn uuid;\n};\n\n// From Lodash\nfunction values(object) {\n\tvar index = -1,\n\t\t\tprops = Object.keys(object),\n\t\t\tlength = props.length,\n\t\t\tresult = Array(length);\n\n\twhile (++index < length) {\n\t\tresult[index] = object[props[index]];\n\t}\n\treturn result;\n};\n\nfunction resolveUrl(base, path) {\n\tvar url = [],\n\t\tsegments = [],\n\t\tbaseUri = uri(base),\n\t\tpathUri = uri(path),\n\t\tbaseDirectory = baseUri.directory,\n\t\tpathDirectory = pathUri.directory,\n\t\tdirectories = [],\n\t\t// folders = base.split(\"/\"),\n\t\tpaths;\n\n\t// if(uri.host) {\n\t// return path;\n\t// }\n\n\tif(baseDirectory[0] === \"/\") {\n\t\tbaseDirectory = baseDirectory.substring(1);\n\t}\n\n\tif(pathDirectory[pathDirectory.length-1] === \"/\") {\n\t\tbaseDirectory = baseDirectory.substring(0, baseDirectory.length-1);\n\t}\n\n\tif(pathDirectory[0] === \"/\") {\n\t\tpathDirectory = pathDirectory.substring(1);\n\t}\n\n\tif(pathDirectory[pathDirectory.length-1] === \"/\") {\n\t\tpathDirectory = pathDirectory.substring(0, pathDirectory.length-1);\n\t}\n\n\tif(baseDirectory) {\n\t\tdirectories = baseDirectory.split(\"/\");\n\t}\n\n\tpaths = pathDirectory.split(\"/\");\n\n\tpaths.reverse().forEach(function(part, index){\n\t\tif(part === \"..\"){\n\t\t\tdirectories.pop();\n\t\t} else if(part === directories[directories.length-1]) {\n\t\t\tdirectories.pop();\n\t\t\tsegments.unshift(part);\n\t\t} else {\n\t\t\tsegments.unshift(part);\n\t\t}\n\t});\n\n\turl = [baseUri.origin];\n\n\tif(directories.length) {\n\t\turl = url.concat(directories);\n\t}\n\n\tif(segments) {\n\t\turl = url.concat(segments);\n\t}\n\n\turl = url.concat(pathUri.filename);\n\n\treturn url.join(\"/\");\n};\n\nfunction documentHeight() {\n\treturn Math.max(\n\t\t\tdocument.documentElement.clientHeight,\n\t\t\tdocument.body.scrollHeight,\n\t\t\tdocument.documentElement.scrollHeight,\n\t\t\tdocument.body.offsetHeight,\n\t\t\tdocument.documentElement.offsetHeight\n\t);\n};\n\nfunction isNumber(n) {\n\treturn !isNaN(parseFloat(n)) && isFinite(n);\n};\n\nfunction prefixed(unprefixed) {\n\tvar vendors = [\"Webkit\", \"Moz\", \"O\", \"ms\" ],\n\t\tprefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'],\n\t\tupper = unprefixed[0].toUpperCase() + unprefixed.slice(1),\n\t\tlength = vendors.length;\n\n\tif (typeof(document) === 'undefined' || typeof(document.body.style[unprefixed]) != 'undefined') {\n\t\treturn unprefixed;\n\t}\n\n\tfor ( var i=0; i < length; i++ ) {\n\t\tif (typeof(document.body.style[vendors[i] + upper]) != 'undefined') {\n\t\t\treturn vendors[i] + upper;\n\t\t}\n\t}\n\n\treturn unprefixed;\n};\n\nfunction defaults(obj) {\n\tfor (var i = 1, length = arguments.length; i < length; i++) {\n\t\tvar source = arguments[i];\n\t\tfor (var prop in source) {\n\t\t\tif (obj[prop] === void 0) obj[prop] = source[prop];\n\t\t}\n\t}\n\treturn obj;\n};\n\nfunction extend(target) {\n\t\tvar sources = [].slice.call(arguments, 1);\n\t\tsources.forEach(function (source) {\n\t\t\tif(!source) return;\n\t\t\tObject.getOwnPropertyNames(source).forEach(function(propName) {\n\t\t\t\tObject.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName));\n\t\t\t});\n\t\t});\n\t\treturn target;\n};\n\n// Fast quicksort insert for sorted array -- based on:\n// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers\nfunction insert(item, array, compareFunction) {\n\tvar location = locationOf(item, array, compareFunction);\n\tarray.splice(location, 0, item);\n\n\treturn location;\n};\n// Returns where something would fit in\nfunction locationOf(item, array, compareFunction, _start, _end) {\n\tvar start = _start || 0;\n\tvar end = _end || array.length;\n\tvar pivot = parseInt(start + (end - start) / 2);\n\tvar compared;\n\tif(!compareFunction){\n\t\tcompareFunction = function(a, b) {\n\t\t\tif(a > b) return 1;\n\t\t\tif(a < b) return -1;\n\t\t\tif(a = b) return 0;\n\t\t};\n\t}\n\tif(end-start <= 0) {\n\t\treturn pivot;\n\t}\n\n\tcompared = compareFunction(array[pivot], item);\n\tif(end-start === 1) {\n\t\treturn compared > 0 ? pivot : pivot + 1;\n\t}\n\n\tif(compared === 0) {\n\t\treturn pivot;\n\t}\n\tif(compared === -1) {\n\t\treturn locationOf(item, array, compareFunction, pivot, end);\n\t} else{\n\t\treturn locationOf(item, array, compareFunction, start, pivot);\n\t}\n};\n// Returns -1 of mpt found\nfunction indexOfSorted(item, array, compareFunction, _start, _end) {\n\tvar start = _start || 0;\n\tvar end = _end || array.length;\n\tvar pivot = parseInt(start + (end - start) / 2);\n\tvar compared;\n\tif(!compareFunction){\n\t\tcompareFunction = function(a, b) {\n\t\t\tif(a > b) return 1;\n\t\t\tif(a < b) return -1;\n\t\t\tif(a = b) return 0;\n\t\t};\n\t}\n\tif(end-start <= 0) {\n\t\treturn -1; // Not found\n\t}\n\n\tcompared = compareFunction(array[pivot], item);\n\tif(end-start === 1) {\n\t\treturn compared === 0 ? pivot : -1;\n\t}\n\tif(compared === 0) {\n\t\treturn pivot; // Found\n\t}\n\tif(compared === -1) {\n\t\treturn indexOfSorted(item, array, compareFunction, pivot, end);\n\t} else{\n\t\treturn indexOfSorted(item, array, compareFunction, start, pivot);\n\t}\n};\n\nfunction bounds(el) {\n\n\tvar style = window.getComputedStyle(el);\n\tvar widthProps = [\"width\", \"paddingRight\", \"paddingLeft\", \"marginRight\", \"marginLeft\", \"borderRightWidth\", \"borderLeftWidth\"];\n\tvar heightProps = [\"height\", \"paddingTop\", \"paddingBottom\", \"marginTop\", \"marginBottom\", \"borderTopWidth\", \"borderBottomWidth\"];\n\n\tvar width = 0;\n\tvar height = 0;\n\n\twidthProps.forEach(function(prop){\n\t\twidth += parseFloat(style[prop]) || 0;\n\t});\n\n\theightProps.forEach(function(prop){\n\t\theight += parseFloat(style[prop]) || 0;\n\t});\n\n\treturn {\n\t\theight: height,\n\t\twidth: width\n\t};\n\n};\n\nfunction borders(el) {\n\n\tvar style = window.getComputedStyle(el);\n\tvar widthProps = [\"paddingRight\", \"paddingLeft\", \"marginRight\", \"marginLeft\", \"borderRightWidth\", \"borderLeftWidth\"];\n\tvar heightProps = [\"paddingTop\", \"paddingBottom\", \"marginTop\", \"marginBottom\", \"borderTopWidth\", \"borderBottomWidth\"];\n\n\tvar width = 0;\n\tvar height = 0;\n\n\twidthProps.forEach(function(prop){\n\t\twidth += parseFloat(style[prop]) || 0;\n\t});\n\n\theightProps.forEach(function(prop){\n\t\theight += parseFloat(style[prop]) || 0;\n\t});\n\n\treturn {\n\t\theight: height,\n\t\twidth: width\n\t};\n\n};\n\nfunction windowBounds() {\n\n\tvar width = window.innerWidth;\n\tvar height = window.innerHeight;\n\n\treturn {\n\t\ttop: 0,\n\t\tleft: 0,\n\t\tright: width,\n\t\tbottom: height,\n\t\twidth: width,\n\t\theight: height\n\t};\n\n};\n\n//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496\nfunction cleanStringForXpath(str) {\n\t\tvar parts = str.match(/[^'\"]+|['\"]/g);\n\t\tparts = parts.map(function(part){\n\t\t\t\tif (part === \"'\") {\n\t\t\t\t\t\treturn '\\\"\\'\\\"'; // output \"'\"\n\t\t\t\t}\n\n\t\t\t\tif (part === '\"') {\n\t\t\t\t\t\treturn \"\\'\\\"\\'\"; // output '\"'\n\t\t\t\t}\n\t\t\t\treturn \"\\'\" + part + \"\\'\";\n\t\t});\n\t\treturn \"concat(\\'\\',\" + parts.join(\",\") + \")\";\n};\n\nfunction indexOfTextNode(textNode){\n\tvar parent = textNode.parentNode;\n\tvar children = parent.childNodes;\n\tvar sib;\n\tvar index = -1;\n\tfor (var i = 0; i < children.length; i++) {\n\t\tsib = children[i];\n\t\tif(sib.nodeType === Node.TEXT_NODE){\n\t\t\tindex++;\n\t\t}\n\t\tif(sib == textNode) break;\n\t}\n\n\treturn index;\n};\n\nfunction isXml(ext) {\n\treturn ['xml', 'opf', 'ncx'].indexOf(ext) > -1;\n}\n\nfunction createBlob(content, mime){\n\tvar blob = new Blob([content], {type : mime });\n\n\treturn blob;\n};\n\nfunction createBlobUrl(content, mime){\n\tvar _URL = window.URL || window.webkitURL || window.mozURL;\n\tvar tempUrl;\n\tvar blob = this.createBlob(content, mime);\n\n\ttempUrl = _URL.createObjectURL(blob);\n\n\treturn tempUrl;\n};\n\nfunction createBase64Url(content, mime){\n\tvar string;\n\tvar data;\n\tvar datauri;\n\n\tif (typeof(content) !== \"string\") {\n\t\t// Only handles strings\n\t\treturn;\n\t}\n\n\tdata = btoa(content);\n\n\tdatauri = \"data:\" + mime + \";base64,\" + data;\n\n\treturn datauri;\n};\n\nfunction type(obj){\n\treturn Object.prototype.toString.call(obj).slice(8, -1);\n}\n\nfunction parse(markup, mime) {\n\tvar doc;\n\t// console.log(\"parse\", markup);\n\n\tif (typeof DOMParser === \"undefined\") {\n\t\tDOMParser = require('xmldom').DOMParser;\n\t}\n\n\n\tdoc = new DOMParser().parseFromString(markup, mime);\n\n\treturn doc;\n}\n\nfunction qs(el, sel) {\n\tvar elements;\n\n\tif (typeof el.querySelector != \"undefined\") {\n\t\treturn el.querySelector(sel);\n\t} else {\n\t\telements = el.getElementsByTagName(sel);\n\t\tif (elements.length) {\n\t\t\treturn elements[0];\n\t\t}\n\t}\n}\n\nfunction qsa(el, sel) {\n\n\tif (typeof el.querySelector != \"undefined\") {\n\t\treturn el.querySelectorAll(sel);\n\t} else {\n\t\treturn el.getElementsByTagName(sel);\n\t}\n}\n\nfunction qsp(el, sel, props) {\n\tvar q, filtered;\n\tif (typeof el.querySelector != \"undefined\") {\n\t\tsel += '[';\n\t\tfor (var prop in props) {\n\t\t\tsel += prop + \"='\" + props[prop] + \"'\";\n\t\t}\n\t\tsel += ']';\n\t\treturn el.querySelector(sel);\n\t} else {\n\t\tq = el.getElementsByTagName(sel);\n\t\tfiltered = Array.prototype.slice.call(q, 0).filter(function(el) {\n\t\t\tfor (var prop in props) {\n\t\t\t\tif(el.getAttribute(prop) === props[prop]){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\n\t\tif (filtered) {\n\t\t\treturn filtered[0];\n\t\t}\n\t}\n}\n\nfunction blob2base64(blob, cb) {\n\tvar reader = new FileReader();\n\treader.readAsDataURL(blob);\n\treader.onloadend = function() {\n\t\tcb(reader.result);\n\t}\n}\n\nmodule.exports = {\n\t// 'uri': uri,\n\t// 'folder': folder,\n\t'isElement': isElement,\n\t'uuid': uuid,\n\t'values': values,\n\t'resolveUrl': resolveUrl,\n\t'indexOfSorted': indexOfSorted,\n\t'documentHeight': documentHeight,\n\t'isNumber': isNumber,\n\t'prefixed': prefixed,\n\t'defaults': defaults,\n\t'extend': extend,\n\t'insert': insert,\n\t'locationOf': locationOf,\n\t'indexOfSorted': indexOfSorted,\n\t'requestAnimationFrame': requestAnimationFrame,\n\t'bounds': bounds,\n\t'borders': borders,\n\t'windowBounds': windowBounds,\n\t'cleanStringForXpath': cleanStringForXpath,\n\t'indexOfTextNode': indexOfTextNode,\n\t'isXml': isXml,\n\t'createBlob': createBlob,\n\t'createBlobUrl': createBlobUrl,\n\t'type': type,\n\t'parse' : parse,\n\t'qs' : qs,\n\t'qsa' : qsa,\n\t'qsp' : qsp,\n\t'blob2base64' : blob2base64,\n\t'createBase64Url': createBase64Url\n};\n","var URI = require('urijs');\nvar core = require('./core');\n\n/**\n\tEPUB CFI spec: http://www.idpf.org/epub/linking/cfi/epub-cfi.html\n\n\tImplements:\n\t- Character Offset: epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3)\n\t- Simple Ranges : epubcfi(/6/4[chap01ref]!/4[body01]/10[para05],/2/1:1,/3:4)\n\n\tDoes Not Implement:\n\t- Temporal Offset (~)\n\t- Spatial Offset (@)\n\t- Temporal-Spatial Offset (~ + @)\n\t- Text Location Assertion ([)\n*/\n\nfunction EpubCFI(cfiFrom, base, ignoreClass){\n\tvar type;\n\n\tthis.str = '';\n\n\tthis.base = {};\n\tthis.spinePos = 0; // For compatibility\n\n\tthis.range = false; // true || false;\n\n\tthis.path = {};\n\tthis.start = null;\n\tthis.end = null;\n\n\t// Allow instantiation without the 'new' keyword\n\tif (!(this instanceof EpubCFI)) {\n\t\treturn new EpubCFI(cfiFrom, base, ignoreClass);\n\t}\n\n\tif(typeof base === 'string') {\n\t\tthis.base = this.parseComponent(base);\n\t} else if(typeof base === 'object' && base.steps) {\n\t\tthis.base = base;\n\t}\n\n\ttype = this.checkType(cfiFrom);\n\n\n\tif(type === 'string') {\n\t\tthis.str = cfiFrom;\n\t\treturn core.extend(this, this.parse(cfiFrom));\n\t} else if (type === 'range') {\n\t\treturn core.extend(this, this.fromRange(cfiFrom, this.base, ignoreClass));\n\t} else if (type === 'node') {\n\t\treturn core.extend(this, this.fromNode(cfiFrom, this.base, ignoreClass));\n\t} else if (type === 'EpubCFI' && cfiFrom.path) {\n\t\treturn cfiFrom;\n\t} else if (!cfiFrom) {\n\t\treturn this;\n\t} else {\n\t\tthrow new TypeError('not a valid argument for EpubCFI');\n\t}\n\n};\n\nEpubCFI.prototype.checkType = function(cfi) {\n\n\tif (this.isCfiString(cfi)) {\n\t\treturn 'string';\n\t// Is a range object\n\t} else if (typeof cfi === 'object' && core.type(cfi) === \"Range\"){\n\t\treturn 'range';\n\t} else if (typeof cfi === 'object' && typeof(cfi.nodeType) != \"undefined\" ){ // || typeof cfi === 'function'\n\t\treturn 'node';\n\t} else if (typeof cfi === 'object' && cfi instanceof EpubCFI){\n\t\treturn 'EpubCFI';\n\t} else {\n\t\treturn false;\n\t}\n};\n\nEpubCFI.prototype.parse = function(cfiStr) {\n\tvar cfi = {\n\t\t\tspinePos: -1,\n\t\t\trange: false,\n\t\t\tbase: {},\n\t\t\tpath: {},\n\t\t\tstart: null,\n\t\t\tend: null\n\t\t};\n\tvar baseComponent, pathComponent, range;\n\n\tif(typeof cfiStr !== \"string\") {\n\t\treturn {spinePos: -1};\n\t}\n\n\tif(cfiStr.indexOf(\"epubcfi(\") === 0 && cfiStr[cfiStr.length-1] === \")\") {\n\t\t// Remove intial epubcfi( and ending )\n\t\tcfiStr = cfiStr.slice(8, cfiStr.length-1);\n\t}\n\n\tbaseComponent = this.getChapterComponent(cfiStr);\n\n\t// Make sure this is a valid cfi or return\n\tif(!baseComponent) {\n\t\treturn {spinePos: -1};\n\t}\n\n\tcfi.base = this.parseComponent(baseComponent);\n\n\tpathComponent = this.getPathComponent(cfiStr);\n\tcfi.path = this.parseComponent(pathComponent);\n\n\trange = this.getRange(cfiStr);\n\n\tif(range) {\n\t\tcfi.range = true;\n\t\tcfi.start = this.parseComponent(range[0]);\n\t\tcfi.end = this.parseComponent(range[1]);\n\t}\n\n\t// Get spine node position\n\t// cfi.spineSegment = cfi.base.steps[1];\n\n\t// Chapter segment is always the second step\n\tcfi.spinePos = cfi.base.steps[1].index;\n\n\treturn cfi;\n};\n\nEpubCFI.prototype.parseComponent = function(componentStr){\n\tvar component = {\n\t\tsteps: [],\n\t\tterminal: {\n\t\t\toffset: null,\n\t\t\tassertion: null\n\t\t}\n\t};\n\tvar parts = componentStr.split(':');\n\tvar steps = parts[0].split('/');\n\tvar terminal;\n\n\tif(parts.length > 1) {\n\t\tterminal = parts[1];\n\t\tcomponent.terminal = this.parseTerminal(terminal);\n\t}\n\n\tif (steps[0] === '') {\n\t\tsteps.shift(); // Ignore the first slash\n\t}\n\n\tcomponent.steps = steps.map(function(step){\n\t\treturn this.parseStep(step);\n\t}.bind(this));\n\n\treturn component;\n};\n\nEpubCFI.prototype.parseStep = function(stepStr){\n\tvar type, num, index, has_brackets, id;\n\n\thas_brackets = stepStr.match(/\\[(.*)\\]/);\n\tif(has_brackets && has_brackets[1]){\n\t\tid = has_brackets[1];\n\t}\n\n\t//-- Check if step is a text node or element\n\tnum = parseInt(stepStr);\n\n\tif(isNaN(num)) {\n\t\treturn;\n\t}\n\n\tif(num % 2 === 0) { // Even = is an element\n\t\ttype = \"element\";\n\t\tindex = num / 2 - 1;\n\t} else {\n\t\ttype = \"text\";\n\t\tindex = (num - 1 ) / 2;\n\t}\n\n\treturn {\n\t\t\"type\" : type,\n\t\t'index' : index,\n\t\t'id' : id || null\n\t};\n};\n\nEpubCFI.prototype.parseTerminal = function(termialStr){\n\tvar characterOffset, textLocationAssertion;\n\tvar assertion = termialStr.match(/\\[(.*)\\]/);\n\n\tif(assertion && assertion[1]){\n\t\tcharacterOffset = parseInt(termialStr.split('[')[0]) || null;\n\t\ttextLocationAssertion = assertion[1];\n\t} else {\n\t\tcharacterOffset = parseInt(termialStr) || null;\n\t}\n\n\treturn {\n\t\t'offset': characterOffset,\n\t\t'assertion': textLocationAssertion\n\t};\n\n};\n\nEpubCFI.prototype.getChapterComponent = function(cfiStr) {\n\n\tvar indirection = cfiStr.split(\"!\");\n\n\treturn indirection[0];\n};\n\nEpubCFI.prototype.getPathComponent = function(cfiStr) {\n\n\tvar indirection = cfiStr.split(\"!\");\n\n\tif(indirection[1]) {\n\t\tranges = indirection[1].split(',');\n\t\treturn ranges[0];\n\t}\n\n};\n\nEpubCFI.prototype.getRange = function(cfiStr) {\n\n\tvar ranges = cfiStr.split(\",\");\n\n\tif(ranges.length === 3){\n\t\treturn [\n\t\t\tranges[1],\n\t\t\tranges[2]\n\t\t];\n\t}\n\n\treturn false;\n};\n\nEpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) {\n\tvar splitStr = cfiStr.split(\":\");\n\treturn splitStr[1] || '';\n};\n\nEpubCFI.prototype.joinSteps = function(steps) {\n\tif(!steps) {\n\t\treturn \"\";\n\t}\n\n\treturn steps.map(function(part){\n\t\tvar segment = '';\n\n\t\tif(part.type === 'element') {\n\t\t\tsegment += (part.index + 1) * 2;\n\t\t}\n\n\t\tif(part.type === 'text') {\n\t\t\tsegment += 1 + (2 * part.index); // TODO: double check that this is odd\n\t\t}\n\n\t\tif(part.id) {\n\t\t\tsegment += \"[\" + part.id + \"]\";\n\t\t}\n\n\t\treturn segment;\n\n\t}).join('/');\n\n};\n\nEpubCFI.prototype.segmentString = function(segment) {\n\tvar segmentString = '/';\n\n\tsegmentString += this.joinSteps(segment.steps);\n\n\tif(segment.terminal && segment.terminal.offset != null){\n\t\tsegmentString += ':' + segment.terminal.offset;\n\t}\n\n\tif(segment.terminal && segment.terminal.assertion != null){\n\t\tsegmentString += '[' + segment.terminal.assertion + ']';\n\t}\n\n\treturn segmentString;\n};\n\nEpubCFI.prototype.toString = function() {\n\tvar cfiString = 'epubcfi(';\n\n\tcfiString += this.segmentString(this.base);\n\n\tcfiString += '!';\n\tcfiString += this.segmentString(this.path);\n\n\t// Add Range, if present\n\tif(this.start) {\n\t\tcfiString += ',';\n\t\tcfiString += this.segmentString(this.start);\n\t}\n\n\tif(this.end) {\n\t\tcfiString += ',';\n\t\tcfiString += this.segmentString(this.end);\n\t}\n\n\tcfiString += \")\";\n\n\treturn cfiString;\n};\n\nEpubCFI.prototype.compare = function(cfiOne, cfiTwo) {\n\tif(typeof cfiOne === 'string') {\n\t\tcfiOne = new EpubCFI(cfiOne);\n\t}\n\tif(typeof cfiTwo === 'string') {\n\t\tcfiTwo = new EpubCFI(cfiTwo);\n\t}\n\t// Compare Spine Positions\n\tif(cfiOne.spinePos > cfiTwo.spinePos) {\n\t\treturn 1;\n\t}\n\tif(cfiOne.spinePos < cfiTwo.spinePos) {\n\t\treturn -1;\n\t}\n\n\n\t// Compare Each Step in the First item\n\tfor (var i = 0; i < cfiOne.path.steps.length; i++) {\n\t\tif(!cfiTwo.path.steps[i]) {\n\t\t\treturn 1;\n\t\t}\n\t\tif(cfiOne.path.steps[i].index > cfiTwo.path.steps[i].index) {\n\t\t\treturn 1;\n\t\t}\n\t\tif(cfiOne.path.steps[i].index < cfiTwo.path.steps[i].index) {\n\t\t\treturn -1;\n\t\t}\n\t\t// Otherwise continue checking\n\t}\n\n\t// All steps in First equal to Second and First is Less Specific\n\tif(cfiOne.path.steps.length < cfiTwo.path.steps.length) {\n\t\treturn 1;\n\t}\n\n\t// Compare the charecter offset of the text node\n\tif(cfiOne.path.terminal.offset > cfiTwo.path.terminal.offset) {\n\t\treturn 1;\n\t}\n\tif(cfiOne.path.terminal.offset < cfiTwo.path.terminal.offset) {\n\t\treturn -1;\n\t}\n\n\t// TODO: compare ranges\n\n\t// CFI's are equal\n\treturn 0;\n};\n\nEpubCFI.prototype.step = function(node) {\n\tvar nodeType = (node.nodeType === Node.TEXT_NODE) ? 'text' : 'element';\n\n\treturn {\n\t\t'id' : node.id,\n\t\t'tagName' : node.tagName,\n\t\t'type' : nodeType,\n\t\t'index' : this.position(node)\n\t};\n};\n\nEpubCFI.prototype.filteredStep = function(node, ignoreClass) {\n\tvar filteredNode = this.filter(node, ignoreClass);\n\tvar nodeType;\n\n\t// Node filtered, so ignore\n\tif (!filteredNode) {\n\t\treturn;\n\t}\n\n\t// Otherwise add the filter node in\n\tnodeType = (filteredNode.nodeType === Node.TEXT_NODE) ? 'text' : 'element';\n\n\treturn {\n\t\t'id' : filteredNode.id,\n\t\t'tagName' : filteredNode.tagName,\n\t\t'type' : nodeType,\n\t\t'index' : this.filteredPosition(filteredNode, ignoreClass)\n\t};\n};\n\nEpubCFI.prototype.pathTo = function(node, offset, ignoreClass) {\n\tvar segment = {\n\t\tsteps: [],\n\t\tterminal: {\n\t\t\toffset: null,\n\t\t\tassertion: null\n\t\t}\n\t};\n\tvar currentNode = node;\n\tvar step;\n\n\twhile(currentNode && currentNode.parentNode &&\n\t\t\t\tcurrentNode.parentNode.nodeType != Node.DOCUMENT_NODE) {\n\n\t\tif (ignoreClass) {\n\t\t\tstep = this.filteredStep(currentNode, ignoreClass);\n\t\t} else {\n\t\t\tstep = this.step(currentNode);\n\t\t}\n\n\t\tif (step) {\n\t\t\tsegment.steps.unshift(step);\n\t\t}\n\n\t\tcurrentNode = currentNode.parentNode;\n\n\t}\n\n\tif (offset != null && offset >= 0) {\n\n\t\tsegment.terminal.offset = offset;\n\n\t\t// Make sure we are getting to a textNode if there is an offset\n\t\tif(segment.steps[segment.steps.length-1].type != \"text\") {\n\t\t\tsegment.steps.push({\n\t\t\t\t'type' : \"text\",\n\t\t\t\t'index' : 0\n\t\t\t});\n\t\t}\n\n\t}\n\n\n\treturn segment;\n}\n\nEpubCFI.prototype.equalStep = function(stepA, stepB) {\n\tif (!stepA || !stepB) {\n\t\treturn false;\n\t}\n\n\tif(stepA.index === stepB.index &&\n\t\t stepA.id === stepB.id &&\n\t\t stepA.type === stepB.type) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\nEpubCFI.prototype.fromRange = function(range, base, ignoreClass) {\n\tvar cfi = {\n\t\t\trange: false,\n\t\t\tbase: {},\n\t\t\tpath: {},\n\t\t\tstart: null,\n\t\t\tend: null\n\t\t};\n\n\tvar start = range.startContainer;\n\tvar end = range.endContainer;\n\n\tvar startOffset = range.startOffset;\n\tvar endOffset = range.endOffset;\n\n\tvar needsIgnoring = false;\n\n\tif (ignoreClass) {\n\t\t// Tell pathTo if / what to ignore\n\t\tneedsIgnoring = (start.ownerDocument.querySelector('.' + ignoreClass) != null);\n\t}\n\n\n\tif (typeof base === 'string') {\n\t\tcfi.base = this.parseComponent(base);\n\t\tcfi.spinePos = cfi.base.steps[1].index;\n\t} else if (typeof base === 'object') {\n\t\tcfi.base = base;\n\t}\n\n\tif (range.collapsed) {\n\t\tif (needsIgnoring) {\n\t\t\tstartOffset = this.patchOffset(start, startOffset, ignoreClass);\n\t\t}\n\t\tcfi.path = this.pathTo(start, startOffset, ignoreClass);\n\t} else {\n\t\tcfi.range = true;\n\n\t\tif (needsIgnoring) {\n\t\t\tstartOffset = this.patchOffset(start, startOffset, ignoreClass);\n\t\t}\n\n\t\tcfi.start = this.pathTo(start, startOffset, ignoreClass);\n\n\t\tif (needsIgnoring) {\n\t\t\tendOffset = this.patchOffset(end, endOffset, ignoreClass);\n\t\t}\n\n\t\tcfi.end = this.pathTo(end, endOffset, ignoreClass);\n\n\t\t// Create a new empty path\n\t\tcfi.path = {\n\t\t\tsteps: [],\n\t\t\tterminal: null\n\t\t};\n\n\t\t// Push steps that are shared between start and end to the common path\n\t\tvar len = cfi.start.steps.length;\n\t\tvar i;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (this.equalStep(cfi.start.steps[i], cfi.end.steps[i])) {\n\t\t\t\tif(i == len-1) {\n\t\t\t\t\t// Last step is equal, check terminals\n\t\t\t\t\tif(cfi.start.terminal === cfi.end.terminal) {\n\t\t\t\t\t\t// CFI's are equal\n\t\t\t\t\t\tcfi.path.steps.push(cfi.start.steps[i]);\n\t\t\t\t\t\t// Not a range\n\t\t\t\t\t\tcfi.range = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcfi.path.steps.push(cfi.start.steps[i]);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t};\n\n\t\tcfi.start.steps = cfi.start.steps.slice(cfi.path.steps.length);\n\t\tcfi.end.steps = cfi.end.steps.slice(cfi.path.steps.length);\n\n\t\t// TODO: Add Sanity check to make sure that the end if greater than the start\n\t}\n\n\treturn cfi;\n}\n\nEpubCFI.prototype.fromNode = function(anchor, base, ignoreClass) {\n\tvar cfi = {\n\t\t\trange: false,\n\t\t\tbase: {},\n\t\t\tpath: {},\n\t\t\tstart: null,\n\t\t\tend: null\n\t\t};\n\n\tvar needsIgnoring = false;\n\n\tif (ignoreClass) {\n\t\t// Tell pathTo if / what to ignore\n\t\tneedsIgnoring = (anchor.ownerDocument.querySelector('.' + ignoreClass) != null);\n\t}\n\n\tif (typeof base === 'string') {\n\t\tcfi.base = this.parseComponent(base);\n\t\tcfi.spinePos = cfi.base.steps[1].index;\n\t} else if (typeof base === 'object') {\n\t\tcfi.base = base;\n\t}\n\n\tcfi.path = this.pathTo(anchor, null, ignoreClass);\n\n\treturn cfi;\n};\n\n\nEpubCFI.prototype.filter = function(anchor, ignoreClass) {\n\tvar needsIgnoring;\n\tvar sibling; // to join with\n\tvar parent, prevSibling, nextSibling;\n\tvar isText = false;\n\n\tif (anchor.nodeType === Node.TEXT_NODE) {\n\t\tisText = true;\n\t\tparent = anchor.parentNode;\n\t\tneedsIgnoring = anchor.parentNode.classList.contains(ignoreClass);\n\t} else {\n\t\tisText = false;\n\t\tneedsIgnoring = anchor.classList.contains(ignoreClass);\n\t}\n\n\tif (needsIgnoring && isText) {\n\t\tpreviousSibling = parent.previousSibling;\n\t\tnextSibling = parent.nextSibling;\n\n\t\t// If the sibling is a text node, join the nodes\n\t\tif (previousSibling && previousSibling.nodeType === Node.TEXT_NODE) {\n\t\t\tsibling = previousSibling;\n\t\t} else if (nextSibling && nextSibling.nodeType === Node.TEXT_NODE) {\n\t\t\tsibling = nextSibling;\n\t\t}\n\n\t\tif (sibling) {\n\t\t\treturn sibling;\n\t\t} else {\n\t\t\t// Parent will be ignored on next step\n\t\t\treturn anchor;\n\t\t}\n\n\t} else if (needsIgnoring && !isText) {\n\t\t// Otherwise just skip the element node\n\t\treturn false;\n\t} else {\n\t\t// No need to filter\n\t\treturn anchor;\n\t}\n\n};\n\nEpubCFI.prototype.patchOffset = function(anchor, offset, ignoreClass) {\n\tvar needsIgnoring;\n\tvar sibling;\n\n\tif (anchor.nodeType != Node.TEXT_NODE) {\n\t\tconsole.error(\"Anchor must be a text node\");\n\t\treturn;\n\t}\n\n\tvar curr = anchor;\n\tvar totalOffset = offset;\n\n\t// If the parent is a ignored node, get offset from it's start\n\tif (anchor.parentNode.classList.contains(ignoreClass)) {\n\t\tcurr = anchor.parentNode;\n\t}\n\n\twhile (curr.previousSibling) {\n\t\tif(curr.previousSibling.nodeType === Node.ELEMENT_NODE) {\n\t\t\t// Originally a text node, so join\n\t\t\tif(curr.previousSibling.classList.contains(ignoreClass)){\n\t\t\t\ttotalOffset += curr.previousSibling.textContent.length;\n\t\t\t} else {\n\t\t\t\tbreak; // Normal node, dont join\n\t\t\t}\n\t\t} else {\n\t\t\t// If the previous sibling is a text node, join the nodes\n\t\t\ttotalOffset += curr.previousSibling.textContent.length;\n\t\t}\n\n\t\tcurr = curr.previousSibling;\n\t}\n\n\treturn totalOffset;\n\n};\n\nEpubCFI.prototype.normalizedMap = function(children, nodeType, ignoreClass) {\n\tvar output = {};\n\tvar prevIndex = -1;\n\tvar i, len = children.length;\n\tvar currNodeType;\n\tvar prevNodeType;\n\n\tfor (i = 0; i < len; i++) {\n\n\t\tcurrNodeType = children[i].nodeType;\n\n\t\t// Check if needs ignoring\n\t\tif (currNodeType === Node.ELEMENT_NODE &&\n\t\t\t\tchildren[i].classList.contains(ignoreClass)) {\n\t\t\tcurrNodeType = Node.TEXT_NODE;\n\t\t}\n\n\t\tif (i > 0 &&\n\t\t\t\tcurrNodeType === Node.TEXT_NODE &&\n\t\t\t\tprevNodeType === Node.TEXT_NODE) {\n\t\t\t// join text nodes\n\t\t\toutput[i] = prevIndex;\n\t\t} else if (nodeType === currNodeType){\n\t\t\tprevIndex = prevIndex + 1;\n\t\t\toutput[i] = prevIndex;\n\t\t}\n\n\t\tprevNodeType = currNodeType;\n\n\t}\n\n\treturn output;\n};\n\nEpubCFI.prototype.position = function(anchor) {\n\tvar children, index, map;\n\n\tif (anchor.nodeType === Node.ELEMENT_NODE) {\n\t\tchildren = anchor.parentNode.children;\n\t\tindex = Array.prototype.indexOf.call(children, anchor);\n\t} else {\n\t\tchildren = this.textNodes(anchor.parentNode);\n\t\tindex = children.indexOf(anchor);\n\t}\n\n\treturn index;\n};\n\nEpubCFI.prototype.filteredPosition = function(anchor, ignoreClass) {\n\tvar children, index, map;\n\n\tif (anchor.nodeType === Node.ELEMENT_NODE) {\n\t\tchildren = anchor.parentNode.children;\n\t\tmap = this.normalizedMap(children, Node.ELEMENT_NODE, ignoreClass);\n\t} else {\n\t\tchildren = anchor.parentNode.childNodes;\n\t\t// Inside an ignored node\n\t\tif(anchor.parentNode.classList.contains(ignoreClass)) {\n\t\t\tanchor = anchor.parentNode;\n\t\t\tchildren = anchor.parentNode.childNodes;\n\t\t}\n\t\tmap = this.normalizedMap(children, Node.TEXT_NODE, ignoreClass);\n\t}\n\n\n\tindex = Array.prototype.indexOf.call(children, anchor);\n\n\treturn map[index];\n};\n\nEpubCFI.prototype.stepsToXpath = function(steps) {\n\tvar xpath = [\".\", \"*\"];\n\n\tsteps.forEach(function(step){\n\t\tvar position = step.index + 1;\n\n\t\tif(step.id){\n\t\t\txpath.push(\"*[position()=\" + position + \" and @id='\" + step.id + \"']\");\n\t\t} else if(step.type === \"text\") {\n\t\t\txpath.push(\"text()[\" + position + \"]\");\n\t\t} else {\n\t\t\txpath.push(\"*[\" + position + \"]\");\n\t\t}\n\t});\n\n\treturn xpath.join(\"/\");\n};\n\n\n/*\n\nTo get the last step if needed:\n\n// Get the terminal step\nlastStep = steps[steps.length-1];\n// Get the query string\nquery = this.stepsToQuery(steps);\n// Find the containing element\nstartContainerParent = doc.querySelector(query);\n// Find the text node within that element\nif(startContainerParent && lastStep.type == \"text\") {\n\tcontainer = startContainerParent.childNodes[lastStep.index];\n}\n*/\nEpubCFI.prototype.stepsToQuerySelector = function(steps) {\n\tvar query = [\"html\"];\n\n\tsteps.forEach(function(step){\n\t\tvar position = step.index + 1;\n\n\t\tif(step.id){\n\t\t\tquery.push(\"#\" + step.id);\n\t\t} else if(step.type === \"text\") {\n\t\t\t// unsupported in querySelector\n\t\t\t// query.push(\"text()[\" + position + \"]\");\n\t\t} else {\n\t\t\tquery.push(\"*:nth-child(\" + position + \")\");\n\t\t}\n\t});\n\n\treturn query.join(\">\");\n\n};\n\nEpubCFI.prototype.textNodes = function(container, ignoreClass) {\n\treturn Array.prototype.slice.call(container.childNodes).\n\t\tfilter(function (node) {\n\t\t\tif (node.nodeType === Node.TEXT_NODE) {\n\t\t\t\treturn true;\n\t\t\t} else if (ignoreClass && node.classList.contains(ignoreClass)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n};\n\nEpubCFI.prototype.walkToNode = function(steps, _doc, ignoreClass) {\n\tvar doc = _doc || document;\n\tvar container = doc.documentElement;\n\tvar step;\n\tvar len = steps.length;\n\tvar i;\n\n\tfor (i = 0; i < len; i++) {\n\t\tstep = steps[i];\n\n\t\tif(step.type === \"element\") {\n\t\t\tcontainer = container.children[step.index];\n\t\t} else if(step.type === \"text\"){\n\t\t\tcontainer = this.textNodes(container, ignoreClass)[step.index];\n\t\t}\n\n\t};\n\n\treturn container;\n};\n\nEpubCFI.prototype.findNode = function(steps, _doc, ignoreClass) {\n\tvar doc = _doc || document;\n\tvar container;\n\tvar xpath;\n\n\tif(!ignoreClass && typeof doc.evaluate != 'undefined') {\n\t\txpath = this.stepsToXpath(steps);\n\t\tcontainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n\t} else if(ignoreClass) {\n\t\tcontainer = this.walkToNode(steps, doc, ignoreClass);\n\t} else {\n\t\tcontainer = this.walkToNode(steps, doc);\n\t}\n\n\treturn container;\n};\n\nEpubCFI.prototype.fixMiss = function(steps, offset, _doc, ignoreClass) {\n\tvar container = this.findNode(steps.slice(0,-1), _doc, ignoreClass);\n\tvar children = container.childNodes;\n\tvar map = this.normalizedMap(children, Node.TEXT_NODE, ignoreClass);\n\tvar i;\n\tvar child;\n\tvar len;\n\tvar childIndex;\n\tvar lastStepIndex = steps[steps.length-1].index;\n\n\tfor (var childIndex in map) {\n\t\tif (!map.hasOwnProperty(childIndex)) return;\n\n\t\tif(map[childIndex] === lastStepIndex) {\n\t\t\tchild = children[childIndex];\n\t\t\tlen = child.textContent.length;\n\t\t\tif(offset > len) {\n\t\t\t\toffset = offset - len;\n\t\t\t} else {\n\t\t\t\tif (child.nodeType === Node.ELEMENT_NODE) {\n\t\t\t\t\tcontainer = child.childNodes[0];\n\t\t\t\t} else {\n\t\t\t\t\tcontainer = child;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tcontainer: container,\n\t\toffset: offset\n\t};\n\n};\n\nEpubCFI.prototype.toRange = function(_doc, ignoreClass) {\n\tvar doc = _doc || document;\n\tvar range = doc.createRange();\n\tvar start, end, startContainer, endContainer;\n\tvar cfi = this;\n\tvar startSteps, endSteps;\n\tvar needsIgnoring = ignoreClass ? (doc.querySelector('.' + ignoreClass) != null) : false;\n\tvar missed;\n\n\tif (cfi.range) {\n\t\tstart = cfi.start;\n\t\tstartSteps = cfi.path.steps.concat(start.steps);\n\t\tstartContainer = this.findNode(startSteps, doc, needsIgnoring ? ignoreClass : null);\n\t\tend = cfi.end;\n\t\tendSteps = cfi.path.steps.concat(end.steps);\n\t\tendContainer = this.findNode(endSteps, doc, needsIgnoring ? ignoreClass : null);\n\t} else {\n\t\tstart = cfi.path;\n\t\tstartSteps = cfi.path.steps;\n\t\tstartContainer = this.findNode(cfi.path.steps, doc, needsIgnoring ? ignoreClass : null);\n\t}\n\n\tif(startContainer) {\n\t\ttry {\n\n\t\t\tif(start.terminal.offset != null) {\n\t\t\t\trange.setStart(startContainer, start.terminal.offset);\n\t\t\t} else {\n\t\t\t\trange.setStart(startContainer, 0);\n\t\t\t}\n\n\t\t} catch (e) {\n\t\t\tmissed = this.fixMiss(startSteps, start.terminal.offset, doc, needsIgnoring ? ignoreClass : null);\n\t\t\trange.setStart(missed.container, missed.offset);\n\t\t}\n\t} else {\n\t\t// No start found\n\t\treturn null;\n\t}\n\n\tif (endContainer) {\n\t\ttry {\n\n\t\t\tif(end.terminal.offset != null) {\n\t\t\t\trange.setEnd(endContainer, end.terminal.offset);\n\t\t\t} else {\n\t\t\t\trange.setEnd(endContainer, 0);\n\t\t\t}\n\n\t\t} catch (e) {\n\t\t\tmissed = this.fixMiss(endSteps, cfi.end.terminal.offset, doc, needsIgnoring ? ignoreClass : null);\n\t\t\trange.setEnd(missed.container, missed.offset);\n\t\t}\n\t}\n\n\n\t// doc.defaultView.getSelection().addRange(range);\n\treturn range;\n};\n\n// is a cfi string, should be wrapped with \"epubcfi()\"\nEpubCFI.prototype.isCfiString = function(str) {\n\tif(typeof str === 'string' &&\n\t\t\tstr.indexOf(\"epubcfi(\") === 0 &&\n\t\t\tstr[str.length-1] === \")\") {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\nEpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) {\n\tvar pos = parseInt(_pos),\n\t\tspineNodeIndex = _spineNodeIndex + 1,\n\t\tcfi = '/'+spineNodeIndex+'/';\n\n\tcfi += (pos + 1) * 2;\n\n\tif(id) {\n\t\tcfi += \"[\" + id + \"]\";\n\t}\n\n\treturn cfi;\n};\n\nmodule.exports = EpubCFI;\n","var RSVP = require('rsvp');\n\n//-- Hooks allow for injecting functions that must all complete in order before finishing\n// They will execute in parallel but all must finish before continuing\n// Functions may return a promise if they are asycn.\n\n// this.content = new EPUBJS.Hook();\n// this.content.register(function(){});\n// this.content.trigger(args).then(function(){});\n\nfunction Hook(context){\n\tthis.context = context || this;\n\tthis.hooks = [];\n};\n\n// Adds a function to be run before a hook completes\nHook.prototype.register = function(){\n\tfor(var i = 0; i < arguments.length; ++i) {\n\t\tif (typeof arguments[i] === \"function\") {\n\t\t\tthis.hooks.push(arguments[i]);\n\t\t} else {\n\t\t\t// unpack array\n\t\t\tfor(var j = 0; j < arguments[i].length; ++j) {\n\t\t\t\tthis.hooks.push(arguments[i][j]);\n\t\t\t}\n\t\t}\n\t}\n};\n\n// Triggers a hook to run all functions\nHook.prototype.trigger = function(){\n\tvar args = arguments;\n\tvar context = this.context;\n\tvar promises = [];\n\n\tthis.hooks.forEach(function(task, i) {\n\t\tvar executing = task.apply(context, args);\n\n\t\tif(executing && typeof executing[\"then\"] === \"function\") {\n\t\t\t// Task is a function that returns a promise\n\t\t\tpromises.push(executing);\n\t\t}\n\t\t// Otherwise Task resolves immediately, continue\n\t});\n\n\n\treturn RSVP.all(promises);\n};\n\n// Adds a function to be run before a hook completes\nHook.prototype.list = function(){\n\treturn this.hooks;\n};\n\nHook.prototype.clear = function(){\n\treturn this.hooks = [];\n};\n\nmodule.exports = Hook;\n","var core = require('./core');\nvar RSVP = require('rsvp');\n\nfunction Layout(settings){\n\tthis.name = settings.layout || \"reflowable\";\n\tthis._spread = (settings.spread === \"none\") ? false : true;\n\tthis._minSpreadWidth = settings.spread || 800;\n\tthis._evenSpreads = settings.evenSpreads || false;\n\n\tif (settings.flow === \"scrolled-continuous\" ||\n\t\t\tsettings.flow === \"scrolled-doc\") {\n\t\tthis._flow = \"scrolled\";\n\t} else {\n\t\tthis._flow = \"paginated\";\n\t}\n\n\n\tthis.width = 0;\n\tthis.height = 0;\n\tthis.spreadWidth = 0;\n\tthis.delta = 0;\n\n\tthis.columnWidth = 0;\n\tthis.gap = 0;\n\tthis.divisor = 1;\n};\n\n// paginated | scrolled\nLayout.prototype.flow = function(flow) {\n\tthis._flow = (flow === \"paginated\") ? \"paginated\" : \"scrolled\";\n}\n\n// true | false\nLayout.prototype.spread = function(spread, min) {\n\n\tthis._spread = (spread === \"none\") ? false : true;\n\n\tif (min >= 0) {\n\t\tthis._minSpreadWidth = min;\n\t}\n}\n\nLayout.prototype.calculate = function(_width, _height, _gap){\n\n\tvar divisor = 1;\n\tvar gap = _gap || 0;\n\n\t//-- Check the width and create even width columns\n\tvar fullWidth = Math.floor(_width);\n\tvar width = _width;\n\n\tvar section = Math.floor(width / 8);\n\n\tvar colWidth;\n\tvar spreadWidth;\n\tvar delta;\n\n\tif (this._spread && width >= this._minSpreadWidth) {\n\t\tdivisor = 2;\n\t} else {\n\t\tdivisor = 1;\n\t}\n\n\tif (this.name === \"reflowable\" && this._flow === \"paginated\" && !(_gap >= 0)) {\n\t\tgap = ((section % 2 === 0) ? section : section - 1);\n\t}\n\n\tif (this.name === \"pre-paginated\" ) {\n\t\tgap = 0;\n\t}\n\n\t//-- Double Page\n\tif(divisor > 1) {\n\t\tcolWidth = Math.floor((width - gap) / divisor);\n\t} else {\n\t\tcolWidth = width;\n\t}\n\n\tif (this.name === \"pre-paginated\" && divisor > 1) {\n\t\twidth = colWidth;\n\t}\n\n\tspreadWidth = colWidth * divisor;\n\n\tdelta = (colWidth + gap) * divisor;\n\n\tthis.width = width;\n\tthis.height = _height;\n\tthis.spreadWidth = spreadWidth;\n\tthis.delta = delta;\n\n\tthis.columnWidth = colWidth;\n\tthis.gap = gap;\n\tthis.divisor = divisor;\n};\n\nLayout.prototype.format = function(contents){\n\tvar formating;\n\n\tif (this.name === \"pre-paginated\") {\n\t\tformating = contents.fit(this.columnWidth, this.height);\n\t} else if (this._flow === \"paginated\") {\n\t\tformating = contents.columns(this.width, this.height, this.columnWidth, this.gap);\n\t} else { // scrolled\n\t\tformating = contents.size(this.width, null);\n\t}\n\n\treturn formating; // might be a promise in some View Managers\n};\n\nLayout.prototype.count = function(totalWidth) {\n\t// var totalWidth = contents.scrollWidth();\n\tvar spreads = Math.ceil( totalWidth / this.spreadWidth);\n\n\treturn {\n\t\tspreads : spreads,\n\t\tpages : spreads * this.divisor\n\t};\n};\n\nmodule.exports = Layout;\n","var core = require('./core');\nvar Queue = require('./queue');\nvar EpubCFI = require('./epubcfi');\nvar RSVP = require('rsvp');\n\nfunction Locations(spine, request) {\n\tthis.spine = spine;\n\tthis.request = request;\n\n\tthis.q = new Queue(this);\n\tthis.epubcfi = new EpubCFI();\n\n\tthis._locations = [];\n\tthis.total = 0;\n\n\tthis.break = 150;\n\n\tthis._current = 0;\n\n};\n\n// Load all of sections in the book\nLocations.prototype.generate = function(chars) {\n\n\tif (chars) {\n\t\tthis.break = chars;\n\t}\n\n\tthis.q.pause();\n\n\tthis.spine.each(function(section) {\n\n\t\tthis.q.enqueue(this.process, section);\n\n\t}.bind(this));\n\n\treturn this.q.run().then(function() {\n\t\tthis.total = this._locations.length-1;\n\n\t\tif (this._currentCfi) {\n\t\t\tthis.currentLocation = this._currentCfi;\n\t\t}\n\n\t\treturn this._locations;\n\t\t// console.log(this.precentage(this.book.rendition.location.start), this.precentage(this.book.rendition.location.end));\n\t}.bind(this));\n\n};\n\nLocations.prototype.process = function(section) {\n\n\treturn section.load(this.request)\n\t\t.then(function(contents) {\n\n\t\t\tvar range;\n\t\t\tvar doc = contents.ownerDocument;\n\t\t\tvar counter = 0;\n\n\t\t\tthis.sprint(contents, function(node) {\n\t\t\t\tvar len = node.length;\n\t\t\t\tvar dist;\n\t\t\t\tvar pos = 0;\n\n\t\t\t\t// Start range\n\t\t\t\tif (counter == 0) {\n\t\t\t\t\trange = doc.createRange();\n\t\t\t\t\trange.setStart(node, 0);\n\t\t\t\t}\n\n\t\t\t\tdist = this.break - counter;\n\n\t\t\t\t// Node is smaller than a break\n\t\t\t\tif(dist > len){\n\t\t\t\t\tcounter += len;\n\t\t\t\t\tpos = len;\n\t\t\t\t}\n\n\t\t\t\twhile (pos < len) {\n\t\t\t\t\tcounter = this.break;\n\t\t\t\t\tpos += this.break;\n\n\t\t\t\t\t// Gone over\n\t\t\t\t\tif(pos >= len){\n\t\t\t\t\t\t// Continue counter for next node\n\t\t\t\t\t\tcounter = len - (pos - this.break);\n\n\t\t\t\t\t// At End\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// End the previous range\n\t\t\t\t\t\trange.setEnd(node, pos);\n\t\t\t\t\t\tcfi = section.cfiFromRange(range);\n\t\t\t\t\t\tthis._locations.push(cfi);\n\t\t\t\t\t\tcounter = 0;\n\n\t\t\t\t\t\t// Start new range\n\t\t\t\t\t\tpos += 1;\n\t\t\t\t\t\trange = doc.createRange();\n\t\t\t\t\t\trange.setStart(node, pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\n\t\t\t}.bind(this));\n\n\t\t\t// Close remaining\n\t\t\tif (range) {\n\t\t\t\trange.setEnd(prev, prev.length);\n\t\t\t\tcfi = section.cfiFromRange(range);\n\t\t\t\tthis._locations.push(cfi)\n\t\t\t\tcounter = 0;\n\t\t\t}\n\n\t\t}.bind(this));\n\n};\n\nLocations.prototype.sprint = function(root, func) {\n\tvar treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);\n\n\twhile ((node = treeWalker.nextNode())) {\n\t\tfunc(node);\n\t}\n\n};\n\nLocations.prototype.locationFromCfi = function(cfi){\n\t// Check if the location has not been set yet\n\tif(this._locations.length === 0) {\n\t\treturn -1;\n\t}\n\n\treturn core.locationOf(cfi, this._locations, this.epubcfi.compare);\n};\n\nLocations.prototype.precentageFromCfi = function(cfi) {\n\t// Find closest cfi\n\tvar loc = this.locationFromCfi(cfi);\n\t// Get percentage in total\n\treturn this.precentageFromLocation(loc);\n};\n\nLocations.prototype.percentageFromLocation = function(loc) {\n\tif (!loc || !this.total) {\n\t\treturn 0;\n\t}\n\treturn (loc / this.total);\n};\n\nLocations.prototype.cfiFromLocation = function(loc){\n\tvar cfi = -1;\n\t// check that pg is an int\n\tif(typeof loc != \"number\"){\n\t\tloc = parseInt(pg);\n\t}\n\n\tif(loc >= 0 && loc < this._locations.length) {\n\t\tcfi = this._locations[loc];\n\t}\n\n\treturn cfi;\n};\n\nLocations.prototype.cfiFromPercentage = function(value){\n\tvar percentage = (value > 1) ? value / 100 : value; // Normalize value to 0-1\n\tvar loc = Math.ceil(this.total * percentage);\n\n\treturn this.cfiFromLocation(loc);\n};\n\nLocations.prototype.load = function(locations){\n\tthis._locations = JSON.parse(locations);\n\tthis.total = this._locations.length-1;\n\treturn this._locations;\n};\n\nLocations.prototype.save = function(json){\n\treturn JSON.stringify(this._locations);\n};\n\nLocations.prototype.getCurrent = function(json){\n\treturn this._current;\n};\n\nLocations.prototype.setCurrent = function(curr){\n\tvar loc;\n\n\tif(typeof curr == \"string\"){\n\t\tthis._currentCfi = curr;\n\t} else if (typeof curr == \"number\") {\n\t\tthis._current = curr;\n\t} else {\n\t\treturn;\n\t}\n\n\tif(this._locations.length === 0) {\n\t\treturn;\n\t}\n\n\tif(typeof curr == \"string\"){\n\t\tloc = this.locationFromCfi(curr);\n\t\tthis._current = loc;\n\t} else {\n\t\tloc = curr;\n\t}\n\n\tthis.trigger(\"changed\", {\n\t\tpercentage: this.precentageFromLocation(loc)\n\t});\n};\n\nObject.defineProperty(Locations.prototype, 'currentLocation', {\n\tget: function () {\n\t\treturn this._current;\n\t},\n\tset: function (curr) {\n\t\tthis.setCurrent(curr);\n\t}\n});\n\nRSVP.EventTarget.mixin(Locations.prototype);\n\nmodule.exports = Locations;\n","var RSVP = require('rsvp');\nvar core = require('../core');\nvar SingleViewManager = require('./single');\n\nfunction ContinuousViewManager(options) {\n\n\tSingleViewManager.apply(this, arguments); // call super constructor.\n\n\tthis.name = \"continuous\";\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\tinfinite: true,\n\t\toverflow: \"auto\",\n\t\taxis: \"vertical\",\n\t\toffset: 500,\n\t\toffsetDelta: 250,\n\t\twidth: undefined,\n\t\theight: undefined\n\t});\n\n\tcore.extend(this.settings, options.settings || {});\n\n\t// Gap can be 0, byt defaults doesn't handle that\n\tif (options.settings.gap != \"undefined\" && options.settings.gap === 0) {\n\t\tthis.settings.gap = options.settings.gap;\n\t}\n\n\t// this.viewSettings.axis = this.settings.axis;\n\tthis.viewSettings = {\n\t\tignoreClass: this.settings.ignoreClass,\n\t\taxis: this.settings.axis,\n\t\tlayout: this.layout,\n\t\twidth: 0,\n\t\theight: 0\n\t};\n\n\tthis.scrollTop = 0;\n\tthis.scrollLeft = 0;\n};\n\n// subclass extends superclass\nContinuousViewManager.prototype = Object.create(SingleViewManager.prototype);\nContinuousViewManager.prototype.constructor = ContinuousViewManager;\n\nContinuousViewManager.prototype.display = function(section, target){\n\treturn SingleViewManager.prototype.display.call(this, section, target)\n\t\t.then(function () {\n\t\t\treturn this.fill();\n\t\t}.bind(this));\n};\n\nContinuousViewManager.prototype.fill = function(_full){\n\tvar full = _full || new RSVP.defer();\n\n\tthis.check().then(function(result) {\n\t\tif (result) {\n\t\t\tthis.fill(full);\n\t\t} else {\n\t\t\tfull.resolve();\n\t\t}\n\t}.bind(this));\n\n\treturn full.promise;\n}\n\nContinuousViewManager.prototype.moveTo = function(offset){\n\t// var bounds = this.stage.bounds();\n\t// var dist = Math.floor(offset.top / bounds.height) * bounds.height;\n\tvar distX = 0,\n\t\t\tdistY = 0;\n\n\tvar offsetX = 0,\n\t\t\toffsetY = 0;\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tdistY = offset.top;\n\t\toffsetY = offset.top+this.settings.offset;\n\t} else {\n\t\tdistX = Math.floor(offset.left / this.layout.delta) * this.layout.delta;\n\t\toffsetX = distX+this.settings.offset;\n\t}\n\n\treturn this.check(offsetX, offsetY)\n\t\t.then(function(){\n\t\t\tthis.scrollBy(distX, distY);\n\t\t}.bind(this));\n};\n\n/*\nContinuousViewManager.prototype.afterDisplayed = function(currView){\n\tvar next = currView.section.next();\n\tvar prev = currView.section.prev();\n\tvar index = this.views.indexOf(currView);\n\tvar prevView, nextView;\n\n\tif(index + 1 === this.views.length && next) {\n\t\tnextView = this.createView(next);\n\t\tthis.q.enqueue(this.append.bind(this), nextView);\n\t}\n\n\tif(index === 0 && prev) {\n\t\tprevView = this.createView(prev, this.viewSettings);\n\t\tthis.q.enqueue(this.prepend.bind(this), prevView);\n\t}\n\n\t// this.removeShownListeners(currView);\n\t// currView.onShown = this.afterDisplayed.bind(this);\n\tthis.trigger(\"added\", currView.section);\n\n};\n*/\n\nContinuousViewManager.prototype.resize = function(width, height){\n\n\t// Clear the queue\n\tthis.q.clear();\n\n\tthis._stageSize = this.stage.size(width, height);\n\tthis._bounds = this.bounds();\n\n\t// Update for new views\n\tthis.viewSettings.width = this._stageSize.width;\n\tthis.viewSettings.height = this._stageSize.height;\n\n\t// Update for existing views\n\tthis.views.each(function(view) {\n\t\tview.size(this._stageSize.width, this._stageSize.height);\n\t}.bind(this));\n\n\tthis.updateLayout();\n\n\t// if(this.location) {\n\t// this.rendition.display(this.location.start);\n\t// }\n\n\tthis.trigger(\"resized\", {\n\t\twidth: this.stage.width,\n\t\theight: this.stage.height\n\t});\n\n};\n\nContinuousViewManager.prototype.onResized = function(e) {\n\n\t// this.views.clear();\n\n\tclearTimeout(this.resizeTimeout);\n\tthis.resizeTimeout = setTimeout(function(){\n\t\tthis.resize();\n\t}.bind(this), 150);\n};\n\nContinuousViewManager.prototype.afterResized = function(view){\n\tthis.trigger(\"resize\", view.section);\n};\n\n// Remove Previous Listeners if present\nContinuousViewManager.prototype.removeShownListeners = function(view){\n\n\t// view.off(\"shown\", this.afterDisplayed);\n\t// view.off(\"shown\", this.afterDisplayedAbove);\n\tview.onDisplayed = function(){};\n\n};\n\n\n// ContinuousViewManager.prototype.append = function(section){\n// \treturn this.q.enqueue(function() {\n//\n// \t\tthis._append(section);\n//\n//\n// \t}.bind(this));\n// };\n//\n// ContinuousViewManager.prototype.prepend = function(section){\n// \treturn this.q.enqueue(function() {\n//\n// \t\tthis._prepend(section);\n//\n// \t}.bind(this));\n//\n// };\n\nContinuousViewManager.prototype.append = function(section){\n\tvar view = this.createView(section);\n\tthis.views.append(view);\n\treturn view;\n};\n\nContinuousViewManager.prototype.prepend = function(section){\n\tvar view = this.createView(section);\n\n\tview.on(\"resized\", this.counter.bind(this));\n\n\tthis.views.prepend(view);\n\treturn view;\n};\n\nContinuousViewManager.prototype.counter = function(bounds){\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tthis.scrollBy(0, bounds.heightDelta, true);\n\t} else {\n\t\tthis.scrollBy(bounds.widthDelta, 0, true);\n\t}\n\n};\n\nContinuousViewManager.prototype.update = function(_offset){\n\tvar container = this.bounds();\n\tvar views = this.views.all();\n\tvar viewsLength = views.length;\n\tvar visible = [];\n\tvar offset = typeof _offset != \"undefined\" ? _offset : (this.settings.offset || 0);\n\tvar isVisible;\n\tvar view;\n\n\tvar updating = new RSVP.defer();\n\tvar promises = [];\n\n\tfor (var i = 0; i < viewsLength; i++) {\n\t\tview = views[i];\n\n\t\tisVisible = this.isVisible(view, offset, offset, container);\n\n\t\tif(isVisible === true) {\n\t\t\tif (!view.displayed) {\n\t\t\t\tpromises.push(view.display(this.request).then(function (view) {\n\t\t\t\t\tview.show();\n\t\t\t\t}));\n\t\t\t}\n\t\t\tvisible.push(view);\n\t\t} else {\n\t\t\tthis.q.enqueue(view.destroy.bind(view));\n\n\t\t\tclearTimeout(this.trimTimeout);\n\t\t\tthis.trimTimeout = setTimeout(function(){\n\t\t\t\tthis.q.enqueue(this.trim.bind(this));\n\t\t\t}.bind(this), 250);\n\t\t}\n\n\t}\n\n\tif(promises.length){\n\t\treturn RSVP.all(promises);\n\t} else {\n\t\tupdating.resolve();\n\t\treturn updating.promise;\n\t}\n\n};\n\nContinuousViewManager.prototype.check = function(_offsetLeft, _offsetTop){\n\tvar last, first, next, prev;\n\n\tvar checking = new RSVP.defer();\n\tvar newViews = [];\n\n\tvar horizontal = (this.settings.axis === \"horizontal\");\n\tvar delta = this.settings.offset || 0;\n\n\tif (_offsetLeft && horizontal) {\n\t\tdelta = _offsetLeft;\n\t}\n\n\tif (_offsetTop && !horizontal) {\n\t\tdelta = _offsetTop;\n\t}\n\n\tvar bounds = this._bounds; // bounds saved this until resize\n\n\tvar offset = horizontal ? this.scrollLeft : this.scrollTop;\n\tvar visibleLength = horizontal ? bounds.width : bounds.height;\n\tvar contentLength = horizontal ? this.container.scrollWidth : this.container.scrollHeight;\n\n\tif (offset + visibleLength + delta >= contentLength) {\n\t\tlast = this.views.last();\n\t\tnext = last && last.section.next();\n\t\tif(next) {\n\t\t\tnewViews.push(this.append(next));\n\t\t}\n\t}\n\n\tif (offset - delta < 0 ) {\n\t\tfirst = this.views.first();\n\t\tprev = first && first.section.prev();\n\t\tif(prev) {\n\t\t\tnewViews.push(this.prepend(prev));\n\t\t}\n\t}\n\n\tif(newViews.length){\n\t\t// RSVP.all(promises)\n\t\t\t// .then(function() {\n\t\t\t\t// Check to see if anything new is on screen after rendering\n\t\t\t\treturn this.q.enqueue(function(){\n\t\t\t\t\treturn this.update(delta);\n\t\t\t\t}.bind(this));\n\n\n\t\t\t// }.bind(this));\n\n\t} else {\n\t\tchecking.resolve(false);\n\t\treturn checking.promise;\n\t}\n\n\n};\n\nContinuousViewManager.prototype.trim = function(){\n\tvar task = new RSVP.defer();\n\tvar displayed = this.views.displayed();\n\tvar first = displayed[0];\n\tvar last = displayed[displayed.length-1];\n\tvar firstIndex = this.views.indexOf(first);\n\tvar lastIndex = this.views.indexOf(last);\n\tvar above = this.views.slice(0, firstIndex);\n\tvar below = this.views.slice(lastIndex+1);\n\n\t// Erase all but last above\n\tfor (var i = 0; i < above.length-1; i++) {\n\t\tthis.erase(above[i], above);\n\t}\n\n\t// Erase all except first below\n\tfor (var j = 1; j < below.length; j++) {\n\t\tthis.erase(below[j]);\n\t}\n\n\ttask.resolve();\n\treturn task.promise;\n};\n\nContinuousViewManager.prototype.erase = function(view, above){ //Trim\n\n\tvar prevTop;\n\tvar prevLeft;\n\n\tif(this.settings.height) {\n\t\tprevTop = this.container.scrollTop;\n\t\tprevLeft = this.container.scrollLeft;\n\t} else {\n\t\tprevTop = window.scrollY;\n\t\tprevLeft = window.scrollX;\n\t}\n\n\tvar bounds = view.bounds();\n\n\tthis.views.remove(view);\n\n\tif(above) {\n\n\t\tif(this.settings.axis === \"vertical\") {\n\t\t\tthis.scrollTo(0, prevTop - bounds.height, true);\n\t\t} else {\n\t\t\tthis.scrollTo(prevLeft - bounds.width, 0, true);\n\t\t}\n\t}\n\n};\n\nContinuousViewManager.prototype.addEventListeners = function(stage){\n\n\twindow.addEventListener('unload', function(e){\n\t\tthis.ignore = true;\n\t\t// this.scrollTo(0,0);\n\t\tthis.destroy();\n\t}.bind(this));\n\n\tthis.addScrollListeners();\n};\n\nContinuousViewManager.prototype.addScrollListeners = function() {\n\tvar scroller;\n\n\tthis.tick = core.requestAnimationFrame;\n\n\tif(this.settings.height) {\n\t\tthis.prevScrollTop = this.container.scrollTop;\n\t\tthis.prevScrollLeft = this.container.scrollLeft;\n\t} else {\n\t\tthis.prevScrollTop = window.scrollY;\n\t\tthis.prevScrollLeft = window.scrollX;\n\t}\n\n\tthis.scrollDeltaVert = 0;\n\tthis.scrollDeltaHorz = 0;\n\n\tif(this.settings.height) {\n\t\tscroller = this.container;\n\t\tthis.scrollTop = this.container.scrollTop;\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\t} else {\n\t\tscroller = window;\n\t\tthis.scrollTop = window.scrollY;\n\t\tthis.scrollLeft = window.scrollX;\n\t}\n\n\tscroller.addEventListener(\"scroll\", this.onScroll.bind(this));\n\n\t// this.tick.call(window, this.onScroll.bind(this));\n\n\tthis.scrolled = false;\n\n};\n\nContinuousViewManager.prototype.onScroll = function(){\n\n\t// if(!this.ignore) {\n\n\t\tif(this.settings.height) {\n\t\t\tscrollTop = this.container.scrollTop;\n\t\t\tscrollLeft = this.container.scrollLeft;\n\t\t} else {\n\t\t\tscrollTop = window.scrollY;\n\t\t\tscrollLeft = window.scrollX;\n\t\t}\n\n\t\tthis.scrollTop = scrollTop;\n\t\tthis.scrollLeft = scrollLeft;\n\n\t\tif(!this.ignore) {\n\n\t\t\tif((this.scrollDeltaVert === 0 &&\n\t\t\t\t this.scrollDeltaHorz === 0) ||\n\t\t\t\t this.scrollDeltaVert > this.settings.offsetDelta ||\n\t\t\t\t this.scrollDeltaHorz > this.settings.offsetDelta) {\n\n\t\t\t\tthis.q.enqueue(function() {\n\t\t\t\t\tthis.check();\n\t\t\t\t}.bind(this));\n\t\t\t\t// this.check();\n\n\t\t\t\tthis.scrollDeltaVert = 0;\n\t\t\t\tthis.scrollDeltaHorz = 0;\n\n\t\t\t\tthis.trigger(\"scroll\", {\n\t\t\t\t\ttop: scrollTop,\n\t\t\t\t\tleft: scrollLeft\n\t\t\t\t});\n\n\t\t\t\tclearTimeout(this.afterScrolled);\n\t\t\t\tthis.afterScrolled = setTimeout(function () {\n\t\t\t\t\tthis.trigger(\"scrolled\", {\n\t\t\t\t\t\ttop: this.scrollTop,\n\t\t\t\t\t\tleft: this.scrollLeft\n\t\t\t\t\t});\n\t\t\t\t}.bind(this));\n\n\t\t\t}\n\n\t\t} else {\n\t\t\tthis.ignore = false;\n\t\t}\n\n\t\tthis.scrollDeltaVert += Math.abs(scrollTop-this.prevScrollTop);\n\t\tthis.scrollDeltaHorz += Math.abs(scrollLeft-this.prevScrollLeft);\n\n\t\tthis.prevScrollTop = scrollTop;\n\t\tthis.prevScrollLeft = scrollLeft;\n\n\t\tclearTimeout(this.scrollTimeout);\n\t\tthis.scrollTimeout = setTimeout(function(){\n\t\t\tthis.scrollDeltaVert = 0;\n\t\t\tthis.scrollDeltaHorz = 0;\n\t\t}.bind(this), 150);\n\n\n\t\tthis.scrolled = false;\n\t// }\n\n\t// this.tick.call(window, this.onScroll.bind(this));\n\n};\n\n\n// ContinuousViewManager.prototype.resizeView = function(view) {\n//\n// \tif(this.settings.axis === \"horizontal\") {\n// \t\tview.lock(\"height\", this.stage.width, this.stage.height);\n// \t} else {\n// \t\tview.lock(\"width\", this.stage.width, this.stage.height);\n// \t}\n//\n// };\n\nContinuousViewManager.prototype.currentLocation = function(){\n\n\tif (this.settings.axis === \"vertical\") {\n\t\tthis.location = this.scrolledLocation();\n\t} else {\n\t\tthis.location = this.paginatedLocation();\n\t}\n\n\treturn this.location;\n};\n\nContinuousViewManager.prototype.scrolledLocation = function(){\n\n\tvar visible = this.visible();\n\tvar startPage, endPage;\n\n\tvar container = this.container.getBoundingClientRect();\n\n\tif(visible.length === 1) {\n\t\treturn this.mapping.page(visible[0].contents, visible[0].section.cfiBase);\n\t}\n\n\tif(visible.length > 1) {\n\n\t\tstartPage = this.mapping.page(visible[0].contents, visible[0].section.cfiBase);\n\t\tendPage = this.mapping.page(visible[visible.length-1].contents, visible[visible.length-1].section.cfiBase);\n\n\t\treturn {\n\t\t\tstart: startPage.start,\n\t\t\tend: endPage.end\n\t\t};\n\t}\n\n};\n\nContinuousViewManager.prototype.paginatedLocation = function(){\n\tvar visible = this.visible();\n\tvar startA, startB, endA, endB;\n\tvar pageLeft, pageRight;\n\tvar container = this.container.getBoundingClientRect();\n\n\tif(visible.length === 1) {\n\t\tstartA = container.left - visible[0].position().left;\n\t\tendA = startA + this.layout.spreadWidth;\n\n\t\treturn this.mapping.page(visible[0].contents, visible[0].section.cfiBase, startA, endA);\n\t}\n\n\tif(visible.length > 1) {\n\n\t\t// Left Col\n\t\tstartA = container.left - visible[0].position().left;\n\t\tendA = startA + this.layout.columnWidth;\n\n\t\t// Right Col\n\t\tstartB = container.left + this.layout.spreadWidth - visible[visible.length-1].position().left;\n\t\tendB = startB + this.layout.columnWidth;\n\n\t\tpageLeft = this.mapping.page(visible[0].contents, visible[0].section.cfiBase, startA, endA);\n\t\tpageRight = this.mapping.page(visible[visible.length-1].contents, visible[visible.length-1].section.cfiBase, startB, endB);\n\n\t\treturn {\n\t\t\tstart: pageLeft.start,\n\t\t\tend: pageRight.end\n\t\t};\n\t}\n};\n\n/*\nContinuous.prototype.current = function(what){\n\tvar view, top;\n\tvar container = this.container.getBoundingClientRect();\n\tvar length = this.views.length - 1;\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tfor (var i = length; i >= 0; i--) {\n\t\t\tview = this.views[i];\n\t\t\tleft = view.position().left;\n\n\t\t\tif(left < container.right) {\n\n\t\t\t\tif(this._current == view) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tthis._current = view;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t} else {\n\n\t\tfor (var i = length; i >= 0; i--) {\n\t\t\tview = this.views[i];\n\t\t\ttop = view.bounds().top;\n\t\t\tif(top < container.bottom) {\n\n\t\t\t\tif(this._current == view) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tthis._current = view;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn this._current;\n};\n*/\n\nContinuousViewManager.prototype.updateLayout = function() {\n\n\tif (!this.stage) {\n\t\treturn;\n\t}\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tthis.layout.calculate(this._stageSize.width, this._stageSize.height);\n\t} else {\n\t\tthis.layout.calculate(\n\t\t\tthis._stageSize.width,\n\t\t\tthis._stageSize.height,\n\t\t\tthis.settings.gap\n\t\t);\n\n\t\t// Set the look ahead offset for what is visible\n\t\tthis.settings.offset = this.layout.delta;\n\n\t\tthis.stage.addStyleRules(\"iframe\", [{\"margin-right\" : this.layout.gap + \"px\"}]);\n\n\t}\n\n\t// Set the dimensions for views\n\tthis.viewSettings.width = this.layout.width;\n\tthis.viewSettings.height = this.layout.height;\n\n\tthis.setLayout(this.layout);\n\n};\n\nContinuousViewManager.prototype.next = function(){\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\n\t\tif(this.container.scrollLeft +\n\t\t\t this.container.offsetWidth +\n\t\t\t this.layout.delta < this.container.scrollWidth) {\n\t\t\tthis.scrollBy(this.layout.delta, 0);\n\t\t} else {\n\t\t\tthis.scrollTo(this.container.scrollWidth - this.layout.delta, 0);\n\t\t}\n\n\t} else {\n\t\tthis.scrollBy(0, this.layout.height);\n\t}\n};\n\nContinuousViewManager.prototype.prev = function(){\n\tif(this.settings.axis === \"horizontal\") {\n\t\tthis.scrollBy(-this.layout.delta, 0);\n\t} else {\n\t\tthis.scrollBy(0, -this.layout.height);\n\t}\n};\n\nContinuousViewManager.prototype.updateFlow = function(flow){\n\tvar axis = (flow === \"paginated\") ? \"horizontal\" : \"vertical\";\n\n\tthis.settings.axis = axis;\n\n\tthis.viewSettings.axis = axis;\n\n\tthis.settings.overflow = (flow === \"paginated\") ? \"hidden\" : \"auto\";\n\n\t// this.views.each(function(view){\n\t// \tview.setAxis(axis);\n\t// });\n\n\tif (this.settings.axis === \"vertical\") {\n\t\tthis.settings.infinite = true;\n\t} else {\n\t\tthis.settings.infinite = false;\n\t}\n\n};\nmodule.exports = ContinuousViewManager;\n","var RSVP = require('rsvp');\nvar core = require('../core');\nvar Stage = require('../stage');\nvar Views = require('../views');\nvar EpubCFI = require('../epubcfi');\n// var Layout = require('../layout');\nvar Mapping = require('../mapping');\nvar Queue = require('../queue');\n\nfunction SingleViewManager(options) {\n\n\tthis.name = \"single\";\n\tthis.View = options.view;\n\tthis.request = options.request;\n\tthis.renditionQueue = options.queue;\n\tthis.q = new Queue(this);\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\tinfinite: true,\n\t\thidden: false,\n\t\twidth: undefined,\n\t\theight: undefined,\n\t\t// globalLayoutProperties : { layout: 'reflowable', spread: 'auto', orientation: 'auto'},\n\t\t// layout: null,\n\t\taxis: \"vertical\",\n\t\tignoreClass: ''\n\t});\n\n\tcore.extend(this.settings, options.settings || {});\n\n\tthis.viewSettings = {\n\t\tignoreClass: this.settings.ignoreClass,\n\t\taxis: this.settings.axis,\n\t\tlayout: this.layout,\n\t\twidth: 0,\n\t\theight: 0\n\t};\n\n}\n\nSingleViewManager.prototype.render = function(element, size){\n\n\t// Save the stage\n\tthis.stage = new Stage({\n\t\twidth: size.width,\n\t\theight: size.height,\n\t\toverflow: this.settings.overflow,\n\t\thidden: this.settings.hidden,\n\t\taxis: this.settings.axis\n\t});\n\n\tthis.stage.attachTo(element);\n\n\t// Get this stage container div\n\tthis.container = this.stage.getContainer();\n\n\t// Views array methods\n\tthis.views = new Views(this.container);\n\n\t// Calculate Stage Size\n\tthis._bounds = this.bounds();\n\tthis._stageSize = this.stage.size();\n\n\t// Set the dimensions for views\n\tthis.viewSettings.width = this._stageSize.width;\n\tthis.viewSettings.height = this._stageSize.height;\n\n\t// Function to handle a resize event.\n\t// Will only attach if width and height are both fixed.\n\tthis.stage.onResize(this.onResized.bind(this));\n\n\t// Add Event Listeners\n\tthis.addEventListeners();\n\n\t// Add Layout method\n\t// this.applyLayoutMethod();\n\tif (this.layout) {\n\t\tthis.updateLayout();\n\t}\n};\n\nSingleViewManager.prototype.addEventListeners = function(){\n\twindow.addEventListener('unload', function(e){\n\t\tthis.destroy();\n\t}.bind(this));\n};\n\nSingleViewManager.prototype.destroy = function(){\n\t// this.views.each(function(view){\n\t// \tview.destroy();\n\t// });\n};\n\nSingleViewManager.prototype.onResized = function(e) {\n\tclearTimeout(this.resizeTimeout);\n\tthis.resizeTimeout = setTimeout(function(){\n\t\tthis.resize();\n\t}.bind(this), 150);\n};\n\nSingleViewManager.prototype.resize = function(width, height){\n\n\t// Clear the queue\n\tthis.q.clear();\n\n\tthis._stageSize = this.stage.size(width, height);\n\tthis._bounds = this.bounds();\n\n\t// Update for new views\n\tthis.viewSettings.width = this._stageSize.width;\n\tthis.viewSettings.height = this._stageSize.height;\n\n\t// Update for existing views\n\tthis.views.each(function(view) {\n\t\tview.size(this._stageSize.width, this._stageSize.height);\n\t}.bind(this));\n\n\tthis.updateLayout();\n\n\tthis.trigger(\"resized\", {\n\t\twidth: this.stage.width,\n\t\theight: this.stage.height\n\t});\n\n};\n\nSingleViewManager.prototype.createView = function(section) {\n\treturn new this.View(section, this.viewSettings);\n};\n\nSingleViewManager.prototype.display = function(section, target){\n\n\tvar displaying = new RSVP.defer();\n\tvar displayed = displaying.promise;\n\n\t// Check to make sure the section we want isn't already shown\n\tvar visible = this.views.find(section);\n\n\t// View is already shown, just move to correct location\n\tif(visible && target) {\n\t\toffset = visible.locationOf(target);\n\t\tthis.moveTo(offset);\n\t\tdisplaying.resolve();\n\t\treturn displayed;\n\t}\n\n\t// Hide all current views\n\tthis.views.hide();\n\n\tthis.views.clear();\n\n\tthis.add(section)\n\t\t.then(function(){\n\t\t\tvar next;\n\t\t\tif (this.layout.name === \"pre-paginated\" &&\n\t\t\t\t\tthis.layout.divisor > 1) {\n\t\t\t\tnext = section.next();\n\t\t\t\tif (next) {\n\t\t\t\t\treturn this.add(next);\n\t\t\t\t}\n\t\t\t}\n\t\t}.bind(this))\n\t\t.then(function(view){\n\n\t\t\t// Move to correct place within the section, if needed\n\t\t\tif(target) {\n\t\t\t\toffset = view.locationOf(target);\n\t\t\t\tthis.moveTo(offset);\n\t\t\t}\n\n\t\t\tthis.views.show();\n\n\t\t\tdisplaying.resolve();\n\n\t\t}.bind(this))\n\t\t// .then(function(){\n\t\t// \treturn this.hooks.display.trigger(view);\n\t\t// }.bind(this))\n\t\t// .then(function(){\n\t\t// \tthis.views.show();\n\t\t// }.bind(this));\n\t\treturn displayed;\n};\n\nSingleViewManager.prototype.afterDisplayed = function(view){\n\tthis.trigger(\"added\", view);\n};\n\nSingleViewManager.prototype.afterResized = function(view){\n\tthis.trigger(\"resize\", view.section);\n};\n\n// SingleViewManager.prototype.moveTo = function(offset){\n// \tthis.scrollTo(offset.left, offset.top);\n// };\n\nSingleViewManager.prototype.moveTo = function(offset){\n\tvar distX = 0,\n\t\t\tdistY = 0;\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tdistY = offset.top;\n\t} else {\n\t\tdistX = Math.floor(offset.left / this.layout.delta) * this.layout.delta;\n\n\t\tif (distX + this.layout.delta > this.container.scrollWidth) {\n\t\t\tdistX = this.container.scrollWidth - this.layout.delta;\n\t\t}\n\t}\n\n\tthis.scrollTo(distX, distY);\n};\n\nSingleViewManager.prototype.add = function(section){\n\tvar view = this.createView(section);\n\n\tthis.views.append(view);\n\n\t// view.on(\"shown\", this.afterDisplayed.bind(this));\n\tview.onDisplayed = this.afterDisplayed.bind(this);\n\tview.onResize = this.afterResized.bind(this);\n\n\treturn view.display(this.request);\n\n};\n\nSingleViewManager.prototype.append = function(section){\n\tvar view = this.createView(section);\n\tthis.views.append(view);\n\treturn view.display(this.request);\n};\n\nSingleViewManager.prototype.prepend = function(section){\n\tvar view = this.createView(section);\n\n\tthis.views.prepend(view);\n\treturn view.display(this.request);\n};\n// SingleViewManager.prototype.resizeView = function(view) {\n//\n// \tif(this.settings.globalLayoutProperties.layout === \"pre-paginated\") {\n// \t\tview.lock(\"both\", this.bounds.width, this.bounds.height);\n// \t} else {\n// \t\tview.lock(\"width\", this.bounds.width, this.bounds.height);\n// \t}\n//\n// };\n\nSingleViewManager.prototype.next = function(){\n\tvar next;\n\tvar view;\n\tvar left;\n\n\tif(!this.views.length) return;\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\n\t\tleft = this.container.scrollLeft + this.container.offsetWidth + this.layout.delta;\n\n\t\tif(left < this.container.scrollWidth) {\n\t\t\tthis.scrollBy(this.layout.delta, 0);\n\t\t} else if (left - this.layout.columnWidth === this.container.scrollWidth) {\n\t\t\tthis.scrollTo(this.container.scrollWidth - this.layout.delta, 0);\n\t\t} else {\n\t\t\tnext = this.views.last().section.next();\n\t\t}\n\n\n\t} else {\n\n\t\tnext = this.views.last().section.next();\n\n\t}\n\n\tif(next) {\n\t\tthis.views.clear();\n\n\t\treturn this.append(next)\n\t\t\t.then(function(){\n\t\t\t\tvar right;\n\t\t\t\tif (this.layout.name && this.layout.divisor > 1) {\n\t\t\t\t\tright = next.next();\n\t\t\t\t\tif (right) {\n\t\t\t\t\t\treturn this.append(right);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}.bind(this))\n\t\t\t.then(function(){\n\t\t\t\tthis.views.show();\n\t\t\t}.bind(this));\n\t}\n\n\n};\n\nSingleViewManager.prototype.prev = function(){\n\tvar prev;\n\tvar view;\n\tvar left;\n\n\tif(!this.views.length) return;\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\n\t\tleft = this.container.scrollLeft;\n\n\t\tif(left > 0) {\n\t\t\tthis.scrollBy(-this.layout.delta, 0);\n\t\t} else {\n\t\t\tprev = this.views.first().section.prev();\n\t\t}\n\n\n\t} else {\n\n\t\tprev = this.views.first().section.prev();\n\n\t}\n\n\tif(prev) {\n\t\tthis.views.clear();\n\n\t\treturn this.prepend(prev)\n\t\t\t.then(function(){\n\t\t\t\tvar left;\n\t\t\t\tif (this.layout.name && this.layout.divisor > 1) {\n\t\t\t\t\tleft = prev.prev();\n\t\t\t\t\tif (left) {\n\t\t\t\t\t\treturn this.prepend(left);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}.bind(this))\n\t\t\t.then(function(){\n\t\t\t\tif(this.settings.axis === \"horizontal\") {\n\t\t\t\t\tthis.scrollTo(this.container.scrollWidth - this.layout.delta, 0);\n\t\t\t\t}\n\t\t\t\tthis.views.show();\n\t\t\t}.bind(this));\n\t}\n};\n\nSingleViewManager.prototype.current = function(){\n\tvar visible = this.visible();\n\tif(visible.length){\n\t\t// Current is the last visible view\n\t\treturn visible[visible.length-1];\n\t}\n\treturn null;\n};\n\nSingleViewManager.prototype.currentLocation = function(){\n\tvar view;\n\tvar start, end;\n\n\tif(this.views.length) {\n\t\tview = this.views.first();\n\t\tstart = container.left - view.position().left;\n\t\tend = start + this.layout.spread;\n\n\t\treturn this.mapping.page(view, view.section.cfiBase);\n\t}\n\n};\n\nSingleViewManager.prototype.isVisible = function(view, offsetPrev, offsetNext, _container){\n\tvar position = view.position();\n\tvar container = _container || this.bounds();\n\n\tif(this.settings.axis === \"horizontal\" &&\n\t\tposition.right > container.left - offsetPrev &&\n\t\tposition.left < container.right + offsetNext) {\n\n\t\treturn true;\n\n\t} else if(this.settings.axis === \"vertical\" &&\n\t\tposition.bottom > container.top - offsetPrev &&\n\t\tposition.top < container.bottom + offsetNext) {\n\n\t\treturn true;\n\t}\n\n\treturn false;\n\n};\n\nSingleViewManager.prototype.visible = function(){\n\t// return this.views.displayed();\n\tvar container = this.bounds();\n\tvar views = this.views.displayed();\n\tvar viewsLength = views.length;\n\tvar visible = [];\n\tvar isVisible;\n\tvar view;\n\n\tfor (var i = 0; i < viewsLength; i++) {\n\t\tview = views[i];\n\t\tisVisible = this.isVisible(view, 0, 0, container);\n\n\t\tif(isVisible === true) {\n\t\t\tvisible.push(view);\n\t\t}\n\n\t}\n\treturn visible;\n};\n\nSingleViewManager.prototype.scrollBy = function(x, y, silent){\n\tif(silent) {\n\t\tthis.ignore = true;\n\t}\n\n\tif(this.settings.height) {\n\n\t\tif(x) this.container.scrollLeft += x;\n\t\tif(y) this.container.scrollTop += y;\n\n\t} else {\n\t\twindow.scrollBy(x,y);\n\t}\n\t// console.log(\"scrollBy\", x, y);\n\tthis.scrolled = true;\n\tthis.onScroll();\n};\n\nSingleViewManager.prototype.scrollTo = function(x, y, silent){\n\tif(silent) {\n\t\tthis.ignore = true;\n\t}\n\n\tif(this.settings.height) {\n\t\tthis.container.scrollLeft = x;\n\t\tthis.container.scrollTop = y;\n\t} else {\n\t\twindow.scrollTo(x,y);\n\t}\n\t// console.log(\"scrollTo\", x, y);\n\tthis.scrolled = true;\n\tthis.onScroll();\n\t// if(this.container.scrollLeft != x){\n\t// setTimeout(function() {\n\t// this.scrollTo(x, y, silent);\n\t// }.bind(this), 10);\n\t// return;\n\t// };\n };\n\nSingleViewManager.prototype.onScroll = function(){\n\n};\n\nSingleViewManager.prototype.bounds = function() {\n\tvar bounds;\n\n\tbounds = this.stage.bounds();\n\n\treturn bounds;\n};\n\nSingleViewManager.prototype.applyLayout = function(layout) {\n\n\tthis.layout = layout;\n\tthis.updateLayout();\n\n\tthis.mapping = new Mapping(this.layout);\n\t // this.manager.layout(this.layout.format);\n};\n\nSingleViewManager.prototype.updateLayout = function() {\n\tif (!this.stage) {\n\t\treturn;\n\t}\n\n\tthis._stageSize = this.stage.size();\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tthis.layout.calculate(this._stageSize.width, this._stageSize.height);\n\t} else {\n\t\tthis.layout.calculate(\n\t\t\tthis._stageSize.width,\n\t\t\tthis._stageSize.height,\n\t\t\tthis.settings.gap\n\t\t);\n\n\t\t// Set the look ahead offset for what is visible\n\t\tthis.settings.offset = this.layout.delta;\n\n\t\tthis.stage.addStyleRules(\"iframe\", [{\"margin-right\" : this.layout.gap + \"px\"}]);\n\n\t}\n\n\t// Set the dimensions for views\n\tthis.viewSettings.width = this.layout.width;\n\tthis.viewSettings.height = this.layout.height;\n\n\tthis.setLayout(this.layout);\n\n};\n\nSingleViewManager.prototype.setLayout = function(layout){\n\n\tthis.viewSettings.layout = layout;\n\n\tif(this.views) {\n\n\t\tthis.views.each(function(view){\n\t\t\tview.setLayout(layout);\n\t\t});\n\n\t}\n\n};\n\nSingleViewManager.prototype.updateFlow = function(flow){\n\tvar axis = (flow === \"paginated\") ? \"horizontal\" : \"vertical\";\n\n\tthis.settings.axis = axis;\n\n\tthis.viewSettings.axis = axis;\n\n\tthis.settings.overflow = (flow === \"paginated\") ? \"hidden\" : \"auto\";\n\t// this.views.each(function(view){\n\t// \tview.setAxis(axis);\n\t// });\n\n};\n\n //-- Enable binding events to Manager\n RSVP.EventTarget.mixin(SingleViewManager.prototype);\n\n module.exports = SingleViewManager;\n","var EpubCFI = require('./epubcfi');\n\nfunction Mapping(layout){\n\tthis.layout = layout;\n};\n\nMapping.prototype.section = function(view) {\n\tvar ranges = this.findRanges(view);\n\tvar map = this.rangeListToCfiList(view.section.cfiBase, ranges);\n\n\treturn map;\n};\n\nMapping.prototype.page = function(contents, cfiBase, start, end) {\n\tvar root = contents && contents.document ? contents.document.body : false;\n\n\tif (!root) {\n\t\treturn;\n\t}\n\n\treturn this.rangePairToCfiPair(cfiBase, {\n\t\tstart: this.findStart(root, start, end),\n\t\tend: this.findEnd(root, start, end)\n\t});\n};\n\nMapping.prototype.walk = function(root, func) {\n\t//var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false);\n\tvar treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {\n\t\t\tacceptNode: function (node) {\n\t\t\t\t\tif ( node.data.trim().length > 0 ) {\n\t\t\t\t\t\treturn NodeFilter.FILTER_ACCEPT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn NodeFilter.FILTER_REJECT;\n\t\t\t\t\t}\n\t\t\t}\n\t}, false);\n\tvar node;\n\tvar result;\n\twhile ((node = treeWalker.nextNode())) {\n\t\tresult = func(node);\n\t\tif(result) break;\n\t}\n\n\treturn result;\n};\n\nMapping.prototype.findRanges = function(view){\n\tvar columns = [];\n\tvar scrollWidth = view.contents.scrollWidth();\n\tvar count = this.layout.count(scrollWidth);\n\tvar column = this.layout.column;\n\tvar gap = this.layout.gap;\n\tvar start, end;\n\n\tfor (var i = 0; i < count.pages; i++) {\n\t\tstart = (column + gap) * i;\n\t\tend = (column * (i+1)) + (gap * i);\n\t\tcolumns.push({\n\t\t\tstart: this.findStart(view.document.body, start, end),\n\t\t\tend: this.findEnd(view.document.body, start, end)\n\t\t});\n\t}\n\n\treturn columns;\n};\n\nMapping.prototype.findStart = function(root, start, end){\n\tvar stack = [root];\n\tvar $el;\n\tvar found;\n\tvar $prev = root;\n\twhile (stack.length) {\n\n\t\t$el = stack.shift();\n\n\t\tfound = this.walk($el, function(node){\n\t\t\tvar left, right;\n\t\t\tvar elPos;\n\t\t\tvar elRange;\n\n\n\t\t\tif(node.nodeType == Node.TEXT_NODE){\n\t\t\t\telRange = document.createRange();\n\t\t\t\telRange.selectNodeContents(node);\n\t\t\t\telPos = elRange.getBoundingClientRect();\n\t\t\t} else {\n\t\t\t\telPos = node.getBoundingClientRect();\n\t\t\t}\n\n\t\t\tleft = elPos.left;\n\t\t\tright = elPos.right;\n\n\t\t\tif( left >= start && left <= end ) {\n\t\t\t\treturn node;\n\t\t\t} else if (right > start) {\n\t\t\t\treturn node;\n\t\t\t} else {\n\t\t\t\t$prev = node;\n\t\t\t\tstack.push(node);\n\t\t\t}\n\n\t\t});\n\n\t\tif(found) {\n\t\t\treturn this.findTextStartRange(found, start, end);\n\t\t}\n\n\t}\n\n\t// Return last element\n\treturn this.findTextStartRange($prev, start, end);\n};\n\nMapping.prototype.findEnd = function(root, start, end){\n\tvar stack = [root];\n\tvar $el;\n\tvar $prev = root;\n\tvar found;\n\n\twhile (stack.length) {\n\n\t\t$el = stack.shift();\n\n\t\tfound = this.walk($el, function(node){\n\n\t\t\tvar left, right;\n\t\t\tvar elPos;\n\t\t\tvar elRange;\n\n\n\t\t\tif(node.nodeType == Node.TEXT_NODE){\n\t\t\t\telRange = document.createRange();\n\t\t\t\telRange.selectNodeContents(node);\n\t\t\t\telPos = elRange.getBoundingClientRect();\n\t\t\t} else {\n\t\t\t\telPos = node.getBoundingClientRect();\n\t\t\t}\n\n\t\t\tleft = elPos.left;\n\t\t\tright = elPos.right;\n\n\t\t\tif(left > end && $prev) {\n\t\t\t\treturn $prev;\n\t\t\t} else if(right > end) {\n\t\t\t\treturn node;\n\t\t\t} else {\n\t\t\t\t$prev = node;\n\t\t\t\tstack.push(node);\n\t\t\t}\n\n\t\t});\n\n\n\t\tif(found){\n\t\t\treturn this.findTextEndRange(found, start, end);\n\t\t}\n\n\t}\n\n\t// end of chapter\n\treturn this.findTextEndRange($prev, start, end);\n};\n\n\nMapping.prototype.findTextStartRange = function(node, start, end){\n\tvar ranges = this.splitTextNodeIntoRanges(node);\n\tvar prev;\n\tvar range;\n\tvar pos;\n\n\tfor (var i = 0; i < ranges.length; i++) {\n\t\trange = ranges[i];\n\n\t\tpos = range.getBoundingClientRect();\n\n\t\tif( pos.left >= start ) {\n\t\t\treturn range;\n\t\t}\n\n\t\tprev = range;\n\n\t}\n\n\treturn ranges[0];\n};\n\nMapping.prototype.findTextEndRange = function(node, start, end){\n\tvar ranges = this.splitTextNodeIntoRanges(node);\n\tvar prev;\n\tvar range;\n\tvar pos;\n\n\tfor (var i = 0; i < ranges.length; i++) {\n\t\trange = ranges[i];\n\n\t\tpos = range.getBoundingClientRect();\n\n\t\tif(pos.left > end && prev) {\n\t\t\treturn prev;\n\t\t} else if(pos.right > end) {\n\t\t\treturn range;\n\t\t}\n\n\t\tprev = range;\n\n\t}\n\n\t// Ends before limit\n\treturn ranges[ranges.length-1];\n\n};\n\nMapping.prototype.splitTextNodeIntoRanges = function(node, _splitter){\n\tvar ranges = [];\n\tvar textContent = node.textContent || \"\";\n\tvar text = textContent.trim();\n\tvar range;\n\tvar rect;\n\tvar list;\n\tvar doc = node.ownerDocument;\n\tvar splitter = _splitter || \" \";\n\n\tpos = text.indexOf(splitter);\n\n\tif(pos === -1 || node.nodeType != Node.TEXT_NODE) {\n\t\trange = doc.createRange();\n\t\trange.selectNodeContents(node);\n\t\treturn [range];\n\t}\n\n\trange = doc.createRange();\n\trange.setStart(node, 0);\n\trange.setEnd(node, pos);\n\tranges.push(range);\n\trange = false;\n\n\twhile ( pos != -1 ) {\n\n\t\tpos = text.indexOf(splitter, pos + 1);\n\t\tif(pos > 0) {\n\n\t\t\tif(range) {\n\t\t\t\trange.setEnd(node, pos);\n\t\t\t\tranges.push(range);\n\t\t\t}\n\n\t\t\trange = doc.createRange();\n\t\t\trange.setStart(node, pos+1);\n\t\t}\n\t}\n\n\tif(range) {\n\t\trange.setEnd(node, text.length);\n\t\tranges.push(range);\n\t}\n\n\treturn ranges;\n};\n\n\n\nMapping.prototype.rangePairToCfiPair = function(cfiBase, rangePair){\n\n\tvar startRange = rangePair.start;\n\tvar endRange = rangePair.end;\n\n\tstartRange.collapse(true);\n\tendRange.collapse(true);\n\n\t// startCfi = section.cfiFromRange(startRange);\n\t// endCfi = section.cfiFromRange(endRange);\n\tstartCfi = new EpubCFI(startRange, cfiBase).toString();\n\tendCfi = new EpubCFI(endRange, cfiBase).toString();\n\n\treturn {\n\t\tstart: startCfi,\n\t\tend: endCfi\n\t};\n\n};\n\nMapping.prototype.rangeListToCfiList = function(cfiBase, columns){\n\tvar map = [];\n\tvar rangePair, cifPair;\n\n\tfor (var i = 0; i < columns.length; i++) {\n\t\tcifPair = this.rangePairToCfiPair(cfiBase, columns[i]);\n\n\t\tmap.push(cifPair);\n\n\t}\n\n\treturn map;\n};\n\nmodule.exports = Mapping;\n","var core = require('./core');\nvar Parser = require('./parser');\nvar RSVP = require('rsvp');\nvar URI = require('urijs');\n\nfunction Navigation(_package, _request){\n\tvar navigation = this;\n\tvar parse = new Parser();\n\tvar request = _request || require('./request');\n\n\tthis.package = _package;\n\tthis.toc = [];\n\tthis.tocByHref = {};\n\tthis.tocById = {};\n\n\tif(_package.navPath) {\n\t\tthis.navUrl = URI(_package.navPath).absoluteTo(_package.baseUrl).toString();\n\t\tthis.nav = {};\n\n\t\tthis.nav.load = function(_request){\n\t\t\tvar loading = new RSVP.defer();\n\t\t\tvar loaded = loading.promise;\n\n\t\t\trequest(navigation.navUrl, 'xml').then(function(xml){\n\t\t\t\tnavigation.toc = parse.nav(xml);\n\t\t\t\tnavigation.loaded(navigation.toc);\n\t\t\t\tloading.resolve(navigation.toc);\n\t\t\t});\n\n\t\t\treturn loaded;\n\t\t};\n\n\t}\n\n\tif(_package.ncxPath) {\n\t\tthis.ncxUrl = URI(_package.ncxPath).absoluteTo(_package.baseUrl).toString();\n\t\tthis.ncx = {};\n\n\t\tthis.ncx.load = function(_request){\n\t\t\tvar loading = new RSVP.defer();\n\t\t\tvar loaded = loading.promise;\n\n\t\t\trequest(navigation.ncxUrl, 'xml').then(function(xml){\n\t\t\t\tnavigation.toc = parse.toc(xml);\n\t\t\t\tnavigation.loaded(navigation.toc);\n\t\t\t\tloading.resolve(navigation.toc);\n\t\t\t});\n\n\t\t\treturn loaded;\n\t\t};\n\n\t}\n};\n\n// Load the navigation\nNavigation.prototype.load = function(_request) {\n\tvar request = _request || require('./request');\n\tvar loading, loaded;\n\n\tif(this.nav) {\n\t\tloading = this.nav.load();\n\t} else if(this.ncx) {\n\t\tloading = this.ncx.load();\n\t} else {\n\t\tloaded = new RSVP.defer();\n\t\tloaded.resolve([]);\n\t\tloading = loaded.promise;\n\t}\n\n\treturn loading;\n\n};\n\nNavigation.prototype.loaded = function(toc) {\n\tvar item;\n\n\tfor (var i = 0; i < toc.length; i++) {\n\t\titem = toc[i];\n\t\tthis.tocByHref[item.href] = i;\n\t\tthis.tocById[item.id] = i;\n\t}\n\n};\n\n// Get an item from the navigation\nNavigation.prototype.get = function(target) {\n\tvar index;\n\n\tif(!target) {\n\t\treturn this.toc;\n\t}\n\n\tif(target.indexOf(\"#\") === 0) {\n\t\tindex = this.tocById[target.substring(1)];\n\t} else if(target in this.tocByHref){\n\t\tindex = this.tocByHref[target];\n\t}\n\n\treturn this.toc[index];\n};\n\nmodule.exports = Navigation;\n","var URI = require('urijs');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\n\n\nfunction Parser(){};\n\nParser.prototype.container = function(containerXml){\n\t\t//-- \n\t\tvar rootfile, fullpath, folder, encoding;\n\n\t\tif(!containerXml) {\n\t\t\tconsole.error(\"Container File Not Found\");\n\t\t\treturn;\n\t\t}\n\n\t\trootfile = core.qs(containerXml, \"rootfile\");\n\n\t\tif(!rootfile) {\n\t\t\tconsole.error(\"No RootFile Found\");\n\t\t\treturn;\n\t\t}\n\n\t\tfullpath = rootfile.getAttribute('full-path');\n\t\tfolder = URI(fullpath).directory();\n\t\tencoding = containerXml.xmlEncoding;\n\n\t\t//-- Now that we have the path we can parse the contents\n\t\treturn {\n\t\t\t'packagePath' : fullpath,\n\t\t\t'basePath' : folder,\n\t\t\t'encoding' : encoding\n\t\t};\n};\n\nParser.prototype.identifier = function(packageXml){\n\tvar metadataNode;\n\n\tif(!packageXml) {\n\t\tconsole.error(\"Package File Not Found\");\n\t\treturn;\n\t}\n\n\tmetadataNode = core.qs(packageXml, \"metadata\");\n\n\tif(!metadataNode) {\n\t\tconsole.error(\"No Metadata Found\");\n\t\treturn;\n\t}\n\n\treturn this.getElementText(metadataNode, \"identifier\");\n};\n\nParser.prototype.packageContents = function(packageXml){\n\tvar parse = this;\n\tvar metadataNode, manifestNode, spineNode;\n\tvar manifest, navPath, ncxPath, coverPath;\n\tvar spineNodeIndex;\n\tvar spine;\n\tvar spineIndexByURL;\n\tvar metadata;\n\n\tif(!packageXml) {\n\t\tconsole.error(\"Package File Not Found\");\n\t\treturn;\n\t}\n\n\tmetadataNode = core.qs(packageXml, \"metadata\");\n\tif(!metadataNode) {\n\t\tconsole.error(\"No Metadata Found\");\n\t\treturn;\n\t}\n\n\tmanifestNode = core.qs(packageXml, \"manifest\");\n\tif(!manifestNode) {\n\t\tconsole.error(\"No Manifest Found\");\n\t\treturn;\n\t}\n\n\tspineNode = core.qs(packageXml, \"spine\");\n\tif(!spineNode) {\n\t\tconsole.error(\"No Spine Found\");\n\t\treturn;\n\t}\n\n\tmanifest = parse.manifest(manifestNode);\n\tnavPath = parse.findNavPath(manifestNode);\n\tncxPath = parse.findNcxPath(manifestNode, spineNode);\n\tcoverPath = parse.findCoverPath(packageXml);\n\n\tspineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode);\n\n\tspine = parse.spine(spineNode, manifest);\n\n\tmetadata = parse.metadata(metadataNode);\n\n\tmetadata.direction = spineNode.getAttribute(\"page-progression-direction\");\n\n\treturn {\n\t\t'metadata' : metadata,\n\t\t'spine' : spine,\n\t\t'manifest' : manifest,\n\t\t'navPath' : navPath,\n\t\t'ncxPath' : ncxPath,\n\t\t'coverPath': coverPath,\n\t\t'spineNodeIndex' : spineNodeIndex\n\t};\n};\n\n//-- Find TOC NAV\nParser.prototype.findNavPath = function(manifestNode){\n\t// Find item with property 'nav'\n\t// Should catch nav irregardless of order\n\t// var node = manifestNode.querySelector(\"item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']\");\n\tvar node = core.qsp(manifestNode, \"item\", {\"properties\":\"nav\"});\n\treturn node ? node.getAttribute('href') : false;\n};\n\n//-- Find TOC NCX: media-type=\"application/x-dtbncx+xml\" href=\"toc.ncx\"\nParser.prototype.findNcxPath = function(manifestNode, spineNode){\n\t// var node = manifestNode.querySelector(\"item[media-type='application/x-dtbncx+xml']\");\n\tvar node = core.qsp(manifestNode, \"item\", {\"media-type\":\"application/x-dtbncx+xml\"});\n\tvar tocId;\n\n\t// If we can't find the toc by media-type then try to look for id of the item in the spine attributes as\n\t// according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2,\n\t// \"The item that describes the NCX must be referenced by the spine toc attribute.\"\n\tif (!node) {\n\t\ttocId = spineNode.getAttribute(\"toc\");\n\t\tif(tocId) {\n\t\t\t// node = manifestNode.querySelector(\"item[id='\" + tocId + \"']\");\n\t\t\tnode = manifestNode.getElementById(tocId);\n\t\t}\n\t}\n\n\treturn node ? node.getAttribute('href') : false;\n};\n\n//-- Expanded to match Readium web components\nParser.prototype.metadata = function(xml){\n\tvar metadata = {},\n\t\t\tp = this;\n\n\tmetadata.title = p.getElementText(xml, 'title');\n\tmetadata.creator = p.getElementText(xml, 'creator');\n\tmetadata.description = p.getElementText(xml, 'description');\n\n\tmetadata.pubdate = p.getElementText(xml, 'date');\n\n\tmetadata.publisher = p.getElementText(xml, 'publisher');\n\n\tmetadata.identifier = p.getElementText(xml, \"identifier\");\n\tmetadata.language = p.getElementText(xml, \"language\");\n\tmetadata.rights = p.getElementText(xml, \"rights\");\n\n\tmetadata.modified_date = p.getPropertyText(xml, 'dcterms:modified');\n\n\tmetadata.layout = p.getPropertyText(xml, \"rendition:layout\");\n\tmetadata.orientation = p.getPropertyText(xml, 'rendition:orientation');\n\tmetadata.flow = p.getPropertyText(xml, 'rendition:flow');\n\tmetadata.viewport = p.getPropertyText(xml, 'rendition:viewport');\n\t// metadata.page_prog_dir = packageXml.querySelector(\"spine\").getAttribute(\"page-progression-direction\");\n\n\treturn metadata;\n};\n\n//-- Find Cover: \n//-- Fallback for Epub 2.0\nParser.prototype.findCoverPath = function(packageXml){\n\tvar pkg = core.qs(packageXml, \"package\");\n\tvar epubVersion = pkg.getAttribute('version');\n\n\tif (epubVersion === '2.0') {\n\t\tvar metaCover = core.qsp(packageXml, 'meta', {'name':'cover'});\n\t\tif (metaCover) {\n\t\t\tvar coverId = metaCover.getAttribute('content');\n\t\t\t// var cover = packageXml.querySelector(\"item[id='\" + coverId + \"']\");\n\t\t\tvar cover = packageXml.getElementById(coverId);\n\t\t\treturn cover ? cover.getAttribute('href') : false;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\telse {\n\t\t// var node = packageXml.querySelector(\"item[properties='cover-image']\");\n\t\tvar node = core.qsp(packageXml, 'item', {'properties':'cover-image'});\n\t\treturn node ? node.getAttribute('href') : false;\n\t}\n};\n\nParser.prototype.getElementText = function(xml, tag){\n\tvar found = xml.getElementsByTagNameNS(\"http://purl.org/dc/elements/1.1/\", tag),\n\t\tel;\n\n\tif(!found || found.length === 0) return '';\n\n\tel = found[0];\n\n\tif(el.childNodes.length){\n\t\treturn el.childNodes[0].nodeValue;\n\t}\n\n\treturn '';\n\n};\n\nParser.prototype.getPropertyText = function(xml, property){\n\tvar el = core.qsp(xml, \"meta\", {\"property\":property});\n\n\tif(el && el.childNodes.length){\n\t\treturn el.childNodes[0].nodeValue;\n\t}\n\n\treturn '';\n};\n\nParser.prototype.querySelectorText = function(xml, q){\n\tvar el = xml.querySelector(q);\n\n\tif(el && el.childNodes.length){\n\t\treturn el.childNodes[0].nodeValue;\n\t}\n\n\treturn '';\n};\n\nParser.prototype.manifest = function(manifestXml){\n\tvar manifest = {};\n\n\t//-- Turn items into an array\n\t// var selected = manifestXml.querySelectorAll(\"item\");\n\tvar selected = core.qsa(manifestXml, \"item\");\n\tvar items = Array.prototype.slice.call(selected);\n\n\t//-- Create an object with the id as key\n\titems.forEach(function(item){\n\t\tvar id = item.getAttribute('id'),\n\t\t\t\thref = item.getAttribute('href') || '',\n\t\t\t\ttype = item.getAttribute('media-type') || '',\n\t\t\t\tproperties = item.getAttribute('properties') || '';\n\n\t\tmanifest[id] = {\n\t\t\t'href' : href,\n\t\t\t// 'url' : href,\n\t\t\t'type' : type,\n\t\t\t'properties' : properties.length ? properties.split(' ') : []\n\t\t};\n\n\t});\n\n\treturn manifest;\n\n};\n\nParser.prototype.spine = function(spineXml, manifest){\n\tvar spine = [];\n\n\tvar selected = spineXml.getElementsByTagName(\"itemref\"),\n\t\t\titems = Array.prototype.slice.call(selected);\n\n\tvar epubcfi = new EpubCFI();\n\n\t//-- Add to array to mantain ordering and cross reference with manifest\n\titems.forEach(function(item, index){\n\t\tvar idref = item.getAttribute('idref');\n\t\t// var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id);\n\t\tvar props = item.getAttribute('properties') || '';\n\t\tvar propArray = props.length ? props.split(' ') : [];\n\t\t// var manifestProps = manifest[Id].properties;\n\t\t// var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : [];\n\n\t\tvar itemref = {\n\t\t\t'idref' : idref,\n\t\t\t'linear' : item.getAttribute('linear') || '',\n\t\t\t'properties' : propArray,\n\t\t\t// 'href' : manifest[Id].href,\n\t\t\t// 'url' : manifest[Id].url,\n\t\t\t'index' : index\n\t\t\t// 'cfiBase' : cfiBase\n\t\t};\n\t\tspine.push(itemref);\n\t});\n\n\treturn spine;\n};\n\nParser.prototype.querySelectorByType = function(html, element, type){\n\tvar query;\n\tif (typeof html.querySelector != \"undefined\") {\n\t\tquery = html.querySelector(element+'[*|type=\"'+type+'\"]');\n\t}\n\t// Handle IE not supporting namespaced epub:type in querySelector\n\tif(!query || query.length === 0) {\n\t\tquery = core.qsa(html, element);\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tif(query[i].getAttributeNS(\"http://www.idpf.org/2007/ops\", \"type\") === type) {\n\t\t\t\treturn query[i];\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn query;\n\t}\n};\n\nParser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){\n\tvar navElement = this.querySelectorByType(navHtml, \"nav\", \"toc\");\n\t// var navItems = navElement ? navElement.querySelectorAll(\"ol li\") : [];\n\tvar navItems = navElement ? core.qsa(navElement, \"li\") : [];\n\tvar length = navItems.length;\n\tvar i;\n\tvar toc = {};\n\tvar list = [];\n\tvar item, parent;\n\n\tif(!navItems || length === 0) return list;\n\n\tfor (i = 0; i < length; ++i) {\n\t\titem = this.navItem(navItems[i], spineIndexByURL, bookSpine);\n\t\ttoc[item.id] = item;\n\t\tif(!item.parent) {\n\t\t\tlist.push(item);\n\t\t} else {\n\t\t\tparent = toc[item.parent];\n\t\t\tparent.subitems.push(item);\n\t\t}\n\t}\n\n\treturn list;\n};\n\nParser.prototype.navItem = function(item, spineIndexByURL, bookSpine){\n\tvar id = item.getAttribute('id') || false,\n\t\t\t// content = item.querySelector(\"a, span\"),\n\t\t\tcontent = core.qs(item, \"a\"),\n\t\t\tsrc = content.getAttribute('href') || '',\n\t\t\ttext = content.textContent || \"\",\n\t\t\t// split = src.split(\"#\"),\n\t\t\t// baseUrl = split[0],\n\t\t\t// spinePos = spineIndexByURL[baseUrl],\n\t\t\t// spineItem = bookSpine[spinePos],\n\t\t\tsubitems = [],\n\t\t\tparentNode = item.parentNode,\n\t\t\tparent;\n\t\t\t// cfi = spineItem ? spineItem.cfi : '';\n\n\tif(parentNode && parentNode.nodeName === \"navPoint\") {\n\t\tparent = parentNode.getAttribute('id');\n\t}\n\n\t/*\n\tif(!id) {\n\t\tif(spinePos) {\n\t\t\tspineItem = bookSpine[spinePos];\n\t\t\tid = spineItem.id;\n\t\t\tcfi = spineItem.cfi;\n\t\t} else {\n\t\t\tid = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid();\n\t\t\titem.setAttribute('id', id);\n\t\t}\n\t}\n\t*/\n\n\treturn {\n\t\t\"id\": id,\n\t\t\"href\": src,\n\t\t\"label\": text,\n\t\t\"subitems\" : subitems,\n\t\t\"parent\" : parent\n\t};\n};\n\nParser.prototype.ncx = function(tocXml, spineIndexByURL, bookSpine){\n\t// var navPoints = tocXml.querySelectorAll(\"navMap navPoint\");\n\tvar navPoints = core.qsa(tocXml, \"navPoint\");\n\tvar length = navPoints.length;\n\tvar i;\n\tvar toc = {};\n\tvar list = [];\n\tvar item, parent;\n\n\tif(!navPoints || length === 0) return list;\n\n\tfor (i = 0; i < length; ++i) {\n\t\titem = this.ncxItem(navPoints[i], spineIndexByURL, bookSpine);\n\t\ttoc[item.id] = item;\n\t\tif(!item.parent) {\n\t\t\tlist.push(item);\n\t\t} else {\n\t\t\tparent = toc[item.parent];\n\t\t\tparent.subitems.push(item);\n\t\t}\n\t}\n\n\treturn list;\n};\n\nParser.prototype.ncxItem = function(item, spineIndexByURL, bookSpine){\n\tvar id = item.getAttribute('id') || false,\n\t\t\t// content = item.querySelector(\"content\"),\n\t\t\tcontent = core.qs(item, \"content\"),\n\t\t\tsrc = content.getAttribute('src'),\n\t\t\t// navLabel = item.querySelector(\"navLabel\"),\n\t\t\tnavLabel = core.qs(item, \"navLabel\"),\n\t\t\ttext = navLabel.textContent ? navLabel.textContent : \"\",\n\t\t\t// split = src.split(\"#\"),\n\t\t\t// baseUrl = split[0],\n\t\t\t// spinePos = spineIndexByURL[baseUrl],\n\t\t\t// spineItem = bookSpine[spinePos],\n\t\t\tsubitems = [],\n\t\t\tparentNode = item.parentNode,\n\t\t\tparent;\n\t\t\t// cfi = spineItem ? spineItem.cfi : '';\n\n\tif(parentNode && parentNode.nodeName === \"navPoint\") {\n\t\tparent = parentNode.getAttribute('id');\n\t}\n\n\t/*\n\tif(!id) {\n\t\tif(spinePos) {\n\t\t\tspineItem = bookSpine[spinePos];\n\t\t\tid = spineItem.id;\n\t\t\tcfi = spineItem.cfi;\n\t\t} else {\n\t\t\tid = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid();\n\t\t\titem.setAttribute('id', id);\n\t\t}\n\t}\n\t*/\n\n\treturn {\n\t\t\"id\": id,\n\t\t\"href\": src,\n\t\t\"label\": text,\n\t\t\"subitems\" : subitems,\n\t\t\"parent\" : parent\n\t};\n};\n\nParser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){\n\tvar navElement = this.querySelectorByType(navHtml, \"nav\", \"page-list\");\n\t// var navItems = navElement ? navElement.querySelectorAll(\"ol li\") : [];\n\tvar navItems = navElement ? core.qsa(navElement, \"li\") : [];\n\tvar length = navItems.length;\n\tvar i;\n\tvar toc = {};\n\tvar list = [];\n\tvar item;\n\n\tif(!navItems || length === 0) return list;\n\n\tfor (i = 0; i < length; ++i) {\n\t\titem = this.pageListItem(navItems[i], spineIndexByURL, bookSpine);\n\t\tlist.push(item);\n\t}\n\n\treturn list;\n};\n\nParser.prototype.pageListItem = function(item, spineIndexByURL, bookSpine){\n\tvar id = item.getAttribute('id') || false,\n\t\t// content = item.querySelector(\"a\"),\n\t\tcontent = core.qs(item, \"a\"),\n\t\thref = content.getAttribute('href') || '',\n\t\ttext = content.textContent || \"\",\n\t\tpage = parseInt(text),\n\t\tisCfi = href.indexOf(\"epubcfi\"),\n\t\tsplit,\n\t\tpackageUrl,\n\t\tcfi;\n\n\tif(isCfi != -1) {\n\t\tsplit = href.split(\"#\");\n\t\tpackageUrl = split[0];\n\t\tcfi = split.length > 1 ? split[1] : false;\n\t\treturn {\n\t\t\t\"cfi\" : cfi,\n\t\t\t\"href\" : href,\n\t\t\t\"packageUrl\" : packageUrl,\n\t\t\t\"page\" : page\n\t\t};\n\t} else {\n\t\treturn {\n\t\t\t\"href\" : href,\n\t\t\t\"page\" : page\n\t\t};\n\t}\n};\n\nmodule.exports = Parser;\n","var RSVP = require('rsvp');\nvar core = require('./core');\n\nfunction Queue(_context){\n\tthis._q = [];\n\tthis.context = _context;\n\tthis.tick = core.requestAnimationFrame;\n\tthis.running = false;\n\tthis.paused = false;\n};\n\n// Add an item to the queue\nQueue.prototype.enqueue = function() {\n\tvar deferred, promise;\n\tvar queued;\n\tvar task = [].shift.call(arguments);\n\tvar args = arguments;\n\n\t// Handle single args without context\n\t// if(args && !Array.isArray(args)) {\n\t// args = [args];\n\t// }\n\tif(!task) {\n\t\treturn console.error(\"No Task Provided\");\n\t}\n\n\tif(typeof task === \"function\"){\n\n\t\tdeferred = new RSVP.defer();\n\t\tpromise = deferred.promise;\n\n\t\tqueued = {\n\t\t\t\"task\" : task,\n\t\t\t\"args\" : args,\n\t\t\t//\"context\" : context,\n\t\t\t\"deferred\" : deferred,\n\t\t\t\"promise\" : promise\n\t\t};\n\n\t} else {\n\t\t// Task is a promise\n\t\tqueued = {\n\t\t\t\"promise\" : task\n\t\t};\n\n\t}\n\n\tthis._q.push(queued);\n\n\t// Wait to start queue flush\n\tif (this.paused == false && !this.running) {\n\t\t// setTimeout(this.flush.bind(this), 0);\n\t\t// this.tick.call(window, this.run.bind(this));\n\t\tthis.run();\n\t}\n\n\treturn queued.promise;\n};\n\n// Run one item\nQueue.prototype.dequeue = function(){\n\tvar inwait, task, result;\n\n\tif(this._q.length) {\n\t\tinwait = this._q.shift();\n\t\ttask = inwait.task;\n\t\tif(task){\n\t\t\t// console.log(task)\n\n\t\t\tresult = task.apply(this.context, inwait.args);\n\n\t\t\tif(result && typeof result[\"then\"] === \"function\") {\n\t\t\t\t// Task is a function that returns a promise\n\t\t\t\treturn result.then(function(){\n\t\t\t\t\tinwait.deferred.resolve.apply(this.context, arguments);\n\t\t\t\t}.bind(this));\n\t\t\t} else {\n\t\t\t\t// Task resolves immediately\n\t\t\t\tinwait.deferred.resolve.apply(this.context, result);\n\t\t\t\treturn inwait.promise;\n\t\t\t}\n\n\n\n\t\t} else if(inwait.promise) {\n\t\t\t// Task is a promise\n\t\t\treturn inwait.promise;\n\t\t}\n\n\t} else {\n\t\tinwait = new RSVP.defer();\n\t\tinwait.deferred.resolve();\n\t\treturn inwait.promise;\n\t}\n\n};\n\n// Run All Immediately\nQueue.prototype.dump = function(){\n\twhile(this._q.length) {\n\t\tthis.dequeue();\n\t}\n};\n\n// Run all sequentially, at convince\n\nQueue.prototype.run = function(){\n\n\tif(!this.running){\n\t\tthis.running = true;\n\t\tthis.defered = new RSVP.defer();\n\t}\n\n\tthis.tick.call(window, function() {\n\n\t\tif(this._q.length) {\n\n\t\t\tthis.dequeue()\n\t\t\t\t.then(function(){\n\t\t\t\t\tthis.run();\n\t\t\t\t}.bind(this));\n\n\t\t} else {\n\t\t\tthis.defered.resolve();\n\t\t\tthis.running = undefined;\n\t\t}\n\n\t}.bind(this));\n\n\t// Unpause\n\tif(this.paused == true) {\n\t\tthis.paused = false;\n\t}\n\n\treturn this.defered.promise;\n};\n\n// Flush all, as quickly as possible\nQueue.prototype.flush = function(){\n\n\tif(this.running){\n\t\treturn this.running;\n\t}\n\n\tif(this._q.length) {\n\t\tthis.running = this.dequeue()\n\t\t\t.then(function(){\n\t\t\t\tthis.running = undefined;\n\t\t\t\treturn this.flush();\n\t\t\t}.bind(this));\n\n\t\treturn this.running;\n\t}\n\n};\n\n// Clear all items in wait\nQueue.prototype.clear = function(){\n\tthis._q = [];\n\tthis.running = false;\n};\n\nQueue.prototype.length = function(){\n\treturn this._q.length;\n};\n\nQueue.prototype.pause = function(){\n\tthis.paused = true;\n};\n\n// Create a new task from a callback\nfunction Task(task, args, context){\n\n\treturn function(){\n\t\tvar toApply = arguments || [];\n\n\t\treturn new RSVP.Promise(function(resolve, reject) {\n\t\t\tvar callback = function(value){\n\t\t\t\tresolve(value);\n\t\t\t};\n\t\t\t// Add the callback to the arguments list\n\t\t\ttoApply.push(callback);\n\n\t\t\t// Apply all arguments to the functions\n\t\t\ttask.apply(this, toApply);\n\n\t}.bind(this));\n\n\t};\n\n};\n\nmodule.exports = Queue;\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar replace = require('./replacements');\nvar Hook = require('./hook');\nvar EpubCFI = require('./epubcfi');\nvar Queue = require('./queue');\n// var View = require('./view');\nvar Views = require('./views');\nvar Layout = require('./layout');\nvar Mapping = require('./mapping');\n\nfunction Rendition(book, options) {\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\twidth: null,\n\t\theight: null,\n\t\tignoreClass: '',\n\t\tmanager: \"single\",\n\t\tview: \"iframe\",\n\t\tflow: null,\n\t\tlayout: null,\n\t\tspread: null,\n\t\tminSpreadWidth: 800, //-- overridden by spread: none (never) / both (always),\n\t\tuseBase64: true\n\t});\n\n\tcore.extend(this.settings, options);\n\n\tthis.viewSettings = {\n\t\tignoreClass: this.settings.ignoreClass\n\t};\n\n\tthis.book = book;\n\n\tthis.views = null;\n\n\t//-- Adds Hook methods to the Rendition prototype\n\tthis.hooks = {};\n\tthis.hooks.display = new Hook(this);\n\tthis.hooks.serialize = new Hook(this);\n\tthis.hooks.content = new Hook(this);\n\tthis.hooks.layout = new Hook(this);\n\tthis.hooks.render = new Hook(this);\n\tthis.hooks.show = new Hook(this);\n\n\tthis.hooks.content.register(replace.links.bind(this));\n\tthis.hooks.content.register(this.passViewEvents.bind(this));\n\n\t// this.hooks.display.register(this.afterDisplay.bind(this));\n\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.q = new Queue(this);\n\n\tthis.q.enqueue(this.book.opened);\n\n\t// Block the queue until rendering is started\n\t// this.starting = new RSVP.defer();\n\t// this.started = this.starting.promise;\n\tthis.q.enqueue(this.start);\n\n\tif(this.book.unarchived) {\n\t\tthis.q.enqueue(this.replacements.bind(this));\n\t}\n\n};\n\nRendition.prototype.setManager = function(manager) {\n\tthis.manager = manager;\n};\n\nRendition.prototype.requireManager = function(manager) {\n\tvar viewManager;\n\n\t// If manager is a string, try to load from register managers,\n\t// or require included managers directly\n\tif (typeof manager === \"string\") {\n\t\t// Use global or require\n\t\tviewManager = typeof ePub != \"undefined\" ? ePub.ViewManagers[manager] : undefined; //require('./managers/'+manager);\n\t} else {\n\t\t// otherwise, assume we were passed a function\n\t\tviewManager = manager\n\t}\n\n\treturn viewManager;\n};\n\nRendition.prototype.requireView = function(view) {\n\tvar View;\n\n\tif (typeof view == \"string\") {\n\t\tView = typeof ePub != \"undefined\" ? ePub.Views[view] : undefined; //require('./views/'+view);\n\t} else {\n\t\t// otherwise, assume we were passed a function\n\t\tView = view\n\t}\n\n\treturn View;\n};\n\nRendition.prototype.start = function(){\n\n\tif(!this.manager) {\n\t\tthis.ViewManager = this.requireManager(this.settings.manager);\n\t\tthis.View = this.requireView(this.settings.view);\n\n\t\tthis.manager = new this.ViewManager({\n\t\t\tview: this.View,\n\t\t\tqueue: this.q,\n\t\t\trequest: this.book.request,\n\t\t\tsettings: this.settings\n\t\t});\n\t}\n\n\t// Parse metadata to get layout props\n\tthis.settings.globalLayoutProperties = this.determineLayoutProperties(this.book.package.metadata);\n\n\tthis.flow(this.settings.globalLayoutProperties.flow);\n\n\tthis.layout(this.settings.globalLayoutProperties);\n\n\t// Listen for displayed views\n\tthis.manager.on(\"added\", this.afterDisplayed.bind(this));\n\n\t// Listen for resizing\n\tthis.manager.on(\"resized\", this.onResized.bind(this));\n\n\t// Listen for scroll changes\n\tthis.manager.on(\"scroll\", this.reportLocation.bind(this));\n\n\n\tthis.on('displayed', this.reportLocation.bind(this));\n\n\t// Trigger that rendering has started\n\tthis.trigger(\"started\");\n\n\t// Start processing queue\n\t// this.starting.resolve();\n};\n\n// Call to attach the container to an element in the dom\n// Container must be attached before rendering can begin\nRendition.prototype.attachTo = function(element){\n\n\treturn this.q.enqueue(function () {\n\n\t\t// Start rendering\n\t\tthis.manager.render(element, {\n\t\t\t\"width\" : this.settings.width,\n\t\t\t\"height\" : this.settings.height\n\t\t});\n\n\t\t// Trigger Attached\n\t\tthis.trigger(\"attached\");\n\n\t}.bind(this));\n\n};\n\nRendition.prototype.display = function(target){\n\n\t// if (!this.book.spine.spineItems.length > 0) {\n\t\t// Book isn't open yet\n\t\t// return this.q.enqueue(this.display, target);\n\t// }\n\n\treturn this.q.enqueue(this._display, target);\n\n};\n\nRendition.prototype._display = function(target){\n\tvar isCfiString = this.epubcfi.isCfiString(target);\n\tvar displaying = new RSVP.defer();\n\tvar displayed = displaying.promise;\n\tvar section;\n\tvar moveTo;\n\n\tsection = this.book.spine.get(target);\n\n\tif(!section){\n\t\tdisplaying.reject(new Error(\"No Section Found\"));\n\t\treturn displayed;\n\t}\n\n\t// Trim the target fragment\n\t// removing the chapter\n\tif(!isCfiString && typeof target === \"string\" &&\n\t\ttarget.indexOf(\"#\") > -1) {\n\t\t\tmoveTo = target.substring(target.indexOf(\"#\")+1);\n\t}\n\n\tif (isCfiString) {\n\t\tmoveTo = target;\n\t}\n\n\treturn this.manager.display(section, moveTo)\n\t\t.then(function(){\n\t\t\tthis.trigger(\"displayed\", section);\n\t\t}.bind(this));\n\n};\n\n/*\nRendition.prototype.render = function(view, show) {\n\n\t// view.onLayout = this.layout.format.bind(this.layout);\n\tview.create();\n\n\t// Fit to size of the container, apply padding\n\tthis.manager.resizeView(view);\n\n\t// Render Chain\n\treturn view.section.render(this.book.request)\n\t\t.then(function(contents){\n\t\t\treturn view.load(contents);\n\t\t}.bind(this))\n\t\t.then(function(doc){\n\t\t\treturn this.hooks.content.trigger(view, this);\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\tthis.layout.format(view.contents);\n\t\t\treturn this.hooks.layout.trigger(view, this);\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\treturn view.display();\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\treturn this.hooks.render.trigger(view, this);\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\tif(show !== false) {\n\t\t\t\tthis.q.enqueue(function(view){\n\t\t\t\t\tview.show();\n\t\t\t\t}, view);\n\t\t\t}\n\t\t\t// this.map = new Map(view, this.layout);\n\t\t\tthis.hooks.show.trigger(view, this);\n\t\t\tthis.trigger(\"rendered\", view.section);\n\n\t\t}.bind(this))\n\t\t.catch(function(e){\n\t\t\tthis.trigger(\"loaderror\", e);\n\t\t}.bind(this));\n\n};\n*/\n\nRendition.prototype.afterDisplayed = function(view){\n\tthis.hooks.content.trigger(view, this);\n\tthis.trigger(\"rendered\", view.section);\n\tthis.reportLocation();\n};\n\nRendition.prototype.onResized = function(size){\n\n\tif(this.location) {\n\t\tthis.display(this.location.start);\n\t}\n\n\tthis.trigger(\"resized\", {\n\t\twidth: size.width,\n\t\theight: size.height\n\t});\n\n};\n\nRendition.prototype.moveTo = function(offset){\n\tthis.manager.moveTo(offset);\n};\n\nRendition.prototype.next = function(){\n\treturn this.q.enqueue(this.manager.next.bind(this.manager))\n\t\t.then(this.reportLocation.bind(this));\n};\n\nRendition.prototype.prev = function(){\n\treturn this.q.enqueue(this.manager.prev.bind(this.manager))\n\t\t.then(this.reportLocation.bind(this));\n};\n\n//-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering\nRendition.prototype.determineLayoutProperties = function(metadata){\n\tvar settings;\n\tvar layout = this.settings.layout || metadata.layout || \"reflowable\";\n\tvar spread = this.settings.spread || metadata.spread || \"auto\";\n\tvar orientation = this.settings.orientation || metadata.orientation || \"auto\";\n\tvar flow = this.settings.flow || metadata.flow || \"auto\";\n\tvar viewport = metadata.viewport || \"\";\n\tvar minSpreadWidth = this.settings.minSpreadWidth || metadata.minSpreadWidth || 800;\n\n\tif (this.settings.width >= 0 && this.settings.height >= 0) {\n\t\tviewport = \"width=\"+this.settings.width+\", height=\"+this.settings.height+\"\";\n\t}\n\n\tsettings = {\n\t\tlayout : layout,\n\t\tspread : spread,\n\t\torientation : orientation,\n\t\tflow : flow,\n\t\tviewport : viewport,\n\t\tminSpreadWidth : minSpreadWidth\n\t};\n\n\treturn settings;\n};\n\n// Rendition.prototype.applyLayoutProperties = function(){\n// \tvar settings = this.determineLayoutProperties(this.book.package.metadata);\n//\n// \tthis.flow(settings.flow);\n//\n// \tthis.layout(settings);\n// };\n\n// paginated | scrolled\n// (scrolled-continuous vs scrolled-doc are handled by different view managers)\nRendition.prototype.flow = function(_flow){\n\tvar flow;\n\tif (_flow === \"scrolled-doc\" || _flow === \"scrolled-continuous\") {\n\t\tflow = \"scrolled\";\n\t}\n\n\tif (_flow === \"auto\" || _flow === \"paginated\") {\n\t\tflow = \"paginated\";\n\t}\n\n\tif (this._layout) {\n\t\tthis._layout.flow(flow);\n\t}\n\n\tif (this.manager) {\n\t\tthis.manager.updateFlow(flow);\n\t}\n};\n\n// reflowable | pre-paginated\nRendition.prototype.layout = function(settings){\n\tif (settings) {\n\t\tthis._layout = new Layout(settings);\n\t\tthis._layout.spread(settings.spread, this.settings.minSpreadWidth);\n\n\t\tthis.mapping = new Mapping(this._layout);\n\t}\n\n\tif (this.manager && this._layout) {\n\t\tthis.manager.applyLayout(this._layout);\n\t}\n\n\treturn this._layout;\n};\n\n// none | auto (TODO: implement landscape, portrait, both)\nRendition.prototype.spread = function(spread, min){\n\n\tthis._layout.spread(spread, min);\n\n\tif (this.manager.isRendered()) {\n\t\tthis.manager.updateLayout();\n\t}\n};\n\n\nRendition.prototype.reportLocation = function(){\n\treturn this.q.enqueue(function(){\n\t\tvar location = this.manager.currentLocation();\n\t\tif (location && location.then && typeof location.then === 'function') {\n\t\t\tlocation.then(function(result) {\n\t\t\t\tthis.location = result;\n\t\t\t\tthis.trigger(\"locationChanged\", this.location);\n\t\t\t}.bind(this));\n\t\t} else if (location) {\n\t\t\tthis.location = location;\n\t\t\tthis.trigger(\"locationChanged\", this.location);\n\t\t}\n\n\t}.bind(this));\n};\n\n\nRendition.prototype.destroy = function(){\n\t// Clear the queue\n\tthis.q.clear();\n\n\tthis.views.clear();\n\n\tclearTimeout(this.trimTimeout);\n\tif(this.settings.hidden) {\n\t\tthis.element.removeChild(this.wrapper);\n\t} else {\n\t\tthis.element.removeChild(this.container);\n\t}\n\n};\n\nRendition.prototype.passViewEvents = function(view){\n\tview.contents.listenedEvents.forEach(function(e){\n\t\tview.on(e, this.triggerViewEvent.bind(this));\n\t}.bind(this));\n\n\tview.on(\"selected\", this.triggerSelectedEvent.bind(this));\n};\n\nRendition.prototype.triggerViewEvent = function(e){\n\tthis.trigger(e.type, e);\n};\n\nRendition.prototype.triggerSelectedEvent = function(cfirange){\n\tthis.trigger(\"selected\", cfirange);\n};\n\nRendition.prototype.replacements = function(){\n\t// Wait for loading\n\t// return this.q.enqueue(function () {\n\t\t// Get thes books manifest\n\t\tvar manifest = this.book.package.manifest;\n\t\tvar manifestArray = Object.keys(manifest).\n\t\t\tmap(function (key){\n\t\t\t\treturn manifest[key];\n\t\t\t});\n\n\t\t// Exclude HTML\n\t\tvar items = manifestArray.\n\t\t\tfilter(function (item){\n\t\t\t\tif (item.type != \"application/xhtml+xml\" &&\n\t\t\t\t\t\titem.type != \"text/html\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Only CSS\n\t\tvar css = items.\n\t\t\tfilter(function (item){\n\t\t\t\tif (item.type === \"text/css\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Css Urls\n\t\tvar cssUrls = css.map(function(item) {\n\t\t\treturn item.href;\n\t\t});\n\n\t\t// All Assets Urls\n\t\tvar urls = items.\n\t\t\tmap(function(item) {\n\t\t\t\treturn item.href;\n\t\t\t}.bind(this));\n\n\t\t// Create blob urls for all the assets\n\t\tvar processing = urls.\n\t\t\tmap(function(url) {\n\t\t\t\tvar absolute = URI(url).absoluteTo(this.book.baseUrl).toString();\n\t\t\t\t// Full url from archive base\n\t\t\t\treturn this.book.unarchived.createUrl(absolute, {\"base64\": this.settings.useBase64});\n\t\t\t}.bind(this));\n\n\t\tvar replacementUrls;\n\n\t\t// After all the urls are created\n\t\treturn RSVP.all(processing)\n\t\t\t.then(function(_replacementUrls) {\n\t\t\t\tvar replaced = [];\n\n\t\t\t\treplacementUrls = _replacementUrls;\n\n\t\t\t\t// Replace Asset Urls in the text of all css files\n\t\t\t\tcssUrls.forEach(function(href) {\n\t\t\t\t\treplaced.push(this.replaceCss(href, urls, replacementUrls));\n\t\t\t\t}.bind(this));\n\n\t\t\t\treturn RSVP.all(replaced);\n\n\t\t\t}.bind(this))\n\t\t\t.then(function () {\n\t\t\t\t// Replace Asset Urls in chapters\n\t\t\t\t// by registering a hook after the sections contents has been serialized\n\t\t\t\tthis.book.spine.hooks.serialize.register(function(output, section) {\n\n\t\t\t\t\tthis.replaceAssets(section, urls, replacementUrls);\n\n\t\t\t\t}.bind(this));\n\n\t\t\t}.bind(this))\n\t\t\t.catch(function(reason){\n\t\t\t\tconsole.error(reason);\n\t\t\t});\n\t// }.bind(this));\n};\n\nRendition.prototype.replaceCss = function(href, urls, replacementUrls){\n\t\tvar newUrl;\n\t\tvar indexInUrls;\n\n\t\t// Find the absolute url of the css file\n\t\tvar fileUri = URI(href);\n\t\tvar absolute = fileUri.absoluteTo(this.book.baseUrl).toString();\n\t\t// Get the text of the css file from the archive\n\t\tvar textResponse = this.book.unarchived.getText(absolute);\n\t\t// Get asset links relative to css file\n\t\tvar relUrls = urls.\n\t\t\tmap(function(assetHref) {\n\t\t\t\tvar assetUri = URI(assetHref).absoluteTo(this.book.baseUrl);\n\t\t\t\tvar relative = assetUri.relativeTo(absolute).toString();\n\t\t\t\treturn relative;\n\t\t\t}.bind(this));\n\n\t\treturn textResponse.then(function (text) {\n\t\t\t// Replacements in the css text\n\t\t\ttext = replace.substitute(text, relUrls, replacementUrls);\n\n\t\t\t// Get the new url\n\t\t\tif (this.settings.useBase64) {\n\t\t\t\tnewUrl = core.createBase64Url(text, 'text/css');\n\t\t\t} else {\n\t\t\t\tnewUrl = core.createBlobUrl(text, 'text/css');\n\t\t\t}\n\n\t\t\t// switch the url in the replacementUrls\n\t\t\tindexInUrls = urls.indexOf(href);\n\t\t\tif (indexInUrls > -1) {\n\t\t\t\treplacementUrls[indexInUrls] = newUrl;\n\t\t\t}\n\n\t\t\treturn new RSVP.Promise(function(resolve, reject){\n\t\t\t\tresolve(urls, replacementUrls);\n\t\t\t});\n\n\t\t}.bind(this));\n\n};\n\nRendition.prototype.replaceAssets = function(section, urls, replacementUrls){\n\tvar fileUri = URI(section.url);\n\t// Get Urls relative to current sections\n\tvar relUrls = urls.\n\t\tmap(function(href) {\n\t\t\tvar assetUri = URI(href).absoluteTo(this.book.baseUrl);\n\t\t\tvar relative = assetUri.relativeTo(fileUri).toString();\n\t\t\treturn relative;\n\t\t}.bind(this));\n\n\n\tsection.output = replace.substitute(section.output, relUrls, replacementUrls);\n};\n\nRendition.prototype.range = function(_cfi, ignoreClass){\n\tvar cfi = new EpubCFI(_cfi);\n\tvar found = this.visible().filter(function (view) {\n\t\tif(cfi.spinePos === view.index) return true;\n\t});\n\n\t// Should only every return 1 item\n\tif (found.length) {\n\t\treturn found[0].range(cfi, ignoreClass);\n\t}\n};\n\nRendition.prototype.adjustImages = function(view) {\n\n\tview.addStylesheetRules([\n\t\t\t[\"img\",\n\t\t\t\t[\"max-width\", (view.layout.spreadWidth) + \"px\"],\n\t\t\t\t[\"max-height\", (view.layout.height) + \"px\"]\n\t\t\t]\n\t]);\n\treturn new RSVP.Promise(function(resolve, reject){\n\t\t// Wait to apply\n\t\tsetTimeout(function() {\n\t\t\tresolve();\n\t\t}, 1);\n\t});\n};\n\n//-- Enable binding events to Renderer\nRSVP.EventTarget.mixin(Rendition.prototype);\n\nmodule.exports = Rendition;\n","var URI = require('urijs');\nvar core = require('./core');\n\nfunction base(doc, section){\n\tvar base;\n\tvar head;\n\n\tif(!doc){\n\t\treturn;\n\t}\n\n\t// head = doc.querySelector(\"head\");\n\t// base = head.querySelector(\"base\");\n\thead = core.qs(doc, \"head\");\n\tbase = core.qs(head, \"base\");\n\n\tif(!base) {\n\t\tbase = doc.createElement(\"base\");\n\t\thead.insertBefore(base, head.firstChild);\n\t}\n\n\tbase.setAttribute(\"href\", section.url);\n}\n\nfunction canonical(doc, section){\n\tvar head;\n\tvar link;\n\tvar url = section.url; // window.location.origin + window.location.pathname + \"?loc=\" + encodeURIComponent(section.url);\n\n\tif(!doc){\n\t\treturn;\n\t}\n\n\thead = core.qs(doc, \"head\");\n\tlink = core.qs(head, \"link[rel='canonical']\");\n\n\tif (link) {\n\t\tlink.setAttribute(\"href\", url);\n\t} else {\n\t\tlink = doc.createElement(\"link\");\n\t\tlink.setAttribute(\"rel\", \"canonical\");\n\t\tlink.setAttribute(\"href\", url);\n\t\thead.appendChild(link);\n\t}\n}\n\nfunction links(view, renderer) {\n\n\tvar links = view.document.querySelectorAll(\"a[href]\");\n\tvar replaceLinks = function(link){\n\t\tvar href = link.getAttribute(\"href\");\n\n\t\tif(href.indexOf(\"mailto:\") === 0){\n\t\t\treturn;\n\t\t}\n\n\t\tvar linkUri = URI(href);\n\t\tvar absolute = linkUri.absoluteTo(view.section.url);\n\t\tvar relative = absolute.relativeTo(this.book.baseUrl).toString();\n\n\t\tif(linkUri.protocol()){\n\n\t\t\tlink.setAttribute(\"target\", \"_blank\");\n\n\t\t}else{\n\t\t\t/*\n\t\t\tif(baseDirectory) {\n\t\t\t\t// We must ensure that the file:// protocol is preserved for\n\t\t\t\t// local file links, as in certain contexts (such as under\n\t\t\t\t// Titanium), file links without the file:// protocol will not\n\t\t\t\t// work\n\t\t\t\tif (baseUri.protocol === \"file\") {\n\t\t\t\t\trelative = core.resolveUrl(baseUri.base, href);\n\t\t\t\t} else {\n\t\t\t\t\trelative = core.resolveUrl(baseDirectory, href);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trelative = href;\n\t\t\t}\n\t\t\t*/\n\n\t\t\tif(linkUri.fragment()) {\n\t\t\t\t// do nothing with fragment yet\n\t\t\t} else {\n\t\t\t\tlink.onclick = function(){\n\t\t\t\t\trenderer.display(relative);\n\t\t\t\t\treturn false;\n\t\t\t\t};\n\t\t\t}\n\n\t\t}\n\t}.bind(this);\n\n\tfor (var i = 0; i < links.length; i++) {\n\t\treplaceLinks(links[i]);\n\t}\n\n\n};\n\nfunction substitute(content, urls, replacements) {\n\turls.forEach(function(url, i){\n\t\tif (url && replacements[i]) {\n\t\t\tcontent = content.replace(new RegExp(url, 'g'), replacements[i]);\n\t\t}\n\t});\n\treturn content;\n}\nmodule.exports = {\n\t'base': base,\n\t'canonical' : canonical,\n\t'links': links,\n\t'substitute': substitute\n};\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\n\nfunction request(url, type, withCredentials, headers) {\n\tvar supportsURL = (typeof window != \"undefined\") ? window.URL : false; // TODO: fallback for url if window isn't defined\n\tvar BLOB_RESPONSE = supportsURL ? \"blob\" : \"arraybuffer\";\n\tvar uri;\n\n\tvar deferred = new RSVP.defer();\n\n\tvar xhr = new XMLHttpRequest();\n\n\t//-- Check from PDF.js:\n\t// https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js\n\tvar xhrPrototype = XMLHttpRequest.prototype;\n\n\tvar header;\n\n\tif (!('overrideMimeType' in xhrPrototype)) {\n\t\t// IE10 might have response, but not overrideMimeType\n\t\tObject.defineProperty(xhrPrototype, 'overrideMimeType', {\n\t\t\tvalue: function xmlHttpRequestOverrideMimeType(mimeType) {}\n\t\t});\n\t}\n\tif(withCredentials) {\n\t\txhr.withCredentials = true;\n\t}\n\n\txhr.onreadystatechange = handler;\n\txhr.onerror = err;\n\n\txhr.open(\"GET\", url, true);\n\n\tfor(header in headers) {\n\t\txhr.setRequestHeader(header, headers[header]);\n\t}\n\n\tif(type == \"json\") {\n\t\txhr.setRequestHeader(\"Accept\", \"application/json\");\n\t}\n\n\t// If type isn't set, determine it from the file extension\n\tif(!type) {\n\t\turi = URI(url);\n\t\ttype = uri.suffix();\n\t}\n\n\tif(type == 'blob'){\n\t\txhr.responseType = BLOB_RESPONSE;\n\t}\n\n\n\tif(core.isXml(type)) {\n\t\t// xhr.responseType = \"document\";\n\t\txhr.overrideMimeType('text/xml'); // for OPF parsing\n\t}\n\n\tif(type == 'xhtml') {\n\t\t// xhr.responseType = \"document\";\n\t}\n\n\tif(type == 'html' || type == 'htm') {\n\t\t// xhr.responseType = \"document\";\n\t }\n\n\tif(type == \"binary\") {\n\t\txhr.responseType = \"arraybuffer\";\n\t}\n\n\txhr.send();\n\n\tfunction err(e) {\n\t\tconsole.error(e);\n\t\tdeferred.reject(e);\n\t}\n\n\tfunction handler() {\n\t\tif (this.readyState === XMLHttpRequest.DONE) {\n\n\t\t\tif (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls\n\t\t\t\tvar r;\n\n\t\t\t\tif (!this.response && !this.responseXML) {\n\t\t\t\t\tdeferred.reject({\n\t\t\t\t\t\tstatus: this.status,\n\t\t\t\t\t\tmessage : \"Empty Response\",\n\t\t\t\t\t\tstack : new Error().stack\n\t\t\t\t\t});\n\t\t\t\t\treturn deferred.promise;\n\t\t\t\t}\n\n\t\t\t\tif (this.status === 403) {\n\t\t\t\t\tdeferred.reject({\n\t\t\t\t\t\tstatus: this.status,\n\t\t\t\t\t\tresponse: this.response,\n\t\t\t\t\t\tmessage : \"Forbidden\",\n\t\t\t\t\t\tstack : new Error().stack\n\t\t\t\t\t});\n\t\t\t\t\treturn deferred.promise;\n\t\t\t\t}\n\n\t\t\t\tif((this.responseType == '' || this.responseType == 'document')\n\t\t\t\t\t\t&& this.responseXML){\n\t\t\t\t\tr = this.responseXML;\n\t\t\t\t} else\n\t\t\t\tif(core.isXml(type)){\n\t\t\t\t\t// xhr.overrideMimeType('text/xml'); // for OPF parsing\n\t\t\t\t\t// If this.responseXML wasn't set, try to parse using a DOMParser from text\n\t\t\t\t\tr = core.parse(this.response, \"text/xml\");\n\t\t\t\t}else\n\t\t\t\tif(type == 'xhtml'){\n\t\t\t\t\tr = core.parse(this.response, \"application/xhtml+xml\");\n\t\t\t\t}else\n\t\t\t\tif(type == 'html' || type == 'htm'){\n\t\t\t\t\tr = core.parse(this.response, \"text/html\");\n\t\t\t\t}else\n\t\t\t\tif(type == 'json'){\n\t\t\t\t\tr = JSON.parse(this.response);\n\t\t\t\t}else\n\t\t\t\tif(type == 'blob'){\n\n\t\t\t\t\tif(supportsURL) {\n\t\t\t\t\t\tr = this.response;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//-- Safari doesn't support responseType blob, so create a blob from arraybuffer\n\t\t\t\t\t\tr = new Blob([this.response]);\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\t\t\t\t\tr = this.response;\n\t\t\t\t}\n\n\t\t\t\tdeferred.resolve(r);\n\t\t\t} else {\n\n\t\t\t\tdeferred.reject({\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t\tmessage : this.response,\n\t\t\t\t\tstack : new Error().stack\n\t\t\t\t});\n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn deferred.promise;\n};\n\nmodule.exports = request;\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\nvar Hook = require('./hook');\n\nfunction Section(item, hooks){\n\t\tthis.idref = item.idref;\n\t\tthis.linear = item.linear;\n\t\tthis.properties = item.properties;\n\t\tthis.index = item.index;\n\t\tthis.href = item.href;\n\t\tthis.url = item.url;\n\t\tthis.next = item.next;\n\t\tthis.prev = item.prev;\n\n\t\tthis.cfiBase = item.cfiBase;\n\n\t\tif (hooks) {\n\t\t\tthis.hooks = hooks;\n\t\t} else {\n\t\t\tthis.hooks = {};\n\t\t\tthis.hooks.serialize = new Hook(this);\n\t\t\tthis.hooks.content = new Hook(this);\n\t\t}\n\n};\n\n\nSection.prototype.load = function(_request){\n\tvar request = _request || this.request || require('./request');\n\tvar loading = new RSVP.defer();\n\tvar loaded = loading.promise;\n\n\tif(this.contents) {\n\t\tloading.resolve(this.contents);\n\t} else {\n\t\trequest(this.url)\n\t\t\t.then(function(xml){\n\t\t\t\tvar base;\n\t\t\t\tvar directory = URI(this.url).directory();\n\n\t\t\t\tthis.document = xml;\n\t\t\t\tthis.contents = xml.documentElement;\n\n\t\t\t\treturn this.hooks.content.trigger(this.document, this);\n\t\t\t}.bind(this))\n\t\t\t.then(function(){\n\t\t\t\tloading.resolve(this.contents);\n\t\t\t}.bind(this))\n\t\t\t.catch(function(error){\n\t\t\t\tloading.reject(error);\n\t\t\t});\n\t}\n\n\treturn loaded;\n};\n\nSection.prototype.base = function(_document){\n\t\tvar task = new RSVP.defer();\n\t\tvar base = _document.createElement(\"base\"); // TODO: check if exists\n\t\tvar head;\n\t\tconsole.log(window.location.origin + \"/\" +this.url);\n\n\t\tbase.setAttribute(\"href\", window.location.origin + \"/\" +this.url);\n\n\t\tif(_document) {\n\t\t\thead = _document.querySelector(\"head\");\n\t\t}\n\t\tif(head) {\n\t\t\thead.insertBefore(base, head.firstChild);\n\t\t\ttask.resolve();\n\t\t} else {\n\t\t\ttask.reject(new Error(\"No head to insert into\"));\n\t\t}\n\n\n\t\treturn task.promise;\n};\n\nSection.prototype.beforeSectionLoad = function(){\n\t// Stub for a hook - replace me for now\n};\n\nSection.prototype.render = function(_request){\n\tvar rendering = new RSVP.defer();\n\tvar rendered = rendering.promise;\n\tthis.output; // TODO: better way to return this from hooks?\n\n\tthis.load(_request).\n\t\tthen(function(contents){\n\t\t\tvar serializer;\n\n\t\t\tif (typeof XMLSerializer === \"undefined\") {\n\t\t\t\tXMLSerializer = require('xmldom').XMLSerializer;\n\t\t\t}\n\t\t\tserializer = new XMLSerializer();\n\t\t\tthis.output = serializer.serializeToString(contents);\n\t\t\treturn this.output;\n\t\t}.bind(this)).\n\t\tthen(function(){\n\t\t\treturn this.hooks.serialize.trigger(this.output, this);\n\t\t}.bind(this)).\n\t\tthen(function(){\n\t\t\trendering.resolve(this.output);\n\t\t}.bind(this))\n\t\t.catch(function(error){\n\t\t\trendering.reject(error);\n\t\t});\n\n\treturn rendered;\n};\n\nSection.prototype.find = function(_query){\n\n};\n\n/**\n* Reconciles the current chapters layout properies with\n* the global layout properities.\n* Takes: global layout settings object, chapter properties string\n* Returns: Object with layout properties\n*/\nSection.prototype.reconcileLayoutSettings = function(global){\n\t//-- Get the global defaults\n\tvar settings = {\n\t\tlayout : global.layout,\n\t\tspread : global.spread,\n\t\torientation : global.orientation\n\t};\n\n\t//-- Get the chapter's display type\n\tthis.properties.forEach(function(prop){\n\t\tvar rendition = prop.replace(\"rendition:\", '');\n\t\tvar split = rendition.indexOf(\"-\");\n\t\tvar property, value;\n\n\t\tif(split != -1){\n\t\t\tproperty = rendition.slice(0, split);\n\t\t\tvalue = rendition.slice(split+1);\n\n\t\t\tsettings[property] = value;\n\t\t}\n\t});\n return settings;\n};\n\nSection.prototype.cfiFromRange = function(_range) {\n\treturn new EpubCFI(_range, this.cfiBase).toString();\n};\n\nSection.prototype.cfiFromElement = function(el) {\n\treturn new EpubCFI(el, this.cfiBase).toString();\n};\n\nmodule.exports = Section;\n","var RSVP = require('rsvp');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\nvar Hook = require('./hook');\nvar Section = require('./section');\nvar replacements = require('./replacements');\n\nfunction Spine(_request){\n\tthis.request = _request;\n\tthis.spineItems = [];\n\tthis.spineByHref = {};\n\tthis.spineById = {};\n\n\tthis.hooks = {};\n\tthis.hooks.serialize = new Hook();\n\tthis.hooks.content = new Hook();\n\n\t// Register replacements\n\tthis.hooks.content.register(replacements.base);\n\tthis.hooks.content.register(replacements.canonical);\n\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.loaded = false;\n};\n\nSpine.prototype.load = function(_package) {\n\n\tthis.items = _package.spine;\n\tthis.manifest = _package.manifest;\n\tthis.spineNodeIndex = _package.spineNodeIndex;\n\tthis.baseUrl = _package.baseUrl || '';\n\tthis.length = this.items.length;\n\n\tthis.items.forEach(function(item, index){\n\t\tvar href, url;\n\t\tvar manifestItem = this.manifest[item.idref];\n\t\tvar spineItem;\n\n\t\titem.cfiBase = this.epubcfi.generateChapterComponent(this.spineNodeIndex, item.index, item.idref);\n\n\t\tif(manifestItem) {\n\t\t\titem.href = manifestItem.href;\n\t\t\titem.url = this.baseUrl + item.href;\n\n\t\t\tif(manifestItem.properties.length){\n\t\t\t\titem.properties.push.apply(item.properties, manifestItem.properties);\n\t\t\t}\n\t\t}\n\n\t\t// if(index > 0) {\n\t\t\titem.prev = function(){ return this.get(index-1); }.bind(this);\n\t\t// }\n\n\t\t// if(index+1 < this.items.length) {\n\t\t\titem.next = function(){ return this.get(index+1); }.bind(this);\n\t\t// }\n\n\t\tspineItem = new Section(item, this.hooks);\n\n\t\tthis.append(spineItem);\n\n\n\t}.bind(this));\n\n\tthis.loaded = true;\n};\n\n// book.spine.get();\n// book.spine.get(1);\n// book.spine.get(\"chap1.html\");\n// book.spine.get(\"#id1234\");\nSpine.prototype.get = function(target) {\n\tvar index = 0;\n\n\tif(this.epubcfi.isCfiString(target)) {\n\t\tcfi = new EpubCFI(target);\n\t\tindex = cfi.spinePos;\n\t} else if(target && (typeof target === \"number\" || isNaN(target) === false)){\n\t\tindex = target;\n\t} else if(target && target.indexOf(\"#\") === 0) {\n\t\tindex = this.spineById[target.substring(1)];\n\t} else if(target) {\n\t\t// Remove fragments\n\t\ttarget = target.split(\"#\")[0];\n\t\tindex = this.spineByHref[target];\n\t}\n\n\treturn this.spineItems[index] || null;\n};\n\nSpine.prototype.append = function(section) {\n\tvar index = this.spineItems.length;\n\tsection.index = index;\n\n\tthis.spineItems.push(section);\n\n\tthis.spineByHref[section.href] = index;\n\tthis.spineById[section.idref] = index;\n\n\treturn index;\n};\n\nSpine.prototype.prepend = function(section) {\n\tvar index = this.spineItems.unshift(section);\n\tthis.spineByHref[section.href] = 0;\n\tthis.spineById[section.idref] = 0;\n\n\t// Re-index\n\tthis.spineItems.forEach(function(item, index){\n\t\titem.index = index;\n\t});\n\n\treturn 0;\n};\n\nSpine.prototype.insert = function(section, index) {\n\n};\n\nSpine.prototype.remove = function(section) {\n\tvar index = this.spineItems.indexOf(section);\n\n\tif(index > -1) {\n\t\tdelete this.spineByHref[section.href];\n\t\tdelete this.spineById[section.idref];\n\n\t\treturn this.spineItems.splice(index, 1);\n\t}\n};\n\nSpine.prototype.each = function() {\n\treturn this.spineItems.forEach.apply(this.spineItems, arguments);\n};\n\nmodule.exports = Spine;\n","var core = require('./core');\n\nfunction Stage(_options) {\n\tthis.settings = _options || {};\n\tthis.id = \"epubjs-container-\" + core.uuid();\n\n\tthis.container = this.create(this.settings);\n\n\tif(this.settings.hidden) {\n\t\tthis.wrapper = this.wrap(this.container);\n\t}\n\n}\n\n/**\n* Creates an element to render to.\n* Resizes to passed width and height or to the elements size\n*/\nStage.prototype.create = function(options){\n\tvar height = options.height;// !== false ? options.height : \"100%\";\n\tvar width = options.width;// !== false ? options.width : \"100%\";\n\tvar overflow = options.overflow || false;\n\tvar axis = options.axis || \"vertical\";\n\n\tif(options.height && core.isNumber(options.height)) {\n\t\theight = options.height + \"px\";\n\t}\n\n\tif(options.width && core.isNumber(options.width)) {\n\t\twidth = options.width + \"px\";\n\t}\n\n\t// Create new container element\n\tcontainer = document.createElement(\"div\");\n\n\tcontainer.id = this.id;\n\tcontainer.classList.add(\"epub-container\");\n\n\t// Style Element\n\t// container.style.fontSize = \"0\";\n\tcontainer.style.wordSpacing = \"0\";\n\tcontainer.style.lineHeight = \"0\";\n\tcontainer.style.verticalAlign = \"top\";\n\n\tif(axis === \"horizontal\") {\n\t\tcontainer.style.whiteSpace = \"nowrap\";\n\t}\n\n\tif(width){\n\t\tcontainer.style.width = width;\n\t}\n\n\tif(height){\n\t\tcontainer.style.height = height;\n\t}\n\n\tif (overflow) {\n\t\tcontainer.style.overflow = overflow;\n\t}\n\n\treturn container;\n};\n\nStage.wrap = function(container) {\n\tvar wrapper = document.createElement(\"div\");\n\n\twrapper.style.visibility = \"hidden\";\n\twrapper.style.overflow = \"hidden\";\n\twrapper.style.width = \"0\";\n\twrapper.style.height = \"0\";\n\n\twrapper.appendChild(container);\n\treturn wrapper;\n};\n\n\nStage.prototype.getElement = function(_element){\n\tvar element;\n\n\tif(core.isElement(_element)) {\n\t\telement = _element;\n\t} else if (typeof _element === \"string\") {\n\t\telement = document.getElementById(_element);\n\t}\n\n\tif(!element){\n\t\tconsole.error(\"Not an Element\");\n\t\treturn;\n\t}\n\n\treturn element;\n};\n\nStage.prototype.attachTo = function(what){\n\n\tvar element = this.getElement(what);\n\tvar base;\n\n\tif(!element){\n\t\treturn;\n\t}\n\n\tif(this.settings.hidden) {\n\t\tbase = this.wrapper;\n\t} else {\n\t\tbase = this.container;\n\t}\n\n\telement.appendChild(base);\n\n\tthis.element = element;\n\n\treturn element;\n\n};\n\nStage.prototype.getContainer = function() {\n\treturn this.container;\n};\n\nStage.prototype.onResize = function(func){\n\t// Only listen to window for resize event if width and height are not fixed.\n\t// This applies if it is set to a percent or auto.\n\tif(!core.isNumber(this.settings.width) ||\n\t\t !core.isNumber(this.settings.height) ) {\n\t\twindow.addEventListener(\"resize\", func, false);\n\t}\n\n};\n\nStage.prototype.size = function(width, height){\n\tvar bounds;\n\t// var width = _width || this.settings.width;\n\t// var height = _height || this.settings.height;\n\n\t// If width or height are set to false, inherit them from containing element\n\tif(width === null) {\n\t\tbounds = this.element.getBoundingClientRect();\n\n\t\tif(bounds.width) {\n\t\t\twidth = bounds.width;\n\t\t\tthis.container.style.width = bounds.width + \"px\";\n\t\t}\n\t}\n\n\tif(height === null) {\n\t\tbounds = bounds || this.element.getBoundingClientRect();\n\n\t\tif(bounds.height) {\n\t\t\theight = bounds.height;\n\t\t\tthis.container.style.height = bounds.height + \"px\";\n\t\t}\n\n\t}\n\n\tif(!core.isNumber(width)) {\n\t\tbounds = this.container.getBoundingClientRect();\n\t\twidth = bounds.width;\n\t\t//height = bounds.height;\n\t}\n\n\tif(!core.isNumber(height)) {\n\t\tbounds = bounds || this.container.getBoundingClientRect();\n\t\t//width = bounds.width;\n\t\theight = bounds.height;\n\t}\n\n\n\tthis.containerStyles = window.getComputedStyle(this.container);\n\n\tthis.containerPadding = {\n\t\tleft: parseFloat(this.containerStyles[\"padding-left\"]) || 0,\n\t\tright: parseFloat(this.containerStyles[\"padding-right\"]) || 0,\n\t\ttop: parseFloat(this.containerStyles[\"padding-top\"]) || 0,\n\t\tbottom: parseFloat(this.containerStyles[\"padding-bottom\"]) || 0\n\t};\n\n\treturn {\n\t\twidth: width -\n\t\t\t\t\t\tthis.containerPadding.left -\n\t\t\t\t\t\tthis.containerPadding.right,\n\t\theight: height -\n\t\t\t\t\t\tthis.containerPadding.top -\n\t\t\t\t\t\tthis.containerPadding.bottom\n\t};\n\n};\n\nStage.prototype.bounds = function(){\n\n\tif(!this.container) {\n\t\treturn core.windowBounds();\n\t} else {\n\t\treturn this.container.getBoundingClientRect();\n\t}\n\n}\n\nStage.prototype.getSheet = function(){\n\tvar style = document.createElement(\"style\");\n\n\t// WebKit hack --> https://davidwalsh.name/add-rules-stylesheets\n\tstyle.appendChild(document.createTextNode(\"\"));\n\n\tdocument.head.appendChild(style);\n\n\treturn style.sheet;\n}\n\nStage.prototype.addStyleRules = function(selector, rulesArray){\n\tvar scope = \"#\" + this.id + \" \";\n\tvar rules = \"\";\n\n\tif(!this.sheet){\n\t\tthis.sheet = this.getSheet();\n\t}\n\n\trulesArray.forEach(function(set) {\n\t\tfor (var prop in set) {\n\t\t\tif(set.hasOwnProperty(prop)) {\n\t\t\t\trules += prop + \":\" + set[prop] + \";\";\n\t\t\t}\n\t\t}\n\t})\n\n\tthis.sheet.insertRule(scope + selector + \" {\" + rules + \"}\", 0);\n}\n\n\n\nmodule.exports = Stage;\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar request = require('./request');\nvar mime = require('../libs/mime/mime');\n\nfunction Unarchive() {\n\n\tthis.checkRequirements();\n\tthis.urlCache = {};\n\n}\n\nUnarchive.prototype.checkRequirements = function(callback){\n\ttry {\n\t\tif (typeof JSZip !== 'undefined') {\n\t\t\tthis.zip = new JSZip();\n\t\t} else {\n\t\t\tJSZip = require('jszip');\n\t\t\tthis.zip = new JSZip();\n\t\t}\n\t} catch (e) {\n\t\tconsole.error(\"JSZip lib not loaded\");\n\t}\n};\n\nUnarchive.prototype.open = function(zipUrl, isBase64){\n\tif (zipUrl instanceof ArrayBuffer || isBase64) {\n\t\treturn this.zip.loadAsync(zipUrl, {\"base64\": isBase64});\n\t} else {\n\t\treturn request(zipUrl, \"binary\")\n\t\t\t.then(function(data){\n\t\t\t\treturn this.zip.loadAsync(data);\n\t\t\t}.bind(this));\n\t}\n};\n\nUnarchive.prototype.request = function(url, type){\n\tvar deferred = new RSVP.defer();\n\tvar response;\n\tvar r;\n\n\t// If type isn't set, determine it from the file extension\n\tif(!type) {\n\t\turi = URI(url);\n\t\ttype = uri.suffix();\n\t}\n\n\tif(type == 'blob'){\n\t\tresponse = this.getBlob(url);\n\t} else {\n\t\tresponse = this.getText(url);\n\t}\n\n\tif (response) {\n\t\tresponse.then(function (r) {\n\t\t\tresult = this.handleResponse(r, type);\n\t\t\tdeferred.resolve(result);\n\t\t}.bind(this));\n\t} else {\n\t\tdeferred.reject({\n\t\t\tmessage : \"File not found in the epub: \" + url,\n\t\t\tstack : new Error().stack\n\t\t});\n\t}\n\treturn deferred.promise;\n};\n\nUnarchive.prototype.handleResponse = function(response, type){\n\tvar r;\n\n\tif(type == \"json\") {\n\t\tr = JSON.parse(response);\n\t}\n\telse\n\tif(core.isXml(type)) {\n\t\tr = core.parse(response, \"text/xml\");\n\t}\n\telse\n\tif(type == 'xhtml') {\n\t\tr = core.parse(response, \"application/xhtml+xml\");\n\t}\n\telse\n\tif(type == 'html' || type == 'htm') {\n\t\tr = core.parse(response, \"text/html\");\n\t } else {\n\t\t r = response;\n\t }\n\n\treturn r;\n};\n\nUnarchive.prototype.getBlob = function(url, _mimeType){\n\tvar decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash\n\tvar entry = this.zip.file(decodededUrl);\n\tvar mimeType;\n\n\tif(entry) {\n\t\tmimeType = _mimeType || mime.lookup(entry.name);\n\t\treturn entry.async(\"uint8array\").then(function(uint8array) {\n\t\t\treturn new Blob([uint8array], {type : mimeType});\n\t\t});\n\t}\n};\n\nUnarchive.prototype.getText = function(url, encoding){\n\tvar decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash\n\tvar entry = this.zip.file(decodededUrl);\n\n\tif(entry) {\n\t\treturn entry.async(\"string\").then(function(text) {\n\t\t\treturn text;\n\t\t});\n\t}\n};\n\nUnarchive.prototype.getBase64 = function(url, _mimeType){\n\tvar decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash\n\tvar entry = this.zip.file(decodededUrl);\n\tvar mimeType;\n\n\tif(entry) {\n\t\tmimeType = _mimeType || mime.lookup(entry.name);\n\t\treturn entry.async(\"base64\").then(function(data) {\n\t\t\treturn \"data:\" + mimeType + \";base64,\" + data;\n\t\t});\n\t}\n};\n\nUnarchive.prototype.createUrl = function(url, options){\n\tvar deferred = new RSVP.defer();\n\tvar _URL = window.URL || window.webkitURL || window.mozURL;\n\tvar tempUrl;\n\tvar blob;\n\tvar response;\n\tvar useBase64 = options && options.base64;\n\n\tif(url in this.urlCache) {\n\t\tdeferred.resolve(this.urlCache[url]);\n\t\treturn deferred.promise;\n\t}\n\n\tif (useBase64) {\n\t\tresponse = this.getBase64(url);\n\n\t\tif (response) {\n\t\t\tresponse.then(function(tempUrl) {\n\n\t\t\t\tthis.urlCache[url] = tempUrl;\n\t\t\t\tdeferred.resolve(tempUrl);\n\n\t\t\t}.bind(this));\n\n\t\t}\n\n\t} else {\n\n\t\tresponse = this.getBlob(url);\n\n\t\tif (response) {\n\t\t\tresponse.then(function(blob) {\n\n\t\t\t\ttempUrl = _URL.createObjectURL(blob);\n\t\t\t\tthis.urlCache[url] = tempUrl;\n\t\t\t\tdeferred.resolve(tempUrl);\n\n\t\t\t}.bind(this));\n\n\t\t}\n\t}\n\n\n\tif (!response) {\n\t\tdeferred.reject({\n\t\t\tmessage : \"File not found in the epub: \" + url,\n\t\t\tstack : new Error().stack\n\t\t});\n\t}\n\n\treturn deferred.promise;\n};\n\nUnarchive.prototype.revokeUrl = function(url){\n\tvar _URL = window.URL || window.webkitURL || window.mozURL;\n\tvar fromCache = this.urlCache[url];\n\tif(fromCache) _URL.revokeObjectURL(fromCache);\n};\n\nmodule.exports = Unarchive;\n","function Views(container) {\n\tthis.container = container;\n\tthis._views = [];\n\tthis.length = 0;\n\tthis.hidden = false;\n};\n\nViews.prototype.all = function() {\n\treturn this._views;\n};\n\nViews.prototype.first = function() {\n\treturn this._views[0];\n};\n\nViews.prototype.last = function() {\n\treturn this._views[this._views.length-1];\n};\n\nViews.prototype.indexOf = function(view) {\n\treturn this._views.indexOf(view);\n};\n\nViews.prototype.slice = function() {\n\treturn this._views.slice.apply(this._views, arguments);\n};\n\nViews.prototype.get = function(i) {\n\treturn this._views[i];\n};\n\nViews.prototype.append = function(view){\n\tthis._views.push(view);\n\tif(this.container){\n\t\tthis.container.appendChild(view.element);\n\t}\n\tthis.length++;\n\treturn view;\n};\n\nViews.prototype.prepend = function(view){\n\tthis._views.unshift(view);\n\tif(this.container){\n\t\tthis.container.insertBefore(view.element, this.container.firstChild);\n\t}\n\tthis.length++;\n\treturn view;\n};\n\nViews.prototype.insert = function(view, index) {\n\tthis._views.splice(index, 0, view);\n\n\tif(this.container){\n\t\tif(index < this.container.children.length){\n\t\t\tthis.container.insertBefore(view.element, this.container.children[index]);\n\t\t} else {\n\t\t\tthis.container.appendChild(view.element);\n\t\t}\n\t}\n\n\tthis.length++;\n\treturn view;\n};\n\nViews.prototype.remove = function(view) {\n\tvar index = this._views.indexOf(view);\n\n\tif(index > -1) {\n\t\tthis._views.splice(index, 1);\n\t}\n\n\n\tthis.destroy(view);\n\n\tthis.length--;\n};\n\nViews.prototype.destroy = function(view) {\n\tview.off(\"resized\");\n\n\tif(view.displayed){\n\t\tview.destroy();\n\t}\n\n\tif(this.container){\n\t\t this.container.removeChild(view.element);\n\t}\n\tview = null;\n};\n\n// Iterators\n\nViews.prototype.each = function() {\n\treturn this._views.forEach.apply(this._views, arguments);\n};\n\nViews.prototype.clear = function(){\n\t// Remove all views\n\tvar view;\n\tvar len = this.length;\n\n\tif(!this.length) return;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tthis.destroy(view);\n\t}\n\n\tthis._views = [];\n\tthis.length = 0;\n};\n\nViews.prototype.find = function(section){\n\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed && view.section.index == section.index) {\n\t\t\treturn view;\n\t\t}\n\t}\n\n};\n\nViews.prototype.displayed = function(){\n\tvar displayed = [];\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed){\n\t\t\tdisplayed.push(view);\n\t\t}\n\t}\n\treturn displayed;\n};\n\nViews.prototype.show = function(){\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed){\n\t\t\tview.show();\n\t\t}\n\t}\n\tthis.hidden = false;\n};\n\nViews.prototype.hide = function(){\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed){\n\t\t\tview.hide();\n\t\t}\n\t}\n\tthis.hidden = true;\n};\n\nmodule.exports = Views;\n","var RSVP = require('rsvp');\nvar core = require('../core');\nvar EpubCFI = require('../epubcfi');\nvar Contents = require('../contents');\n\nfunction IframeView(section, options) {\n\tthis.settings = core.extend({\n\t\tignoreClass : '',\n\t\taxis: 'vertical',\n\t\twidth: 0,\n\t\theight: 0,\n\t\tlayout: undefined,\n\t\tglobalLayoutProperties: {},\n\t}, options || {});\n\n\tthis.id = \"epubjs-view-\" + core.uuid();\n\tthis.section = section;\n\tthis.index = section.index;\n\n\tthis.element = this.container(this.settings.axis);\n\n\tthis.added = false;\n\tthis.displayed = false;\n\tthis.rendered = false;\n\n\tthis.width = this.settings.width;\n\tthis.height = this.settings.height;\n\n\tthis.fixedWidth = 0;\n\tthis.fixedHeight = 0;\n\n\t// Blank Cfi for Parsing\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.layout = this.settings.layout;\n\t// Dom events to listen for\n\t// this.listenedEvents = [\"keydown\", \"keyup\", \"keypressed\", \"mouseup\", \"mousedown\", \"click\", \"touchend\", \"touchstart\"];\n};\n\nIframeView.prototype.container = function(axis) {\n\tvar element = document.createElement('div');\n\n\telement.classList.add(\"epub-view\");\n\n\t// this.element.style.minHeight = \"100px\";\n\telement.style.height = \"0px\";\n\telement.style.width = \"0px\";\n\telement.style.overflow = \"hidden\";\n\n\tif(axis && axis == \"horizontal\"){\n\t\telement.style.display = \"inline-block\";\n\t} else {\n\t\telement.style.display = \"block\";\n\t}\n\n\treturn element;\n};\n\nIframeView.prototype.create = function() {\n\n\tif(this.iframe) {\n\t\treturn this.iframe;\n\t}\n\n\tif(!this.element) {\n\t\tthis.element = this.createContainer();\n\t}\n\n\tthis.iframe = document.createElement('iframe');\n\tthis.iframe.id = this.id;\n\tthis.iframe.scrolling = \"no\"; // Might need to be removed: breaks ios width calculations\n\tthis.iframe.style.overflow = \"hidden\";\n\tthis.iframe.seamless = \"seamless\";\n\t// Back up if seamless isn't supported\n\tthis.iframe.style.border = \"none\";\n\n\tthis.resizing = true;\n\n\t// this.iframe.style.display = \"none\";\n\tthis.element.style.visibility = \"hidden\";\n\tthis.iframe.style.visibility = \"hidden\";\n\n\tthis.iframe.style.width = \"0\";\n\tthis.iframe.style.height = \"0\";\n\tthis._width = 0;\n\tthis._height = 0;\n\n\tthis.element.appendChild(this.iframe);\n\tthis.added = true;\n\n\tthis.elementBounds = core.bounds(this.element);\n\n\t// if(width || height){\n\t// this.resize(width, height);\n\t// } else if(this.width && this.height){\n\t// this.resize(this.width, this.height);\n\t// } else {\n\t// this.iframeBounds = core.bounds(this.iframe);\n\t// }\n\n\t// Firefox has trouble with baseURI and srcdoc\n\t// TODO: Disable for now in firefox\n\n\tif(!!(\"srcdoc\" in this.iframe)) {\n\t\tthis.supportsSrcdoc = true;\n\t} else {\n\t\tthis.supportsSrcdoc = false;\n\t}\n\n\treturn this.iframe;\n};\n\nIframeView.prototype.render = function(request, show) {\n\n\t// view.onLayout = this.layout.format.bind(this.layout);\n\tthis.create();\n\n\t// Fit to size of the container, apply padding\n\tthis.size();\n\n\tif(!this.sectionRender) {\n\t\tthis.sectionRender = this.section.render(request);\n\t}\n\n\t// Render Chain\n\treturn this.sectionRender\n\t\t.then(function(contents){\n\t\t\treturn this.load(contents);\n\t\t}.bind(this))\n\t\t// .then(function(doc){\n\t\t// \treturn this.hooks.content.trigger(view, this);\n\t\t// }.bind(this))\n\t\t.then(function(){\n\t\t\t// this.settings.layout.format(view.contents);\n\t\t\t// return this.hooks.layout.trigger(view, this);\n\t\t}.bind(this))\n\t\t// .then(function(){\n\t\t// \treturn this.display();\n\t\t// }.bind(this))\n\t\t// .then(function(){\n\t\t// \treturn this.hooks.render.trigger(view, this);\n\t\t// }.bind(this))\n\t\t.then(function(){\n\n\t\t\t// apply the layout function to the contents\n\t\t\tthis.settings.layout.format(this.contents);\n\n\t\t\t// Expand the iframe to the full size of the content\n\t\t\tthis.expand();\n\n\t\t\t// Listen for events that require an expansion of the iframe\n\t\t\tthis.addListeners();\n\n\t\t\tif(show !== false) {\n\t\t\t\t//this.q.enqueue(function(view){\n\t\t\t\t\t// this.show();\n\t\t\t\t//}, view);\n\t\t\t}\n\t\t\t// this.map = new Map(view, this.layout);\n\t\t\t//this.hooks.show.trigger(view, this);\n\t\t\tthis.trigger(\"rendered\", this.section);\n\n\t\t}.bind(this))\n\t\t.catch(function(e){\n\t\t\tthis.trigger(\"loaderror\", e);\n\t\t}.bind(this));\n\n};\n\n// Determine locks base on settings\nIframeView.prototype.size = function(_width, _height) {\n\tvar width = _width || this.settings.width;\n\tvar height = _height || this.settings.height;\n\n\tif(this.layout.name === \"pre-paginated\") {\n\t\tthis.lock(\"both\", width, height);\n\t} else if(this.settings.axis === \"horizontal\") {\n\t\tthis.lock(\"height\", width, height);\n\t} else {\n\t\tthis.lock(\"width\", width, height);\n\t}\n\n};\n\n// Lock an axis to element dimensions, taking borders into account\nIframeView.prototype.lock = function(what, width, height) {\n\tvar elBorders = core.borders(this.element);\n\tvar iframeBorders;\n\n\tif(this.iframe) {\n\t\tiframeBorders = core.borders(this.iframe);\n\t} else {\n\t\tiframeBorders = {width: 0, height: 0};\n\t}\n\n\tif(what == \"width\" && core.isNumber(width)){\n\t\tthis.lockedWidth = width - elBorders.width - iframeBorders.width;\n\t\tthis.resize(this.lockedWidth, width); // width keeps ratio correct\n\t}\n\n\tif(what == \"height\" && core.isNumber(height)){\n\t\tthis.lockedHeight = height - elBorders.height - iframeBorders.height;\n\t\tthis.resize(width, this.lockedHeight);\n\t}\n\n\tif(what === \"both\" &&\n\t\t core.isNumber(width) &&\n\t\t core.isNumber(height)){\n\n\t\tthis.lockedWidth = width - elBorders.width - iframeBorders.width;\n\t\tthis.lockedHeight = height - elBorders.height - iframeBorders.height;\n\n\t\tthis.resize(this.lockedWidth, this.lockedHeight);\n\t}\n\n\tif(this.displayed && this.iframe) {\n\n\t\t\t// this.contents.layout();\n\t\t\tthis.expand();\n\n\t}\n\n\n\n};\n\n// Resize a single axis based on content dimensions\nIframeView.prototype.expand = function(force) {\n\tvar width = this.lockedWidth;\n\tvar height = this.lockedHeight;\n\tvar columns;\n\n\tvar textWidth, textHeight;\n\n\tif(!this.iframe || this._expanding) return;\n\n\tthis._expanding = true;\n\n\t// Expand Horizontally\n\t// if(height && !width) {\n\tif(this.settings.axis === \"horizontal\") {\n\t\t// Get the width of the text\n\t\ttextWidth = this.contents.textWidth();\n\t\t// Check if the textWidth has changed\n\t\tif(textWidth != this._textWidth){\n\t\t\t// Get the contentWidth by resizing the iframe\n\t\t\t// Check with a min reset of the textWidth\n\t\t\twidth = this.contentWidth(textWidth);\n\n\t\t\tcolumns = Math.ceil(width / (this.settings.layout.columnWidth + this.settings.layout.gap));\n\n\t\t\tif ( this.settings.layout.divisor > 1 &&\n\t\t\t\t\t this.settings.layout.name === \"reflowable\" &&\n\t\t\t\t\t(columns % 2 > 0)) {\n\t\t\t\t\t// add a blank page\n\t\t\t\t\twidth += this.settings.layout.gap + this.settings.layout.columnWidth;\n\t\t\t}\n\n\t\t\t// Save the textWdith\n\t\t\tthis._textWidth = textWidth;\n\t\t\t// Save the contentWidth\n\t\t\tthis._contentWidth = width;\n\t\t} else {\n\t\t\t// Otherwise assume content height hasn't changed\n\t\t\twidth = this._contentWidth;\n\t\t}\n\t} // Expand Vertically\n\telse if(this.settings.axis === \"vertical\") {\n\t\ttextHeight = this.contents.textHeight();\n\t\tif(textHeight != this._textHeight){\n\t\t\theight = this.contentHeight(textHeight);\n\t\t\tthis._textHeight = textHeight;\n\t\t\tthis._contentHeight = height;\n\t\t} else {\n\t\t\theight = this._contentHeight;\n\t\t}\n\n\t}\n\n\t// Only Resize if dimensions have changed or\n\t// if Frame is still hidden, so needs reframing\n\tif(this._needsReframe || width != this._width || height != this._height){\n\t\tthis.resize(width, height);\n\t}\n\n\tthis._expanding = false;\n};\n\nIframeView.prototype.contentWidth = function(min) {\n\tvar prev;\n\tvar width;\n\n\t// Save previous width\n\tprev = this.iframe.style.width;\n\t// Set the iframe size to min, width will only ever be greater\n\t// Will preserve the aspect ratio\n\tthis.iframe.style.width = (min || 0) + \"px\";\n\t// Get the scroll overflow width\n\twidth = this.contents.scrollWidth();\n\t// Reset iframe size back\n\tthis.iframe.style.width = prev;\n\treturn width;\n};\n\nIframeView.prototype.contentHeight = function(min) {\n\tvar prev;\n\tvar height;\n\n\tprev = this.iframe.style.height;\n\tthis.iframe.style.height = (min || 0) + \"px\";\n\theight = this.contents.scrollHeight();\n\n\tthis.iframe.style.height = prev;\n\treturn height;\n};\n\n\nIframeView.prototype.resize = function(width, height) {\n\n\tif(!this.iframe) return;\n\n\tif(core.isNumber(width)){\n\t\tthis.iframe.style.width = width + \"px\";\n\t\tthis._width = width;\n\t}\n\n\tif(core.isNumber(height)){\n\t\tthis.iframe.style.height = height + \"px\";\n\t\tthis._height = height;\n\t}\n\n\tthis.iframeBounds = core.bounds(this.iframe);\n\n\tthis.reframe(this.iframeBounds.width, this.iframeBounds.height);\n\n};\n\nIframeView.prototype.reframe = function(width, height) {\n\tvar size;\n\n\t// if(!this.displayed) {\n\t// this._needsReframe = true;\n\t// return;\n\t// }\n\tif(core.isNumber(width)){\n\t\tthis.element.style.width = width + \"px\";\n\t}\n\n\tif(core.isNumber(height)){\n\t\tthis.element.style.height = height + \"px\";\n\t}\n\n\tthis.prevBounds = this.elementBounds;\n\n\tthis.elementBounds = core.bounds(this.element);\n\n\tsize = {\n\t\twidth: this.elementBounds.width,\n\t\theight: this.elementBounds.height,\n\t\twidthDelta: this.elementBounds.width - this.prevBounds.width,\n\t\theightDelta: this.elementBounds.height - this.prevBounds.height,\n\t};\n\n\tthis.onResize(this, size);\n\n\tthis.trigger(\"resized\", size);\n\n};\n\n\nIframeView.prototype.load = function(contents) {\n\tvar loading = new RSVP.defer();\n\tvar loaded = loading.promise;\n\n\tif(!this.iframe) {\n\t\tloading.reject(new Error(\"No Iframe Available\"));\n\t\treturn loaded;\n\t}\n\n\tthis.iframe.onload = function(event) {\n\n\t\tthis.onLoad(event, loading);\n\n\t}.bind(this);\n\n\tif(this.supportsSrcdoc){\n\t\tthis.iframe.srcdoc = contents;\n\t} else {\n\n\t\tthis.document = this.iframe.contentDocument;\n\n\t\tif(!this.document) {\n\t\t\tloading.reject(new Error(\"No Document Available\"));\n\t\t\treturn loaded;\n\t\t}\n\n\t\tthis.iframe.contentDocument.open();\n\t\tthis.iframe.contentDocument.write(contents);\n\t\tthis.iframe.contentDocument.close();\n\n\t}\n\n\treturn loaded;\n};\n\nIframeView.prototype.onLoad = function(event, promise) {\n\n\t\tthis.window = this.iframe.contentWindow;\n\t\tthis.document = this.iframe.contentDocument;\n\n\t\tthis.contents = new Contents(this.document, this.document.body, this.section.cfiBase);\n\n\t\tthis.rendering = false;\n\n\t\tvar link = this.document.querySelector(\"link[rel='canonical']\");\n\t\tif (link) {\n\t\t\tlink.setAttribute(\"href\", this.section.url);\n\t\t} else {\n\t\t\tlink = this.document.createElement(\"link\");\n\t\t\tlink.setAttribute(\"rel\", \"canonical\");\n\t\t\tlink.setAttribute(\"href\", this.section.url);\n\t\t\tthis.document.querySelector(\"head\").appendChild(link);\n\t\t}\n\n\t\tthis.contents.on(\"expand\", function () {\n\t\t\tif(this.displayed && this.iframe) {\n\t\t\t\t\tthis.expand();\n\t\t\t}\n\t\t});\n\n\t\tpromise.resolve(this.contents);\n};\n\n\n\n// IframeView.prototype.layout = function(layoutFunc) {\n//\n// this.iframe.style.display = \"inline-block\";\n//\n// // Reset Body Styles\n// // this.document.body.style.margin = \"0\";\n// //this.document.body.style.display = \"inline-block\";\n// //this.document.documentElement.style.width = \"auto\";\n//\n// if(layoutFunc){\n// this.layoutFunc = layoutFunc;\n// }\n//\n// this.contents.layout(this.layoutFunc);\n//\n// };\n//\n// IframeView.prototype.onLayout = function(view) {\n// // stub\n// };\n\nIframeView.prototype.setLayout = function(layout) {\n\tthis.layout = layout;\n};\n\nIframeView.prototype.setAxis = function(axis) {\n\tthis.settings.axis = axis;\n};\n\nIframeView.prototype.resizeListenters = function() {\n\t// Test size again\n\tclearTimeout(this.expanding);\n\tthis.expanding = setTimeout(this.expand.bind(this), 350);\n};\n\nIframeView.prototype.addListeners = function() {\n\t//TODO: Add content listeners for expanding\n};\n\nIframeView.prototype.removeListeners = function(layoutFunc) {\n\t//TODO: remove content listeners for expanding\n};\n\nIframeView.prototype.display = function(request) {\n\tvar displayed = new RSVP.defer();\n\n\tif (!this.displayed) {\n\n\t\tthis.render(request).then(function () {\n\n\t\t\tthis.trigger(\"displayed\", this);\n\t\t\tthis.onDisplayed(this);\n\n\t\t\tthis.displayed = true;\n\t\t\tdisplayed.resolve(this);\n\n\t\t}.bind(this));\n\n\t} else {\n\t\tdisplayed.resolve(this);\n\t}\n\n\n\treturn displayed.promise;\n};\n\nIframeView.prototype.show = function() {\n\n\tthis.element.style.visibility = \"visible\";\n\n\tif(this.iframe){\n\t\tthis.iframe.style.visibility = \"visible\";\n\t}\n\n\tthis.trigger(\"shown\", this);\n};\n\nIframeView.prototype.hide = function() {\n\t// this.iframe.style.display = \"none\";\n\tthis.element.style.visibility = \"hidden\";\n\tthis.iframe.style.visibility = \"hidden\";\n\n\tthis.stopExpanding = true;\n\tthis.trigger(\"hidden\", this);\n};\n\nIframeView.prototype.position = function() {\n\treturn this.element.getBoundingClientRect();\n};\n\nIframeView.prototype.locationOf = function(target) {\n\tvar parentPos = this.iframe.getBoundingClientRect();\n\tvar targetPos = this.contents.locationOf(target, this.settings.ignoreClass);\n\n\treturn {\n\t\t\"left\": window.scrollX + parentPos.left + targetPos.left,\n\t\t\"top\": window.scrollY + parentPos.top + targetPos.top\n\t};\n};\n\nIframeView.prototype.onDisplayed = function(view) {\n\t// Stub, override with a custom functions\n};\n\nIframeView.prototype.onResize = function(view, e) {\n\t// Stub, override with a custom functions\n};\n\nIframeView.prototype.bounds = function() {\n\tif(!this.elementBounds) {\n\t\tthis.elementBounds = core.bounds(this.element);\n\t}\n\treturn this.elementBounds;\n};\n\nIframeView.prototype.destroy = function() {\n\n\tif(this.displayed){\n\t\tthis.displayed = false;\n\n\t\tthis.removeListeners();\n\n\t\tthis.stopExpanding = true;\n\t\tthis.element.removeChild(this.iframe);\n\t\tthis.displayed = false;\n\t\tthis.iframe = null;\n\n\t\tthis._textWidth = null;\n\t\tthis._textHeight = null;\n\t\tthis._width = null;\n\t\tthis._height = null;\n\t}\n\t// this.element.style.height = \"0px\";\n\t// this.element.style.width = \"0px\";\n};\n\nRSVP.EventTarget.mixin(IframeView.prototype);\n\nmodule.exports = IframeView;\n","var Book = require('./book');\nvar EpubCFI = require('./epubcfi');\nvar Rendition = require('./rendition');\nvar Contents = require('./contents');\nvar RSVP = require('rsvp');\n\nfunction ePub(_url) {\n\treturn new Book(_url);\n};\n\nePub.VERSION = \"0.3.0\";\n\nePub.CFI = EpubCFI;\nePub.Rendition = Rendition;\nePub.Contents = Contents;\nePub.RSVP = RSVP;\n\nePub.ViewManagers = {};\nePub.Views = {};\nePub.register = {\n\tmanager : function(name, manager){\n\t\treturn ePub.ViewManagers[name] = manager;\n\t},\n\tview : function(name, view){\n\t\treturn ePub.Views[name] = view;\n\t}\n};\n\n// Default Views\nePub.register.view(\"iframe\", require('./views/iframe'));\n// ePub.register.view(\"inline\", require('./views/inline'));\n\n// Default View Managers\nePub.register.manager(\"single\", require('./managers/single'));\nePub.register.manager(\"continuous\", require('./managers/continuous'));\n\nmodule.exports = ePub;\n"]} \ No newline at end of file +{"version":3,"sources":["node_modules/browser-pack/_prelude.js","libs/mime/mime.js","node_modules/base64-js/index.js","node_modules/browserify/lib/_empty.js","node_modules/process/browser.js","node_modules/rsvp/dist/rsvp.js","node_modules/urijs/src/SecondLevelDomains.js","node_modules/urijs/src/URI.js","src/book.js","src/contents.js","src/core.js","src/epubcfi.js","src/hook.js","src/layout.js","src/locations.js","src/managers/continuous.js","src/managers/helpers/stage.js","src/managers/helpers/views.js","src/managers/single.js","src/managers/views/iframe.js","src/mapping.js","src/navigation.js","src/parser.js","src/queue.js","src/rendition.js","src/replacements.js","src/request.js","src/section.js","src/spine.js","src/unarchive.js","src/epub.js"],"names":[],"mappings":"AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3KA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;ACpLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;;;ACh8EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClqEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3VA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxpBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5hBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC16BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3DA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/NA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxqBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChiBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9jBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzSA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3eA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5JA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7LA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"epub.js","sourceRoot":"/source/","sourcesContent":["(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require==\"function\"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error(\"Cannot find module '\"+o+\"'\");throw f.code=\"MODULE_NOT_FOUND\",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require==\"function\"&&require;for(var o=0;o 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n}\n\nfunction byteLength (b64) {\n // base64 is 4/3 + up to two characters of the original data\n return b64.length * 3 / 4 - placeHoldersCount(b64)\n}\n\nfunction toByteArray (b64) {\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n placeHolders = placeHoldersCount(b64)\n\n arr = new Arr(len * 3 / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n","","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","/*!\n * @overview RSVP - a tiny implementation of Promises/A+.\n * @copyright Copyright (c) 2016 Yehuda Katz, Tom Dale, Stefan Penner and contributors\n * @license Licensed under MIT license\n * See https://raw.githubusercontent.com/tildeio/rsvp.js/master/LICENSE\n * @version 3.3.2\n */\n\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (factory((global.RSVP = global.RSVP || {})));\n}(this, (function (exports) { 'use strict';\n\nfunction indexOf(callbacks, callback) {\n for (var i = 0, l = callbacks.length; i < l; i++) {\n if (callbacks[i] === callback) {\n return i;\n }\n }\n\n return -1;\n}\n\nfunction callbacksFor(object) {\n var callbacks = object._promiseCallbacks;\n\n if (!callbacks) {\n callbacks = object._promiseCallbacks = {};\n }\n\n return callbacks;\n}\n\n/**\n @class RSVP.EventTarget\n*/\nvar EventTarget = {\n\n /**\n `RSVP.EventTarget.mixin` extends an object with EventTarget methods. For\n Example:\n ```javascript\n let object = {};\n RSVP.EventTarget.mixin(object);\n object.on('finished', function(event) {\n // handle event\n });\n object.trigger('finished', { detail: value });\n ```\n `EventTarget.mixin` also works with prototypes:\n ```javascript\n let Person = function() {};\n RSVP.EventTarget.mixin(Person.prototype);\n let yehuda = new Person();\n let tom = new Person();\n yehuda.on('poke', function(event) {\n console.log('Yehuda says OW');\n });\n tom.on('poke', function(event) {\n console.log('Tom says OW');\n });\n yehuda.trigger('poke');\n tom.trigger('poke');\n ```\n @method mixin\n @for RSVP.EventTarget\n @private\n @param {Object} object object to extend with EventTarget methods\n */\n mixin: function mixin(object) {\n object['on'] = this['on'];\n object['off'] = this['off'];\n object['trigger'] = this['trigger'];\n object._promiseCallbacks = undefined;\n return object;\n },\n\n /**\n Registers a callback to be executed when `eventName` is triggered\n ```javascript\n object.on('event', function(eventInfo){\n // handle the event\n });\n object.trigger('event');\n ```\n @method on\n @for RSVP.EventTarget\n @private\n @param {String} eventName name of the event to listen for\n @param {Function} callback function to be called when the event is triggered.\n */\n on: function on(eventName, callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function');\n }\n\n var allCallbacks = callbacksFor(this),\n callbacks = undefined;\n\n callbacks = allCallbacks[eventName];\n\n if (!callbacks) {\n callbacks = allCallbacks[eventName] = [];\n }\n\n if (indexOf(callbacks, callback) === -1) {\n callbacks.push(callback);\n }\n },\n\n /**\n You can use `off` to stop firing a particular callback for an event:\n ```javascript\n function doStuff() { // do stuff! }\n object.on('stuff', doStuff);\n object.trigger('stuff'); // doStuff will be called\n // Unregister ONLY the doStuff callback\n object.off('stuff', doStuff);\n object.trigger('stuff'); // doStuff will NOT be called\n ```\n If you don't pass a `callback` argument to `off`, ALL callbacks for the\n event will not be executed when the event fires. For example:\n ```javascript\n let callback1 = function(){};\n let callback2 = function(){};\n object.on('stuff', callback1);\n object.on('stuff', callback2);\n object.trigger('stuff'); // callback1 and callback2 will be executed.\n object.off('stuff');\n object.trigger('stuff'); // callback1 and callback2 will not be executed!\n ```\n @method off\n @for RSVP.EventTarget\n @private\n @param {String} eventName event to stop listening to\n @param {Function} callback optional argument. If given, only the function\n given will be removed from the event's callback queue. If no `callback`\n argument is given, all callbacks will be removed from the event's callback\n queue.\n */\n off: function off(eventName, callback) {\n var allCallbacks = callbacksFor(this),\n callbacks = undefined,\n index = undefined;\n\n if (!callback) {\n allCallbacks[eventName] = [];\n return;\n }\n\n callbacks = allCallbacks[eventName];\n\n index = indexOf(callbacks, callback);\n\n if (index !== -1) {\n callbacks.splice(index, 1);\n }\n },\n\n /**\n Use `trigger` to fire custom events. For example:\n ```javascript\n object.on('foo', function(){\n console.log('foo event happened!');\n });\n object.trigger('foo');\n // 'foo event happened!' logged to the console\n ```\n You can also pass a value as a second argument to `trigger` that will be\n passed as an argument to all event listeners for the event:\n ```javascript\n object.on('foo', function(value){\n console.log(value.name);\n });\n object.trigger('foo', { name: 'bar' });\n // 'bar' logged to the console\n ```\n @method trigger\n @for RSVP.EventTarget\n @private\n @param {String} eventName name of the event to be triggered\n @param {*} options optional value to be passed to any event handlers for\n the given `eventName`\n */\n trigger: function trigger(eventName, options, label) {\n var allCallbacks = callbacksFor(this),\n callbacks = undefined,\n callback = undefined;\n\n if (callbacks = allCallbacks[eventName]) {\n // Don't cache the callbacks.length since it may grow\n for (var i = 0; i < callbacks.length; i++) {\n callback = callbacks[i];\n\n callback(options, label);\n }\n }\n }\n};\n\nvar config = {\n instrument: false\n};\n\nEventTarget['mixin'](config);\n\nfunction configure(name, value) {\n if (name === 'onerror') {\n // handle for legacy users that expect the actual\n // error to be passed to their function added via\n // `RSVP.configure('onerror', someFunctionHere);`\n config['on']('error', value);\n return;\n }\n\n if (arguments.length === 2) {\n config[name] = value;\n } else {\n return config[name];\n }\n}\n\nfunction objectOrFunction(x) {\n return typeof x === 'function' || typeof x === 'object' && x !== null;\n}\n\nfunction isFunction(x) {\n return typeof x === 'function';\n}\n\nfunction isMaybeThenable(x) {\n return typeof x === 'object' && x !== null;\n}\n\nvar _isArray = undefined;\nif (!Array.isArray) {\n _isArray = function (x) {\n return Object.prototype.toString.call(x) === '[object Array]';\n };\n} else {\n _isArray = Array.isArray;\n}\n\nvar isArray = _isArray;\n\n// Date.now is not available in browsers < IE9\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility\nvar now = Date.now || function () {\n return new Date().getTime();\n};\n\nfunction F() {}\n\nvar o_create = Object.create || function (o) {\n if (arguments.length > 1) {\n throw new Error('Second argument not supported');\n }\n if (typeof o !== 'object') {\n throw new TypeError('Argument must be an object');\n }\n F.prototype = o;\n return new F();\n};\n\nvar queue = [];\n\nfunction scheduleFlush() {\n setTimeout(function () {\n for (var i = 0; i < queue.length; i++) {\n var entry = queue[i];\n\n var payload = entry.payload;\n\n payload.guid = payload.key + payload.id;\n payload.childGuid = payload.key + payload.childId;\n if (payload.error) {\n payload.stack = payload.error.stack;\n }\n\n config['trigger'](entry.name, entry.payload);\n }\n queue.length = 0;\n }, 50);\n}\nfunction instrument(eventName, promise, child) {\n if (1 === queue.push({\n name: eventName,\n payload: {\n key: promise._guidKey,\n id: promise._id,\n eventName: eventName,\n detail: promise._result,\n childId: child && child._id,\n label: promise._label,\n timeStamp: now(),\n error: config[\"instrument-with-stack\"] ? new Error(promise._label) : null\n } })) {\n scheduleFlush();\n }\n}\n\n/**\n `RSVP.Promise.resolve` returns a promise that will become resolved with the\n passed `value`. It is shorthand for the following:\n\n ```javascript\n let promise = new RSVP.Promise(function(resolve, reject){\n resolve(1);\n });\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = RSVP.Promise.resolve(1);\n\n promise.then(function(value){\n // value === 1\n });\n ```\n\n @method resolve\n @static\n @param {*} object value that the returned promise will be resolved with\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve$1(object, label) {\n /*jshint validthis:true */\n var Constructor = this;\n\n if (object && typeof object === 'object' && object.constructor === Constructor) {\n return object;\n }\n\n var promise = new Constructor(noop, label);\n resolve(promise, object);\n return promise;\n}\n\nfunction withOwnPromise() {\n return new TypeError('A promises callback cannot return that same promise.');\n}\n\nfunction noop() {}\n\nvar PENDING = void 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\n\nvar GET_THEN_ERROR = new ErrorObject();\n\nfunction getThen(promise) {\n try {\n return promise.then;\n } catch (error) {\n GET_THEN_ERROR.error = error;\n return GET_THEN_ERROR;\n }\n}\n\nfunction tryThen(then, value, fulfillmentHandler, rejectionHandler) {\n try {\n then.call(value, fulfillmentHandler, rejectionHandler);\n } catch (e) {\n return e;\n }\n}\n\nfunction handleForeignThenable(promise, thenable, then) {\n config.async(function (promise) {\n var sealed = false;\n var error = tryThen(then, thenable, function (value) {\n if (sealed) {\n return;\n }\n sealed = true;\n if (thenable !== value) {\n resolve(promise, value, undefined);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n if (sealed) {\n return;\n }\n sealed = true;\n\n reject(promise, reason);\n }, 'Settle: ' + (promise._label || ' unknown promise'));\n\n if (!sealed && error) {\n sealed = true;\n reject(promise, error);\n }\n }, promise);\n}\n\nfunction handleOwnThenable(promise, thenable) {\n if (thenable._state === FULFILLED) {\n fulfill(promise, thenable._result);\n } else if (thenable._state === REJECTED) {\n thenable._onError = null;\n reject(promise, thenable._result);\n } else {\n subscribe(thenable, undefined, function (value) {\n if (thenable !== value) {\n resolve(promise, value, undefined);\n } else {\n fulfill(promise, value);\n }\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n}\n\nfunction handleMaybeThenable(promise, maybeThenable, then$$) {\n if (maybeThenable.constructor === promise.constructor && then$$ === then && promise.constructor.resolve === resolve$1) {\n handleOwnThenable(promise, maybeThenable);\n } else {\n if (then$$ === GET_THEN_ERROR) {\n reject(promise, GET_THEN_ERROR.error);\n } else if (then$$ === undefined) {\n fulfill(promise, maybeThenable);\n } else if (isFunction(then$$)) {\n handleForeignThenable(promise, maybeThenable, then$$);\n } else {\n fulfill(promise, maybeThenable);\n }\n }\n}\n\nfunction resolve(promise, value) {\n if (promise === value) {\n fulfill(promise, value);\n } else if (objectOrFunction(value)) {\n handleMaybeThenable(promise, value, getThen(value));\n } else {\n fulfill(promise, value);\n }\n}\n\nfunction publishRejection(promise) {\n if (promise._onError) {\n promise._onError(promise._result);\n }\n\n publish(promise);\n}\n\nfunction fulfill(promise, value) {\n if (promise._state !== PENDING) {\n return;\n }\n\n promise._result = value;\n promise._state = FULFILLED;\n\n if (promise._subscribers.length === 0) {\n if (config.instrument) {\n instrument('fulfilled', promise);\n }\n } else {\n config.async(publish, promise);\n }\n}\n\nfunction reject(promise, reason) {\n if (promise._state !== PENDING) {\n return;\n }\n promise._state = REJECTED;\n promise._result = reason;\n config.async(publishRejection, promise);\n}\n\nfunction subscribe(parent, child, onFulfillment, onRejection) {\n var subscribers = parent._subscribers;\n var length = subscribers.length;\n\n parent._onError = null;\n\n subscribers[length] = child;\n subscribers[length + FULFILLED] = onFulfillment;\n subscribers[length + REJECTED] = onRejection;\n\n if (length === 0 && parent._state) {\n config.async(publish, parent);\n }\n}\n\nfunction publish(promise) {\n var subscribers = promise._subscribers;\n var settled = promise._state;\n\n if (config.instrument) {\n instrument(settled === FULFILLED ? 'fulfilled' : 'rejected', promise);\n }\n\n if (subscribers.length === 0) {\n return;\n }\n\n var child = undefined,\n callback = undefined,\n detail = promise._result;\n\n for (var i = 0; i < subscribers.length; i += 3) {\n child = subscribers[i];\n callback = subscribers[i + settled];\n\n if (child) {\n invokeCallback(settled, child, callback, detail);\n } else {\n callback(detail);\n }\n }\n\n promise._subscribers.length = 0;\n}\n\nfunction ErrorObject() {\n this.error = null;\n}\n\nvar TRY_CATCH_ERROR = new ErrorObject();\n\nfunction tryCatch(callback, detail) {\n try {\n return callback(detail);\n } catch (e) {\n TRY_CATCH_ERROR.error = e;\n return TRY_CATCH_ERROR;\n }\n}\n\nfunction invokeCallback(settled, promise, callback, detail) {\n var hasCallback = isFunction(callback),\n value = undefined,\n error = undefined,\n succeeded = undefined,\n failed = undefined;\n\n if (hasCallback) {\n value = tryCatch(callback, detail);\n\n if (value === TRY_CATCH_ERROR) {\n failed = true;\n error = value.error;\n value = null;\n } else {\n succeeded = true;\n }\n\n if (promise === value) {\n reject(promise, withOwnPromise());\n return;\n }\n } else {\n value = detail;\n succeeded = true;\n }\n\n if (promise._state !== PENDING) {\n // noop\n } else if (hasCallback && succeeded) {\n resolve(promise, value);\n } else if (failed) {\n reject(promise, error);\n } else if (settled === FULFILLED) {\n fulfill(promise, value);\n } else if (settled === REJECTED) {\n reject(promise, value);\n }\n}\n\nfunction initializePromise(promise, resolver) {\n var resolved = false;\n try {\n resolver(function (value) {\n if (resolved) {\n return;\n }\n resolved = true;\n resolve(promise, value);\n }, function (reason) {\n if (resolved) {\n return;\n }\n resolved = true;\n reject(promise, reason);\n });\n } catch (e) {\n reject(promise, e);\n }\n}\n\nfunction then(onFulfillment, onRejection, label) {\n var _arguments = arguments;\n\n var parent = this;\n var state = parent._state;\n\n if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) {\n config.instrument && instrument('chained', parent, parent);\n return parent;\n }\n\n parent._onError = null;\n\n var child = new parent.constructor(noop, label);\n var result = parent._result;\n\n config.instrument && instrument('chained', parent, child);\n\n if (state) {\n (function () {\n var callback = _arguments[state - 1];\n config.async(function () {\n return invokeCallback(state, child, callback, result);\n });\n })();\n } else {\n subscribe(parent, child, onFulfillment, onRejection);\n }\n\n return child;\n}\n\nfunction makeSettledResult(state, position, value) {\n if (state === FULFILLED) {\n return {\n state: 'fulfilled',\n value: value\n };\n } else {\n return {\n state: 'rejected',\n reason: value\n };\n }\n}\n\nfunction Enumerator(Constructor, input, abortOnReject, label) {\n this._instanceConstructor = Constructor;\n this.promise = new Constructor(noop, label);\n this._abortOnReject = abortOnReject;\n\n if (this._validateInput(input)) {\n this._input = input;\n this.length = input.length;\n this._remaining = input.length;\n\n this._init();\n\n if (this.length === 0) {\n fulfill(this.promise, this._result);\n } else {\n this.length = this.length || 0;\n this._enumerate();\n if (this._remaining === 0) {\n fulfill(this.promise, this._result);\n }\n }\n } else {\n reject(this.promise, this._validationError());\n }\n}\n\nEnumerator.prototype._validateInput = function (input) {\n return isArray(input);\n};\n\nEnumerator.prototype._validationError = function () {\n return new Error('Array Methods must be provided an Array');\n};\n\nEnumerator.prototype._init = function () {\n this._result = new Array(this.length);\n};\n\nEnumerator.prototype._enumerate = function () {\n var length = this.length;\n var promise = this.promise;\n var input = this._input;\n\n for (var i = 0; promise._state === PENDING && i < length; i++) {\n this._eachEntry(input[i], i);\n }\n};\n\nEnumerator.prototype._settleMaybeThenable = function (entry, i) {\n var c = this._instanceConstructor;\n var resolve = c.resolve;\n\n if (resolve === resolve$1) {\n var then$$ = getThen(entry);\n\n if (then$$ === then && entry._state !== PENDING) {\n entry._onError = null;\n this._settledAt(entry._state, i, entry._result);\n } else if (typeof then$$ !== 'function') {\n this._remaining--;\n this._result[i] = this._makeResult(FULFILLED, i, entry);\n } else if (c === Promise) {\n var promise = new c(noop);\n handleMaybeThenable(promise, entry, then$$);\n this._willSettleAt(promise, i);\n } else {\n this._willSettleAt(new c(function (resolve) {\n return resolve(entry);\n }), i);\n }\n } else {\n this._willSettleAt(resolve(entry), i);\n }\n};\n\nEnumerator.prototype._eachEntry = function (entry, i) {\n if (isMaybeThenable(entry)) {\n this._settleMaybeThenable(entry, i);\n } else {\n this._remaining--;\n this._result[i] = this._makeResult(FULFILLED, i, entry);\n }\n};\n\nEnumerator.prototype._settledAt = function (state, i, value) {\n var promise = this.promise;\n\n if (promise._state === PENDING) {\n this._remaining--;\n\n if (this._abortOnReject && state === REJECTED) {\n reject(promise, value);\n } else {\n this._result[i] = this._makeResult(state, i, value);\n }\n }\n\n if (this._remaining === 0) {\n fulfill(promise, this._result);\n }\n};\n\nEnumerator.prototype._makeResult = function (state, i, value) {\n return value;\n};\n\nEnumerator.prototype._willSettleAt = function (promise, i) {\n var enumerator = this;\n\n subscribe(promise, undefined, function (value) {\n return enumerator._settledAt(FULFILLED, i, value);\n }, function (reason) {\n return enumerator._settledAt(REJECTED, i, reason);\n });\n};\n\n/**\n `RSVP.Promise.all` accepts an array of promises, and returns a new promise which\n is fulfilled with an array of fulfillment values for the passed promises, or\n rejected with the reason of the first passed promise to be rejected. It casts all\n elements of the passed iterable to promises as it runs this algorithm.\n\n Example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.Promise.all(promises).then(function(array){\n // The array here would be [ 1, 2, 3 ];\n });\n ```\n\n If any of the `promises` given to `RSVP.all` are rejected, the first promise\n that is rejected will be given as an argument to the returned promises's\n rejection handler. For example:\n\n Example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error(\"2\"));\n let promise3 = RSVP.reject(new Error(\"3\"));\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.Promise.all(promises).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(error) {\n // error.message === \"2\"\n });\n ```\n\n @method all\n @static\n @param {Array} entries array of promises\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all `promises` have been\n fulfilled, or rejected if any of them become rejected.\n @static\n*/\nfunction all(entries, label) {\n return new Enumerator(this, entries, true, /* abort on reject */label).promise;\n}\n\n/**\n `RSVP.Promise.race` returns a new promise which is settled in the same way as the\n first passed promise to settle.\n\n Example:\n\n ```javascript\n let promise1 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 2');\n }, 100);\n });\n\n RSVP.Promise.race([promise1, promise2]).then(function(result){\n // result === 'promise 2' because it was resolved before promise1\n // was resolved.\n });\n ```\n\n `RSVP.Promise.race` is deterministic in that only the state of the first\n settled promise matters. For example, even if other promises given to the\n `promises` array argument are resolved, but the first settled promise has\n become rejected before the other promises became fulfilled, the returned\n promise will become rejected:\n\n ```javascript\n let promise1 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n resolve('promise 1');\n }, 200);\n });\n\n let promise2 = new RSVP.Promise(function(resolve, reject){\n setTimeout(function(){\n reject(new Error('promise 2'));\n }, 100);\n });\n\n RSVP.Promise.race([promise1, promise2]).then(function(result){\n // Code here never runs\n }, function(reason){\n // reason.message === 'promise 2' because promise 2 became rejected before\n // promise 1 became fulfilled\n });\n ```\n\n An example real-world use case is implementing timeouts:\n\n ```javascript\n RSVP.Promise.race([ajax('foo.json'), timeout(5000)])\n ```\n\n @method race\n @static\n @param {Array} entries array of promises to observe\n @param {String} label optional string for describing the promise returned.\n Useful for tooling.\n @return {Promise} a promise which settles in the same way as the first passed\n promise to settle.\n*/\nfunction race(entries, label) {\n /*jshint validthis:true */\n var Constructor = this;\n\n var promise = new Constructor(noop, label);\n\n if (!isArray(entries)) {\n reject(promise, new TypeError('You must pass an array to race.'));\n return promise;\n }\n\n for (var i = 0; promise._state === PENDING && i < entries.length; i++) {\n subscribe(Constructor.resolve(entries[i]), undefined, function (value) {\n return resolve(promise, value);\n }, function (reason) {\n return reject(promise, reason);\n });\n }\n\n return promise;\n}\n\n/**\n `RSVP.Promise.reject` returns a promise rejected with the passed `reason`.\n It is shorthand for the following:\n\n ```javascript\n let promise = new RSVP.Promise(function(resolve, reject){\n reject(new Error('WHOOPS'));\n });\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n Instead of writing the above, your code now simply becomes the following:\n\n ```javascript\n let promise = RSVP.Promise.reject(new Error('WHOOPS'));\n\n promise.then(function(value){\n // Code here doesn't run because the promise is rejected!\n }, function(reason){\n // reason.message === 'WHOOPS'\n });\n ```\n\n @method reject\n @static\n @param {*} reason value that the returned promise will be rejected with.\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject$1(reason, label) {\n /*jshint validthis:true */\n var Constructor = this;\n var promise = new Constructor(noop, label);\n reject(promise, reason);\n return promise;\n}\n\nvar guidKey = 'rsvp_' + now() + '-';\nvar counter = 0;\n\nfunction needsResolver() {\n throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');\n}\n\nfunction needsNew() {\n throw new TypeError(\"Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.\");\n}\n\n/**\n Promise objects represent the eventual result of an asynchronous operation. The\n primary way of interacting with a promise is through its `then` method, which\n registers callbacks to receive either a promise’s eventual value or the reason\n why the promise cannot be fulfilled.\n\n Terminology\n -----------\n\n - `promise` is an object or function with a `then` method whose behavior conforms to this specification.\n - `thenable` is an object or function that defines a `then` method.\n - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).\n - `exception` is a value that is thrown using the throw statement.\n - `reason` is a value that indicates why a promise was rejected.\n - `settled` the final resting state of a promise, fulfilled or rejected.\n\n A promise can be in one of three states: pending, fulfilled, or rejected.\n\n Promises that are fulfilled have a fulfillment value and are in the fulfilled\n state. Promises that are rejected have a rejection reason and are in the\n rejected state. A fulfillment value is never a thenable.\n\n Promises can also be said to *resolve* a value. If this value is also a\n promise, then the original promise's settled state will match the value's\n settled state. So a promise that *resolves* a promise that rejects will\n itself reject, and a promise that *resolves* a promise that fulfills will\n itself fulfill.\n\n\n Basic Usage:\n ------------\n\n ```js\n let promise = new Promise(function(resolve, reject) {\n // on success\n resolve(value);\n\n // on failure\n reject(reason);\n });\n\n promise.then(function(value) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Advanced Usage:\n ---------------\n\n Promises shine when abstracting away asynchronous interactions such as\n `XMLHttpRequest`s.\n\n ```js\n function getJSON(url) {\n return new Promise(function(resolve, reject){\n let xhr = new XMLHttpRequest();\n\n xhr.open('GET', url);\n xhr.onreadystatechange = handler;\n xhr.responseType = 'json';\n xhr.setRequestHeader('Accept', 'application/json');\n xhr.send();\n\n function handler() {\n if (this.readyState === this.DONE) {\n if (this.status === 200) {\n resolve(this.response);\n } else {\n reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));\n }\n }\n };\n });\n }\n\n getJSON('/posts.json').then(function(json) {\n // on fulfillment\n }, function(reason) {\n // on rejection\n });\n ```\n\n Unlike callbacks, promises are great composable primitives.\n\n ```js\n Promise.all([\n getJSON('/posts'),\n getJSON('/comments')\n ]).then(function(values){\n values[0] // => postsJSON\n values[1] // => commentsJSON\n\n return values;\n });\n ```\n\n @class RSVP.Promise\n @param {function} resolver\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @constructor\n*/\nfunction Promise(resolver, label) {\n this._id = counter++;\n this._label = label;\n this._state = undefined;\n this._result = undefined;\n this._subscribers = [];\n\n config.instrument && instrument('created', this);\n\n if (noop !== resolver) {\n typeof resolver !== 'function' && needsResolver();\n this instanceof Promise ? initializePromise(this, resolver) : needsNew();\n }\n}\n\nPromise.cast = resolve$1; // deprecated\nPromise.all = all;\nPromise.race = race;\nPromise.resolve = resolve$1;\nPromise.reject = reject$1;\n\nPromise.prototype = {\n constructor: Promise,\n\n _guidKey: guidKey,\n\n _onError: function _onError(reason) {\n var promise = this;\n config.after(function () {\n if (promise._onError) {\n config['trigger']('error', reason, promise._label);\n }\n });\n },\n\n /**\n The primary way of interacting with a promise is through its `then` method,\n which registers callbacks to receive either a promise's eventual value or the\n reason why the promise cannot be fulfilled.\n \n ```js\n findUser().then(function(user){\n // user is available\n }, function(reason){\n // user is unavailable, and you are given the reason why\n });\n ```\n \n Chaining\n --------\n \n The return value of `then` is itself a promise. This second, 'downstream'\n promise is resolved with the return value of the first promise's fulfillment\n or rejection handler, or rejected if the handler throws an exception.\n \n ```js\n findUser().then(function (user) {\n return user.name;\n }, function (reason) {\n return 'default name';\n }).then(function (userName) {\n // If `findUser` fulfilled, `userName` will be the user's name, otherwise it\n // will be `'default name'`\n });\n \n findUser().then(function (user) {\n throw new Error('Found user, but still unhappy');\n }, function (reason) {\n throw new Error('`findUser` rejected and we\\'re unhappy');\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.\n // If `findUser` rejected, `reason` will be '`findUser` rejected and we\\'re unhappy'.\n });\n ```\n If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.\n \n ```js\n findUser().then(function (user) {\n throw new PedagogicalException('Upstream error');\n }).then(function (value) {\n // never reached\n }).then(function (value) {\n // never reached\n }, function (reason) {\n // The `PedgagocialException` is propagated all the way down to here\n });\n ```\n \n Assimilation\n ------------\n \n Sometimes the value you want to propagate to a downstream promise can only be\n retrieved asynchronously. This can be achieved by returning a promise in the\n fulfillment or rejection handler. The downstream promise will then be pending\n until the returned promise is settled. This is called *assimilation*.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // The user's comments are now available\n });\n ```\n \n If the assimliated promise rejects, then the downstream promise will also reject.\n \n ```js\n findUser().then(function (user) {\n return findCommentsByAuthor(user);\n }).then(function (comments) {\n // If `findCommentsByAuthor` fulfills, we'll have the value here\n }, function (reason) {\n // If `findCommentsByAuthor` rejects, we'll have the reason here\n });\n ```\n \n Simple Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let result;\n \n try {\n result = findResult();\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n findResult(function(result, err){\n if (err) {\n // failure\n } else {\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findResult().then(function(result){\n // success\n }, function(reason){\n // failure\n });\n ```\n \n Advanced Example\n --------------\n \n Synchronous Example\n \n ```javascript\n let author, books;\n \n try {\n author = findAuthor();\n books = findBooksByAuthor(author);\n // success\n } catch(reason) {\n // failure\n }\n ```\n \n Errback Example\n \n ```js\n \n function foundBooks(books) {\n \n }\n \n function failure(reason) {\n \n }\n \n findAuthor(function(author, err){\n if (err) {\n failure(err);\n // failure\n } else {\n try {\n findBoooksByAuthor(author, function(books, err) {\n if (err) {\n failure(err);\n } else {\n try {\n foundBooks(books);\n } catch(reason) {\n failure(reason);\n }\n }\n });\n } catch(error) {\n failure(err);\n }\n // success\n }\n });\n ```\n \n Promise Example;\n \n ```javascript\n findAuthor().\n then(findBooksByAuthor).\n then(function(books){\n // found books\n }).catch(function(reason){\n // something went wrong\n });\n ```\n \n @method then\n @param {Function} onFulfillment\n @param {Function} onRejection\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n then: then,\n\n /**\n `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same\n as the catch block of a try/catch statement.\n \n ```js\n function findAuthor(){\n throw new Error('couldn\\'t find that author');\n }\n \n // synchronous\n try {\n findAuthor();\n } catch(reason) {\n // something went wrong\n }\n \n // async with promises\n findAuthor().catch(function(reason){\n // something went wrong\n });\n ```\n \n @method catch\n @param {Function} onRejection\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n 'catch': function _catch(onRejection, label) {\n return this.then(undefined, onRejection, label);\n },\n\n /**\n `finally` will be invoked regardless of the promise's fate just as native\n try/catch/finally behaves\n \n Synchronous example:\n \n ```js\n findAuthor() {\n if (Math.random() > 0.5) {\n throw new Error();\n }\n return new Author();\n }\n \n try {\n return findAuthor(); // succeed or fail\n } catch(error) {\n return findOtherAuther();\n } finally {\n // always runs\n // doesn't affect the return value\n }\n ```\n \n Asynchronous example:\n \n ```js\n findAuthor().catch(function(reason){\n return findOtherAuther();\n }).finally(function(){\n // author was either found, or not\n });\n ```\n \n @method finally\n @param {Function} callback\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise}\n */\n 'finally': function _finally(callback, label) {\n var promise = this;\n var constructor = promise.constructor;\n\n return promise.then(function (value) {\n return constructor.resolve(callback()).then(function () {\n return value;\n });\n }, function (reason) {\n return constructor.resolve(callback()).then(function () {\n throw reason;\n });\n }, label);\n }\n};\n\nfunction Result() {\n this.value = undefined;\n}\n\nvar ERROR = new Result();\nvar GET_THEN_ERROR$1 = new Result();\n\nfunction getThen$1(obj) {\n try {\n return obj.then;\n } catch (error) {\n ERROR.value = error;\n return ERROR;\n }\n}\n\nfunction tryApply(f, s, a) {\n try {\n f.apply(s, a);\n } catch (error) {\n ERROR.value = error;\n return ERROR;\n }\n}\n\nfunction makeObject(_, argumentNames) {\n var obj = {};\n var length = _.length;\n var args = new Array(length);\n\n for (var x = 0; x < length; x++) {\n args[x] = _[x];\n }\n\n for (var i = 0; i < argumentNames.length; i++) {\n var _name = argumentNames[i];\n obj[_name] = args[i + 1];\n }\n\n return obj;\n}\n\nfunction arrayResult(_) {\n var length = _.length;\n var args = new Array(length - 1);\n\n for (var i = 1; i < length; i++) {\n args[i - 1] = _[i];\n }\n\n return args;\n}\n\nfunction wrapThenable(_then, promise) {\n return {\n then: function then(onFulFillment, onRejection) {\n return _then.call(promise, onFulFillment, onRejection);\n }\n };\n}\n\n/**\n `RSVP.denodeify` takes a 'node-style' function and returns a function that\n will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the\n browser when you'd prefer to use promises over using callbacks. For example,\n `denodeify` transforms the following:\n\n ```javascript\n let fs = require('fs');\n\n fs.readFile('myfile.txt', function(err, data){\n if (err) return handleError(err);\n handleData(data);\n });\n ```\n\n into:\n\n ```javascript\n let fs = require('fs');\n let readFile = RSVP.denodeify(fs.readFile);\n\n readFile('myfile.txt').then(handleData, handleError);\n ```\n\n If the node function has multiple success parameters, then `denodeify`\n just returns the first one:\n\n ```javascript\n let request = RSVP.denodeify(require('request'));\n\n request('http://example.com').then(function(res) {\n // ...\n });\n ```\n\n However, if you need all success parameters, setting `denodeify`'s\n second parameter to `true` causes it to return all success parameters\n as an array:\n\n ```javascript\n let request = RSVP.denodeify(require('request'), true);\n\n request('http://example.com').then(function(result) {\n // result[0] -> res\n // result[1] -> body\n });\n ```\n\n Or if you pass it an array with names it returns the parameters as a hash:\n\n ```javascript\n let request = RSVP.denodeify(require('request'), ['res', 'body']);\n\n request('http://example.com').then(function(result) {\n // result.res\n // result.body\n });\n ```\n\n Sometimes you need to retain the `this`:\n\n ```javascript\n let app = require('express')();\n let render = RSVP.denodeify(app.render.bind(app));\n ```\n\n The denodified function inherits from the original function. It works in all\n environments, except IE 10 and below. Consequently all properties of the original\n function are available to you. However, any properties you change on the\n denodeified function won't be changed on the original function. Example:\n\n ```javascript\n let request = RSVP.denodeify(require('request')),\n cookieJar = request.jar(); // <- Inheritance is used here\n\n request('http://example.com', {jar: cookieJar}).then(function(res) {\n // cookieJar.cookies holds now the cookies returned by example.com\n });\n ```\n\n Using `denodeify` makes it easier to compose asynchronous operations instead\n of using callbacks. For example, instead of:\n\n ```javascript\n let fs = require('fs');\n\n fs.readFile('myfile.txt', function(err, data){\n if (err) { ... } // Handle error\n fs.writeFile('myfile2.txt', data, function(err){\n if (err) { ... } // Handle error\n console.log('done')\n });\n });\n ```\n\n you can chain the operations together using `then` from the returned promise:\n\n ```javascript\n let fs = require('fs');\n let readFile = RSVP.denodeify(fs.readFile);\n let writeFile = RSVP.denodeify(fs.writeFile);\n\n readFile('myfile.txt').then(function(data){\n return writeFile('myfile2.txt', data);\n }).then(function(){\n console.log('done')\n }).catch(function(error){\n // Handle error\n });\n ```\n\n @method denodeify\n @static\n @for RSVP\n @param {Function} nodeFunc a 'node-style' function that takes a callback as\n its last argument. The callback expects an error to be passed as its first\n argument (if an error occurred, otherwise null), and the value from the\n operation as its second argument ('function(err, value){ }').\n @param {Boolean|Array} [options] An optional paramter that if set\n to `true` causes the promise to fulfill with the callback's success arguments\n as an array. This is useful if the node function has multiple success\n paramters. If you set this paramter to an array with names, the promise will\n fulfill with a hash with these names as keys and the success parameters as\n values.\n @return {Function} a function that wraps `nodeFunc` to return an\n `RSVP.Promise`\n @static\n*/\nfunction denodeify(nodeFunc, options) {\n var fn = function fn() {\n var self = this;\n var l = arguments.length;\n var args = new Array(l + 1);\n var promiseInput = false;\n\n for (var i = 0; i < l; ++i) {\n var arg = arguments[i];\n\n if (!promiseInput) {\n // TODO: clean this up\n promiseInput = needsPromiseInput(arg);\n if (promiseInput === GET_THEN_ERROR$1) {\n var p = new Promise(noop);\n reject(p, GET_THEN_ERROR$1.value);\n return p;\n } else if (promiseInput && promiseInput !== true) {\n arg = wrapThenable(promiseInput, arg);\n }\n }\n args[i] = arg;\n }\n\n var promise = new Promise(noop);\n\n args[l] = function (err, val) {\n if (err) reject(promise, err);else if (options === undefined) resolve(promise, val);else if (options === true) resolve(promise, arrayResult(arguments));else if (isArray(options)) resolve(promise, makeObject(arguments, options));else resolve(promise, val);\n };\n\n if (promiseInput) {\n return handlePromiseInput(promise, args, nodeFunc, self);\n } else {\n return handleValueInput(promise, args, nodeFunc, self);\n }\n };\n\n fn.__proto__ = nodeFunc;\n\n return fn;\n}\n\nfunction handleValueInput(promise, args, nodeFunc, self) {\n var result = tryApply(nodeFunc, self, args);\n if (result === ERROR) {\n reject(promise, result.value);\n }\n return promise;\n}\n\nfunction handlePromiseInput(promise, args, nodeFunc, self) {\n return Promise.all(args).then(function (args) {\n var result = tryApply(nodeFunc, self, args);\n if (result === ERROR) {\n reject(promise, result.value);\n }\n return promise;\n });\n}\n\nfunction needsPromiseInput(arg) {\n if (arg && typeof arg === 'object') {\n if (arg.constructor === Promise) {\n return true;\n } else {\n return getThen$1(arg);\n }\n } else {\n return false;\n }\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.all`.\n\n @method all\n @static\n @for RSVP\n @param {Array} array Array of promises.\n @param {String} label An optional label. This is useful\n for tooling.\n*/\nfunction all$1(array, label) {\n return Promise.all(array, label);\n}\n\nfunction AllSettled(Constructor, entries, label) {\n this._superConstructor(Constructor, entries, false, /* don't abort on reject */label);\n}\n\nAllSettled.prototype = o_create(Enumerator.prototype);\nAllSettled.prototype._superConstructor = Enumerator;\nAllSettled.prototype._makeResult = makeSettledResult;\nAllSettled.prototype._validationError = function () {\n return new Error('allSettled must be called with an array');\n};\n\n/**\n `RSVP.allSettled` is similar to `RSVP.all`, but instead of implementing\n a fail-fast method, it waits until all the promises have returned and\n shows you all the results. This is useful if you want to handle multiple\n promises' failure states together as a set.\n\n Returns a promise that is fulfilled when all the given promises have been\n settled. The return promise is fulfilled with an array of the states of\n the promises passed into the `promises` array argument.\n\n Each state object will either indicate fulfillment or rejection, and\n provide the corresponding value or reason. The states will take one of\n the following formats:\n\n ```javascript\n { state: 'fulfilled', value: value }\n or\n { state: 'rejected', reason: reason }\n ```\n\n Example:\n\n ```javascript\n let promise1 = RSVP.Promise.resolve(1);\n let promise2 = RSVP.Promise.reject(new Error('2'));\n let promise3 = RSVP.Promise.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n RSVP.allSettled(promises).then(function(array){\n // array == [\n // { state: 'fulfilled', value: 1 },\n // { state: 'rejected', reason: Error },\n // { state: 'rejected', reason: Error }\n // ]\n // Note that for the second item, reason.message will be '2', and for the\n // third item, reason.message will be '3'.\n }, function(error) {\n // Not run. (This block would only be called if allSettled had failed,\n // for instance if passed an incorrect argument type.)\n });\n ```\n\n @method allSettled\n @static\n @for RSVP\n @param {Array} entries\n @param {String} label - optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled with an array of the settled\n states of the constituent promises.\n*/\nfunction allSettled(entries, label) {\n return new AllSettled(Promise, entries, label).promise;\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.race`.\n\n @method race\n @static\n @for RSVP\n @param {Array} array Array of promises.\n @param {String} label An optional label. This is useful\n for tooling.\n */\nfunction race$1(array, label) {\n return Promise.race(array, label);\n}\n\nfunction PromiseHash(Constructor, object, label) {\n this._superConstructor(Constructor, object, true, label);\n}\n\nPromiseHash.prototype = o_create(Enumerator.prototype);\nPromiseHash.prototype._superConstructor = Enumerator;\nPromiseHash.prototype._init = function () {\n this._result = {};\n};\n\nPromiseHash.prototype._validateInput = function (input) {\n return input && typeof input === 'object';\n};\n\nPromiseHash.prototype._validationError = function () {\n return new Error('Promise.hash must be called with an object');\n};\n\nPromiseHash.prototype._enumerate = function () {\n var enumerator = this;\n var promise = enumerator.promise;\n var input = enumerator._input;\n var results = [];\n\n for (var key in input) {\n if (promise._state === PENDING && Object.prototype.hasOwnProperty.call(input, key)) {\n results.push({\n position: key,\n entry: input[key]\n });\n }\n }\n\n var length = results.length;\n enumerator._remaining = length;\n var result = undefined;\n\n for (var i = 0; promise._state === PENDING && i < length; i++) {\n result = results[i];\n enumerator._eachEntry(result.entry, result.position);\n }\n};\n\n/**\n `RSVP.hash` is similar to `RSVP.all`, but takes an object instead of an array\n for its `promises` argument.\n\n Returns a promise that is fulfilled when all the given promises have been\n fulfilled, or rejected if any of them become rejected. The returned promise\n is fulfilled with a hash that has the same key names as the `promises` object\n argument. If any of the values in the object are not promises, they will\n simply be copied over to the fulfilled object.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.resolve(1),\n yourPromise: RSVP.resolve(2),\n theirPromise: RSVP.resolve(3),\n notAPromise: 4\n };\n\n RSVP.hash(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: 1,\n // yourPromise: 2,\n // theirPromise: 3,\n // notAPromise: 4\n // }\n });\n ````\n\n If any of the `promises` given to `RSVP.hash` are rejected, the first promise\n that is rejected will be given as the reason to the rejection handler.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.resolve(1),\n rejectedPromise: RSVP.reject(new Error('rejectedPromise')),\n anotherRejectedPromise: RSVP.reject(new Error('anotherRejectedPromise')),\n };\n\n RSVP.hash(promises).then(function(hash){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === 'rejectedPromise'\n });\n ```\n\n An important note: `RSVP.hash` is intended for plain JavaScript objects that\n are just a set of keys and values. `RSVP.hash` will NOT preserve prototype\n chains.\n\n Example:\n\n ```javascript\n function MyConstructor(){\n this.example = RSVP.resolve('Example');\n }\n\n MyConstructor.prototype = {\n protoProperty: RSVP.resolve('Proto Property')\n };\n\n let myObject = new MyConstructor();\n\n RSVP.hash(myObject).then(function(hash){\n // protoProperty will not be present, instead you will just have an\n // object that looks like:\n // {\n // example: 'Example'\n // }\n //\n // hash.hasOwnProperty('protoProperty'); // false\n // 'undefined' === typeof hash.protoProperty\n });\n ```\n\n @method hash\n @static\n @for RSVP\n @param {Object} object\n @param {String} label optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when all properties of `promises`\n have been fulfilled, or rejected if any of them become rejected.\n*/\nfunction hash(object, label) {\n return new PromiseHash(Promise, object, label).promise;\n}\n\nfunction HashSettled(Constructor, object, label) {\n this._superConstructor(Constructor, object, false, label);\n}\n\nHashSettled.prototype = o_create(PromiseHash.prototype);\nHashSettled.prototype._superConstructor = Enumerator;\nHashSettled.prototype._makeResult = makeSettledResult;\n\nHashSettled.prototype._validationError = function () {\n return new Error('hashSettled must be called with an object');\n};\n\n/**\n `RSVP.hashSettled` is similar to `RSVP.allSettled`, but takes an object\n instead of an array for its `promises` argument.\n\n Unlike `RSVP.all` or `RSVP.hash`, which implement a fail-fast method,\n but like `RSVP.allSettled`, `hashSettled` waits until all the\n constituent promises have returned and then shows you all the results\n with their states and values/reasons. This is useful if you want to\n handle multiple promises' failure states together as a set.\n\n Returns a promise that is fulfilled when all the given promises have been\n settled, or rejected if the passed parameters are invalid.\n\n The returned promise is fulfilled with a hash that has the same key names as\n the `promises` object argument. If any of the values in the object are not\n promises, they will be copied over to the fulfilled object and marked with state\n 'fulfilled'.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.Promise.resolve(1),\n yourPromise: RSVP.Promise.resolve(2),\n theirPromise: RSVP.Promise.resolve(3),\n notAPromise: 4\n };\n\n RSVP.hashSettled(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: { state: 'fulfilled', value: 1 },\n // yourPromise: { state: 'fulfilled', value: 2 },\n // theirPromise: { state: 'fulfilled', value: 3 },\n // notAPromise: { state: 'fulfilled', value: 4 }\n // }\n });\n ```\n\n If any of the `promises` given to `RSVP.hash` are rejected, the state will\n be set to 'rejected' and the reason for rejection provided.\n\n Example:\n\n ```javascript\n let promises = {\n myPromise: RSVP.Promise.resolve(1),\n rejectedPromise: RSVP.Promise.reject(new Error('rejection')),\n anotherRejectedPromise: RSVP.Promise.reject(new Error('more rejection')),\n };\n\n RSVP.hashSettled(promises).then(function(hash){\n // hash here is an object that looks like:\n // {\n // myPromise: { state: 'fulfilled', value: 1 },\n // rejectedPromise: { state: 'rejected', reason: Error },\n // anotherRejectedPromise: { state: 'rejected', reason: Error },\n // }\n // Note that for rejectedPromise, reason.message == 'rejection',\n // and for anotherRejectedPromise, reason.message == 'more rejection'.\n });\n ```\n\n An important note: `RSVP.hashSettled` is intended for plain JavaScript objects that\n are just a set of keys and values. `RSVP.hashSettled` will NOT preserve prototype\n chains.\n\n Example:\n\n ```javascript\n function MyConstructor(){\n this.example = RSVP.Promise.resolve('Example');\n }\n\n MyConstructor.prototype = {\n protoProperty: RSVP.Promise.resolve('Proto Property')\n };\n\n let myObject = new MyConstructor();\n\n RSVP.hashSettled(myObject).then(function(hash){\n // protoProperty will not be present, instead you will just have an\n // object that looks like:\n // {\n // example: { state: 'fulfilled', value: 'Example' }\n // }\n //\n // hash.hasOwnProperty('protoProperty'); // false\n // 'undefined' === typeof hash.protoProperty\n });\n ```\n\n @method hashSettled\n @for RSVP\n @param {Object} object\n @param {String} label optional string that describes the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled when when all properties of `promises`\n have been settled.\n @static\n*/\nfunction hashSettled(object, label) {\n return new HashSettled(Promise, object, label).promise;\n}\n\nfunction rethrow(reason) {\n setTimeout(function () {\n throw reason;\n });\n throw reason;\n}\n\n/**\n `RSVP.defer` returns an object similar to jQuery's `$.Deferred`.\n `RSVP.defer` should be used when porting over code reliant on `$.Deferred`'s\n interface. New code should use the `RSVP.Promise` constructor instead.\n\n The object returned from `RSVP.defer` is a plain object with three properties:\n\n * promise - an `RSVP.Promise`.\n * reject - a function that causes the `promise` property on this object to\n become rejected\n * resolve - a function that causes the `promise` property on this object to\n become fulfilled.\n\n Example:\n\n ```javascript\n let deferred = RSVP.defer();\n\n deferred.resolve(\"Success!\");\n\n deferred.promise.then(function(value){\n // value here is \"Success!\"\n });\n ```\n\n @method defer\n @static\n @for RSVP\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Object}\n */\nfunction defer(label) {\n var deferred = { resolve: undefined, reject: undefined };\n\n deferred.promise = new Promise(function (resolve, reject) {\n deferred.resolve = resolve;\n deferred.reject = reject;\n }, label);\n\n return deferred;\n}\n\n/**\n `RSVP.map` is similar to JavaScript's native `map` method, except that it\n waits for all promises to become fulfilled before running the `mapFn` on\n each item in given to `promises`. `RSVP.map` returns a promise that will\n become fulfilled with the result of running `mapFn` on the values the promises\n become fulfilled with.\n\n For example:\n\n ```javascript\n\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n let promises = [ promise1, promise2, promise3 ];\n\n let mapFn = function(item){\n return item + 1;\n };\n\n RSVP.map(promises, mapFn).then(function(result){\n // result is [ 2, 3, 4 ]\n });\n ```\n\n If any of the `promises` given to `RSVP.map` are rejected, the first promise\n that is rejected will be given as an argument to the returned promise's\n rejection handler. For example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error('2'));\n let promise3 = RSVP.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n let mapFn = function(item){\n return item + 1;\n };\n\n RSVP.map(promises, mapFn).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === '2'\n });\n ```\n\n `RSVP.map` will also wait if a promise is returned from `mapFn`. For example,\n say you want to get all comments from a set of blog posts, but you need\n the blog posts first because they contain a url to those comments.\n\n ```javscript\n\n let mapFn = function(blogPost){\n // getComments does some ajax and returns an RSVP.Promise that is fulfilled\n // with some comments data\n return getComments(blogPost.comments_url);\n };\n\n // getBlogPosts does some ajax and returns an RSVP.Promise that is fulfilled\n // with some blog post data\n RSVP.map(getBlogPosts(), mapFn).then(function(comments){\n // comments is the result of asking the server for the comments\n // of all blog posts returned from getBlogPosts()\n });\n ```\n\n @method map\n @static\n @for RSVP\n @param {Array} promises\n @param {Function} mapFn function to be called on each fulfilled promise.\n @param {String} label optional string for labeling the promise.\n Useful for tooling.\n @return {Promise} promise that is fulfilled with the result of calling\n `mapFn` on each fulfilled promise or value when they become fulfilled.\n The promise will be rejected if any of the given `promises` become rejected.\n @static\n*/\nfunction map(promises, mapFn, label) {\n return Promise.all(promises, label).then(function (values) {\n if (!isFunction(mapFn)) {\n throw new TypeError(\"You must pass a function as map's second argument.\");\n }\n\n var length = values.length;\n var results = new Array(length);\n\n for (var i = 0; i < length; i++) {\n results[i] = mapFn(values[i]);\n }\n\n return Promise.all(results, label);\n });\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.resolve`.\n\n @method resolve\n @static\n @for RSVP\n @param {*} value value that the returned promise will be resolved with\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise that will become fulfilled with the given\n `value`\n*/\nfunction resolve$2(value, label) {\n return Promise.resolve(value, label);\n}\n\n/**\n This is a convenient alias for `RSVP.Promise.reject`.\n\n @method reject\n @static\n @for RSVP\n @param {*} reason value that the returned promise will be rejected with.\n @param {String} label optional string for identifying the returned promise.\n Useful for tooling.\n @return {Promise} a promise rejected with the given `reason`.\n*/\nfunction reject$2(reason, label) {\n return Promise.reject(reason, label);\n}\n\n/**\n `RSVP.filter` is similar to JavaScript's native `filter` method, except that it\n waits for all promises to become fulfilled before running the `filterFn` on\n each item in given to `promises`. `RSVP.filter` returns a promise that will\n become fulfilled with the result of running `filterFn` on the values the\n promises become fulfilled with.\n\n For example:\n\n ```javascript\n\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.resolve(2);\n let promise3 = RSVP.resolve(3);\n\n let promises = [promise1, promise2, promise3];\n\n let filterFn = function(item){\n return item > 1;\n };\n\n RSVP.filter(promises, filterFn).then(function(result){\n // result is [ 2, 3 ]\n });\n ```\n\n If any of the `promises` given to `RSVP.filter` are rejected, the first promise\n that is rejected will be given as an argument to the returned promise's\n rejection handler. For example:\n\n ```javascript\n let promise1 = RSVP.resolve(1);\n let promise2 = RSVP.reject(new Error('2'));\n let promise3 = RSVP.reject(new Error('3'));\n let promises = [ promise1, promise2, promise3 ];\n\n let filterFn = function(item){\n return item > 1;\n };\n\n RSVP.filter(promises, filterFn).then(function(array){\n // Code here never runs because there are rejected promises!\n }, function(reason) {\n // reason.message === '2'\n });\n ```\n\n `RSVP.filter` will also wait for any promises returned from `filterFn`.\n For instance, you may want to fetch a list of users then return a subset\n of those users based on some asynchronous operation:\n\n ```javascript\n\n let alice = { name: 'alice' };\n let bob = { name: 'bob' };\n let users = [ alice, bob ];\n\n let promises = users.map(function(user){\n return RSVP.resolve(user);\n });\n\n let filterFn = function(user){\n // Here, Alice has permissions to create a blog post, but Bob does not.\n return getPrivilegesForUser(user).then(function(privs){\n return privs.can_create_blog_post === true;\n });\n };\n RSVP.filter(promises, filterFn).then(function(users){\n // true, because the server told us only Alice can create a blog post.\n users.length === 1;\n // false, because Alice is the only user present in `users`\n users[0] === bob;\n });\n ```\n\n @method filter\n @static\n @for RSVP\n @param {Array} promises\n @param {Function} filterFn - function to be called on each resolved value to\n filter the final results.\n @param {String} label optional string describing the promise. Useful for\n tooling.\n @return {Promise}\n*/\n\nfunction resolveAll(promises, label) {\n return Promise.all(promises, label);\n}\n\nfunction resolveSingle(promise, label) {\n return Promise.resolve(promise, label).then(function (promises) {\n return resolveAll(promises, label);\n });\n}\nfunction filter(promises, filterFn, label) {\n var promise = isArray(promises) ? resolveAll(promises, label) : resolveSingle(promises, label);\n return promise.then(function (values) {\n if (!isFunction(filterFn)) {\n throw new TypeError(\"You must pass a function as filter's second argument.\");\n }\n\n var length = values.length;\n var filtered = new Array(length);\n\n for (var i = 0; i < length; i++) {\n filtered[i] = filterFn(values[i]);\n }\n\n return resolveAll(filtered, label).then(function (filtered) {\n var results = new Array(length);\n var newLength = 0;\n\n for (var i = 0; i < length; i++) {\n if (filtered[i]) {\n results[newLength] = values[i];\n newLength++;\n }\n }\n\n results.length = newLength;\n\n return results;\n });\n });\n}\n\nvar len = 0;\nvar vertxNext = undefined;\nfunction asap(callback, arg) {\n queue$1[len] = callback;\n queue$1[len + 1] = arg;\n len += 2;\n if (len === 2) {\n // If len is 1, that means that we need to schedule an async flush.\n // If additional callbacks are queued before the queue is flushed, they\n // will be processed by this flush that we are scheduling.\n scheduleFlush$1();\n }\n}\n\nvar browserWindow = typeof window !== 'undefined' ? window : undefined;\nvar browserGlobal = browserWindow || {};\nvar BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;\nvar isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';\n\n// test for web worker but not in IE10\nvar isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';\n\n// node\nfunction useNextTick() {\n var nextTick = process.nextTick;\n // node version 0.10.x displays a deprecation warning when nextTick is used recursively\n // setImmediate should be used instead instead\n var version = process.versions.node.match(/^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$/);\n if (Array.isArray(version) && version[1] === '0' && version[2] === '10') {\n nextTick = setImmediate;\n }\n return function () {\n return nextTick(flush);\n };\n}\n\n// vertx\nfunction useVertxTimer() {\n return function () {\n return vertxNext(flush);\n };\n}\n\nfunction useMutationObserver() {\n var iterations = 0;\n var observer = new BrowserMutationObserver(flush);\n var node = document.createTextNode('');\n observer.observe(node, { characterData: true });\n\n return function () {\n return node.data = iterations = ++iterations % 2;\n };\n}\n\n// web worker\nfunction useMessageChannel() {\n var channel = new MessageChannel();\n channel.port1.onmessage = flush;\n return function () {\n return channel.port2.postMessage(0);\n };\n}\n\nfunction useSetTimeout() {\n return function () {\n return setTimeout(flush, 1);\n };\n}\n\nvar queue$1 = new Array(1000);\n\nfunction flush() {\n for (var i = 0; i < len; i += 2) {\n var callback = queue$1[i];\n var arg = queue$1[i + 1];\n\n callback(arg);\n\n queue$1[i] = undefined;\n queue$1[i + 1] = undefined;\n }\n\n len = 0;\n}\n\nfunction attemptVertex() {\n try {\n var r = require;\n var vertx = r('vertx');\n vertxNext = vertx.runOnLoop || vertx.runOnContext;\n return useVertxTimer();\n } catch (e) {\n return useSetTimeout();\n }\n}\n\nvar scheduleFlush$1 = undefined;\n// Decide what async method to use to triggering processing of queued callbacks:\nif (isNode) {\n scheduleFlush$1 = useNextTick();\n} else if (BrowserMutationObserver) {\n scheduleFlush$1 = useMutationObserver();\n} else if (isWorker) {\n scheduleFlush$1 = useMessageChannel();\n} else if (browserWindow === undefined && typeof require === 'function') {\n scheduleFlush$1 = attemptVertex();\n} else {\n scheduleFlush$1 = useSetTimeout();\n}\n\nvar platform = undefined;\n\n/* global self */\nif (typeof self === 'object') {\n platform = self;\n\n /* global global */\n} else if (typeof global === 'object') {\n platform = global;\n } else {\n throw new Error('no global: `self` or `global` found');\n }\n\nvar _async$filter;\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\n// defaults\n\n// the default export here is for backwards compat:\n// https://github.com/tildeio/rsvp.js/issues/434\nconfig.async = asap;\nconfig.after = function (cb) {\n return setTimeout(cb, 0);\n};\nvar cast = resolve$2;\n\nvar async = function async(callback, arg) {\n return config.async(callback, arg);\n};\n\nfunction on() {\n config['on'].apply(config, arguments);\n}\n\nfunction off() {\n config['off'].apply(config, arguments);\n}\n\n// Set up instrumentation through `window.__PROMISE_INTRUMENTATION__`\nif (typeof window !== 'undefined' && typeof window['__PROMISE_INSTRUMENTATION__'] === 'object') {\n var callbacks = window['__PROMISE_INSTRUMENTATION__'];\n configure('instrument', true);\n for (var eventName in callbacks) {\n if (callbacks.hasOwnProperty(eventName)) {\n on(eventName, callbacks[eventName]);\n }\n }\n}var rsvp = (_async$filter = {\n cast: cast,\n Promise: Promise,\n EventTarget: EventTarget,\n all: all$1,\n allSettled: allSettled,\n race: race$1,\n hash: hash,\n hashSettled: hashSettled,\n rethrow: rethrow,\n defer: defer,\n denodeify: denodeify,\n configure: configure,\n on: on,\n off: off,\n resolve: resolve$2,\n reject: reject$2,\n map: map\n}, _defineProperty(_async$filter, 'async', async), _defineProperty(_async$filter, 'filter', // babel seems to error if async isn't a computed prop here...\nfilter), _async$filter);\n\nexports['default'] = rsvp;\nexports.cast = cast;\nexports.Promise = Promise;\nexports.EventTarget = EventTarget;\nexports.all = all$1;\nexports.allSettled = allSettled;\nexports.race = race$1;\nexports.hash = hash;\nexports.hashSettled = hashSettled;\nexports.rethrow = rethrow;\nexports.defer = defer;\nexports.denodeify = denodeify;\nexports.configure = configure;\nexports.on = on;\nexports.off = off;\nexports.resolve = resolve$2;\nexports.reject = reject$2;\nexports.map = map;\nexports.async = async;\nexports.filter = filter;\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\n})));\n//# sourceMappingURL=rsvp.map","/*!\n * URI.js - Mutating URLs\n * Second Level Domain (SLD) Support\n *\n * Version: 1.18.1\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof exports === 'object') {\n // Node\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(factory);\n } else {\n // Browser globals (root is window)\n root.SecondLevelDomains = factory(root);\n }\n}(this, function (root) {\n 'use strict';\n\n // save current SecondLevelDomains variable, if any\n var _SecondLevelDomains = root && root.SecondLevelDomains;\n\n var SLD = {\n // list of known Second Level Domains\n // converted list of SLDs from https://github.com/gavingmiller/second-level-domains\n // ----\n // publicsuffix.org is more current and actually used by a couple of browsers internally.\n // downside is it also contains domains like \"dyndns.org\" - which is fine for the security\n // issues browser have to deal with (SOP for cookies, etc) - but is way overboard for URI.js\n // ----\n list: {\n 'ac':' com gov mil net org ',\n 'ae':' ac co gov mil name net org pro sch ',\n 'af':' com edu gov net org ',\n 'al':' com edu gov mil net org ',\n 'ao':' co ed gv it og pb ',\n 'ar':' com edu gob gov int mil net org tur ',\n 'at':' ac co gv or ',\n 'au':' asn com csiro edu gov id net org ',\n 'ba':' co com edu gov mil net org rs unbi unmo unsa untz unze ',\n 'bb':' biz co com edu gov info net org store tv ',\n 'bh':' biz cc com edu gov info net org ',\n 'bn':' com edu gov net org ',\n 'bo':' com edu gob gov int mil net org tv ',\n 'br':' adm adv agr am arq art ato b bio blog bmd cim cng cnt com coop ecn edu eng esp etc eti far flog fm fnd fot fst g12 ggf gov imb ind inf jor jus lel mat med mil mus net nom not ntr odo org ppg pro psc psi qsl rec slg srv tmp trd tur tv vet vlog wiki zlg ',\n 'bs':' com edu gov net org ',\n 'bz':' du et om ov rg ',\n 'ca':' ab bc mb nb nf nl ns nt nu on pe qc sk yk ',\n 'ck':' biz co edu gen gov info net org ',\n 'cn':' ac ah bj com cq edu fj gd gov gs gx gz ha hb he hi hl hn jl js jx ln mil net nm nx org qh sc sd sh sn sx tj tw xj xz yn zj ',\n 'co':' com edu gov mil net nom org ',\n 'cr':' ac c co ed fi go or sa ',\n 'cy':' ac biz com ekloges gov ltd name net org parliament press pro tm ',\n 'do':' art com edu gob gov mil net org sld web ',\n 'dz':' art asso com edu gov net org pol ',\n 'ec':' com edu fin gov info med mil net org pro ',\n 'eg':' com edu eun gov mil name net org sci ',\n 'er':' com edu gov ind mil net org rochest w ',\n 'es':' com edu gob nom org ',\n 'et':' biz com edu gov info name net org ',\n 'fj':' ac biz com info mil name net org pro ',\n 'fk':' ac co gov net nom org ',\n 'fr':' asso com f gouv nom prd presse tm ',\n 'gg':' co net org ',\n 'gh':' com edu gov mil org ',\n 'gn':' ac com gov net org ',\n 'gr':' com edu gov mil net org ',\n 'gt':' com edu gob ind mil net org ',\n 'gu':' com edu gov net org ',\n 'hk':' com edu gov idv net org ',\n 'hu':' 2000 agrar bolt casino city co erotica erotika film forum games hotel info ingatlan jogasz konyvelo lakas media news org priv reklam sex shop sport suli szex tm tozsde utazas video ',\n 'id':' ac co go mil net or sch web ',\n 'il':' ac co gov idf k12 muni net org ',\n 'in':' ac co edu ernet firm gen gov i ind mil net nic org res ',\n 'iq':' com edu gov i mil net org ',\n 'ir':' ac co dnssec gov i id net org sch ',\n 'it':' edu gov ',\n 'je':' co net org ',\n 'jo':' com edu gov mil name net org sch ',\n 'jp':' ac ad co ed go gr lg ne or ',\n 'ke':' ac co go info me mobi ne or sc ',\n 'kh':' com edu gov mil net org per ',\n 'ki':' biz com de edu gov info mob net org tel ',\n 'km':' asso com coop edu gouv k medecin mil nom notaires pharmaciens presse tm veterinaire ',\n 'kn':' edu gov net org ',\n 'kr':' ac busan chungbuk chungnam co daegu daejeon es gangwon go gwangju gyeongbuk gyeonggi gyeongnam hs incheon jeju jeonbuk jeonnam k kg mil ms ne or pe re sc seoul ulsan ',\n 'kw':' com edu gov net org ',\n 'ky':' com edu gov net org ',\n 'kz':' com edu gov mil net org ',\n 'lb':' com edu gov net org ',\n 'lk':' assn com edu gov grp hotel int ltd net ngo org sch soc web ',\n 'lr':' com edu gov net org ',\n 'lv':' asn com conf edu gov id mil net org ',\n 'ly':' com edu gov id med net org plc sch ',\n 'ma':' ac co gov m net org press ',\n 'mc':' asso tm ',\n 'me':' ac co edu gov its net org priv ',\n 'mg':' com edu gov mil nom org prd tm ',\n 'mk':' com edu gov inf name net org pro ',\n 'ml':' com edu gov net org presse ',\n 'mn':' edu gov org ',\n 'mo':' com edu gov net org ',\n 'mt':' com edu gov net org ',\n 'mv':' aero biz com coop edu gov info int mil museum name net org pro ',\n 'mw':' ac co com coop edu gov int museum net org ',\n 'mx':' com edu gob net org ',\n 'my':' com edu gov mil name net org sch ',\n 'nf':' arts com firm info net other per rec store web ',\n 'ng':' biz com edu gov mil mobi name net org sch ',\n 'ni':' ac co com edu gob mil net nom org ',\n 'np':' com edu gov mil net org ',\n 'nr':' biz com edu gov info net org ',\n 'om':' ac biz co com edu gov med mil museum net org pro sch ',\n 'pe':' com edu gob mil net nom org sld ',\n 'ph':' com edu gov i mil net ngo org ',\n 'pk':' biz com edu fam gob gok gon gop gos gov net org web ',\n 'pl':' art bialystok biz com edu gda gdansk gorzow gov info katowice krakow lodz lublin mil net ngo olsztyn org poznan pwr radom slupsk szczecin torun warszawa waw wroc wroclaw zgora ',\n 'pr':' ac biz com edu est gov info isla name net org pro prof ',\n 'ps':' com edu gov net org plo sec ',\n 'pw':' belau co ed go ne or ',\n 'ro':' arts com firm info nom nt org rec store tm www ',\n 'rs':' ac co edu gov in org ',\n 'sb':' com edu gov net org ',\n 'sc':' com edu gov net org ',\n 'sh':' co com edu gov net nom org ',\n 'sl':' com edu gov net org ',\n 'st':' co com consulado edu embaixada gov mil net org principe saotome store ',\n 'sv':' com edu gob org red ',\n 'sz':' ac co org ',\n 'tr':' av bbs bel biz com dr edu gen gov info k12 name net org pol tel tsk tv web ',\n 'tt':' aero biz cat co com coop edu gov info int jobs mil mobi museum name net org pro tel travel ',\n 'tw':' club com ebiz edu game gov idv mil net org ',\n 'mu':' ac co com gov net or org ',\n 'mz':' ac co edu gov org ',\n 'na':' co com ',\n 'nz':' ac co cri geek gen govt health iwi maori mil net org parliament school ',\n 'pa':' abo ac com edu gob ing med net nom org sld ',\n 'pt':' com edu gov int net nome org publ ',\n 'py':' com edu gov mil net org ',\n 'qa':' com edu gov mil net org ',\n 're':' asso com nom ',\n 'ru':' ac adygeya altai amur arkhangelsk astrakhan bashkiria belgorod bir bryansk buryatia cbg chel chelyabinsk chita chukotka chuvashia com dagestan e-burg edu gov grozny int irkutsk ivanovo izhevsk jar joshkar-ola kalmykia kaluga kamchatka karelia kazan kchr kemerovo khabarovsk khakassia khv kirov koenig komi kostroma kranoyarsk kuban kurgan kursk lipetsk magadan mari mari-el marine mil mordovia mosreg msk murmansk nalchik net nnov nov novosibirsk nsk omsk orenburg org oryol penza perm pp pskov ptz rnd ryazan sakhalin samara saratov simbirsk smolensk spb stavropol stv surgut tambov tatarstan tom tomsk tsaritsyn tsk tula tuva tver tyumen udm udmurtia ulan-ude vladikavkaz vladimir vladivostok volgograd vologda voronezh vrn vyatka yakutia yamal yekaterinburg yuzhno-sakhalinsk ',\n 'rw':' ac co com edu gouv gov int mil net ',\n 'sa':' com edu gov med net org pub sch ',\n 'sd':' com edu gov info med net org tv ',\n 'se':' a ac b bd c d e f g h i k l m n o org p parti pp press r s t tm u w x y z ',\n 'sg':' com edu gov idn net org per ',\n 'sn':' art com edu gouv org perso univ ',\n 'sy':' com edu gov mil net news org ',\n 'th':' ac co go in mi net or ',\n 'tj':' ac biz co com edu go gov info int mil name net nic org test web ',\n 'tn':' agrinet com defense edunet ens fin gov ind info intl mincom nat net org perso rnrt rns rnu tourism ',\n 'tz':' ac co go ne or ',\n 'ua':' biz cherkassy chernigov chernovtsy ck cn co com crimea cv dn dnepropetrovsk donetsk dp edu gov if in ivano-frankivsk kh kharkov kherson khmelnitskiy kiev kirovograd km kr ks kv lg lugansk lutsk lviv me mk net nikolaev od odessa org pl poltava pp rovno rv sebastopol sumy te ternopil uzhgorod vinnica vn zaporizhzhe zhitomir zp zt ',\n 'ug':' ac co go ne or org sc ',\n 'uk':' ac bl british-library co cym gov govt icnet jet lea ltd me mil mod national-library-scotland nel net nhs nic nls org orgn parliament plc police sch scot soc ',\n 'us':' dni fed isa kids nsn ',\n 'uy':' com edu gub mil net org ',\n 've':' co com edu gob info mil net org web ',\n 'vi':' co com k12 net org ',\n 'vn':' ac biz com edu gov health info int name net org pro ',\n 'ye':' co com gov ltd me net org plc ',\n 'yu':' ac co edu gov org ',\n 'za':' ac agric alt bourse city co cybernet db edu gov grondar iaccess imt inca landesign law mil net ngo nis nom olivetti org pix school tm web ',\n 'zm':' ac co com edu gov net org sch '\n },\n // gorhill 2013-10-25: Using indexOf() instead Regexp(). Significant boost\n // in both performance and memory footprint. No initialization required.\n // http://jsperf.com/uri-js-sld-regex-vs-binary-search/4\n // Following methods use lastIndexOf() rather than array.split() in order\n // to avoid any memory allocations.\n has: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return false;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {\n return false;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return false;\n }\n return sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') >= 0;\n },\n is: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return false;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset >= 0) {\n return false;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return false;\n }\n return sldList.indexOf(' ' + domain.slice(0, tldOffset) + ' ') >= 0;\n },\n get: function(domain) {\n var tldOffset = domain.lastIndexOf('.');\n if (tldOffset <= 0 || tldOffset >= (domain.length-1)) {\n return null;\n }\n var sldOffset = domain.lastIndexOf('.', tldOffset-1);\n if (sldOffset <= 0 || sldOffset >= (tldOffset-1)) {\n return null;\n }\n var sldList = SLD.list[domain.slice(tldOffset+1)];\n if (!sldList) {\n return null;\n }\n if (sldList.indexOf(' ' + domain.slice(sldOffset+1, tldOffset) + ' ') < 0) {\n return null;\n }\n return domain.slice(sldOffset+1);\n },\n noConflict: function(){\n if (root.SecondLevelDomains === this) {\n root.SecondLevelDomains = _SecondLevelDomains;\n }\n return this;\n }\n };\n\n return SLD;\n}));\n","/*!\n * URI.js - Mutating URLs\n *\n * Version: 1.18.1\n *\n * Author: Rodney Rehm\n * Web: http://medialize.github.io/URI.js/\n *\n * Licensed under\n * MIT License http://www.opensource.org/licenses/mit-license\n *\n */\n(function (root, factory) {\n 'use strict';\n // https://github.com/umdjs/umd/blob/master/returnExports.js\n if (typeof exports === 'object') {\n // Node\n module.exports = factory(require('./punycode'), require('./IPv6'), require('./SecondLevelDomains'));\n } else if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(['./punycode', './IPv6', './SecondLevelDomains'], factory);\n } else {\n // Browser globals (root is window)\n root.URI = factory(root.punycode, root.IPv6, root.SecondLevelDomains, root);\n }\n}(this, function (punycode, IPv6, SLD, root) {\n 'use strict';\n /*global location, escape, unescape */\n // FIXME: v2.0.0 renamce non-camelCase properties to uppercase\n /*jshint camelcase: false */\n\n // save current URI variable, if any\n var _URI = root && root.URI;\n\n function URI(url, base) {\n var _urlSupplied = arguments.length >= 1;\n var _baseSupplied = arguments.length >= 2;\n\n // Allow instantiation without the 'new' keyword\n if (!(this instanceof URI)) {\n if (_urlSupplied) {\n if (_baseSupplied) {\n return new URI(url, base);\n }\n\n return new URI(url);\n }\n\n return new URI();\n }\n\n if (url === undefined) {\n if (_urlSupplied) {\n throw new TypeError('undefined is not a valid argument for URI');\n }\n\n if (typeof location !== 'undefined') {\n url = location.href + '';\n } else {\n url = '';\n }\n }\n\n this.href(url);\n\n // resolve to base according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#constructor\n if (base !== undefined) {\n return this.absoluteTo(base);\n }\n\n return this;\n }\n\n URI.version = '1.18.1';\n\n var p = URI.prototype;\n var hasOwn = Object.prototype.hasOwnProperty;\n\n function escapeRegEx(string) {\n // https://github.com/medialize/URI.js/commit/85ac21783c11f8ccab06106dba9735a31a86924d#commitcomment-821963\n return string.replace(/([.*+?^=!:${}()|[\\]\\/\\\\])/g, '\\\\$1');\n }\n\n function getType(value) {\n // IE8 doesn't return [Object Undefined] but [Object Object] for undefined value\n if (value === undefined) {\n return 'Undefined';\n }\n\n return String(Object.prototype.toString.call(value)).slice(8, -1);\n }\n\n function isArray(obj) {\n return getType(obj) === 'Array';\n }\n\n function filterArrayValues(data, value) {\n var lookup = {};\n var i, length;\n\n if (getType(value) === 'RegExp') {\n lookup = null;\n } else if (isArray(value)) {\n for (i = 0, length = value.length; i < length; i++) {\n lookup[value[i]] = true;\n }\n } else {\n lookup[value] = true;\n }\n\n for (i = 0, length = data.length; i < length; i++) {\n /*jshint laxbreak: true */\n var _match = lookup && lookup[data[i]] !== undefined\n || !lookup && value.test(data[i]);\n /*jshint laxbreak: false */\n if (_match) {\n data.splice(i, 1);\n length--;\n i--;\n }\n }\n\n return data;\n }\n\n function arrayContains(list, value) {\n var i, length;\n\n // value may be string, number, array, regexp\n if (isArray(value)) {\n // Note: this can be optimized to O(n) (instead of current O(m * n))\n for (i = 0, length = value.length; i < length; i++) {\n if (!arrayContains(list, value[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n var _type = getType(value);\n for (i = 0, length = list.length; i < length; i++) {\n if (_type === 'RegExp') {\n if (typeof list[i] === 'string' && list[i].match(value)) {\n return true;\n }\n } else if (list[i] === value) {\n return true;\n }\n }\n\n return false;\n }\n\n function arraysEqual(one, two) {\n if (!isArray(one) || !isArray(two)) {\n return false;\n }\n\n // arrays can't be equal if they have different amount of content\n if (one.length !== two.length) {\n return false;\n }\n\n one.sort();\n two.sort();\n\n for (var i = 0, l = one.length; i < l; i++) {\n if (one[i] !== two[i]) {\n return false;\n }\n }\n\n return true;\n }\n\n function trimSlashes(text) {\n var trim_expression = /^\\/+|\\/+$/g;\n return text.replace(trim_expression, '');\n }\n\n URI._parts = function() {\n return {\n protocol: null,\n username: null,\n password: null,\n hostname: null,\n urn: null,\n port: null,\n path: null,\n query: null,\n fragment: null,\n // state\n duplicateQueryParameters: URI.duplicateQueryParameters,\n escapeQuerySpace: URI.escapeQuerySpace\n };\n };\n // state: allow duplicate query parameters (a=1&a=1)\n URI.duplicateQueryParameters = false;\n // state: replaces + with %20 (space in query strings)\n URI.escapeQuerySpace = true;\n // static properties\n URI.protocol_expression = /^[a-z][a-z0-9.+-]*$/i;\n URI.idn_expression = /[^a-z0-9\\.-]/i;\n URI.punycode_expression = /(xn--)/i;\n // well, 333.444.555.666 matches, but it sure ain't no IPv4 - do we care?\n URI.ip4_expression = /^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$/;\n // credits to Rich Brown\n // source: http://forums.intermapper.com/viewtopic.php?p=1096#1096\n // specification: http://www.ietf.org/rfc/rfc4291.txt\n URI.ip6_expression = /^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?\\s*$/;\n // expression used is \"gruber revised\" (@gruber v2) determined to be the\n // best solution in a regex-golf we did a couple of ages ago at\n // * http://mathiasbynens.be/demo/url-regex\n // * http://rodneyrehm.de/t/url-regex.html\n URI.find_uri_expression = /\\b((?:[a-z][\\w-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))/ig;\n URI.findUri = {\n // valid \"scheme://\" or \"www.\"\n start: /\\b(?:([a-z][a-z0-9.+-]*:\\/\\/)|www\\.)/gi,\n // everything up to the next whitespace\n end: /[\\s\\r\\n]|$/,\n // trim trailing punctuation captured by end RegExp\n trim: /[`!()\\[\\]{};:'\".,<>?«»“”„‘’]+$/\n };\n // http://www.iana.org/assignments/uri-schemes.html\n // http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports\n URI.defaultPorts = {\n http: '80',\n https: '443',\n ftp: '21',\n gopher: '70',\n ws: '80',\n wss: '443'\n };\n // allowed hostname characters according to RFC 3986\n // ALPHA DIGIT \"-\" \".\" \"_\" \"~\" \"!\" \"$\" \"&\" \"'\" \"(\" \")\" \"*\" \"+\" \",\" \";\" \"=\" %encoded\n // I've never seen a (non-IDN) hostname other than: ALPHA DIGIT . -\n URI.invalid_hostname_characters = /[^a-zA-Z0-9\\.-]/;\n // map DOM Elements to their URI attribute\n URI.domAttributes = {\n 'a': 'href',\n 'blockquote': 'cite',\n 'link': 'href',\n 'base': 'href',\n 'script': 'src',\n 'form': 'action',\n 'img': 'src',\n 'area': 'href',\n 'iframe': 'src',\n 'embed': 'src',\n 'source': 'src',\n 'track': 'src',\n 'input': 'src', // but only if type=\"image\"\n 'audio': 'src',\n 'video': 'src'\n };\n URI.getDomAttribute = function(node) {\n if (!node || !node.nodeName) {\n return undefined;\n }\n\n var nodeName = node.nodeName.toLowerCase();\n // should only expose src for type=\"image\"\n if (nodeName === 'input' && node.type !== 'image') {\n return undefined;\n }\n\n return URI.domAttributes[nodeName];\n };\n\n function escapeForDumbFirefox36(value) {\n // https://github.com/medialize/URI.js/issues/91\n return escape(value);\n }\n\n // encoding / decoding according to RFC3986\n function strictEncodeURIComponent(string) {\n // see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/encodeURIComponent\n return encodeURIComponent(string)\n .replace(/[!'()*]/g, escapeForDumbFirefox36)\n .replace(/\\*/g, '%2A');\n }\n URI.encode = strictEncodeURIComponent;\n URI.decode = decodeURIComponent;\n URI.iso8859 = function() {\n URI.encode = escape;\n URI.decode = unescape;\n };\n URI.unicode = function() {\n URI.encode = strictEncodeURIComponent;\n URI.decode = decodeURIComponent;\n };\n URI.characters = {\n pathname: {\n encode: {\n // RFC3986 2.1: For consistency, URI producers and normalizers should\n // use uppercase hexadecimal digits for all percent-encodings.\n expression: /%(24|26|2B|2C|3B|3D|3A|40)/ig,\n map: {\n // -._~!'()*\n '%24': '$',\n '%26': '&',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '=',\n '%3A': ':',\n '%40': '@'\n }\n },\n decode: {\n expression: /[\\/\\?#]/g,\n map: {\n '/': '%2F',\n '?': '%3F',\n '#': '%23'\n }\n }\n },\n reserved: {\n encode: {\n // RFC3986 2.1: For consistency, URI producers and normalizers should\n // use uppercase hexadecimal digits for all percent-encodings.\n expression: /%(21|23|24|26|27|28|29|2A|2B|2C|2F|3A|3B|3D|3F|40|5B|5D)/ig,\n map: {\n // gen-delims\n '%3A': ':',\n '%2F': '/',\n '%3F': '?',\n '%23': '#',\n '%5B': '[',\n '%5D': ']',\n '%40': '@',\n // sub-delims\n '%21': '!',\n '%24': '$',\n '%26': '&',\n '%27': '\\'',\n '%28': '(',\n '%29': ')',\n '%2A': '*',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '='\n }\n }\n },\n urnpath: {\n // The characters under `encode` are the characters called out by RFC 2141 as being acceptable\n // for usage in a URN. RFC2141 also calls out \"-\", \".\", and \"_\" as acceptable characters, but\n // these aren't encoded by encodeURIComponent, so we don't have to call them out here. Also\n // note that the colon character is not featured in the encoding map; this is because URI.js\n // gives the colons in URNs semantic meaning as the delimiters of path segements, and so it\n // should not appear unencoded in a segment itself.\n // See also the note above about RFC3986 and capitalalized hex digits.\n encode: {\n expression: /%(21|24|27|28|29|2A|2B|2C|3B|3D|40)/ig,\n map: {\n '%21': '!',\n '%24': '$',\n '%27': '\\'',\n '%28': '(',\n '%29': ')',\n '%2A': '*',\n '%2B': '+',\n '%2C': ',',\n '%3B': ';',\n '%3D': '=',\n '%40': '@'\n }\n },\n // These characters are the characters called out by RFC2141 as \"reserved\" characters that\n // should never appear in a URN, plus the colon character (see note above).\n decode: {\n expression: /[\\/\\?#:]/g,\n map: {\n '/': '%2F',\n '?': '%3F',\n '#': '%23',\n ':': '%3A'\n }\n }\n }\n };\n URI.encodeQuery = function(string, escapeQuerySpace) {\n var escaped = URI.encode(string + '');\n if (escapeQuerySpace === undefined) {\n escapeQuerySpace = URI.escapeQuerySpace;\n }\n\n return escapeQuerySpace ? escaped.replace(/%20/g, '+') : escaped;\n };\n URI.decodeQuery = function(string, escapeQuerySpace) {\n string += '';\n if (escapeQuerySpace === undefined) {\n escapeQuerySpace = URI.escapeQuerySpace;\n }\n\n try {\n return URI.decode(escapeQuerySpace ? string.replace(/\\+/g, '%20') : string);\n } catch(e) {\n // we're not going to mess with weird encodings,\n // give up and return the undecoded original string\n // see https://github.com/medialize/URI.js/issues/87\n // see https://github.com/medialize/URI.js/issues/92\n return string;\n }\n };\n // generate encode/decode path functions\n var _parts = {'encode':'encode', 'decode':'decode'};\n var _part;\n var generateAccessor = function(_group, _part) {\n return function(string) {\n try {\n return URI[_part](string + '').replace(URI.characters[_group][_part].expression, function(c) {\n return URI.characters[_group][_part].map[c];\n });\n } catch (e) {\n // we're not going to mess with weird encodings,\n // give up and return the undecoded original string\n // see https://github.com/medialize/URI.js/issues/87\n // see https://github.com/medialize/URI.js/issues/92\n return string;\n }\n };\n };\n\n for (_part in _parts) {\n URI[_part + 'PathSegment'] = generateAccessor('pathname', _parts[_part]);\n URI[_part + 'UrnPathSegment'] = generateAccessor('urnpath', _parts[_part]);\n }\n\n var generateSegmentedPathFunction = function(_sep, _codingFuncName, _innerCodingFuncName) {\n return function(string) {\n // Why pass in names of functions, rather than the function objects themselves? The\n // definitions of some functions (but in particular, URI.decode) will occasionally change due\n // to URI.js having ISO8859 and Unicode modes. Passing in the name and getting it will ensure\n // that the functions we use here are \"fresh\".\n var actualCodingFunc;\n if (!_innerCodingFuncName) {\n actualCodingFunc = URI[_codingFuncName];\n } else {\n actualCodingFunc = function(string) {\n return URI[_codingFuncName](URI[_innerCodingFuncName](string));\n };\n }\n\n var segments = (string + '').split(_sep);\n\n for (var i = 0, length = segments.length; i < length; i++) {\n segments[i] = actualCodingFunc(segments[i]);\n }\n\n return segments.join(_sep);\n };\n };\n\n // This takes place outside the above loop because we don't want, e.g., encodeUrnPath functions.\n URI.decodePath = generateSegmentedPathFunction('/', 'decodePathSegment');\n URI.decodeUrnPath = generateSegmentedPathFunction(':', 'decodeUrnPathSegment');\n URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');\n URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');\n\n URI.encodeReserved = generateAccessor('reserved', 'encode');\n\n URI.parse = function(string, parts) {\n var pos;\n if (!parts) {\n parts = {};\n }\n // [protocol\"://\"[username[\":\"password]\"@\"]hostname[\":\"port]\"/\"?][path][\"?\"querystring][\"#\"fragment]\n\n // extract fragment\n pos = string.indexOf('#');\n if (pos > -1) {\n // escaping?\n parts.fragment = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // extract query\n pos = string.indexOf('?');\n if (pos > -1) {\n // escaping?\n parts.query = string.substring(pos + 1) || null;\n string = string.substring(0, pos);\n }\n\n // extract protocol\n if (string.substring(0, 2) === '//') {\n // relative-scheme\n parts.protocol = null;\n string = string.substring(2);\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n pos = string.indexOf(':');\n if (pos > -1) {\n parts.protocol = string.substring(0, pos) || null;\n if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {\n // : may be within the path\n parts.protocol = undefined;\n } else if (string.substring(pos + 1, pos + 3) === '//') {\n string = string.substring(pos + 3);\n\n // extract \"user:pass@host:port\"\n string = URI.parseAuthority(string, parts);\n } else {\n string = string.substring(pos + 1);\n parts.urn = true;\n }\n }\n }\n\n // what's left must be the path\n parts.path = string;\n\n // and we're done\n return parts;\n };\n URI.parseHost = function(string, parts) {\n // Copy chrome, IE, opera backslash-handling behavior.\n // Back slashes before the query string get converted to forward slashes\n // See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124\n // See: https://code.google.com/p/chromium/issues/detail?id=25916\n // https://github.com/medialize/URI.js/pull/233\n string = string.replace(/\\\\/g, '/');\n\n // extract host:port\n var pos = string.indexOf('/');\n var bracketPos;\n var t;\n\n if (pos === -1) {\n pos = string.length;\n }\n\n if (string.charAt(0) === '[') {\n // IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6\n // I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts\n // IPv6+port in the format [2001:db8::1]:80 (for the time being)\n bracketPos = string.indexOf(']');\n parts.hostname = string.substring(1, bracketPos) || null;\n parts.port = string.substring(bracketPos + 2, pos) || null;\n if (parts.port === '/') {\n parts.port = null;\n }\n } else {\n var firstColon = string.indexOf(':');\n var firstSlash = string.indexOf('/');\n var nextColon = string.indexOf(':', firstColon + 1);\n if (nextColon !== -1 && (firstSlash === -1 || nextColon < firstSlash)) {\n // IPv6 host contains multiple colons - but no port\n // this notation is actually not allowed by RFC 3986, but we're a liberal parser\n parts.hostname = string.substring(0, pos) || null;\n parts.port = null;\n } else {\n t = string.substring(0, pos).split(':');\n parts.hostname = t[0] || null;\n parts.port = t[1] || null;\n }\n }\n\n if (parts.hostname && string.substring(pos).charAt(0) !== '/') {\n pos++;\n string = '/' + string;\n }\n\n return string.substring(pos) || '/';\n };\n URI.parseAuthority = function(string, parts) {\n string = URI.parseUserinfo(string, parts);\n return URI.parseHost(string, parts);\n };\n URI.parseUserinfo = function(string, parts) {\n // extract username:password\n var firstSlash = string.indexOf('/');\n var pos = string.lastIndexOf('@', firstSlash > -1 ? firstSlash : string.length - 1);\n var t;\n\n // authority@ must come before /path\n if (pos > -1 && (firstSlash === -1 || pos < firstSlash)) {\n t = string.substring(0, pos).split(':');\n parts.username = t[0] ? URI.decode(t[0]) : null;\n t.shift();\n parts.password = t[0] ? URI.decode(t.join(':')) : null;\n string = string.substring(pos + 1);\n } else {\n parts.username = null;\n parts.password = null;\n }\n\n return string;\n };\n URI.parseQuery = function(string, escapeQuerySpace) {\n if (!string) {\n return {};\n }\n\n // throw out the funky business - \"?\"[name\"=\"value\"&\"]+\n string = string.replace(/&+/g, '&').replace(/^\\?*&*|&+$/g, '');\n\n if (!string) {\n return {};\n }\n\n var items = {};\n var splits = string.split('&');\n var length = splits.length;\n var v, name, value;\n\n for (var i = 0; i < length; i++) {\n v = splits[i].split('=');\n name = URI.decodeQuery(v.shift(), escapeQuerySpace);\n // no \"=\" is null according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#collect-url-parameters\n value = v.length ? URI.decodeQuery(v.join('='), escapeQuerySpace) : null;\n\n if (hasOwn.call(items, name)) {\n if (typeof items[name] === 'string' || items[name] === null) {\n items[name] = [items[name]];\n }\n\n items[name].push(value);\n } else {\n items[name] = value;\n }\n }\n\n return items;\n };\n\n URI.build = function(parts) {\n var t = '';\n\n if (parts.protocol) {\n t += parts.protocol + ':';\n }\n\n if (!parts.urn && (t || parts.hostname)) {\n t += '//';\n }\n\n t += (URI.buildAuthority(parts) || '');\n\n if (typeof parts.path === 'string') {\n if (parts.path.charAt(0) !== '/' && typeof parts.hostname === 'string') {\n t += '/';\n }\n\n t += parts.path;\n }\n\n if (typeof parts.query === 'string' && parts.query) {\n t += '?' + parts.query;\n }\n\n if (typeof parts.fragment === 'string' && parts.fragment) {\n t += '#' + parts.fragment;\n }\n return t;\n };\n URI.buildHost = function(parts) {\n var t = '';\n\n if (!parts.hostname) {\n return '';\n } else if (URI.ip6_expression.test(parts.hostname)) {\n t += '[' + parts.hostname + ']';\n } else {\n t += parts.hostname;\n }\n\n if (parts.port) {\n t += ':' + parts.port;\n }\n\n return t;\n };\n URI.buildAuthority = function(parts) {\n return URI.buildUserinfo(parts) + URI.buildHost(parts);\n };\n URI.buildUserinfo = function(parts) {\n var t = '';\n\n if (parts.username) {\n t += URI.encode(parts.username);\n }\n\n if (parts.password) {\n t += ':' + URI.encode(parts.password);\n }\n\n if (t) {\n t += '@';\n }\n\n return t;\n };\n URI.buildQuery = function(data, duplicateQueryParameters, escapeQuerySpace) {\n // according to http://tools.ietf.org/html/rfc3986 or http://labs.apache.org/webarch/uri/rfc/rfc3986.html\n // being »-._~!$&'()*+,;=:@/?« %HEX and alnum are allowed\n // the RFC explicitly states ?/foo being a valid use case, no mention of parameter syntax!\n // URI.js treats the query string as being application/x-www-form-urlencoded\n // see http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type\n\n var t = '';\n var unique, key, i, length;\n for (key in data) {\n if (hasOwn.call(data, key) && key) {\n if (isArray(data[key])) {\n unique = {};\n for (i = 0, length = data[key].length; i < length; i++) {\n if (data[key][i] !== undefined && unique[data[key][i] + ''] === undefined) {\n t += '&' + URI.buildQueryParameter(key, data[key][i], escapeQuerySpace);\n if (duplicateQueryParameters !== true) {\n unique[data[key][i] + ''] = true;\n }\n }\n }\n } else if (data[key] !== undefined) {\n t += '&' + URI.buildQueryParameter(key, data[key], escapeQuerySpace);\n }\n }\n }\n\n return t.substring(1);\n };\n URI.buildQueryParameter = function(name, value, escapeQuerySpace) {\n // http://www.w3.org/TR/REC-html40/interact/forms.html#form-content-type -- application/x-www-form-urlencoded\n // don't append \"=\" for null values, according to http://dvcs.w3.org/hg/url/raw-file/tip/Overview.html#url-parameter-serialization\n return URI.encodeQuery(name, escapeQuerySpace) + (value !== null ? '=' + URI.encodeQuery(value, escapeQuerySpace) : '');\n };\n\n URI.addQuery = function(data, name, value) {\n if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n URI.addQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n if (data[name] === undefined) {\n data[name] = value;\n return;\n } else if (typeof data[name] === 'string') {\n data[name] = [data[name]];\n }\n\n if (!isArray(value)) {\n value = [value];\n }\n\n data[name] = (data[name] || []).concat(value);\n } else {\n throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');\n }\n };\n URI.removeQuery = function(data, name, value) {\n var i, length, key;\n\n if (isArray(name)) {\n for (i = 0, length = name.length; i < length; i++) {\n data[name[i]] = undefined;\n }\n } else if (getType(name) === 'RegExp') {\n for (key in data) {\n if (name.test(key)) {\n data[key] = undefined;\n }\n }\n } else if (typeof name === 'object') {\n for (key in name) {\n if (hasOwn.call(name, key)) {\n URI.removeQuery(data, key, name[key]);\n }\n }\n } else if (typeof name === 'string') {\n if (value !== undefined) {\n if (getType(value) === 'RegExp') {\n if (!isArray(data[name]) && value.test(data[name])) {\n data[name] = undefined;\n } else {\n data[name] = filterArrayValues(data[name], value);\n }\n } else if (data[name] === String(value) && (!isArray(value) || value.length === 1)) {\n data[name] = undefined;\n } else if (isArray(data[name])) {\n data[name] = filterArrayValues(data[name], value);\n }\n } else {\n data[name] = undefined;\n }\n } else {\n throw new TypeError('URI.removeQuery() accepts an object, string, RegExp as the first parameter');\n }\n };\n URI.hasQuery = function(data, name, value, withinArray) {\n switch (getType(name)) {\n case 'String':\n // Nothing to do here\n break;\n\n case 'RegExp':\n for (var key in data) {\n if (hasOwn.call(data, key)) {\n if (name.test(key) && (value === undefined || URI.hasQuery(data, key, value))) {\n return true;\n }\n }\n }\n\n return false;\n\n case 'Object':\n for (var _key in name) {\n if (hasOwn.call(name, _key)) {\n if (!URI.hasQuery(data, _key, name[_key])) {\n return false;\n }\n }\n }\n\n return true;\n\n default:\n throw new TypeError('URI.hasQuery() accepts a string, regular expression or object as the name parameter');\n }\n\n switch (getType(value)) {\n case 'Undefined':\n // true if exists (but may be empty)\n return name in data; // data[name] !== undefined;\n\n case 'Boolean':\n // true if exists and non-empty\n var _booly = Boolean(isArray(data[name]) ? data[name].length : data[name]);\n return value === _booly;\n\n case 'Function':\n // allow complex comparison\n return !!value(data[name], name, data);\n\n case 'Array':\n if (!isArray(data[name])) {\n return false;\n }\n\n var op = withinArray ? arrayContains : arraysEqual;\n return op(data[name], value);\n\n case 'RegExp':\n if (!isArray(data[name])) {\n return Boolean(data[name] && data[name].match(value));\n }\n\n if (!withinArray) {\n return false;\n }\n\n return arrayContains(data[name], value);\n\n case 'Number':\n value = String(value);\n /* falls through */\n case 'String':\n if (!isArray(data[name])) {\n return data[name] === value;\n }\n\n if (!withinArray) {\n return false;\n }\n\n return arrayContains(data[name], value);\n\n default:\n throw new TypeError('URI.hasQuery() accepts undefined, boolean, string, number, RegExp, Function as the value parameter');\n }\n };\n\n\n URI.joinPaths = function() {\n var input = [];\n var segments = [];\n var nonEmptySegments = 0;\n\n for (var i = 0; i < arguments.length; i++) {\n var url = new URI(arguments[i]);\n input.push(url);\n var _segments = url.segment();\n for (var s = 0; s < _segments.length; s++) {\n if (typeof _segments[s] === 'string') {\n segments.push(_segments[s]);\n }\n\n if (_segments[s]) {\n nonEmptySegments++;\n }\n }\n }\n\n if (!segments.length || !nonEmptySegments) {\n return new URI('');\n }\n\n var uri = new URI('').segment(segments);\n\n if (input[0].path() === '' || input[0].path().slice(0, 1) === '/') {\n uri.path('/' + uri.path());\n }\n\n return uri.normalize();\n };\n\n URI.commonPath = function(one, two) {\n var length = Math.min(one.length, two.length);\n var pos;\n\n // find first non-matching character\n for (pos = 0; pos < length; pos++) {\n if (one.charAt(pos) !== two.charAt(pos)) {\n pos--;\n break;\n }\n }\n\n if (pos < 1) {\n return one.charAt(0) === two.charAt(0) && one.charAt(0) === '/' ? '/' : '';\n }\n\n // revert to last /\n if (one.charAt(pos) !== '/' || two.charAt(pos) !== '/') {\n pos = one.substring(0, pos).lastIndexOf('/');\n }\n\n return one.substring(0, pos + 1);\n };\n\n URI.withinString = function(string, callback, options) {\n options || (options = {});\n var _start = options.start || URI.findUri.start;\n var _end = options.end || URI.findUri.end;\n var _trim = options.trim || URI.findUri.trim;\n var _attributeOpen = /[a-z0-9-]=[\"']?$/i;\n\n _start.lastIndex = 0;\n while (true) {\n var match = _start.exec(string);\n if (!match) {\n break;\n }\n\n var start = match.index;\n if (options.ignoreHtml) {\n // attribut(e=[\"']?$)\n var attributeOpen = string.slice(Math.max(start - 3, 0), start);\n if (attributeOpen && _attributeOpen.test(attributeOpen)) {\n continue;\n }\n }\n\n var end = start + string.slice(start).search(_end);\n var slice = string.slice(start, end).replace(_trim, '');\n if (options.ignore && options.ignore.test(slice)) {\n continue;\n }\n\n end = start + slice.length;\n var result = callback(slice, start, end, string);\n string = string.slice(0, start) + result + string.slice(end);\n _start.lastIndex = start + result.length;\n }\n\n _start.lastIndex = 0;\n return string;\n };\n\n URI.ensureValidHostname = function(v) {\n // Theoretically URIs allow percent-encoding in Hostnames (according to RFC 3986)\n // they are not part of DNS and therefore ignored by URI.js\n\n if (v.match(URI.invalid_hostname_characters)) {\n // test punycode\n if (!punycode) {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-] and Punycode.js is not available');\n }\n\n if (punycode.toASCII(v).match(URI.invalid_hostname_characters)) {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n }\n };\n\n // noConflict\n URI.noConflict = function(removeAll) {\n if (removeAll) {\n var unconflicted = {\n URI: this.noConflict()\n };\n\n if (root.URITemplate && typeof root.URITemplate.noConflict === 'function') {\n unconflicted.URITemplate = root.URITemplate.noConflict();\n }\n\n if (root.IPv6 && typeof root.IPv6.noConflict === 'function') {\n unconflicted.IPv6 = root.IPv6.noConflict();\n }\n\n if (root.SecondLevelDomains && typeof root.SecondLevelDomains.noConflict === 'function') {\n unconflicted.SecondLevelDomains = root.SecondLevelDomains.noConflict();\n }\n\n return unconflicted;\n } else if (root.URI === this) {\n root.URI = _URI;\n }\n\n return this;\n };\n\n p.build = function(deferBuild) {\n if (deferBuild === true) {\n this._deferred_build = true;\n } else if (deferBuild === undefined || this._deferred_build) {\n this._string = URI.build(this._parts);\n this._deferred_build = false;\n }\n\n return this;\n };\n\n p.clone = function() {\n return new URI(this);\n };\n\n p.valueOf = p.toString = function() {\n return this.build(false)._string;\n };\n\n\n function generateSimpleAccessor(_part){\n return function(v, build) {\n if (v === undefined) {\n return this._parts[_part] || '';\n } else {\n this._parts[_part] = v || null;\n this.build(!build);\n return this;\n }\n };\n }\n\n function generatePrefixAccessor(_part, _key){\n return function(v, build) {\n if (v === undefined) {\n return this._parts[_part] || '';\n } else {\n if (v !== null) {\n v = v + '';\n if (v.charAt(0) === _key) {\n v = v.substring(1);\n }\n }\n\n this._parts[_part] = v;\n this.build(!build);\n return this;\n }\n };\n }\n\n p.protocol = generateSimpleAccessor('protocol');\n p.username = generateSimpleAccessor('username');\n p.password = generateSimpleAccessor('password');\n p.hostname = generateSimpleAccessor('hostname');\n p.port = generateSimpleAccessor('port');\n p.query = generatePrefixAccessor('query', '?');\n p.fragment = generatePrefixAccessor('fragment', '#');\n\n p.search = function(v, build) {\n var t = this.query(v, build);\n return typeof t === 'string' && t.length ? ('?' + t) : t;\n };\n p.hash = function(v, build) {\n var t = this.fragment(v, build);\n return typeof t === 'string' && t.length ? ('#' + t) : t;\n };\n\n p.pathname = function(v, build) {\n if (v === undefined || v === true) {\n var res = this._parts.path || (this._parts.hostname ? '/' : '');\n return v ? (this._parts.urn ? URI.decodeUrnPath : URI.decodePath)(res) : res;\n } else {\n if (this._parts.urn) {\n this._parts.path = v ? URI.recodeUrnPath(v) : '';\n } else {\n this._parts.path = v ? URI.recodePath(v) : '/';\n }\n this.build(!build);\n return this;\n }\n };\n p.path = p.pathname;\n p.href = function(href, build) {\n var key;\n\n if (href === undefined) {\n return this.toString();\n }\n\n this._string = '';\n this._parts = URI._parts();\n\n var _URI = href instanceof URI;\n var _object = typeof href === 'object' && (href.hostname || href.path || href.pathname);\n if (href.nodeName) {\n var attribute = URI.getDomAttribute(href);\n href = href[attribute] || '';\n _object = false;\n }\n\n // window.location is reported to be an object, but it's not the sort\n // of object we're looking for:\n // * location.protocol ends with a colon\n // * location.query != object.search\n // * location.hash != object.fragment\n // simply serializing the unknown object should do the trick\n // (for location, not for everything...)\n if (!_URI && _object && href.pathname !== undefined) {\n href = href.toString();\n }\n\n if (typeof href === 'string' || href instanceof String) {\n this._parts = URI.parse(String(href), this._parts);\n } else if (_URI || _object) {\n var src = _URI ? href._parts : href;\n for (key in src) {\n if (hasOwn.call(this._parts, key)) {\n this._parts[key] = src[key];\n }\n }\n } else {\n throw new TypeError('invalid input');\n }\n\n this.build(!build);\n return this;\n };\n\n // identification accessors\n p.is = function(what) {\n var ip = false;\n var ip4 = false;\n var ip6 = false;\n var name = false;\n var sld = false;\n var idn = false;\n var punycode = false;\n var relative = !this._parts.urn;\n\n if (this._parts.hostname) {\n relative = false;\n ip4 = URI.ip4_expression.test(this._parts.hostname);\n ip6 = URI.ip6_expression.test(this._parts.hostname);\n ip = ip4 || ip6;\n name = !ip;\n sld = name && SLD && SLD.has(this._parts.hostname);\n idn = name && URI.idn_expression.test(this._parts.hostname);\n punycode = name && URI.punycode_expression.test(this._parts.hostname);\n }\n\n switch (what.toLowerCase()) {\n case 'relative':\n return relative;\n\n case 'absolute':\n return !relative;\n\n // hostname identification\n case 'domain':\n case 'name':\n return name;\n\n case 'sld':\n return sld;\n\n case 'ip':\n return ip;\n\n case 'ip4':\n case 'ipv4':\n case 'inet4':\n return ip4;\n\n case 'ip6':\n case 'ipv6':\n case 'inet6':\n return ip6;\n\n case 'idn':\n return idn;\n\n case 'url':\n return !this._parts.urn;\n\n case 'urn':\n return !!this._parts.urn;\n\n case 'punycode':\n return punycode;\n }\n\n return null;\n };\n\n // component specific input validation\n var _protocol = p.protocol;\n var _port = p.port;\n var _hostname = p.hostname;\n\n p.protocol = function(v, build) {\n if (v !== undefined) {\n if (v) {\n // accept trailing ://\n v = v.replace(/:(\\/\\/)?$/, '');\n\n if (!v.match(URI.protocol_expression)) {\n throw new TypeError('Protocol \"' + v + '\" contains characters other than [A-Z0-9.+-] or doesn\\'t start with [A-Z]');\n }\n }\n }\n return _protocol.call(this, v, build);\n };\n p.scheme = p.protocol;\n p.port = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v !== undefined) {\n if (v === 0) {\n v = null;\n }\n\n if (v) {\n v += '';\n if (v.charAt(0) === ':') {\n v = v.substring(1);\n }\n\n if (v.match(/[^0-9]/)) {\n throw new TypeError('Port \"' + v + '\" contains characters other than [0-9]');\n }\n }\n }\n return _port.call(this, v, build);\n };\n p.hostname = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v !== undefined) {\n var x = {};\n var res = URI.parseHost(v, x);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n v = x.hostname;\n }\n return _hostname.call(this, v, build);\n };\n\n // compound accessors\n p.origin = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n var protocol = this.protocol();\n var authority = this.authority();\n if (!authority) {\n return '';\n }\n\n return (protocol ? protocol + '://' : '') + this.authority();\n } else {\n var origin = URI(v);\n this\n .protocol(origin.protocol())\n .authority(origin.authority())\n .build(!build);\n return this;\n }\n };\n p.host = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n return this._parts.hostname ? URI.buildHost(this._parts) : '';\n } else {\n var res = URI.parseHost(v, this._parts);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n this.build(!build);\n return this;\n }\n };\n p.authority = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n return this._parts.hostname ? URI.buildAuthority(this._parts) : '';\n } else {\n var res = URI.parseAuthority(v, this._parts);\n if (res !== '/') {\n throw new TypeError('Hostname \"' + v + '\" contains characters other than [A-Z0-9.-]');\n }\n\n this.build(!build);\n return this;\n }\n };\n p.userinfo = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined) {\n var t = URI.buildUserinfo(this._parts);\n return t ? t.substring(0, t.length -1) : t;\n } else {\n if (v[v.length-1] !== '@') {\n v += '@';\n }\n\n URI.parseUserinfo(v, this._parts);\n this.build(!build);\n return this;\n }\n };\n p.resource = function(v, build) {\n var parts;\n\n if (v === undefined) {\n return this.path() + this.search() + this.hash();\n }\n\n parts = URI.parse(v);\n this._parts.path = parts.path;\n this._parts.query = parts.query;\n this._parts.fragment = parts.fragment;\n this.build(!build);\n return this;\n };\n\n // fraction accessors\n p.subdomain = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n // convenience, return \"www\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n // grab domain and add another segment\n var end = this._parts.hostname.length - this.domain().length - 1;\n return this._parts.hostname.substring(0, end) || '';\n } else {\n var e = this._parts.hostname.length - this.domain().length;\n var sub = this._parts.hostname.substring(0, e);\n var replace = new RegExp('^' + escapeRegEx(sub));\n\n if (v && v.charAt(v.length - 1) !== '.') {\n v += '.';\n }\n\n if (v) {\n URI.ensureValidHostname(v);\n }\n\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n this.build(!build);\n return this;\n }\n };\n p.domain = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v === 'boolean') {\n build = v;\n v = undefined;\n }\n\n // convenience, return \"example.org\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n // if hostname consists of 1 or 2 segments, it must be the domain\n var t = this._parts.hostname.match(/\\./g);\n if (t && t.length < 2) {\n return this._parts.hostname;\n }\n\n // grab tld and add another segment\n var end = this._parts.hostname.length - this.tld(build).length - 1;\n end = this._parts.hostname.lastIndexOf('.', end -1) + 1;\n return this._parts.hostname.substring(end) || '';\n } else {\n if (!v) {\n throw new TypeError('cannot set domain empty');\n }\n\n URI.ensureValidHostname(v);\n\n if (!this._parts.hostname || this.is('IP')) {\n this._parts.hostname = v;\n } else {\n var replace = new RegExp(escapeRegEx(this.domain()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.tld = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (typeof v === 'boolean') {\n build = v;\n v = undefined;\n }\n\n // return \"org\" from \"www.example.org\"\n if (v === undefined) {\n if (!this._parts.hostname || this.is('IP')) {\n return '';\n }\n\n var pos = this._parts.hostname.lastIndexOf('.');\n var tld = this._parts.hostname.substring(pos + 1);\n\n if (build !== true && SLD && SLD.list[tld.toLowerCase()]) {\n return SLD.get(this._parts.hostname) || tld;\n }\n\n return tld;\n } else {\n var replace;\n\n if (!v) {\n throw new TypeError('cannot set TLD empty');\n } else if (v.match(/[^a-zA-Z0-9-]/)) {\n if (SLD && SLD.is(v)) {\n replace = new RegExp(escapeRegEx(this.tld()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n } else {\n throw new TypeError('TLD \"' + v + '\" contains characters other than [A-Z0-9]');\n }\n } else if (!this._parts.hostname || this.is('IP')) {\n throw new ReferenceError('cannot set TLD on non-domain host');\n } else {\n replace = new RegExp(escapeRegEx(this.tld()) + '$');\n this._parts.hostname = this._parts.hostname.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.directory = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path && !this._parts.hostname) {\n return '';\n }\n\n if (this._parts.path === '/') {\n return '/';\n }\n\n var end = this._parts.path.length - this.filename().length - 1;\n var res = this._parts.path.substring(0, end) || (this._parts.hostname ? '/' : '');\n\n return v ? URI.decodePath(res) : res;\n\n } else {\n var e = this._parts.path.length - this.filename().length;\n var directory = this._parts.path.substring(0, e);\n var replace = new RegExp('^' + escapeRegEx(directory));\n\n // fully qualifier directories begin with a slash\n if (!this.is('relative')) {\n if (!v) {\n v = '/';\n }\n\n if (v.charAt(0) !== '/') {\n v = '/' + v;\n }\n }\n\n // directories always end with a slash\n if (v && v.charAt(v.length - 1) !== '/') {\n v += '/';\n }\n\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n this.build(!build);\n return this;\n }\n };\n p.filename = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path || this._parts.path === '/') {\n return '';\n }\n\n var pos = this._parts.path.lastIndexOf('/');\n var res = this._parts.path.substring(pos+1);\n\n return v ? URI.decodePathSegment(res) : res;\n } else {\n var mutatedDirectory = false;\n\n if (v.charAt(0) === '/') {\n v = v.substring(1);\n }\n\n if (v.match(/\\.?\\//)) {\n mutatedDirectory = true;\n }\n\n var replace = new RegExp(escapeRegEx(this.filename()) + '$');\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n\n if (mutatedDirectory) {\n this.normalizePath(build);\n } else {\n this.build(!build);\n }\n\n return this;\n }\n };\n p.suffix = function(v, build) {\n if (this._parts.urn) {\n return v === undefined ? '' : this;\n }\n\n if (v === undefined || v === true) {\n if (!this._parts.path || this._parts.path === '/') {\n return '';\n }\n\n var filename = this.filename();\n var pos = filename.lastIndexOf('.');\n var s, res;\n\n if (pos === -1) {\n return '';\n }\n\n // suffix may only contain alnum characters (yup, I made this up.)\n s = filename.substring(pos+1);\n res = (/^[a-z0-9%]+$/i).test(s) ? s : '';\n return v ? URI.decodePathSegment(res) : res;\n } else {\n if (v.charAt(0) === '.') {\n v = v.substring(1);\n }\n\n var suffix = this.suffix();\n var replace;\n\n if (!suffix) {\n if (!v) {\n return this;\n }\n\n this._parts.path += '.' + URI.recodePath(v);\n } else if (!v) {\n replace = new RegExp(escapeRegEx('.' + suffix) + '$');\n } else {\n replace = new RegExp(escapeRegEx(suffix) + '$');\n }\n\n if (replace) {\n v = URI.recodePath(v);\n this._parts.path = this._parts.path.replace(replace, v);\n }\n\n this.build(!build);\n return this;\n }\n };\n p.segment = function(segment, v, build) {\n var separator = this._parts.urn ? ':' : '/';\n var path = this.path();\n var absolute = path.substring(0, 1) === '/';\n var segments = path.split(separator);\n\n if (segment !== undefined && typeof segment !== 'number') {\n build = v;\n v = segment;\n segment = undefined;\n }\n\n if (segment !== undefined && typeof segment !== 'number') {\n throw new Error('Bad segment \"' + segment + '\", must be 0-based integer');\n }\n\n if (absolute) {\n segments.shift();\n }\n\n if (segment < 0) {\n // allow negative indexes to address from the end\n segment = Math.max(segments.length + segment, 0);\n }\n\n if (v === undefined) {\n /*jshint laxbreak: true */\n return segment === undefined\n ? segments\n : segments[segment];\n /*jshint laxbreak: false */\n } else if (segment === null || segments[segment] === undefined) {\n if (isArray(v)) {\n segments = [];\n // collapse empty elements within array\n for (var i=0, l=v.length; i < l; i++) {\n if (!v[i].length && (!segments.length || !segments[segments.length -1].length)) {\n continue;\n }\n\n if (segments.length && !segments[segments.length -1].length) {\n segments.pop();\n }\n\n segments.push(trimSlashes(v[i]));\n }\n } else if (v || typeof v === 'string') {\n v = trimSlashes(v);\n if (segments[segments.length -1] === '') {\n // empty trailing elements have to be overwritten\n // to prevent results such as /foo//bar\n segments[segments.length -1] = v;\n } else {\n segments.push(v);\n }\n }\n } else {\n if (v) {\n segments[segment] = trimSlashes(v);\n } else {\n segments.splice(segment, 1);\n }\n }\n\n if (absolute) {\n segments.unshift('');\n }\n\n return this.path(segments.join(separator), build);\n };\n p.segmentCoded = function(segment, v, build) {\n var segments, i, l;\n\n if (typeof segment !== 'number') {\n build = v;\n v = segment;\n segment = undefined;\n }\n\n if (v === undefined) {\n segments = this.segment(segment, v, build);\n if (!isArray(segments)) {\n segments = segments !== undefined ? URI.decode(segments) : undefined;\n } else {\n for (i = 0, l = segments.length; i < l; i++) {\n segments[i] = URI.decode(segments[i]);\n }\n }\n\n return segments;\n }\n\n if (!isArray(v)) {\n v = (typeof v === 'string' || v instanceof String) ? URI.encode(v) : v;\n } else {\n for (i = 0, l = v.length; i < l; i++) {\n v[i] = URI.encode(v[i]);\n }\n }\n\n return this.segment(segment, v, build);\n };\n\n // mutating query string\n var q = p.query;\n p.query = function(v, build) {\n if (v === true) {\n return URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n } else if (typeof v === 'function') {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n var result = v.call(this, data);\n this._parts.query = URI.buildQuery(result || data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n this.build(!build);\n return this;\n } else if (v !== undefined && typeof v !== 'string') {\n this._parts.query = URI.buildQuery(v, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n this.build(!build);\n return this;\n } else {\n return q.call(this, v, build);\n }\n };\n p.setQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n\n if (typeof name === 'string' || name instanceof String) {\n data[name] = value !== undefined ? value : null;\n } else if (typeof name === 'object') {\n for (var key in name) {\n if (hasOwn.call(name, key)) {\n data[key] = name[key];\n }\n }\n } else {\n throw new TypeError('URI.addQuery() accepts an object, string as the name parameter');\n }\n\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.addQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n URI.addQuery(data, name, value === undefined ? null : value);\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.removeQuery = function(name, value, build) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n URI.removeQuery(data, name, value);\n this._parts.query = URI.buildQuery(data, this._parts.duplicateQueryParameters, this._parts.escapeQuerySpace);\n if (typeof name !== 'string') {\n build = value;\n }\n\n this.build(!build);\n return this;\n };\n p.hasQuery = function(name, value, withinArray) {\n var data = URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace);\n return URI.hasQuery(data, name, value, withinArray);\n };\n p.setSearch = p.setQuery;\n p.addSearch = p.addQuery;\n p.removeSearch = p.removeQuery;\n p.hasSearch = p.hasQuery;\n\n // sanitizing URLs\n p.normalize = function() {\n if (this._parts.urn) {\n return this\n .normalizeProtocol(false)\n .normalizePath(false)\n .normalizeQuery(false)\n .normalizeFragment(false)\n .build();\n }\n\n return this\n .normalizeProtocol(false)\n .normalizeHostname(false)\n .normalizePort(false)\n .normalizePath(false)\n .normalizeQuery(false)\n .normalizeFragment(false)\n .build();\n };\n p.normalizeProtocol = function(build) {\n if (typeof this._parts.protocol === 'string') {\n this._parts.protocol = this._parts.protocol.toLowerCase();\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeHostname = function(build) {\n if (this._parts.hostname) {\n if (this.is('IDN') && punycode) {\n this._parts.hostname = punycode.toASCII(this._parts.hostname);\n } else if (this.is('IPv6') && IPv6) {\n this._parts.hostname = IPv6.best(this._parts.hostname);\n }\n\n this._parts.hostname = this._parts.hostname.toLowerCase();\n this.build(!build);\n }\n\n return this;\n };\n p.normalizePort = function(build) {\n // remove port of it's the protocol's default\n if (typeof this._parts.protocol === 'string' && this._parts.port === URI.defaultPorts[this._parts.protocol]) {\n this._parts.port = null;\n this.build(!build);\n }\n\n return this;\n };\n p.normalizePath = function(build) {\n var _path = this._parts.path;\n if (!_path) {\n return this;\n }\n\n if (this._parts.urn) {\n this._parts.path = URI.recodeUrnPath(this._parts.path);\n this.build(!build);\n return this;\n }\n\n if (this._parts.path === '/') {\n return this;\n }\n\n _path = URI.recodePath(_path);\n\n var _was_relative;\n var _leadingParents = '';\n var _parent, _pos;\n\n // handle relative paths\n if (_path.charAt(0) !== '/') {\n _was_relative = true;\n _path = '/' + _path;\n }\n\n // handle relative files (as opposed to directories)\n if (_path.slice(-3) === '/..' || _path.slice(-2) === '/.') {\n _path += '/';\n }\n\n // resolve simples\n _path = _path\n .replace(/(\\/(\\.\\/)+)|(\\/\\.$)/g, '/')\n .replace(/\\/{2,}/g, '/');\n\n // remember leading parents\n if (_was_relative) {\n _leadingParents = _path.substring(1).match(/^(\\.\\.\\/)+/) || '';\n if (_leadingParents) {\n _leadingParents = _leadingParents[0];\n }\n }\n\n // resolve parents\n while (true) {\n _parent = _path.search(/\\/\\.\\.(\\/|$)/);\n if (_parent === -1) {\n // no more ../ to resolve\n break;\n } else if (_parent === 0) {\n // top level cannot be relative, skip it\n _path = _path.substring(3);\n continue;\n }\n\n _pos = _path.substring(0, _parent).lastIndexOf('/');\n if (_pos === -1) {\n _pos = _parent;\n }\n _path = _path.substring(0, _pos) + _path.substring(_parent + 3);\n }\n\n // revert to relative\n if (_was_relative && this.is('relative')) {\n _path = _leadingParents + _path.substring(1);\n }\n\n this._parts.path = _path;\n this.build(!build);\n return this;\n };\n p.normalizePathname = p.normalizePath;\n p.normalizeQuery = function(build) {\n if (typeof this._parts.query === 'string') {\n if (!this._parts.query.length) {\n this._parts.query = null;\n } else {\n this.query(URI.parseQuery(this._parts.query, this._parts.escapeQuerySpace));\n }\n\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeFragment = function(build) {\n if (!this._parts.fragment) {\n this._parts.fragment = null;\n this.build(!build);\n }\n\n return this;\n };\n p.normalizeSearch = p.normalizeQuery;\n p.normalizeHash = p.normalizeFragment;\n\n p.iso8859 = function() {\n // expect unicode input, iso8859 output\n var e = URI.encode;\n var d = URI.decode;\n\n URI.encode = escape;\n URI.decode = decodeURIComponent;\n try {\n this.normalize();\n } finally {\n URI.encode = e;\n URI.decode = d;\n }\n return this;\n };\n\n p.unicode = function() {\n // expect iso8859 input, unicode output\n var e = URI.encode;\n var d = URI.decode;\n\n URI.encode = strictEncodeURIComponent;\n URI.decode = unescape;\n try {\n this.normalize();\n } finally {\n URI.encode = e;\n URI.decode = d;\n }\n return this;\n };\n\n p.readable = function() {\n var uri = this.clone();\n // removing username, password, because they shouldn't be displayed according to RFC 3986\n uri.username('').password('').normalize();\n var t = '';\n if (uri._parts.protocol) {\n t += uri._parts.protocol + '://';\n }\n\n if (uri._parts.hostname) {\n if (uri.is('punycode') && punycode) {\n t += punycode.toUnicode(uri._parts.hostname);\n if (uri._parts.port) {\n t += ':' + uri._parts.port;\n }\n } else {\n t += uri.host();\n }\n }\n\n if (uri._parts.hostname && uri._parts.path && uri._parts.path.charAt(0) !== '/') {\n t += '/';\n }\n\n t += uri.path(true);\n if (uri._parts.query) {\n var q = '';\n for (var i = 0, qp = uri._parts.query.split('&'), l = qp.length; i < l; i++) {\n var kv = (qp[i] || '').split('=');\n q += '&' + URI.decodeQuery(kv[0], this._parts.escapeQuerySpace)\n .replace(/&/g, '%26');\n\n if (kv[1] !== undefined) {\n q += '=' + URI.decodeQuery(kv[1], this._parts.escapeQuerySpace)\n .replace(/&/g, '%26');\n }\n }\n t += '?' + q.substring(1);\n }\n\n t += URI.decodeQuery(uri.hash(), true);\n return t;\n };\n\n // resolving relative and absolute URLs\n p.absoluteTo = function(base) {\n var resolved = this.clone();\n var properties = ['protocol', 'username', 'password', 'hostname', 'port'];\n var basedir, i, p;\n\n if (this._parts.urn) {\n throw new Error('URNs do not have any generally defined hierarchical components');\n }\n\n if (!(base instanceof URI)) {\n base = new URI(base);\n }\n\n if (!resolved._parts.protocol) {\n resolved._parts.protocol = base._parts.protocol;\n }\n\n if (this._parts.hostname) {\n return resolved;\n }\n\n for (i = 0; (p = properties[i]); i++) {\n resolved._parts[p] = base._parts[p];\n }\n\n if (!resolved._parts.path) {\n resolved._parts.path = base._parts.path;\n if (!resolved._parts.query) {\n resolved._parts.query = base._parts.query;\n }\n } else if (resolved._parts.path.substring(-2) === '..') {\n resolved._parts.path += '/';\n }\n\n if (resolved.path().charAt(0) !== '/') {\n basedir = base.directory();\n basedir = basedir ? basedir : base.path().indexOf('/') === 0 ? '/' : '';\n resolved._parts.path = (basedir ? (basedir + '/') : '') + resolved._parts.path;\n resolved.normalizePath();\n }\n\n resolved.build();\n return resolved;\n };\n p.relativeTo = function(base) {\n var relative = this.clone().normalize();\n var relativeParts, baseParts, common, relativePath, basePath;\n\n if (relative._parts.urn) {\n throw new Error('URNs do not have any generally defined hierarchical components');\n }\n\n base = new URI(base).normalize();\n relativeParts = relative._parts;\n baseParts = base._parts;\n relativePath = relative.path();\n basePath = base.path();\n\n if (relativePath.charAt(0) !== '/') {\n throw new Error('URI is already relative');\n }\n\n if (basePath.charAt(0) !== '/') {\n throw new Error('Cannot calculate a URI relative to another relative URI');\n }\n\n if (relativeParts.protocol === baseParts.protocol) {\n relativeParts.protocol = null;\n }\n\n if (relativeParts.username !== baseParts.username || relativeParts.password !== baseParts.password) {\n return relative.build();\n }\n\n if (relativeParts.protocol !== null || relativeParts.username !== null || relativeParts.password !== null) {\n return relative.build();\n }\n\n if (relativeParts.hostname === baseParts.hostname && relativeParts.port === baseParts.port) {\n relativeParts.hostname = null;\n relativeParts.port = null;\n } else {\n return relative.build();\n }\n\n if (relativePath === basePath) {\n relativeParts.path = '';\n return relative.build();\n }\n\n // determine common sub path\n common = URI.commonPath(relativePath, basePath);\n\n // If the paths have nothing in common, return a relative URL with the absolute path.\n if (!common) {\n return relative.build();\n }\n\n var parents = baseParts.path\n .substring(common.length)\n .replace(/[^\\/]*$/, '')\n .replace(/.*?\\//g, '../');\n\n relativeParts.path = (parents + relativeParts.path.substring(common.length)) || './';\n\n return relative.build();\n };\n\n // comparing URIs\n p.equals = function(uri) {\n var one = this.clone();\n var two = new URI(uri);\n var one_map = {};\n var two_map = {};\n var checked = {};\n var one_query, two_query, key;\n\n one.normalize();\n two.normalize();\n\n // exact match\n if (one.toString() === two.toString()) {\n return true;\n }\n\n // extract query string\n one_query = one.query();\n two_query = two.query();\n one.query('');\n two.query('');\n\n // definitely not equal if not even non-query parts match\n if (one.toString() !== two.toString()) {\n return false;\n }\n\n // query parameters have the same length, even if they're permuted\n if (one_query.length !== two_query.length) {\n return false;\n }\n\n one_map = URI.parseQuery(one_query, this._parts.escapeQuerySpace);\n two_map = URI.parseQuery(two_query, this._parts.escapeQuerySpace);\n\n for (key in one_map) {\n if (hasOwn.call(one_map, key)) {\n if (!isArray(one_map[key])) {\n if (one_map[key] !== two_map[key]) {\n return false;\n }\n } else if (!arraysEqual(one_map[key], two_map[key])) {\n return false;\n }\n\n checked[key] = true;\n }\n }\n\n for (key in two_map) {\n if (hasOwn.call(two_map, key)) {\n if (!checked[key]) {\n // two contains a parameter not present in one\n return false;\n }\n }\n }\n\n return true;\n };\n\n // state\n p.duplicateQueryParameters = function(v) {\n this._parts.duplicateQueryParameters = !!v;\n return this;\n };\n\n p.escapeQuerySpace = function(v) {\n this._parts.escapeQuerySpace = !!v;\n return this;\n };\n\n return URI;\n}));\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar Spine = require('./spine');\nvar Locations = require('./locations');\nvar Parser = require('./parser');\nvar Navigation = require('./navigation');\nvar Rendition = require('./rendition');\nvar Unarchive = require('./unarchive');\nvar request = require('./request');\nvar EpubCFI = require('./epubcfi');\n\nfunction Book(_url, options){\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\trequestMethod: this.requestMethod\n\t});\n\n\tcore.extend(this.settings, options);\n\n\n\t// Promises\n\tthis.opening = new RSVP.defer();\n\tthis.opened = this.opening.promise;\n\tthis.isOpen = false;\n\n\tthis.url = undefined;\n\n\tthis.loading = {\n\t\tmanifest: new RSVP.defer(),\n\t\tspine: new RSVP.defer(),\n\t\tmetadata: new RSVP.defer(),\n\t\tcover: new RSVP.defer(),\n\t\tnavigation: new RSVP.defer(),\n\t\tpageList: new RSVP.defer()\n\t};\n\n\tthis.loaded = {\n\t\tmanifest: this.loading.manifest.promise,\n\t\tspine: this.loading.spine.promise,\n\t\tmetadata: this.loading.metadata.promise,\n\t\tcover: this.loading.cover.promise,\n\t\tnavigation: this.loading.navigation.promise,\n\t\tpageList: this.loading.pageList.promise\n\t};\n\n\tthis.ready = RSVP.hash(this.loaded);\n\n\t// Queue for methods used before opening\n\tthis.isRendered = false;\n\t// this._q = core.queue(this);\n\n\tthis.request = this.settings.requestMethod.bind(this);\n\n\tthis.spine = new Spine(this.request);\n\tthis.locations = new Locations(this.spine, this.request);\n\n\tif(_url) {\n\t\tthis.open(_url).catch(function (error) {\n\t\t\tvar err = new Error(\"Cannot load book at \"+ _url );\n\t\t\tconsole.error(err);\n\n\t\t\tthis.trigger(\"loadFailed\", error);\n\t\t}.bind(this));\n\t}\n};\n\nBook.prototype.open = function(_url, options){\n\tvar uri;\n\tvar parse = new Parser();\n\tvar epubPackage;\n\tvar epubContainer;\n\tvar book = this;\n\tvar containerPath = \"META-INF/container.xml\";\n\tvar location;\n\tvar absoluteUri;\n\tvar isArrayBuffer = false;\n\tvar isBase64 = options && options.base64;\n\n\tif(!_url) {\n\t\tthis.opening.resolve(this);\n\t\treturn this.opened;\n\t}\n\n\t// Reuse parsed url or create a new uri object\n\t// if(typeof(_url) === \"object\") {\n\t// uri = _url;\n\t// } else {\n\t// uri = core.uri(_url);\n\t// }\n\tif (_url instanceof ArrayBuffer || isBase64) {\n\t\tisArrayBuffer = true;\n\t\tthis.url = '/';\n\t} else {\n\t\turi = URI(_url);\n\t}\n\n\tif (window && window.location && uri) {\n\t\tabsoluteUri = uri.absoluteTo(window.location.href);\n\t\tthis.url = absoluteUri.toString();\n\t} else if (window && window.location) {\n\t\tthis.url = window.location.href;\n\t} else {\n\t\tthis.url = _url;\n\t}\n\n\t// Find path to the Container\n\tif(uri && uri.suffix() === \"opf\") {\n\t\t// Direct link to package, no container\n\t\tthis.packageUrl = _url;\n\t\tthis.containerUrl = '';\n\n\t\tif(uri.origin()) {\n\t\t\tthis.baseUrl = uri.origin() + \"/\" + uri.directory() + \"/\";\n\t\t} else if(absoluteUri){\n\t\t\tthis.baseUrl = absoluteUri.origin();\n\t\t\tthis.baseUrl += absoluteUri.directory() + \"/\";\n\t\t} else {\n\t\t\tthis.baseUrl = uri.directory() + \"/\";\n\t\t}\n\n\t\tepubPackage = this.request(this.packageUrl)\n\t\t\t.catch(function(error) {\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\n\t} else if(isArrayBuffer || isBase64 || this.isArchivedUrl(uri)) {\n\t\t// Book is archived\n\t\tthis.url = '/';\n\t\tthis.containerUrl = URI(containerPath).absoluteTo(this.url).toString();\n\n\t\tepubContainer = this.unarchive(_url, isBase64).\n\t\t\tthen(function() {\n\t\t\t\treturn this.request(this.containerUrl);\n\t\t\t}.bind(this))\n\t\t\t.catch(function(error) {\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\t}\n\t// Find the path to the Package from the container\n\telse if (!uri.suffix()) {\n\n\t\tthis.containerUrl = this.url + containerPath;\n\n\t\tepubContainer = this.request(this.containerUrl)\n\t\t\t.catch(function(error) {\n\t\t\t\t// handle errors in loading container\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\t}\n\n\tif (epubContainer) {\n\t\tepubPackage = epubContainer.\n\t\t\tthen(function(containerXml){\n\t\t\t\treturn parse.container(containerXml); // Container has path to content\n\t\t\t}).\n\t\t\tthen(function(paths){\n\t\t\t\tvar packageUri = URI(paths.packagePath);\n\t\t\t\tvar absPackageUri = packageUri.absoluteTo(book.url);\n\t\t\t\tvar absWindowUri;\n\n\t\t\t\tbook.packageUrl = absPackageUri.toString();\n\t\t\t\tbook.encoding = paths.encoding;\n\n\t\t\t\t// Set Url relative to the content\n\t\t\t\tif(absPackageUri.origin()) {\n\t\t\t\t\tbook.baseUrl = absPackageUri.origin() + absPackageUri.directory() + \"/\";\n\t\t\t\t} else {\n\t\t\t\t\tif(packageUri.directory()) {\n\t\t\t\t\t\tbook.baseUrl = \"/\" + packageUri.directory() + \"/\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbook.baseUrl = \"/\"\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn book.request(book.packageUrl);\n\t\t\t}).catch(function(error) {\n\t\t\t\t// handle errors in either of the two requests\n\t\t\t\tbook.opening.reject(error);\n\t\t\t});\n\t}\n\n\tepubPackage.then(function(packageXml) {\n\n\t\tif (!packageXml) {\n\t\t\treturn;\n\t\t}\n\n\t\t// Get package information from epub opf\n\t\tbook.unpack(packageXml);\n\n\t\t// Resolve promises\n\t\tbook.loading.manifest.resolve(book.package.manifest);\n\t\tbook.loading.metadata.resolve(book.package.metadata);\n\t\tbook.loading.spine.resolve(book.spine);\n\t\tbook.loading.cover.resolve(book.cover);\n\n\t\tbook.isOpen = true;\n\n\t\t// Clear queue of any waiting book request\n\n\t\t// Resolve book opened promise\n\t\tbook.opening.resolve(book);\n\n\t}).catch(function(error) {\n\t\t// handle errors in parsing the book\n\t\t// console.error(error.message, error.stack);\n\t\tbook.opening.reject(error);\n\t});\n\n\treturn this.opened;\n};\n\nBook.prototype.unpack = function(packageXml){\n\tvar book = this,\n\t\t\tparse = new Parser();\n\n\tbook.package = parse.packageContents(packageXml); // Extract info from contents\n\tif(!book.package) {\n\t\treturn;\n\t}\n\n\tbook.package.baseUrl = book.baseUrl; // Provides a url base for resolving paths\n\n\tthis.spine.load(book.package);\n\n\tbook.navigation = new Navigation(book.package, this.request);\n\tbook.navigation.load().then(function(toc){\n\t\tbook.toc = toc;\n\t\tbook.loading.navigation.resolve(book.toc);\n\t});\n\n\t// //-- Set Global Layout setting based on metadata\n\t// MOVE TO RENDER\n\t// book.globalLayoutProperties = book.parseLayoutProperties(book.package.metadata);\n\n\tbook.cover = URI(book.package.coverPath).absoluteTo(book.baseUrl).toString();\n};\n\n// Alias for book.spine.get\nBook.prototype.section = function(target) {\n\treturn this.spine.get(target);\n};\n\n// Sugar to render a book\nBook.prototype.renderTo = function(element, options) {\n\t// var renderMethod = (options && options.method) ?\n\t// options.method :\n\t// \"single\";\n\n\tthis.rendition = new Rendition(this, options);\n\tthis.rendition.attachTo(element);\n\n\treturn this.rendition;\n};\n\nBook.prototype.requestMethod = function(_url) {\n\t// Switch request methods\n\tif(this.unarchived) {\n\t\treturn this.unarchived.request(_url);\n\t} else {\n\t\treturn request(_url, null, this.requestCredentials, this.requestHeaders);\n\t}\n\n};\n\nBook.prototype.setRequestCredentials = function(_credentials) {\n\tthis.requestCredentials = _credentials;\n};\n\nBook.prototype.setRequestHeaders = function(_headers) {\n\tthis.requestHeaders = _headers;\n};\n\nBook.prototype.unarchive = function(bookUrl, isBase64){\n\tthis.unarchived = new Unarchive();\n\treturn this.unarchived.open(bookUrl, isBase64);\n};\n\n//-- Checks if url has a .epub or .zip extension, or is ArrayBuffer (of zip/epub)\nBook.prototype.isArchivedUrl = function(bookUrl){\n\tvar uri;\n\tvar extension;\n\n\tif (bookUrl instanceof ArrayBuffer) {\n\t\treturn true;\n\t}\n\n\t// Reuse parsed url or create a new uri object\n\t// if(typeof(bookUrl) === \"object\") {\n\t// uri = bookUrl;\n\t// } else {\n\t// uri = core.uri(bookUrl);\n\t// }\n\turi = URI(bookUrl);\n\textension = uri.suffix();\n\n\tif(extension && (extension == \"epub\" || extension == \"zip\")){\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\n//-- Returns the cover\nBook.prototype.coverUrl = function(){\n\tvar retrieved = this.loaded.cover.\n\t\tthen(function(url) {\n\t\t\tif(this.unarchived) {\n\t\t\t\treturn this.unarchived.createUrl(this.cover);\n\t\t\t}else{\n\t\t\t\treturn this.cover;\n\t\t\t}\n\t\t}.bind(this));\n\n\n\n\treturn retrieved;\n};\n\nBook.prototype.range = function(cfiRange) {\n\tvar cfi = new EpubCFI(cfiRange);\n\tvar item = this.spine.get(cfi.spinePos);\n\n\treturn item.load().then(function (contents) {\n\t\tvar range = cfi.toRange(item.document);\n\t\treturn range;\n\t})\n};\n\nmodule.exports = Book;\n\n//-- Enable binding events to book\nRSVP.EventTarget.mixin(Book.prototype);\n\n//-- Handle RSVP Errors\nRSVP.on('error', function(event) {\n\tconsole.error(event);\n});\n\nRSVP.configure('instrument', false); //-- true | will logging out all RSVP rejections\n// RSVP.on('created', listener);\n// RSVP.on('chained', listener);\n// RSVP.on('fulfilled', listener);\nRSVP.on('rejected', function(event){\n\tconsole.error(event.detail.message, event.detail.stack);\n});\n","var RSVP = require('rsvp');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\nvar Mapping = require('./mapping');\n\n\nfunction Contents(doc, content, cfiBase) {\n\t// Blank Cfi for Parsing\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.document = doc;\n\tthis.documentElement = this.document.documentElement;\n\tthis.content = content || this.document.body;\n\tthis.window = this.document.defaultView;\n\t// Dom events to listen for\n\tthis.listenedEvents = [\"keydown\", \"keyup\", \"keypressed\", \"mouseup\", \"mousedown\", \"click\", \"touchend\", \"touchstart\"];\n\n\tthis._size = {\n\t\twidth: 0,\n\t\theight: 0\n\t}\n\n\tthis.cfiBase = cfiBase || \"\";\n\n\tthis.listeners();\n};\n\nContents.prototype.width = function(w) {\n\t// var frame = this.documentElement;\n\tvar frame = this.content;\n\n\tif (w && core.isNumber(w)) {\n\t\tw = w + \"px\";\n\t}\n\n\tif (w) {\n\t\tframe.style.width = w;\n\t\t// this.content.style.width = w;\n\t}\n\n\treturn this.window.getComputedStyle(frame)['width'];\n\n\n};\n\nContents.prototype.height = function(h) {\n\t// var frame = this.documentElement;\n\tvar frame = this.content;\n\n\tif (h && core.isNumber(h)) {\n\t\th = h + \"px\";\n\t}\n\n\tif (h) {\n\t\tframe.style.height = h;\n\t\t// this.content.style.height = h;\n\t}\n\n\treturn this.window.getComputedStyle(frame)['height'];\n\n};\n\nContents.prototype.contentWidth = function(w) {\n\n\tvar content = this.content || this.document.body;\n\n\tif (w && core.isNumber(w)) {\n\t\tw = w + \"px\";\n\t}\n\n\tif (w) {\n\t\tcontent.style.width = w;\n\t}\n\n\treturn this.window.getComputedStyle(content)['width'];\n\n\n};\n\nContents.prototype.contentHeight = function(h) {\n\n\tvar content = this.content || this.document.body;\n\n\tif (h && core.isNumber(h)) {\n\t\th = h + \"px\";\n\t}\n\n\tif (h) {\n\t\tcontent.style.height = h;\n\t}\n\n\treturn this.window.getComputedStyle(content)['height'];\n\n};\n\nContents.prototype.textWidth = function() {\n\tvar width;\n\tvar range = this.document.createRange();\n\tvar content = this.content || this.document.body;\n\n\t// Select the contents of frame\n\trange.selectNodeContents(content);\n\n\t// get the width of the text content\n\twidth = range.getBoundingClientRect().width;\n\n\treturn width;\n\n};\n\nContents.prototype.textHeight = function() {\n\tvar height;\n\tvar range = this.document.createRange();\n\tvar content = this.content || this.document.body;\n\n\trange.selectNodeContents(content);\n\n\theight = range.getBoundingClientRect().height;\n\n\treturn height;\n};\n\nContents.prototype.scrollWidth = function() {\n\tvar width = this.documentElement.scrollWidth;\n\n\treturn width;\n};\n\nContents.prototype.scrollHeight = function() {\n\tvar height = this.documentElement.scrollHeight;\n\n\treturn height;\n};\n\nContents.prototype.overflow = function(overflow) {\n\n\tif (overflow) {\n\t\tthis.documentElement.style.overflow = overflow;\n\t}\n\n\treturn this.window.getComputedStyle(this.documentElement)['overflow'];\n};\n\nContents.prototype.overflowX = function(overflow) {\n\n\tif (overflow) {\n\t\tthis.documentElement.style.overflowX = overflow;\n\t}\n\n\treturn this.window.getComputedStyle(this.documentElement)['overflowX'];\n};\n\nContents.prototype.overflowY = function(overflow) {\n\n\tif (overflow) {\n\t\tthis.documentElement.style.overflowY = overflow;\n\t}\n\n\treturn this.window.getComputedStyle(this.documentElement)['overflowY'];\n};\n\nContents.prototype.css = function(property, value) {\n\tvar content = this.content || this.document.body;\n\n\tif (value) {\n\t\tcontent.style[property] = value;\n\t}\n\n\treturn this.window.getComputedStyle(content)[property];\n};\n\nContents.prototype.viewport = function(options) {\n\tvar width, height, scale, scalable;\n\tvar $viewport = this.document.querySelector(\"meta[name='viewport']\");\n\tvar newContent = '';\n\n\t/**\n\t* check for the viewport size\n\t* \n\t*/\n\tif($viewport && $viewport.hasAttribute(\"content\")) {\n\t\tcontent = $viewport.getAttribute(\"content\");\n\t\tcontents = content.split(/\\s*,\\s*/);\n\t\tif(contents[0]){\n\t\t\twidth = contents[0].replace(\"width=\", '').trim();\n\t\t}\n\t\tif(contents[1]){\n\t\t\theight = contents[1].replace(\"height=\", '').trim();\n\t\t}\n\t\tif(contents[2]){\n\t\t\tscale = contents[2].replace(\"initial-scale=\", '').trim();\n\t\t}\n\t\tif(contents[3]){\n\t\t\tscalable = contents[3].replace(\"user-scalable=\", '').trim();\n\t\t}\n\t}\n\n\tif (options) {\n\n\t\tnewContent += \"width=\" + (options.width || width);\n\t\tnewContent += \", height=\" + (options.height || height);\n\t\tif (options.scale || scale) {\n\t\t\tnewContent += \", initial-scale=\" + (options.scale || scale);\n\t\t}\n\t\tif (options.scalable || scalable) {\n\t\t\tnewContent += \", user-scalable=\" + (options.scalable || scalable);\n\t\t}\n\n\t\tif (!$viewport) {\n\t\t\t$viewport = this.document.createElement(\"meta\");\n\t\t\t$viewport.setAttribute(\"name\", \"viewport\");\n\t\t\tthis.document.querySelector('head').appendChild($viewport);\n\t\t}\n\n\t\t$viewport.setAttribute(\"content\", newContent);\n\t}\n\n\n\treturn {\n\t\twidth: parseInt(width),\n\t\theight: parseInt(height)\n\t};\n};\n\n\n// Contents.prototype.layout = function(layoutFunc) {\n//\n// this.iframe.style.display = \"inline-block\";\n//\n// // Reset Body Styles\n// this.content.style.margin = \"0\";\n// //this.document.body.style.display = \"inline-block\";\n// //this.document.documentElement.style.width = \"auto\";\n//\n// if(layoutFunc){\n// layoutFunc(this);\n// }\n//\n// this.onLayout(this);\n//\n// };\n//\n// Contents.prototype.onLayout = function(view) {\n// // stub\n// };\n\nContents.prototype.expand = function() {\n\tthis.trigger(\"expand\");\n};\n\nContents.prototype.listeners = function() {\n\n\tthis.imageLoadListeners();\n\n\tthis.mediaQueryListeners();\n\n\t// this.fontLoadListeners();\n\n\tthis.addEventListeners();\n\n\tthis.addSelectionListeners();\n\n\tthis.resizeListeners();\n\n};\n\nContents.prototype.removeListeners = function() {\n\n\tthis.removeEventListeners();\n\n\tthis.removeSelectionListeners();\n};\n\nContents.prototype.resizeListeners = function() {\n\tvar width, height;\n\t// Test size again\n\tclearTimeout(this.expanding);\n\n\twidth = this.scrollWidth();\n\theight = this.scrollHeight();\n\n\tif (width != this._size.width || height != this._size.height) {\n\n\t\tthis._size = {\n\t\t\twidth: width,\n\t\t\theight: height\n\t\t}\n\n\t\tthis.trigger(\"resize\", this._size);\n\t}\n\n\tthis.expanding = setTimeout(this.resizeListeners.bind(this), 350);\n};\n\n//https://github.com/tylergaw/media-query-events/blob/master/js/mq-events.js\nContents.prototype.mediaQueryListeners = function() {\n\t\tvar sheets = this.document.styleSheets;\n\t\tvar mediaChangeHandler = function(m){\n\t\t\tif(m.matches && !this._expanding) {\n\t\t\t\tsetTimeout(this.expand.bind(this), 1);\n\t\t\t\t// this.expand();\n\t\t\t}\n\t\t}.bind(this);\n\n\t\tfor (var i = 0; i < sheets.length; i += 1) {\n\t\t\t\tvar rules = sheets[i].cssRules;\n\t\t\t\tif(!rules) return; // Stylesheets changed\n\t\t\t\tfor (var j = 0; j < rules.length; j += 1) {\n\t\t\t\t\t\t//if (rules[j].constructor === CSSMediaRule) {\n\t\t\t\t\t\tif(rules[j].media){\n\t\t\t\t\t\t\t\tvar mql = this.window.matchMedia(rules[j].media.mediaText);\n\t\t\t\t\t\t\t\tmql.addListener(mediaChangeHandler);\n\t\t\t\t\t\t\t\t//mql.onchange = mediaChangeHandler;\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t}\n};\n\nContents.prototype.observe = function(target) {\n\tvar renderer = this;\n\n\t// create an observer instance\n\tvar observer = new MutationObserver(function(mutations) {\n\t\tif(renderer._expanding) {\n\t\t\trenderer.expand();\n\t\t}\n\t\t// mutations.forEach(function(mutation) {\n\t\t// console.log(mutation);\n\t\t// });\n\t});\n\n\t// configuration of the observer:\n\tvar config = { attributes: true, childList: true, characterData: true, subtree: true };\n\n\t// pass in the target node, as well as the observer options\n\tobserver.observe(target, config);\n\n\treturn observer;\n};\n\nContents.prototype.imageLoadListeners = function(target) {\n\tvar images = this.document.querySelectorAll(\"img\");\n\tvar img;\n\tfor (var i = 0; i < images.length; i++) {\n\t\timg = images[i];\n\n\t\tif (typeof img.naturalWidth !== \"undefined\" &&\n\t\t\t\timg.naturalWidth === 0) {\n\t\t\timg.onload = this.expand.bind(this);\n\t\t}\n\t}\n};\n\nContents.prototype.fontLoadListeners = function(target) {\n\tif (!this.document || !this.document.fonts) {\n\t\treturn;\n\t}\n\n\tthis.document.fonts.ready.then(function () {\n\t\tthis.expand();\n\t}.bind(this));\n\n};\n\nContents.prototype.root = function() {\n\tif(!this.document) return null;\n\treturn this.document.documentElement;\n};\n\nContents.prototype.locationOf = function(target, ignoreClass) {\n\tvar position;\n\tvar targetPos = {\"left\": 0, \"top\": 0};\n\n\tif(!this.document) return;\n\n\tif(this.epubcfi.isCfiString(target)) {\n\t\trange = new EpubCFI(target).toRange(this.document, ignoreClass);\n\n\t\tif(range) {\n\t\t\tif (range.startContainer.nodeType === Node.ELEMENT_NODE) {\n\t\t\t\tposition = range.startContainer.getBoundingClientRect();\n\t\t\t\ttargetPos.left = position.left;\n\t\t\t\ttargetPos.top = position.top;\n\t\t\t} else {\n\t\t\t\tposition = range.getBoundingClientRect();\n\t\t\t\ttargetPos.left = position.left;\n\t\t\t\ttargetPos.top = position.top;\n\t\t\t}\n\t\t}\n\n\t} else if(typeof target === \"string\" &&\n\t\ttarget.indexOf(\"#\") > -1) {\n\n\t\tid = target.substring(target.indexOf(\"#\")+1);\n\t\tel = this.document.getElementById(id);\n\n\t\tif(el) {\n\t\t\tposition = el.getBoundingClientRect();\n\t\t\ttargetPos.left = position.left;\n\t\t\ttargetPos.top = position.top;\n\t\t}\n\t}\n\n\treturn targetPos;\n};\n\nContents.prototype.addStylesheet = function(src) {\n\treturn new RSVP.Promise(function(resolve, reject){\n\t\tvar $stylesheet;\n\t\tvar ready = false;\n\n\t\tif(!this.document) {\n\t\t\tresolve(false);\n\t\t\treturn;\n\t\t}\n\n\t\t$stylesheet = this.document.createElement('link');\n\t\t$stylesheet.type = 'text/css';\n\t\t$stylesheet.rel = \"stylesheet\";\n\t\t$stylesheet.href = src;\n\t\t$stylesheet.onload = $stylesheet.onreadystatechange = function() {\n\t\t\tif ( !ready && (!this.readyState || this.readyState == 'complete') ) {\n\t\t\t\tready = true;\n\t\t\t\t// Let apply\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tresolve(true);\n\t\t\t\t}, 1);\n\t\t\t}\n\t\t};\n\n\t\tthis.document.head.appendChild($stylesheet);\n\n\t}.bind(this));\n};\n\n// https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule\nContents.prototype.addStylesheetRules = function(rules) {\n\tvar styleEl;\n\tvar styleSheet;\n\n\tif(!this.document) return;\n\n\tstyleEl = this.document.createElement('style');\n\n\t// Append style element to head\n\tthis.document.head.appendChild(styleEl);\n\n\t// Grab style sheet\n\tstyleSheet = styleEl.sheet;\n\n\tfor (var i = 0, rl = rules.length; i < rl; i++) {\n\t\tvar j = 1, rule = rules[i], selector = rules[i][0], propStr = '';\n\t\t// If the second argument of a rule is an array of arrays, correct our variables.\n\t\tif (Object.prototype.toString.call(rule[1][0]) === '[object Array]') {\n\t\t\trule = rule[1];\n\t\t\tj = 0;\n\t\t}\n\n\t\tfor (var pl = rule.length; j < pl; j++) {\n\t\t\tvar prop = rule[j];\n\t\t\tpropStr += prop[0] + ':' + prop[1] + (prop[2] ? ' !important' : '') + ';\\n';\n\t\t}\n\n\t\t// Insert CSS Rule\n\t\tstyleSheet.insertRule(selector + '{' + propStr + '}', styleSheet.cssRules.length);\n\t}\n};\n\nContents.prototype.addScript = function(src) {\n\n\treturn new RSVP.Promise(function(resolve, reject){\n\t\tvar $script;\n\t\tvar ready = false;\n\n\t\tif(!this.document) {\n\t\t\tresolve(false);\n\t\t\treturn;\n\t\t}\n\n\t\t$script = this.document.createElement('script');\n\t\t$script.type = 'text/javascript';\n\t\t$script.async = true;\n\t\t$script.src = src;\n\t\t$script.onload = $script.onreadystatechange = function() {\n\t\t\tif ( !ready && (!this.readyState || this.readyState == 'complete') ) {\n\t\t\t\tready = true;\n\t\t\t\tsetTimeout(function(){\n\t\t\t\t\tresolve(true);\n\t\t\t\t}, 1);\n\t\t\t}\n\t\t};\n\n\t\tthis.document.head.appendChild($script);\n\n\t}.bind(this));\n};\n\nContents.prototype.addEventListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.listenedEvents.forEach(function(eventName){\n\t\tthis.document.addEventListener(eventName, this.triggerEvent.bind(this), false);\n\t}, this);\n\n};\n\nContents.prototype.removeEventListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.listenedEvents.forEach(function(eventName){\n\t\tthis.document.removeEventListener(eventName, this.triggerEvent, false);\n\t}, this);\n\n};\n\n// Pass browser events\nContents.prototype.triggerEvent = function(e){\n\tthis.trigger(e.type, e);\n};\n\nContents.prototype.addSelectionListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.document.addEventListener(\"selectionchange\", this.onSelectionChange.bind(this), false);\n};\n\nContents.prototype.removeSelectionListeners = function(){\n\tif(!this.document) {\n\t\treturn;\n\t}\n\tthis.document.removeEventListener(\"selectionchange\", this.onSelectionChange, false);\n};\n\nContents.prototype.onSelectionChange = function(e){\n\tif (this.selectionEndTimeout) {\n\t\tclearTimeout(this.selectionEndTimeout);\n\t}\n\tthis.selectionEndTimeout = setTimeout(function() {\n\t\tvar selection = this.window.getSelection();\n\t\tthis.triggerSelectedEvent(selection);\n\t}.bind(this), 500);\n};\n\nContents.prototype.triggerSelectedEvent = function(selection){\n\tvar range, cfirange;\n\n\tif (selection && selection.rangeCount > 0) {\n\t\trange = selection.getRangeAt(0);\n\t\tif(!range.collapsed) {\n\t\t\t// cfirange = this.section.cfiFromRange(range);\n\t\t\tcfirange = new EpubCFI(range, this.cfiBase).toString();\n\t\t\tthis.trigger(\"selected\", cfirange);\n\t\t\tthis.trigger(\"selectedRange\", range);\n\t\t}\n\t}\n};\n\nContents.prototype.range = function(_cfi, ignoreClass){\n\tvar cfi = new EpubCFI(_cfi);\n\treturn cfi.toRange(this.document, ignoreClass);\n};\n\nContents.prototype.map = function(layout){\n\tvar map = new Mapping(layout);\n\treturn map.section();\n};\n\nContents.prototype.size = function(width, height){\n\n\tif (width >= 0) {\n\t\tthis.width(width);\n\t}\n\n\tif (height >= 0) {\n\t\tthis.height(height);\n\t}\n\n\tthis.css(\"margin\", \"0\");\n\tthis.css(\"boxSizing\", \"border-box\");\n\n};\n\nContents.prototype.columns = function(width, height, columnWidth, gap){\n\tvar COLUMN_AXIS = core.prefixed('columnAxis');\n\tvar COLUMN_GAP = core.prefixed('columnGap');\n\tvar COLUMN_WIDTH = core.prefixed('columnWidth');\n\tvar COLUMN_FILL = core.prefixed('columnFill');\n\tvar textWidth;\n\n\tthis.width(width);\n\tthis.height(height);\n\n\t// Deal with Mobile trying to scale to viewport\n\tthis.viewport({ width: width, height: height, scale: 1.0 });\n\n\t// this.overflowY(\"hidden\");\n\tthis.css(\"overflowY\", \"hidden\");\n\tthis.css(\"margin\", \"0\");\n\tthis.css(\"boxSizing\", \"border-box\");\n\tthis.css(\"maxWidth\", \"inherit\");\n\n\tthis.css(COLUMN_AXIS, \"horizontal\");\n\tthis.css(COLUMN_FILL, \"auto\");\n\n\tthis.css(COLUMN_GAP, gap+\"px\");\n\tthis.css(COLUMN_WIDTH, columnWidth+\"px\");\n};\n\nContents.prototype.scale = function(scale, offsetX, offsetY){\n\tvar scale = \"scale(\" + scale + \")\";\n\tvar translate = '';\n\t// this.css(\"position\", \"absolute\"));\n\tthis.css(\"transformOrigin\", \"top left\");\n\n\tif (offsetX >= 0 || offsetY >= 0) {\n\t\ttranslate = \" translate(\" + (offsetX || 0 )+ \"px, \" + (offsetY || 0 )+ \"px )\";\n\t}\n\n\tthis.css(\"transform\", scale + translate);\n};\n\nContents.prototype.fit = function(width, height){\n\tvar viewport = this.viewport();\n\tvar widthScale = width / viewport.width;\n\tvar heightScale = height / viewport.height;\n\tvar scale = widthScale < heightScale ? widthScale : heightScale;\n\n\tvar offsetY = (height - (viewport.height * scale)) / 2;\n\n\tthis.width(width);\n\tthis.height(height);\n\tthis.overflow(\"hidden\");\n\n\t// Deal with Mobile trying to scale to viewport\n\tthis.viewport({ scale: 1.0 });\n\n\t// Scale to the correct size\n\tthis.scale(scale, 0, offsetY);\n\n\tthis.css(\"backgroundColor\", \"transparent\");\n};\n\nContents.prototype.mapPage = function(cfiBase, start, end) {\n\tvar mapping = new Mapping();\n\n\treturn mapping.page(this, cfiBase, start, end);\n};\n\nContents.prototype.destroy = function() {\n\t// Stop observing\n\tif(this.observer) {\n\t\tthis.observer.disconnect();\n\t}\n\n\tthis.removeListeners();\n\n};\n\nRSVP.EventTarget.mixin(Contents.prototype);\n\nmodule.exports = Contents;\n","var RSVP = require('rsvp');\nvar base64 = require('base64-js');\n\nvar requestAnimationFrame = (typeof window != 'undefined') ? (window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame) : false;\n/*\n//-- Parse the different parts of a url, returning a object\nfunction uri(url){\n\tvar uri = {\n\t\t\t\tprotocol : '',\n\t\t\t\thost : '',\n\t\t\t\tpath : '',\n\t\t\t\torigin : '',\n\t\t\t\tdirectory : '',\n\t\t\t\tbase : '',\n\t\t\t\tfilename : '',\n\t\t\t\textension : '',\n\t\t\t\tfragment : '',\n\t\t\t\thref : url\n\t\t\t},\n\t\t\tdoubleSlash = url.indexOf('://'),\n\t\t\tsearch = url.indexOf('?'),\n\t\t\tfragment = url.indexOf(\"#\"),\n\t\t\twithoutProtocol,\n\t\t\tdot,\n\t\t\tfirstSlash;\n\n\tif(fragment != -1) {\n\t\turi.fragment = url.slice(fragment + 1);\n\t\turl = url.slice(0, fragment);\n\t}\n\n\tif(search != -1) {\n\t\turi.search = url.slice(search + 1);\n\t\turl = url.slice(0, search);\n\t\thref = url;\n\t}\n\n\tif(doubleSlash != -1) {\n\t\turi.protocol = url.slice(0, doubleSlash);\n\t\twithoutProtocol = url.slice(doubleSlash+3);\n\t\tfirstSlash = withoutProtocol.indexOf('/');\n\n\t\tif(firstSlash === -1) {\n\t\t\turi.host = uri.path;\n\t\t\turi.path = \"\";\n\t\t} else {\n\t\t\turi.host = withoutProtocol.slice(0, firstSlash);\n\t\t\turi.path = withoutProtocol.slice(firstSlash);\n\t\t}\n\n\n\t\turi.origin = uri.protocol + \"://\" + uri.host;\n\n\t\turi.directory = folder(uri.path);\n\n\t\turi.base = uri.origin + uri.directory;\n\t\t// return origin;\n\t} else {\n\t\turi.path = url;\n\t\turi.directory = folder(url);\n\t\turi.base = uri.directory;\n\t}\n\n\t//-- Filename\n\turi.filename = url.replace(uri.base, '');\n\tdot = uri.filename.lastIndexOf('.');\n\tif(dot != -1) {\n\t\turi.extension = uri.filename.slice(dot+1);\n\t}\n\treturn uri;\n};\n\n//-- Parse out the folder, will return everything before the last slash\nfunction folder(url){\n\n\tvar lastSlash = url.lastIndexOf('/');\n\n\tif(lastSlash == -1) var folder = '';\n\n\tfolder = url.slice(0, lastSlash + 1);\n\n\treturn folder;\n\n};\n*/\nfunction isElement(obj) {\n\t\treturn !!(obj && obj.nodeType == 1);\n};\n\n// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript\nfunction uuid() {\n\tvar d = new Date().getTime();\n\tvar uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n\t\t\tvar r = (d + Math.random()*16)%16 | 0;\n\t\t\td = Math.floor(d/16);\n\t\t\treturn (c=='x' ? r : (r&0x7|0x8)).toString(16);\n\t});\n\treturn uuid;\n};\n\n// From Lodash\nfunction values(object) {\n\tvar index = -1,\n\t\t\tprops = Object.keys(object),\n\t\t\tlength = props.length,\n\t\t\tresult = Array(length);\n\n\twhile (++index < length) {\n\t\tresult[index] = object[props[index]];\n\t}\n\treturn result;\n};\n\nfunction resolveUrl(base, path) {\n\tvar url = [],\n\t\tsegments = [],\n\t\tbaseUri = uri(base),\n\t\tpathUri = uri(path),\n\t\tbaseDirectory = baseUri.directory,\n\t\tpathDirectory = pathUri.directory,\n\t\tdirectories = [],\n\t\t// folders = base.split(\"/\"),\n\t\tpaths;\n\n\t// if(uri.host) {\n\t// return path;\n\t// }\n\n\tif(baseDirectory[0] === \"/\") {\n\t\tbaseDirectory = baseDirectory.substring(1);\n\t}\n\n\tif(pathDirectory[pathDirectory.length-1] === \"/\") {\n\t\tbaseDirectory = baseDirectory.substring(0, baseDirectory.length-1);\n\t}\n\n\tif(pathDirectory[0] === \"/\") {\n\t\tpathDirectory = pathDirectory.substring(1);\n\t}\n\n\tif(pathDirectory[pathDirectory.length-1] === \"/\") {\n\t\tpathDirectory = pathDirectory.substring(0, pathDirectory.length-1);\n\t}\n\n\tif(baseDirectory) {\n\t\tdirectories = baseDirectory.split(\"/\");\n\t}\n\n\tpaths = pathDirectory.split(\"/\");\n\n\tpaths.reverse().forEach(function(part, index){\n\t\tif(part === \"..\"){\n\t\t\tdirectories.pop();\n\t\t} else if(part === directories[directories.length-1]) {\n\t\t\tdirectories.pop();\n\t\t\tsegments.unshift(part);\n\t\t} else {\n\t\t\tsegments.unshift(part);\n\t\t}\n\t});\n\n\turl = [baseUri.origin];\n\n\tif(directories.length) {\n\t\turl = url.concat(directories);\n\t}\n\n\tif(segments) {\n\t\turl = url.concat(segments);\n\t}\n\n\turl = url.concat(pathUri.filename);\n\n\treturn url.join(\"/\");\n};\n\nfunction documentHeight() {\n\treturn Math.max(\n\t\t\tdocument.documentElement.clientHeight,\n\t\t\tdocument.body.scrollHeight,\n\t\t\tdocument.documentElement.scrollHeight,\n\t\t\tdocument.body.offsetHeight,\n\t\t\tdocument.documentElement.offsetHeight\n\t);\n};\n\nfunction isNumber(n) {\n\treturn !isNaN(parseFloat(n)) && isFinite(n);\n};\n\nfunction prefixed(unprefixed) {\n\tvar vendors = [\"Webkit\", \"Moz\", \"O\", \"ms\" ],\n\t\tprefixes = ['-Webkit-', '-moz-', '-o-', '-ms-'],\n\t\tupper = unprefixed[0].toUpperCase() + unprefixed.slice(1),\n\t\tlength = vendors.length;\n\n\tif (typeof(document) === 'undefined' || typeof(document.body.style[unprefixed]) != 'undefined') {\n\t\treturn unprefixed;\n\t}\n\n\tfor ( var i=0; i < length; i++ ) {\n\t\tif (typeof(document.body.style[vendors[i] + upper]) != 'undefined') {\n\t\t\treturn vendors[i] + upper;\n\t\t}\n\t}\n\n\treturn unprefixed;\n};\n\nfunction defaults(obj) {\n\tfor (var i = 1, length = arguments.length; i < length; i++) {\n\t\tvar source = arguments[i];\n\t\tfor (var prop in source) {\n\t\t\tif (obj[prop] === void 0) obj[prop] = source[prop];\n\t\t}\n\t}\n\treturn obj;\n};\n\nfunction extend(target) {\n\t\tvar sources = [].slice.call(arguments, 1);\n\t\tsources.forEach(function (source) {\n\t\t\tif(!source) return;\n\t\t\tObject.getOwnPropertyNames(source).forEach(function(propName) {\n\t\t\t\tObject.defineProperty(target, propName, Object.getOwnPropertyDescriptor(source, propName));\n\t\t\t});\n\t\t});\n\t\treturn target;\n};\n\n// Fast quicksort insert for sorted array -- based on:\n// http://stackoverflow.com/questions/1344500/efficient-way-to-insert-a-number-into-a-sorted-array-of-numbers\nfunction insert(item, array, compareFunction) {\n\tvar location = locationOf(item, array, compareFunction);\n\tarray.splice(location, 0, item);\n\n\treturn location;\n};\n// Returns where something would fit in\nfunction locationOf(item, array, compareFunction, _start, _end) {\n\tvar start = _start || 0;\n\tvar end = _end || array.length;\n\tvar pivot = parseInt(start + (end - start) / 2);\n\tvar compared;\n\tif(!compareFunction){\n\t\tcompareFunction = function(a, b) {\n\t\t\tif(a > b) return 1;\n\t\t\tif(a < b) return -1;\n\t\t\tif(a = b) return 0;\n\t\t};\n\t}\n\tif(end-start <= 0) {\n\t\treturn pivot;\n\t}\n\n\tcompared = compareFunction(array[pivot], item);\n\tif(end-start === 1) {\n\t\treturn compared > 0 ? pivot : pivot + 1;\n\t}\n\n\tif(compared === 0) {\n\t\treturn pivot;\n\t}\n\tif(compared === -1) {\n\t\treturn locationOf(item, array, compareFunction, pivot, end);\n\t} else{\n\t\treturn locationOf(item, array, compareFunction, start, pivot);\n\t}\n};\n// Returns -1 of mpt found\nfunction indexOfSorted(item, array, compareFunction, _start, _end) {\n\tvar start = _start || 0;\n\tvar end = _end || array.length;\n\tvar pivot = parseInt(start + (end - start) / 2);\n\tvar compared;\n\tif(!compareFunction){\n\t\tcompareFunction = function(a, b) {\n\t\t\tif(a > b) return 1;\n\t\t\tif(a < b) return -1;\n\t\t\tif(a = b) return 0;\n\t\t};\n\t}\n\tif(end-start <= 0) {\n\t\treturn -1; // Not found\n\t}\n\n\tcompared = compareFunction(array[pivot], item);\n\tif(end-start === 1) {\n\t\treturn compared === 0 ? pivot : -1;\n\t}\n\tif(compared === 0) {\n\t\treturn pivot; // Found\n\t}\n\tif(compared === -1) {\n\t\treturn indexOfSorted(item, array, compareFunction, pivot, end);\n\t} else{\n\t\treturn indexOfSorted(item, array, compareFunction, start, pivot);\n\t}\n};\n\nfunction bounds(el) {\n\n\tvar style = window.getComputedStyle(el);\n\tvar widthProps = [\"width\", \"paddingRight\", \"paddingLeft\", \"marginRight\", \"marginLeft\", \"borderRightWidth\", \"borderLeftWidth\"];\n\tvar heightProps = [\"height\", \"paddingTop\", \"paddingBottom\", \"marginTop\", \"marginBottom\", \"borderTopWidth\", \"borderBottomWidth\"];\n\n\tvar width = 0;\n\tvar height = 0;\n\n\twidthProps.forEach(function(prop){\n\t\twidth += parseFloat(style[prop]) || 0;\n\t});\n\n\theightProps.forEach(function(prop){\n\t\theight += parseFloat(style[prop]) || 0;\n\t});\n\n\treturn {\n\t\theight: height,\n\t\twidth: width\n\t};\n\n};\n\nfunction borders(el) {\n\n\tvar style = window.getComputedStyle(el);\n\tvar widthProps = [\"paddingRight\", \"paddingLeft\", \"marginRight\", \"marginLeft\", \"borderRightWidth\", \"borderLeftWidth\"];\n\tvar heightProps = [\"paddingTop\", \"paddingBottom\", \"marginTop\", \"marginBottom\", \"borderTopWidth\", \"borderBottomWidth\"];\n\n\tvar width = 0;\n\tvar height = 0;\n\n\twidthProps.forEach(function(prop){\n\t\twidth += parseFloat(style[prop]) || 0;\n\t});\n\n\theightProps.forEach(function(prop){\n\t\theight += parseFloat(style[prop]) || 0;\n\t});\n\n\treturn {\n\t\theight: height,\n\t\twidth: width\n\t};\n\n};\n\nfunction windowBounds() {\n\n\tvar width = window.innerWidth;\n\tvar height = window.innerHeight;\n\n\treturn {\n\t\ttop: 0,\n\t\tleft: 0,\n\t\tright: width,\n\t\tbottom: height,\n\t\twidth: width,\n\t\theight: height\n\t};\n\n};\n\n//https://stackoverflow.com/questions/13482352/xquery-looking-for-text-with-single-quote/13483496#13483496\nfunction cleanStringForXpath(str) {\n\t\tvar parts = str.match(/[^'\"]+|['\"]/g);\n\t\tparts = parts.map(function(part){\n\t\t\t\tif (part === \"'\") {\n\t\t\t\t\t\treturn '\\\"\\'\\\"'; // output \"'\"\n\t\t\t\t}\n\n\t\t\t\tif (part === '\"') {\n\t\t\t\t\t\treturn \"\\'\\\"\\'\"; // output '\"'\n\t\t\t\t}\n\t\t\t\treturn \"\\'\" + part + \"\\'\";\n\t\t});\n\t\treturn \"concat(\\'\\',\" + parts.join(\",\") + \")\";\n};\n\nfunction indexOfTextNode(textNode){\n\tvar parent = textNode.parentNode;\n\tvar children = parent.childNodes;\n\tvar sib;\n\tvar index = -1;\n\tfor (var i = 0; i < children.length; i++) {\n\t\tsib = children[i];\n\t\tif(sib.nodeType === Node.TEXT_NODE){\n\t\t\tindex++;\n\t\t}\n\t\tif(sib == textNode) break;\n\t}\n\n\treturn index;\n};\n\nfunction isXml(ext) {\n\treturn ['xml', 'opf', 'ncx'].indexOf(ext) > -1;\n}\n\nfunction createBlob(content, mime){\n\tvar blob = new Blob([content], {type : mime });\n\n\treturn blob;\n};\n\nfunction createBlobUrl(content, mime){\n\tvar _URL = window.URL || window.webkitURL || window.mozURL;\n\tvar tempUrl;\n\tvar blob = this.createBlob(content, mime);\n\n\ttempUrl = _URL.createObjectURL(blob);\n\n\treturn tempUrl;\n};\n\nfunction createBase64Url(content, mime){\n\tvar string;\n\tvar data;\n\tvar datauri;\n\n\tif (typeof(content) !== \"string\") {\n\t\t// Only handles strings\n\t\treturn;\n\t}\n\n\tdata = btoa(content);\n\n\tdatauri = \"data:\" + mime + \";base64,\" + data;\n\n\treturn datauri;\n};\n\nfunction type(obj){\n\treturn Object.prototype.toString.call(obj).slice(8, -1);\n}\n\nfunction parse(markup, mime) {\n\tvar doc;\n\t// console.log(\"parse\", markup);\n\n\tif (typeof DOMParser === \"undefined\") {\n\t\tDOMParser = require('xmldom').DOMParser;\n\t}\n\n\n\tdoc = new DOMParser().parseFromString(markup, mime);\n\n\treturn doc;\n}\n\nfunction qs(el, sel) {\n\tvar elements;\n\n\tif (typeof el.querySelector != \"undefined\") {\n\t\treturn el.querySelector(sel);\n\t} else {\n\t\telements = el.getElementsByTagName(sel);\n\t\tif (elements.length) {\n\t\t\treturn elements[0];\n\t\t}\n\t}\n}\n\nfunction qsa(el, sel) {\n\n\tif (typeof el.querySelector != \"undefined\") {\n\t\treturn el.querySelectorAll(sel);\n\t} else {\n\t\treturn el.getElementsByTagName(sel);\n\t}\n}\n\nfunction qsp(el, sel, props) {\n\tvar q, filtered;\n\tif (typeof el.querySelector != \"undefined\") {\n\t\tsel += '[';\n\t\tfor (var prop in props) {\n\t\t\tsel += prop + \"='\" + props[prop] + \"'\";\n\t\t}\n\t\tsel += ']';\n\t\treturn el.querySelector(sel);\n\t} else {\n\t\tq = el.getElementsByTagName(sel);\n\t\tfiltered = Array.prototype.slice.call(q, 0).filter(function(el) {\n\t\t\tfor (var prop in props) {\n\t\t\t\tif(el.getAttribute(prop) === props[prop]){\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n\n\t\tif (filtered) {\n\t\t\treturn filtered[0];\n\t\t}\n\t}\n}\n\nfunction blob2base64(blob, cb) {\n\tvar reader = new FileReader();\n\treader.readAsDataURL(blob);\n\treader.onloadend = function() {\n\t\tcb(reader.result);\n\t}\n}\n\nmodule.exports = {\n\t// 'uri': uri,\n\t// 'folder': folder,\n\t'isElement': isElement,\n\t'uuid': uuid,\n\t'values': values,\n\t'resolveUrl': resolveUrl,\n\t'indexOfSorted': indexOfSorted,\n\t'documentHeight': documentHeight,\n\t'isNumber': isNumber,\n\t'prefixed': prefixed,\n\t'defaults': defaults,\n\t'extend': extend,\n\t'insert': insert,\n\t'locationOf': locationOf,\n\t'indexOfSorted': indexOfSorted,\n\t'requestAnimationFrame': requestAnimationFrame,\n\t'bounds': bounds,\n\t'borders': borders,\n\t'windowBounds': windowBounds,\n\t'cleanStringForXpath': cleanStringForXpath,\n\t'indexOfTextNode': indexOfTextNode,\n\t'isXml': isXml,\n\t'createBlob': createBlob,\n\t'createBlobUrl': createBlobUrl,\n\t'type': type,\n\t'parse' : parse,\n\t'qs' : qs,\n\t'qsa' : qsa,\n\t'qsp' : qsp,\n\t'blob2base64' : blob2base64,\n\t'createBase64Url': createBase64Url\n};\n","var URI = require('urijs');\nvar core = require('./core');\n\n/**\n\tEPUB CFI spec: http://www.idpf.org/epub/linking/cfi/epub-cfi.html\n\n\tImplements:\n\t- Character Offset: epubcfi(/6/4[chap01ref]!/4[body01]/10[para05]/2/1:3)\n\t- Simple Ranges : epubcfi(/6/4[chap01ref]!/4[body01]/10[para05],/2/1:1,/3:4)\n\n\tDoes Not Implement:\n\t- Temporal Offset (~)\n\t- Spatial Offset (@)\n\t- Temporal-Spatial Offset (~ + @)\n\t- Text Location Assertion ([)\n*/\n\nfunction EpubCFI(cfiFrom, base, ignoreClass){\n\tvar type;\n\n\tthis.str = '';\n\n\tthis.base = {};\n\tthis.spinePos = 0; // For compatibility\n\n\tthis.range = false; // true || false;\n\n\tthis.path = {};\n\tthis.start = null;\n\tthis.end = null;\n\n\t// Allow instantiation without the 'new' keyword\n\tif (!(this instanceof EpubCFI)) {\n\t\treturn new EpubCFI(cfiFrom, base, ignoreClass);\n\t}\n\n\tif(typeof base === 'string') {\n\t\tthis.base = this.parseComponent(base);\n\t} else if(typeof base === 'object' && base.steps) {\n\t\tthis.base = base;\n\t}\n\n\ttype = this.checkType(cfiFrom);\n\n\n\tif(type === 'string') {\n\t\tthis.str = cfiFrom;\n\t\treturn core.extend(this, this.parse(cfiFrom));\n\t} else if (type === 'range') {\n\t\treturn core.extend(this, this.fromRange(cfiFrom, this.base, ignoreClass));\n\t} else if (type === 'node') {\n\t\treturn core.extend(this, this.fromNode(cfiFrom, this.base, ignoreClass));\n\t} else if (type === 'EpubCFI' && cfiFrom.path) {\n\t\treturn cfiFrom;\n\t} else if (!cfiFrom) {\n\t\treturn this;\n\t} else {\n\t\tthrow new TypeError('not a valid argument for EpubCFI');\n\t}\n\n};\n\nEpubCFI.prototype.checkType = function(cfi) {\n\n\tif (this.isCfiString(cfi)) {\n\t\treturn 'string';\n\t// Is a range object\n\t} else if (typeof cfi === 'object' && core.type(cfi) === \"Range\"){\n\t\treturn 'range';\n\t} else if (typeof cfi === 'object' && typeof(cfi.nodeType) != \"undefined\" ){ // || typeof cfi === 'function'\n\t\treturn 'node';\n\t} else if (typeof cfi === 'object' && cfi instanceof EpubCFI){\n\t\treturn 'EpubCFI';\n\t} else {\n\t\treturn false;\n\t}\n};\n\nEpubCFI.prototype.parse = function(cfiStr) {\n\tvar cfi = {\n\t\t\tspinePos: -1,\n\t\t\trange: false,\n\t\t\tbase: {},\n\t\t\tpath: {},\n\t\t\tstart: null,\n\t\t\tend: null\n\t\t};\n\tvar baseComponent, pathComponent, range;\n\n\tif(typeof cfiStr !== \"string\") {\n\t\treturn {spinePos: -1};\n\t}\n\n\tif(cfiStr.indexOf(\"epubcfi(\") === 0 && cfiStr[cfiStr.length-1] === \")\") {\n\t\t// Remove intial epubcfi( and ending )\n\t\tcfiStr = cfiStr.slice(8, cfiStr.length-1);\n\t}\n\n\tbaseComponent = this.getChapterComponent(cfiStr);\n\n\t// Make sure this is a valid cfi or return\n\tif(!baseComponent) {\n\t\treturn {spinePos: -1};\n\t}\n\n\tcfi.base = this.parseComponent(baseComponent);\n\n\tpathComponent = this.getPathComponent(cfiStr);\n\tcfi.path = this.parseComponent(pathComponent);\n\n\trange = this.getRange(cfiStr);\n\n\tif(range) {\n\t\tcfi.range = true;\n\t\tcfi.start = this.parseComponent(range[0]);\n\t\tcfi.end = this.parseComponent(range[1]);\n\t}\n\n\t// Get spine node position\n\t// cfi.spineSegment = cfi.base.steps[1];\n\n\t// Chapter segment is always the second step\n\tcfi.spinePos = cfi.base.steps[1].index;\n\n\treturn cfi;\n};\n\nEpubCFI.prototype.parseComponent = function(componentStr){\n\tvar component = {\n\t\tsteps: [],\n\t\tterminal: {\n\t\t\toffset: null,\n\t\t\tassertion: null\n\t\t}\n\t};\n\tvar parts = componentStr.split(':');\n\tvar steps = parts[0].split('/');\n\tvar terminal;\n\n\tif(parts.length > 1) {\n\t\tterminal = parts[1];\n\t\tcomponent.terminal = this.parseTerminal(terminal);\n\t}\n\n\tif (steps[0] === '') {\n\t\tsteps.shift(); // Ignore the first slash\n\t}\n\n\tcomponent.steps = steps.map(function(step){\n\t\treturn this.parseStep(step);\n\t}.bind(this));\n\n\treturn component;\n};\n\nEpubCFI.prototype.parseStep = function(stepStr){\n\tvar type, num, index, has_brackets, id;\n\n\thas_brackets = stepStr.match(/\\[(.*)\\]/);\n\tif(has_brackets && has_brackets[1]){\n\t\tid = has_brackets[1];\n\t}\n\n\t//-- Check if step is a text node or element\n\tnum = parseInt(stepStr);\n\n\tif(isNaN(num)) {\n\t\treturn;\n\t}\n\n\tif(num % 2 === 0) { // Even = is an element\n\t\ttype = \"element\";\n\t\tindex = num / 2 - 1;\n\t} else {\n\t\ttype = \"text\";\n\t\tindex = (num - 1 ) / 2;\n\t}\n\n\treturn {\n\t\t\"type\" : type,\n\t\t'index' : index,\n\t\t'id' : id || null\n\t};\n};\n\nEpubCFI.prototype.parseTerminal = function(termialStr){\n\tvar characterOffset, textLocationAssertion;\n\tvar assertion = termialStr.match(/\\[(.*)\\]/);\n\n\tif(assertion && assertion[1]){\n\t\tcharacterOffset = parseInt(termialStr.split('[')[0]) || null;\n\t\ttextLocationAssertion = assertion[1];\n\t} else {\n\t\tcharacterOffset = parseInt(termialStr) || null;\n\t}\n\n\treturn {\n\t\t'offset': characterOffset,\n\t\t'assertion': textLocationAssertion\n\t};\n\n};\n\nEpubCFI.prototype.getChapterComponent = function(cfiStr) {\n\n\tvar indirection = cfiStr.split(\"!\");\n\n\treturn indirection[0];\n};\n\nEpubCFI.prototype.getPathComponent = function(cfiStr) {\n\n\tvar indirection = cfiStr.split(\"!\");\n\n\tif(indirection[1]) {\n\t\tranges = indirection[1].split(',');\n\t\treturn ranges[0];\n\t}\n\n};\n\nEpubCFI.prototype.getRange = function(cfiStr) {\n\n\tvar ranges = cfiStr.split(\",\");\n\n\tif(ranges.length === 3){\n\t\treturn [\n\t\t\tranges[1],\n\t\t\tranges[2]\n\t\t];\n\t}\n\n\treturn false;\n};\n\nEpubCFI.prototype.getCharecterOffsetComponent = function(cfiStr) {\n\tvar splitStr = cfiStr.split(\":\");\n\treturn splitStr[1] || '';\n};\n\nEpubCFI.prototype.joinSteps = function(steps) {\n\tif(!steps) {\n\t\treturn \"\";\n\t}\n\n\treturn steps.map(function(part){\n\t\tvar segment = '';\n\n\t\tif(part.type === 'element') {\n\t\t\tsegment += (part.index + 1) * 2;\n\t\t}\n\n\t\tif(part.type === 'text') {\n\t\t\tsegment += 1 + (2 * part.index); // TODO: double check that this is odd\n\t\t}\n\n\t\tif(part.id) {\n\t\t\tsegment += \"[\" + part.id + \"]\";\n\t\t}\n\n\t\treturn segment;\n\n\t}).join('/');\n\n};\n\nEpubCFI.prototype.segmentString = function(segment) {\n\tvar segmentString = '/';\n\n\tsegmentString += this.joinSteps(segment.steps);\n\n\tif(segment.terminal && segment.terminal.offset != null){\n\t\tsegmentString += ':' + segment.terminal.offset;\n\t}\n\n\tif(segment.terminal && segment.terminal.assertion != null){\n\t\tsegmentString += '[' + segment.terminal.assertion + ']';\n\t}\n\n\treturn segmentString;\n};\n\nEpubCFI.prototype.toString = function() {\n\tvar cfiString = 'epubcfi(';\n\n\tcfiString += this.segmentString(this.base);\n\n\tcfiString += '!';\n\tcfiString += this.segmentString(this.path);\n\n\t// Add Range, if present\n\tif(this.start) {\n\t\tcfiString += ',';\n\t\tcfiString += this.segmentString(this.start);\n\t}\n\n\tif(this.end) {\n\t\tcfiString += ',';\n\t\tcfiString += this.segmentString(this.end);\n\t}\n\n\tcfiString += \")\";\n\n\treturn cfiString;\n};\n\nEpubCFI.prototype.compare = function(cfiOne, cfiTwo) {\n\tif(typeof cfiOne === 'string') {\n\t\tcfiOne = new EpubCFI(cfiOne);\n\t}\n\tif(typeof cfiTwo === 'string') {\n\t\tcfiTwo = new EpubCFI(cfiTwo);\n\t}\n\t// Compare Spine Positions\n\tif(cfiOne.spinePos > cfiTwo.spinePos) {\n\t\treturn 1;\n\t}\n\tif(cfiOne.spinePos < cfiTwo.spinePos) {\n\t\treturn -1;\n\t}\n\n\n\t// Compare Each Step in the First item\n\tfor (var i = 0; i < cfiOne.path.steps.length; i++) {\n\t\tif(!cfiTwo.path.steps[i]) {\n\t\t\treturn 1;\n\t\t}\n\t\tif(cfiOne.path.steps[i].index > cfiTwo.path.steps[i].index) {\n\t\t\treturn 1;\n\t\t}\n\t\tif(cfiOne.path.steps[i].index < cfiTwo.path.steps[i].index) {\n\t\t\treturn -1;\n\t\t}\n\t\t// Otherwise continue checking\n\t}\n\n\t// All steps in First equal to Second and First is Less Specific\n\tif(cfiOne.path.steps.length < cfiTwo.path.steps.length) {\n\t\treturn 1;\n\t}\n\n\t// Compare the charecter offset of the text node\n\tif(cfiOne.path.terminal.offset > cfiTwo.path.terminal.offset) {\n\t\treturn 1;\n\t}\n\tif(cfiOne.path.terminal.offset < cfiTwo.path.terminal.offset) {\n\t\treturn -1;\n\t}\n\n\t// TODO: compare ranges\n\n\t// CFI's are equal\n\treturn 0;\n};\n\nEpubCFI.prototype.step = function(node) {\n\tvar nodeType = (node.nodeType === Node.TEXT_NODE) ? 'text' : 'element';\n\n\treturn {\n\t\t'id' : node.id,\n\t\t'tagName' : node.tagName,\n\t\t'type' : nodeType,\n\t\t'index' : this.position(node)\n\t};\n};\n\nEpubCFI.prototype.filteredStep = function(node, ignoreClass) {\n\tvar filteredNode = this.filter(node, ignoreClass);\n\tvar nodeType;\n\n\t// Node filtered, so ignore\n\tif (!filteredNode) {\n\t\treturn;\n\t}\n\n\t// Otherwise add the filter node in\n\tnodeType = (filteredNode.nodeType === Node.TEXT_NODE) ? 'text' : 'element';\n\n\treturn {\n\t\t'id' : filteredNode.id,\n\t\t'tagName' : filteredNode.tagName,\n\t\t'type' : nodeType,\n\t\t'index' : this.filteredPosition(filteredNode, ignoreClass)\n\t};\n};\n\nEpubCFI.prototype.pathTo = function(node, offset, ignoreClass) {\n\tvar segment = {\n\t\tsteps: [],\n\t\tterminal: {\n\t\t\toffset: null,\n\t\t\tassertion: null\n\t\t}\n\t};\n\tvar currentNode = node;\n\tvar step;\n\n\twhile(currentNode && currentNode.parentNode &&\n\t\t\t\tcurrentNode.parentNode.nodeType != Node.DOCUMENT_NODE) {\n\n\t\tif (ignoreClass) {\n\t\t\tstep = this.filteredStep(currentNode, ignoreClass);\n\t\t} else {\n\t\t\tstep = this.step(currentNode);\n\t\t}\n\n\t\tif (step) {\n\t\t\tsegment.steps.unshift(step);\n\t\t}\n\n\t\tcurrentNode = currentNode.parentNode;\n\n\t}\n\n\tif (offset != null && offset >= 0) {\n\n\t\tsegment.terminal.offset = offset;\n\n\t\t// Make sure we are getting to a textNode if there is an offset\n\t\tif(segment.steps[segment.steps.length-1].type != \"text\") {\n\t\t\tsegment.steps.push({\n\t\t\t\t'type' : \"text\",\n\t\t\t\t'index' : 0\n\t\t\t});\n\t\t}\n\n\t}\n\n\n\treturn segment;\n}\n\nEpubCFI.prototype.equalStep = function(stepA, stepB) {\n\tif (!stepA || !stepB) {\n\t\treturn false;\n\t}\n\n\tif(stepA.index === stepB.index &&\n\t\t stepA.id === stepB.id &&\n\t\t stepA.type === stepB.type) {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\nEpubCFI.prototype.fromRange = function(range, base, ignoreClass) {\n\tvar cfi = {\n\t\t\trange: false,\n\t\t\tbase: {},\n\t\t\tpath: {},\n\t\t\tstart: null,\n\t\t\tend: null\n\t\t};\n\n\tvar start = range.startContainer;\n\tvar end = range.endContainer;\n\n\tvar startOffset = range.startOffset;\n\tvar endOffset = range.endOffset;\n\n\tvar needsIgnoring = false;\n\n\tif (ignoreClass) {\n\t\t// Tell pathTo if / what to ignore\n\t\tneedsIgnoring = (start.ownerDocument.querySelector('.' + ignoreClass) != null);\n\t}\n\n\n\tif (typeof base === 'string') {\n\t\tcfi.base = this.parseComponent(base);\n\t\tcfi.spinePos = cfi.base.steps[1].index;\n\t} else if (typeof base === 'object') {\n\t\tcfi.base = base;\n\t}\n\n\tif (range.collapsed) {\n\t\tif (needsIgnoring) {\n\t\t\tstartOffset = this.patchOffset(start, startOffset, ignoreClass);\n\t\t}\n\t\tcfi.path = this.pathTo(start, startOffset, ignoreClass);\n\t} else {\n\t\tcfi.range = true;\n\n\t\tif (needsIgnoring) {\n\t\t\tstartOffset = this.patchOffset(start, startOffset, ignoreClass);\n\t\t}\n\n\t\tcfi.start = this.pathTo(start, startOffset, ignoreClass);\n\n\t\tif (needsIgnoring) {\n\t\t\tendOffset = this.patchOffset(end, endOffset, ignoreClass);\n\t\t}\n\n\t\tcfi.end = this.pathTo(end, endOffset, ignoreClass);\n\n\t\t// Create a new empty path\n\t\tcfi.path = {\n\t\t\tsteps: [],\n\t\t\tterminal: null\n\t\t};\n\n\t\t// Push steps that are shared between start and end to the common path\n\t\tvar len = cfi.start.steps.length;\n\t\tvar i;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (this.equalStep(cfi.start.steps[i], cfi.end.steps[i])) {\n\t\t\t\tif(i == len-1) {\n\t\t\t\t\t// Last step is equal, check terminals\n\t\t\t\t\tif(cfi.start.terminal === cfi.end.terminal) {\n\t\t\t\t\t\t// CFI's are equal\n\t\t\t\t\t\tcfi.path.steps.push(cfi.start.steps[i]);\n\t\t\t\t\t\t// Not a range\n\t\t\t\t\t\tcfi.range = false;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tcfi.path.steps.push(cfi.start.steps[i]);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t};\n\n\t\tcfi.start.steps = cfi.start.steps.slice(cfi.path.steps.length);\n\t\tcfi.end.steps = cfi.end.steps.slice(cfi.path.steps.length);\n\n\t\t// TODO: Add Sanity check to make sure that the end if greater than the start\n\t}\n\n\treturn cfi;\n}\n\nEpubCFI.prototype.fromNode = function(anchor, base, ignoreClass) {\n\tvar cfi = {\n\t\t\trange: false,\n\t\t\tbase: {},\n\t\t\tpath: {},\n\t\t\tstart: null,\n\t\t\tend: null\n\t\t};\n\n\tvar needsIgnoring = false;\n\n\tif (ignoreClass) {\n\t\t// Tell pathTo if / what to ignore\n\t\tneedsIgnoring = (anchor.ownerDocument.querySelector('.' + ignoreClass) != null);\n\t}\n\n\tif (typeof base === 'string') {\n\t\tcfi.base = this.parseComponent(base);\n\t\tcfi.spinePos = cfi.base.steps[1].index;\n\t} else if (typeof base === 'object') {\n\t\tcfi.base = base;\n\t}\n\n\tcfi.path = this.pathTo(anchor, null, ignoreClass);\n\n\treturn cfi;\n};\n\n\nEpubCFI.prototype.filter = function(anchor, ignoreClass) {\n\tvar needsIgnoring;\n\tvar sibling; // to join with\n\tvar parent, prevSibling, nextSibling;\n\tvar isText = false;\n\n\tif (anchor.nodeType === Node.TEXT_NODE) {\n\t\tisText = true;\n\t\tparent = anchor.parentNode;\n\t\tneedsIgnoring = anchor.parentNode.classList.contains(ignoreClass);\n\t} else {\n\t\tisText = false;\n\t\tneedsIgnoring = anchor.classList.contains(ignoreClass);\n\t}\n\n\tif (needsIgnoring && isText) {\n\t\tpreviousSibling = parent.previousSibling;\n\t\tnextSibling = parent.nextSibling;\n\n\t\t// If the sibling is a text node, join the nodes\n\t\tif (previousSibling && previousSibling.nodeType === Node.TEXT_NODE) {\n\t\t\tsibling = previousSibling;\n\t\t} else if (nextSibling && nextSibling.nodeType === Node.TEXT_NODE) {\n\t\t\tsibling = nextSibling;\n\t\t}\n\n\t\tif (sibling) {\n\t\t\treturn sibling;\n\t\t} else {\n\t\t\t// Parent will be ignored on next step\n\t\t\treturn anchor;\n\t\t}\n\n\t} else if (needsIgnoring && !isText) {\n\t\t// Otherwise just skip the element node\n\t\treturn false;\n\t} else {\n\t\t// No need to filter\n\t\treturn anchor;\n\t}\n\n};\n\nEpubCFI.prototype.patchOffset = function(anchor, offset, ignoreClass) {\n\tvar needsIgnoring;\n\tvar sibling;\n\n\tif (anchor.nodeType != Node.TEXT_NODE) {\n\t\tconsole.error(\"Anchor must be a text node\");\n\t\treturn;\n\t}\n\n\tvar curr = anchor;\n\tvar totalOffset = offset;\n\n\t// If the parent is a ignored node, get offset from it's start\n\tif (anchor.parentNode.classList.contains(ignoreClass)) {\n\t\tcurr = anchor.parentNode;\n\t}\n\n\twhile (curr.previousSibling) {\n\t\tif(curr.previousSibling.nodeType === Node.ELEMENT_NODE) {\n\t\t\t// Originally a text node, so join\n\t\t\tif(curr.previousSibling.classList.contains(ignoreClass)){\n\t\t\t\ttotalOffset += curr.previousSibling.textContent.length;\n\t\t\t} else {\n\t\t\t\tbreak; // Normal node, dont join\n\t\t\t}\n\t\t} else {\n\t\t\t// If the previous sibling is a text node, join the nodes\n\t\t\ttotalOffset += curr.previousSibling.textContent.length;\n\t\t}\n\n\t\tcurr = curr.previousSibling;\n\t}\n\n\treturn totalOffset;\n\n};\n\nEpubCFI.prototype.normalizedMap = function(children, nodeType, ignoreClass) {\n\tvar output = {};\n\tvar prevIndex = -1;\n\tvar i, len = children.length;\n\tvar currNodeType;\n\tvar prevNodeType;\n\n\tfor (i = 0; i < len; i++) {\n\n\t\tcurrNodeType = children[i].nodeType;\n\n\t\t// Check if needs ignoring\n\t\tif (currNodeType === Node.ELEMENT_NODE &&\n\t\t\t\tchildren[i].classList.contains(ignoreClass)) {\n\t\t\tcurrNodeType = Node.TEXT_NODE;\n\t\t}\n\n\t\tif (i > 0 &&\n\t\t\t\tcurrNodeType === Node.TEXT_NODE &&\n\t\t\t\tprevNodeType === Node.TEXT_NODE) {\n\t\t\t// join text nodes\n\t\t\toutput[i] = prevIndex;\n\t\t} else if (nodeType === currNodeType){\n\t\t\tprevIndex = prevIndex + 1;\n\t\t\toutput[i] = prevIndex;\n\t\t}\n\n\t\tprevNodeType = currNodeType;\n\n\t}\n\n\treturn output;\n};\n\nEpubCFI.prototype.position = function(anchor) {\n\tvar children, index, map;\n\n\tif (anchor.nodeType === Node.ELEMENT_NODE) {\n\t\tchildren = anchor.parentNode.children;\n\t\tindex = Array.prototype.indexOf.call(children, anchor);\n\t} else {\n\t\tchildren = this.textNodes(anchor.parentNode);\n\t\tindex = children.indexOf(anchor);\n\t}\n\n\treturn index;\n};\n\nEpubCFI.prototype.filteredPosition = function(anchor, ignoreClass) {\n\tvar children, index, map;\n\n\tif (anchor.nodeType === Node.ELEMENT_NODE) {\n\t\tchildren = anchor.parentNode.children;\n\t\tmap = this.normalizedMap(children, Node.ELEMENT_NODE, ignoreClass);\n\t} else {\n\t\tchildren = anchor.parentNode.childNodes;\n\t\t// Inside an ignored node\n\t\tif(anchor.parentNode.classList.contains(ignoreClass)) {\n\t\t\tanchor = anchor.parentNode;\n\t\t\tchildren = anchor.parentNode.childNodes;\n\t\t}\n\t\tmap = this.normalizedMap(children, Node.TEXT_NODE, ignoreClass);\n\t}\n\n\n\tindex = Array.prototype.indexOf.call(children, anchor);\n\n\treturn map[index];\n};\n\nEpubCFI.prototype.stepsToXpath = function(steps) {\n\tvar xpath = [\".\", \"*\"];\n\n\tsteps.forEach(function(step){\n\t\tvar position = step.index + 1;\n\n\t\tif(step.id){\n\t\t\txpath.push(\"*[position()=\" + position + \" and @id='\" + step.id + \"']\");\n\t\t} else if(step.type === \"text\") {\n\t\t\txpath.push(\"text()[\" + position + \"]\");\n\t\t} else {\n\t\t\txpath.push(\"*[\" + position + \"]\");\n\t\t}\n\t});\n\n\treturn xpath.join(\"/\");\n};\n\n\n/*\n\nTo get the last step if needed:\n\n// Get the terminal step\nlastStep = steps[steps.length-1];\n// Get the query string\nquery = this.stepsToQuery(steps);\n// Find the containing element\nstartContainerParent = doc.querySelector(query);\n// Find the text node within that element\nif(startContainerParent && lastStep.type == \"text\") {\n\tcontainer = startContainerParent.childNodes[lastStep.index];\n}\n*/\nEpubCFI.prototype.stepsToQuerySelector = function(steps) {\n\tvar query = [\"html\"];\n\n\tsteps.forEach(function(step){\n\t\tvar position = step.index + 1;\n\n\t\tif(step.id){\n\t\t\tquery.push(\"#\" + step.id);\n\t\t} else if(step.type === \"text\") {\n\t\t\t// unsupported in querySelector\n\t\t\t// query.push(\"text()[\" + position + \"]\");\n\t\t} else {\n\t\t\tquery.push(\"*:nth-child(\" + position + \")\");\n\t\t}\n\t});\n\n\treturn query.join(\">\");\n\n};\n\nEpubCFI.prototype.textNodes = function(container, ignoreClass) {\n\treturn Array.prototype.slice.call(container.childNodes).\n\t\tfilter(function (node) {\n\t\t\tif (node.nodeType === Node.TEXT_NODE) {\n\t\t\t\treturn true;\n\t\t\t} else if (ignoreClass && node.classList.contains(ignoreClass)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t});\n};\n\nEpubCFI.prototype.walkToNode = function(steps, _doc, ignoreClass) {\n\tvar doc = _doc || document;\n\tvar container = doc.documentElement;\n\tvar step;\n\tvar len = steps.length;\n\tvar i;\n\n\tfor (i = 0; i < len; i++) {\n\t\tstep = steps[i];\n\n\t\tif(step.type === \"element\") {\n\t\t\tcontainer = container.children[step.index];\n\t\t} else if(step.type === \"text\"){\n\t\t\tcontainer = this.textNodes(container, ignoreClass)[step.index];\n\t\t}\n\n\t};\n\n\treturn container;\n};\n\nEpubCFI.prototype.findNode = function(steps, _doc, ignoreClass) {\n\tvar doc = _doc || document;\n\tvar container;\n\tvar xpath;\n\n\tif(!ignoreClass && typeof doc.evaluate != 'undefined') {\n\t\txpath = this.stepsToXpath(steps);\n\t\tcontainer = doc.evaluate(xpath, doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;\n\t} else if(ignoreClass) {\n\t\tcontainer = this.walkToNode(steps, doc, ignoreClass);\n\t} else {\n\t\tcontainer = this.walkToNode(steps, doc);\n\t}\n\n\treturn container;\n};\n\nEpubCFI.prototype.fixMiss = function(steps, offset, _doc, ignoreClass) {\n\tvar container = this.findNode(steps.slice(0,-1), _doc, ignoreClass);\n\tvar children = container.childNodes;\n\tvar map = this.normalizedMap(children, Node.TEXT_NODE, ignoreClass);\n\tvar i;\n\tvar child;\n\tvar len;\n\tvar childIndex;\n\tvar lastStepIndex = steps[steps.length-1].index;\n\n\tfor (var childIndex in map) {\n\t\tif (!map.hasOwnProperty(childIndex)) return;\n\n\t\tif(map[childIndex] === lastStepIndex) {\n\t\t\tchild = children[childIndex];\n\t\t\tlen = child.textContent.length;\n\t\t\tif(offset > len) {\n\t\t\t\toffset = offset - len;\n\t\t\t} else {\n\t\t\t\tif (child.nodeType === Node.ELEMENT_NODE) {\n\t\t\t\t\tcontainer = child.childNodes[0];\n\t\t\t\t} else {\n\t\t\t\t\tcontainer = child;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tcontainer: container,\n\t\toffset: offset\n\t};\n\n};\n\nEpubCFI.prototype.toRange = function(_doc, ignoreClass) {\n\tvar doc = _doc || document;\n\tvar range = doc.createRange();\n\tvar start, end, startContainer, endContainer;\n\tvar cfi = this;\n\tvar startSteps, endSteps;\n\tvar needsIgnoring = ignoreClass ? (doc.querySelector('.' + ignoreClass) != null) : false;\n\tvar missed;\n\n\tif (cfi.range) {\n\t\tstart = cfi.start;\n\t\tstartSteps = cfi.path.steps.concat(start.steps);\n\t\tstartContainer = this.findNode(startSteps, doc, needsIgnoring ? ignoreClass : null);\n\t\tend = cfi.end;\n\t\tendSteps = cfi.path.steps.concat(end.steps);\n\t\tendContainer = this.findNode(endSteps, doc, needsIgnoring ? ignoreClass : null);\n\t} else {\n\t\tstart = cfi.path;\n\t\tstartSteps = cfi.path.steps;\n\t\tstartContainer = this.findNode(cfi.path.steps, doc, needsIgnoring ? ignoreClass : null);\n\t}\n\n\tif(startContainer) {\n\t\ttry {\n\n\t\t\tif(start.terminal.offset != null) {\n\t\t\t\trange.setStart(startContainer, start.terminal.offset);\n\t\t\t} else {\n\t\t\t\trange.setStart(startContainer, 0);\n\t\t\t}\n\n\t\t} catch (e) {\n\t\t\tmissed = this.fixMiss(startSteps, start.terminal.offset, doc, needsIgnoring ? ignoreClass : null);\n\t\t\trange.setStart(missed.container, missed.offset);\n\t\t}\n\t} else {\n\t\t// No start found\n\t\treturn null;\n\t}\n\n\tif (endContainer) {\n\t\ttry {\n\n\t\t\tif(end.terminal.offset != null) {\n\t\t\t\trange.setEnd(endContainer, end.terminal.offset);\n\t\t\t} else {\n\t\t\t\trange.setEnd(endContainer, 0);\n\t\t\t}\n\n\t\t} catch (e) {\n\t\t\tmissed = this.fixMiss(endSteps, cfi.end.terminal.offset, doc, needsIgnoring ? ignoreClass : null);\n\t\t\trange.setEnd(missed.container, missed.offset);\n\t\t}\n\t}\n\n\n\t// doc.defaultView.getSelection().addRange(range);\n\treturn range;\n};\n\n// is a cfi string, should be wrapped with \"epubcfi()\"\nEpubCFI.prototype.isCfiString = function(str) {\n\tif(typeof str === 'string' &&\n\t\t\tstr.indexOf(\"epubcfi(\") === 0 &&\n\t\t\tstr[str.length-1] === \")\") {\n\t\treturn true;\n\t}\n\n\treturn false;\n};\n\nEpubCFI.prototype.generateChapterComponent = function(_spineNodeIndex, _pos, id) {\n\tvar pos = parseInt(_pos),\n\t\tspineNodeIndex = _spineNodeIndex + 1,\n\t\tcfi = '/'+spineNodeIndex+'/';\n\n\tcfi += (pos + 1) * 2;\n\n\tif(id) {\n\t\tcfi += \"[\" + id + \"]\";\n\t}\n\n\treturn cfi;\n};\n\nmodule.exports = EpubCFI;\n","var RSVP = require('rsvp');\n\n//-- Hooks allow for injecting functions that must all complete in order before finishing\n// They will execute in parallel but all must finish before continuing\n// Functions may return a promise if they are asycn.\n\n// this.content = new EPUBJS.Hook();\n// this.content.register(function(){});\n// this.content.trigger(args).then(function(){});\n\nfunction Hook(context){\n\tthis.context = context || this;\n\tthis.hooks = [];\n};\n\n// Adds a function to be run before a hook completes\nHook.prototype.register = function(){\n\tfor(var i = 0; i < arguments.length; ++i) {\n\t\tif (typeof arguments[i] === \"function\") {\n\t\t\tthis.hooks.push(arguments[i]);\n\t\t} else {\n\t\t\t// unpack array\n\t\t\tfor(var j = 0; j < arguments[i].length; ++j) {\n\t\t\t\tthis.hooks.push(arguments[i][j]);\n\t\t\t}\n\t\t}\n\t}\n};\n\n// Triggers a hook to run all functions\nHook.prototype.trigger = function(){\n\tvar args = arguments;\n\tvar context = this.context;\n\tvar promises = [];\n\n\tthis.hooks.forEach(function(task, i) {\n\t\tvar executing = task.apply(context, args);\n\n\t\tif(executing && typeof executing[\"then\"] === \"function\") {\n\t\t\t// Task is a function that returns a promise\n\t\t\tpromises.push(executing);\n\t\t}\n\t\t// Otherwise Task resolves immediately, continue\n\t});\n\n\n\treturn RSVP.all(promises);\n};\n\n// Adds a function to be run before a hook completes\nHook.prototype.list = function(){\n\treturn this.hooks;\n};\n\nHook.prototype.clear = function(){\n\treturn this.hooks = [];\n};\n\nmodule.exports = Hook;\n","var core = require('./core');\nvar RSVP = require('rsvp');\n\nfunction Layout(settings){\n\tthis.name = settings.layout || \"reflowable\";\n\tthis._spread = (settings.spread === \"none\") ? false : true;\n\tthis._minSpreadWidth = settings.spread || 800;\n\tthis._evenSpreads = settings.evenSpreads || false;\n\n\tif (settings.flow === \"scrolled-continuous\" ||\n\t\t\tsettings.flow === \"scrolled-doc\") {\n\t\tthis._flow = \"scrolled\";\n\t} else {\n\t\tthis._flow = \"paginated\";\n\t}\n\n\n\tthis.width = 0;\n\tthis.height = 0;\n\tthis.spreadWidth = 0;\n\tthis.delta = 0;\n\n\tthis.columnWidth = 0;\n\tthis.gap = 0;\n\tthis.divisor = 1;\n};\n\n// paginated | scrolled\nLayout.prototype.flow = function(flow) {\n\tthis._flow = (flow === \"paginated\") ? \"paginated\" : \"scrolled\";\n}\n\n// true | false\nLayout.prototype.spread = function(spread, min) {\n\n\tthis._spread = (spread === \"none\") ? false : true;\n\n\tif (min >= 0) {\n\t\tthis._minSpreadWidth = min;\n\t}\n}\n\nLayout.prototype.calculate = function(_width, _height, _gap){\n\n\tvar divisor = 1;\n\tvar gap = _gap || 0;\n\n\t//-- Check the width and create even width columns\n\tvar fullWidth = Math.floor(_width);\n\tvar width = _width;\n\n\tvar section = Math.floor(width / 8);\n\n\tvar colWidth;\n\tvar spreadWidth;\n\tvar delta;\n\n\tif (this._spread && width >= this._minSpreadWidth) {\n\t\tdivisor = 2;\n\t} else {\n\t\tdivisor = 1;\n\t}\n\n\tif (this.name === \"reflowable\" && this._flow === \"paginated\" && !(_gap >= 0)) {\n\t\tgap = ((section % 2 === 0) ? section : section - 1);\n\t}\n\n\tif (this.name === \"pre-paginated\" ) {\n\t\tgap = 0;\n\t}\n\n\t//-- Double Page\n\tif(divisor > 1) {\n\t\tcolWidth = Math.floor((width - gap) / divisor);\n\t} else {\n\t\tcolWidth = width;\n\t}\n\n\tif (this.name === \"pre-paginated\" && divisor > 1) {\n\t\twidth = colWidth;\n\t}\n\n\tspreadWidth = colWidth * divisor;\n\n\tdelta = (colWidth + gap) * divisor;\n\n\tthis.width = width;\n\tthis.height = _height;\n\tthis.spreadWidth = spreadWidth;\n\tthis.delta = delta;\n\n\tthis.columnWidth = colWidth;\n\tthis.gap = gap;\n\tthis.divisor = divisor;\n};\n\nLayout.prototype.format = function(contents){\n\tvar formating;\n\n\tif (this.name === \"pre-paginated\") {\n\t\tformating = contents.fit(this.columnWidth, this.height);\n\t} else if (this._flow === \"paginated\") {\n\t\tformating = contents.columns(this.width, this.height, this.columnWidth, this.gap);\n\t} else { // scrolled\n\t\tformating = contents.size(this.width, null);\n\t}\n\n\treturn formating; // might be a promise in some View Managers\n};\n\nLayout.prototype.count = function(totalWidth) {\n\t// var totalWidth = contents.scrollWidth();\n\tvar spreads = Math.ceil( totalWidth / this.spreadWidth);\n\n\treturn {\n\t\tspreads : spreads,\n\t\tpages : spreads * this.divisor\n\t};\n};\n\nmodule.exports = Layout;\n","var core = require('./core');\nvar Queue = require('./queue');\nvar EpubCFI = require('./epubcfi');\nvar RSVP = require('rsvp');\n\nfunction Locations(spine, request) {\n\tthis.spine = spine;\n\tthis.request = request;\n\n\tthis.q = new Queue(this);\n\tthis.epubcfi = new EpubCFI();\n\n\tthis._locations = [];\n\tthis.total = 0;\n\n\tthis.break = 150;\n\n\tthis._current = 0;\n\n};\n\n// Load all of sections in the book\nLocations.prototype.generate = function(chars) {\n\n\tif (chars) {\n\t\tthis.break = chars;\n\t}\n\n\tthis.q.pause();\n\n\tthis.spine.each(function(section) {\n\n\t\tthis.q.enqueue(this.process, section);\n\n\t}.bind(this));\n\n\treturn this.q.run().then(function() {\n\t\tthis.total = this._locations.length-1;\n\n\t\tif (this._currentCfi) {\n\t\t\tthis.currentLocation = this._currentCfi;\n\t\t}\n\n\t\treturn this._locations;\n\t\t// console.log(this.precentage(this.book.rendition.location.start), this.precentage(this.book.rendition.location.end));\n\t}.bind(this));\n\n};\n\nLocations.prototype.process = function(section) {\n\n\treturn section.load(this.request)\n\t\t.then(function(contents) {\n\n\t\t\tvar range;\n\t\t\tvar doc = contents.ownerDocument;\n\t\t\tvar counter = 0;\n\n\t\t\tthis.sprint(contents, function(node) {\n\t\t\t\tvar len = node.length;\n\t\t\t\tvar dist;\n\t\t\t\tvar pos = 0;\n\n\t\t\t\t// Start range\n\t\t\t\tif (counter == 0) {\n\t\t\t\t\trange = doc.createRange();\n\t\t\t\t\trange.setStart(node, 0);\n\t\t\t\t}\n\n\t\t\t\tdist = this.break - counter;\n\n\t\t\t\t// Node is smaller than a break\n\t\t\t\tif(dist > len){\n\t\t\t\t\tcounter += len;\n\t\t\t\t\tpos = len;\n\t\t\t\t}\n\n\t\t\t\twhile (pos < len) {\n\t\t\t\t\tcounter = this.break;\n\t\t\t\t\tpos += this.break;\n\n\t\t\t\t\t// Gone over\n\t\t\t\t\tif(pos >= len){\n\t\t\t\t\t\t// Continue counter for next node\n\t\t\t\t\t\tcounter = len - (pos - this.break);\n\n\t\t\t\t\t// At End\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// End the previous range\n\t\t\t\t\t\trange.setEnd(node, pos);\n\t\t\t\t\t\tcfi = section.cfiFromRange(range);\n\t\t\t\t\t\tthis._locations.push(cfi);\n\t\t\t\t\t\tcounter = 0;\n\n\t\t\t\t\t\t// Start new range\n\t\t\t\t\t\tpos += 1;\n\t\t\t\t\t\trange = doc.createRange();\n\t\t\t\t\t\trange.setStart(node, pos);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\n\t\t\t}.bind(this));\n\n\t\t\t// Close remaining\n\t\t\tif (range) {\n\t\t\t\trange.setEnd(prev, prev.length);\n\t\t\t\tcfi = section.cfiFromRange(range);\n\t\t\t\tthis._locations.push(cfi)\n\t\t\t\tcounter = 0;\n\t\t\t}\n\n\t\t}.bind(this));\n\n};\n\nLocations.prototype.sprint = function(root, func) {\n\tvar treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null, false);\n\n\twhile ((node = treeWalker.nextNode())) {\n\t\tfunc(node);\n\t}\n\n};\n\nLocations.prototype.locationFromCfi = function(cfi){\n\t// Check if the location has not been set yet\n\tif(this._locations.length === 0) {\n\t\treturn -1;\n\t}\n\n\treturn core.locationOf(cfi, this._locations, this.epubcfi.compare);\n};\n\nLocations.prototype.precentageFromCfi = function(cfi) {\n\t// Find closest cfi\n\tvar loc = this.locationFromCfi(cfi);\n\t// Get percentage in total\n\treturn this.precentageFromLocation(loc);\n};\n\nLocations.prototype.percentageFromLocation = function(loc) {\n\tif (!loc || !this.total) {\n\t\treturn 0;\n\t}\n\treturn (loc / this.total);\n};\n\nLocations.prototype.cfiFromLocation = function(loc){\n\tvar cfi = -1;\n\t// check that pg is an int\n\tif(typeof loc != \"number\"){\n\t\tloc = parseInt(pg);\n\t}\n\n\tif(loc >= 0 && loc < this._locations.length) {\n\t\tcfi = this._locations[loc];\n\t}\n\n\treturn cfi;\n};\n\nLocations.prototype.cfiFromPercentage = function(value){\n\tvar percentage = (value > 1) ? value / 100 : value; // Normalize value to 0-1\n\tvar loc = Math.ceil(this.total * percentage);\n\n\treturn this.cfiFromLocation(loc);\n};\n\nLocations.prototype.load = function(locations){\n\tthis._locations = JSON.parse(locations);\n\tthis.total = this._locations.length-1;\n\treturn this._locations;\n};\n\nLocations.prototype.save = function(json){\n\treturn JSON.stringify(this._locations);\n};\n\nLocations.prototype.getCurrent = function(json){\n\treturn this._current;\n};\n\nLocations.prototype.setCurrent = function(curr){\n\tvar loc;\n\n\tif(typeof curr == \"string\"){\n\t\tthis._currentCfi = curr;\n\t} else if (typeof curr == \"number\") {\n\t\tthis._current = curr;\n\t} else {\n\t\treturn;\n\t}\n\n\tif(this._locations.length === 0) {\n\t\treturn;\n\t}\n\n\tif(typeof curr == \"string\"){\n\t\tloc = this.locationFromCfi(curr);\n\t\tthis._current = loc;\n\t} else {\n\t\tloc = curr;\n\t}\n\n\tthis.trigger(\"changed\", {\n\t\tpercentage: this.precentageFromLocation(loc)\n\t});\n};\n\nObject.defineProperty(Locations.prototype, 'currentLocation', {\n\tget: function () {\n\t\treturn this._current;\n\t},\n\tset: function (curr) {\n\t\tthis.setCurrent(curr);\n\t}\n});\n\nRSVP.EventTarget.mixin(Locations.prototype);\n\nmodule.exports = Locations;\n","var RSVP = require('rsvp');\nvar core = require('../core');\nvar SingleViewManager = require('./single');\n\nfunction ContinuousViewManager(options) {\n\n\tSingleViewManager.apply(this, arguments); // call super constructor.\n\n\tthis.name = \"continuous\";\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\tinfinite: true,\n\t\toverflow: \"auto\",\n\t\taxis: \"vertical\",\n\t\toffset: 500,\n\t\toffsetDelta: 250,\n\t\twidth: undefined,\n\t\theight: undefined\n\t});\n\n\tcore.extend(this.settings, options.settings || {});\n\n\t// Gap can be 0, byt defaults doesn't handle that\n\tif (options.settings.gap != \"undefined\" && options.settings.gap === 0) {\n\t\tthis.settings.gap = options.settings.gap;\n\t}\n\n\t// this.viewSettings.axis = this.settings.axis;\n\tthis.viewSettings = {\n\t\tignoreClass: this.settings.ignoreClass,\n\t\taxis: this.settings.axis,\n\t\tlayout: this.layout,\n\t\twidth: 0,\n\t\theight: 0\n\t};\n\n\tthis.scrollTop = 0;\n\tthis.scrollLeft = 0;\n};\n\n// subclass extends superclass\nContinuousViewManager.prototype = Object.create(SingleViewManager.prototype);\nContinuousViewManager.prototype.constructor = ContinuousViewManager;\n\nContinuousViewManager.prototype.display = function(section, target){\n\treturn SingleViewManager.prototype.display.call(this, section, target)\n\t\t.then(function () {\n\t\t\treturn this.fill();\n\t\t}.bind(this));\n};\n\nContinuousViewManager.prototype.fill = function(_full){\n\tvar full = _full || new RSVP.defer();\n\n\tthis.check().then(function(result) {\n\t\tif (result) {\n\t\t\tthis.fill(full);\n\t\t} else {\n\t\t\tfull.resolve();\n\t\t}\n\t}.bind(this));\n\n\treturn full.promise;\n}\n\nContinuousViewManager.prototype.moveTo = function(offset){\n\t// var bounds = this.stage.bounds();\n\t// var dist = Math.floor(offset.top / bounds.height) * bounds.height;\n\tvar distX = 0,\n\t\t\tdistY = 0;\n\n\tvar offsetX = 0,\n\t\t\toffsetY = 0;\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tdistY = offset.top;\n\t\toffsetY = offset.top+this.settings.offset;\n\t} else {\n\t\tdistX = Math.floor(offset.left / this.layout.delta) * this.layout.delta;\n\t\toffsetX = distX+this.settings.offset;\n\t}\n\n\treturn this.check(offsetX, offsetY)\n\t\t.then(function(){\n\t\t\tthis.scrollBy(distX, distY);\n\t\t}.bind(this));\n};\n\n/*\nContinuousViewManager.prototype.afterDisplayed = function(currView){\n\tvar next = currView.section.next();\n\tvar prev = currView.section.prev();\n\tvar index = this.views.indexOf(currView);\n\tvar prevView, nextView;\n\n\tif(index + 1 === this.views.length && next) {\n\t\tnextView = this.createView(next);\n\t\tthis.q.enqueue(this.append.bind(this), nextView);\n\t}\n\n\tif(index === 0 && prev) {\n\t\tprevView = this.createView(prev, this.viewSettings);\n\t\tthis.q.enqueue(this.prepend.bind(this), prevView);\n\t}\n\n\t// this.removeShownListeners(currView);\n\t// currView.onShown = this.afterDisplayed.bind(this);\n\tthis.trigger(\"added\", currView.section);\n\n};\n*/\n\nContinuousViewManager.prototype.resize = function(width, height){\n\n\t// Clear the queue\n\tthis.q.clear();\n\n\tthis._stageSize = this.stage.size(width, height);\n\tthis._bounds = this.bounds();\n\n\t// Update for new views\n\tthis.viewSettings.width = this._stageSize.width;\n\tthis.viewSettings.height = this._stageSize.height;\n\n\t// Update for existing views\n\tthis.views.each(function(view) {\n\t\tview.size(this._stageSize.width, this._stageSize.height);\n\t}.bind(this));\n\n\tthis.updateLayout();\n\n\t// if(this.location) {\n\t// this.rendition.display(this.location.start);\n\t// }\n\n\tthis.trigger(\"resized\", {\n\t\twidth: this.stage.width,\n\t\theight: this.stage.height\n\t});\n\n};\n\nContinuousViewManager.prototype.onResized = function(e) {\n\n\t// this.views.clear();\n\n\tclearTimeout(this.resizeTimeout);\n\tthis.resizeTimeout = setTimeout(function(){\n\t\tthis.resize();\n\t}.bind(this), 150);\n};\n\nContinuousViewManager.prototype.afterResized = function(view){\n\tthis.trigger(\"resize\", view.section);\n};\n\n// Remove Previous Listeners if present\nContinuousViewManager.prototype.removeShownListeners = function(view){\n\n\t// view.off(\"shown\", this.afterDisplayed);\n\t// view.off(\"shown\", this.afterDisplayedAbove);\n\tview.onDisplayed = function(){};\n\n};\n\n\n// ContinuousViewManager.prototype.append = function(section){\n// \treturn this.q.enqueue(function() {\n//\n// \t\tthis._append(section);\n//\n//\n// \t}.bind(this));\n// };\n//\n// ContinuousViewManager.prototype.prepend = function(section){\n// \treturn this.q.enqueue(function() {\n//\n// \t\tthis._prepend(section);\n//\n// \t}.bind(this));\n//\n// };\n\nContinuousViewManager.prototype.append = function(section){\n\tvar view = this.createView(section);\n\tthis.views.append(view);\n\treturn view;\n};\n\nContinuousViewManager.prototype.prepend = function(section){\n\tvar view = this.createView(section);\n\n\tview.on(\"resized\", this.counter.bind(this));\n\n\tthis.views.prepend(view);\n\treturn view;\n};\n\nContinuousViewManager.prototype.counter = function(bounds){\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tthis.scrollBy(0, bounds.heightDelta, true);\n\t} else {\n\t\tthis.scrollBy(bounds.widthDelta, 0, true);\n\t}\n\n};\n\nContinuousViewManager.prototype.update = function(_offset){\n\tvar container = this.bounds();\n\tvar views = this.views.all();\n\tvar viewsLength = views.length;\n\tvar visible = [];\n\tvar offset = typeof _offset != \"undefined\" ? _offset : (this.settings.offset || 0);\n\tvar isVisible;\n\tvar view;\n\n\tvar updating = new RSVP.defer();\n\tvar promises = [];\n\n\tfor (var i = 0; i < viewsLength; i++) {\n\t\tview = views[i];\n\n\t\tisVisible = this.isVisible(view, offset, offset, container);\n\n\t\tif(isVisible === true) {\n\t\t\tif (!view.displayed) {\n\t\t\t\tpromises.push(view.display(this.request).then(function (view) {\n\t\t\t\t\tview.show();\n\t\t\t\t}));\n\t\t\t}\n\t\t\tvisible.push(view);\n\t\t} else {\n\t\t\tthis.q.enqueue(view.destroy.bind(view));\n\n\t\t\tclearTimeout(this.trimTimeout);\n\t\t\tthis.trimTimeout = setTimeout(function(){\n\t\t\t\tthis.q.enqueue(this.trim.bind(this));\n\t\t\t}.bind(this), 250);\n\t\t}\n\n\t}\n\n\tif(promises.length){\n\t\treturn RSVP.all(promises);\n\t} else {\n\t\tupdating.resolve();\n\t\treturn updating.promise;\n\t}\n\n};\n\nContinuousViewManager.prototype.check = function(_offsetLeft, _offsetTop){\n\tvar last, first, next, prev;\n\n\tvar checking = new RSVP.defer();\n\tvar newViews = [];\n\n\tvar horizontal = (this.settings.axis === \"horizontal\");\n\tvar delta = this.settings.offset || 0;\n\n\tif (_offsetLeft && horizontal) {\n\t\tdelta = _offsetLeft;\n\t}\n\n\tif (_offsetTop && !horizontal) {\n\t\tdelta = _offsetTop;\n\t}\n\n\tvar bounds = this._bounds; // bounds saved this until resize\n\n\tvar offset = horizontal ? this.scrollLeft : this.scrollTop;\n\tvar visibleLength = horizontal ? bounds.width : bounds.height;\n\tvar contentLength = horizontal ? this.container.scrollWidth : this.container.scrollHeight;\n\n\tif (offset + visibleLength + delta >= contentLength) {\n\t\tlast = this.views.last();\n\t\tnext = last && last.section.next();\n\t\tif(next) {\n\t\t\tnewViews.push(this.append(next));\n\t\t}\n\t}\n\n\tif (offset - delta < 0 ) {\n\t\tfirst = this.views.first();\n\t\tprev = first && first.section.prev();\n\t\tif(prev) {\n\t\t\tnewViews.push(this.prepend(prev));\n\t\t}\n\t}\n\n\tif(newViews.length){\n\t\t// RSVP.all(promises)\n\t\t\t// .then(function() {\n\t\t\t\t// Check to see if anything new is on screen after rendering\n\t\t\t\treturn this.q.enqueue(function(){\n\t\t\t\t\treturn this.update(delta);\n\t\t\t\t}.bind(this));\n\n\n\t\t\t// }.bind(this));\n\n\t} else {\n\t\tchecking.resolve(false);\n\t\treturn checking.promise;\n\t}\n\n\n};\n\nContinuousViewManager.prototype.trim = function(){\n\tvar task = new RSVP.defer();\n\tvar displayed = this.views.displayed();\n\tvar first = displayed[0];\n\tvar last = displayed[displayed.length-1];\n\tvar firstIndex = this.views.indexOf(first);\n\tvar lastIndex = this.views.indexOf(last);\n\tvar above = this.views.slice(0, firstIndex);\n\tvar below = this.views.slice(lastIndex+1);\n\n\t// Erase all but last above\n\tfor (var i = 0; i < above.length-1; i++) {\n\t\tthis.erase(above[i], above);\n\t}\n\n\t// Erase all except first below\n\tfor (var j = 1; j < below.length; j++) {\n\t\tthis.erase(below[j]);\n\t}\n\n\ttask.resolve();\n\treturn task.promise;\n};\n\nContinuousViewManager.prototype.erase = function(view, above){ //Trim\n\n\tvar prevTop;\n\tvar prevLeft;\n\n\tif(this.settings.height) {\n\t\tprevTop = this.container.scrollTop;\n\t\tprevLeft = this.container.scrollLeft;\n\t} else {\n\t\tprevTop = window.scrollY;\n\t\tprevLeft = window.scrollX;\n\t}\n\n\tvar bounds = view.bounds();\n\n\tthis.views.remove(view);\n\n\tif(above) {\n\n\t\tif(this.settings.axis === \"vertical\") {\n\t\t\tthis.scrollTo(0, prevTop - bounds.height, true);\n\t\t} else {\n\t\t\tthis.scrollTo(prevLeft - bounds.width, 0, true);\n\t\t}\n\t}\n\n};\n\nContinuousViewManager.prototype.addEventListeners = function(stage){\n\n\twindow.addEventListener('unload', function(e){\n\t\tthis.ignore = true;\n\t\t// this.scrollTo(0,0);\n\t\tthis.destroy();\n\t}.bind(this));\n\n\tthis.addScrollListeners();\n};\n\nContinuousViewManager.prototype.addScrollListeners = function() {\n\tvar scroller;\n\n\tthis.tick = core.requestAnimationFrame;\n\n\tif(this.settings.height) {\n\t\tthis.prevScrollTop = this.container.scrollTop;\n\t\tthis.prevScrollLeft = this.container.scrollLeft;\n\t} else {\n\t\tthis.prevScrollTop = window.scrollY;\n\t\tthis.prevScrollLeft = window.scrollX;\n\t}\n\n\tthis.scrollDeltaVert = 0;\n\tthis.scrollDeltaHorz = 0;\n\n\tif(this.settings.height) {\n\t\tscroller = this.container;\n\t\tthis.scrollTop = this.container.scrollTop;\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\t} else {\n\t\tscroller = window;\n\t\tthis.scrollTop = window.scrollY;\n\t\tthis.scrollLeft = window.scrollX;\n\t}\n\n\tscroller.addEventListener(\"scroll\", this.onScroll.bind(this));\n\n\t// this.tick.call(window, this.onScroll.bind(this));\n\n\tthis.scrolled = false;\n\n};\n\nContinuousViewManager.prototype.onScroll = function(){\n\n\t// if(!this.ignore) {\n\n\t\tif(this.settings.height) {\n\t\t\tscrollTop = this.container.scrollTop;\n\t\t\tscrollLeft = this.container.scrollLeft;\n\t\t} else {\n\t\t\tscrollTop = window.scrollY;\n\t\t\tscrollLeft = window.scrollX;\n\t\t}\n\n\t\tthis.scrollTop = scrollTop;\n\t\tthis.scrollLeft = scrollLeft;\n\n\t\tif(!this.ignore) {\n\n\t\t\tif((this.scrollDeltaVert === 0 &&\n\t\t\t\t this.scrollDeltaHorz === 0) ||\n\t\t\t\t this.scrollDeltaVert > this.settings.offsetDelta ||\n\t\t\t\t this.scrollDeltaHorz > this.settings.offsetDelta) {\n\n\t\t\t\tthis.q.enqueue(function() {\n\t\t\t\t\tthis.check();\n\t\t\t\t}.bind(this));\n\t\t\t\t// this.check();\n\n\t\t\t\tthis.scrollDeltaVert = 0;\n\t\t\t\tthis.scrollDeltaHorz = 0;\n\n\t\t\t\tthis.trigger(\"scroll\", {\n\t\t\t\t\ttop: scrollTop,\n\t\t\t\t\tleft: scrollLeft\n\t\t\t\t});\n\n\t\t\t\tclearTimeout(this.afterScrolled);\n\t\t\t\tthis.afterScrolled = setTimeout(function () {\n\t\t\t\t\tthis.trigger(\"scrolled\", {\n\t\t\t\t\t\ttop: this.scrollTop,\n\t\t\t\t\t\tleft: this.scrollLeft\n\t\t\t\t\t});\n\t\t\t\t}.bind(this));\n\n\t\t\t}\n\n\t\t} else {\n\t\t\tthis.ignore = false;\n\t\t}\n\n\t\tthis.scrollDeltaVert += Math.abs(scrollTop-this.prevScrollTop);\n\t\tthis.scrollDeltaHorz += Math.abs(scrollLeft-this.prevScrollLeft);\n\n\t\tthis.prevScrollTop = scrollTop;\n\t\tthis.prevScrollLeft = scrollLeft;\n\n\t\tclearTimeout(this.scrollTimeout);\n\t\tthis.scrollTimeout = setTimeout(function(){\n\t\t\tthis.scrollDeltaVert = 0;\n\t\t\tthis.scrollDeltaHorz = 0;\n\t\t}.bind(this), 150);\n\n\n\t\tthis.scrolled = false;\n\t// }\n\n\t// this.tick.call(window, this.onScroll.bind(this));\n\n};\n\n\n// ContinuousViewManager.prototype.resizeView = function(view) {\n//\n// \tif(this.settings.axis === \"horizontal\") {\n// \t\tview.lock(\"height\", this.stage.width, this.stage.height);\n// \t} else {\n// \t\tview.lock(\"width\", this.stage.width, this.stage.height);\n// \t}\n//\n// };\n\nContinuousViewManager.prototype.currentLocation = function(){\n\n\tif (this.settings.axis === \"vertical\") {\n\t\tthis.location = this.scrolledLocation();\n\t} else {\n\t\tthis.location = this.paginatedLocation();\n\t}\n\n\treturn this.location;\n};\n\nContinuousViewManager.prototype.scrolledLocation = function(){\n\n\tvar visible = this.visible();\n\tvar startPage, endPage;\n\n\tvar container = this.container.getBoundingClientRect();\n\n\tif(visible.length === 1) {\n\t\treturn this.mapping.page(visible[0].contents, visible[0].section.cfiBase);\n\t}\n\n\tif(visible.length > 1) {\n\n\t\tstartPage = this.mapping.page(visible[0].contents, visible[0].section.cfiBase);\n\t\tendPage = this.mapping.page(visible[visible.length-1].contents, visible[visible.length-1].section.cfiBase);\n\n\t\treturn {\n\t\t\tstart: startPage.start,\n\t\t\tend: endPage.end\n\t\t};\n\t}\n\n};\n\nContinuousViewManager.prototype.paginatedLocation = function(){\n\tvar visible = this.visible();\n\tvar startA, startB, endA, endB;\n\tvar pageLeft, pageRight;\n\tvar container = this.container.getBoundingClientRect();\n\n\tif(visible.length === 1) {\n\t\tstartA = container.left - visible[0].position().left;\n\t\tendA = startA + this.layout.spreadWidth;\n\n\t\treturn this.mapping.page(visible[0].contents, visible[0].section.cfiBase, startA, endA);\n\t}\n\n\tif(visible.length > 1) {\n\n\t\t// Left Col\n\t\tstartA = container.left - visible[0].position().left;\n\t\tendA = startA + this.layout.columnWidth;\n\n\t\t// Right Col\n\t\tstartB = container.left + this.layout.spreadWidth - visible[visible.length-1].position().left;\n\t\tendB = startB + this.layout.columnWidth;\n\n\t\tpageLeft = this.mapping.page(visible[0].contents, visible[0].section.cfiBase, startA, endA);\n\t\tpageRight = this.mapping.page(visible[visible.length-1].contents, visible[visible.length-1].section.cfiBase, startB, endB);\n\n\t\treturn {\n\t\t\tstart: pageLeft.start,\n\t\t\tend: pageRight.end\n\t\t};\n\t}\n};\n\n/*\nContinuous.prototype.current = function(what){\n\tvar view, top;\n\tvar container = this.container.getBoundingClientRect();\n\tvar length = this.views.length - 1;\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tfor (var i = length; i >= 0; i--) {\n\t\t\tview = this.views[i];\n\t\t\tleft = view.position().left;\n\n\t\t\tif(left < container.right) {\n\n\t\t\t\tif(this._current == view) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tthis._current = view;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t} else {\n\n\t\tfor (var i = length; i >= 0; i--) {\n\t\t\tview = this.views[i];\n\t\t\ttop = view.bounds().top;\n\t\t\tif(top < container.bottom) {\n\n\t\t\t\tif(this._current == view) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tthis._current = view;\n\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t}\n\n\treturn this._current;\n};\n*/\n\nContinuousViewManager.prototype.updateLayout = function() {\n\n\tif (!this.stage) {\n\t\treturn;\n\t}\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tthis.layout.calculate(this._stageSize.width, this._stageSize.height);\n\t} else {\n\t\tthis.layout.calculate(\n\t\t\tthis._stageSize.width,\n\t\t\tthis._stageSize.height,\n\t\t\tthis.settings.gap\n\t\t);\n\n\t\t// Set the look ahead offset for what is visible\n\t\tthis.settings.offset = this.layout.delta;\n\n\t\tthis.stage.addStyleRules(\"iframe\", [{\"margin-right\" : this.layout.gap + \"px\"}]);\n\n\t}\n\n\t// Set the dimensions for views\n\tthis.viewSettings.width = this.layout.width;\n\tthis.viewSettings.height = this.layout.height;\n\n\tthis.setLayout(this.layout);\n\n};\n\nContinuousViewManager.prototype.next = function(){\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\n\t\tif(this.container.scrollLeft +\n\t\t\t this.container.offsetWidth +\n\t\t\t this.layout.delta < this.container.scrollWidth) {\n\t\t\tthis.scrollBy(this.layout.delta, 0);\n\t\t} else {\n\t\t\tthis.scrollTo(this.container.scrollWidth - this.layout.delta, 0);\n\t\t}\n\n\t} else {\n\t\tthis.scrollBy(0, this.layout.height);\n\t}\n};\n\nContinuousViewManager.prototype.prev = function(){\n\tif(this.settings.axis === \"horizontal\") {\n\t\tthis.scrollBy(-this.layout.delta, 0);\n\t} else {\n\t\tthis.scrollBy(0, -this.layout.height);\n\t}\n};\n\nContinuousViewManager.prototype.updateFlow = function(flow){\n\tvar axis = (flow === \"paginated\") ? \"horizontal\" : \"vertical\";\n\n\tthis.settings.axis = axis;\n\n\tthis.viewSettings.axis = axis;\n\n\tthis.settings.overflow = (flow === \"paginated\") ? \"hidden\" : \"auto\";\n\n\t// this.views.each(function(view){\n\t// \tview.setAxis(axis);\n\t// });\n\n\tif (this.settings.axis === \"vertical\") {\n\t\tthis.settings.infinite = true;\n\t} else {\n\t\tthis.settings.infinite = false;\n\t}\n\n};\nmodule.exports = ContinuousViewManager;\n","var core = require('../../core');\n\nfunction Stage(_options) {\n\tthis.settings = _options || {};\n\tthis.id = \"epubjs-container-\" + core.uuid();\n\n\tthis.container = this.create(this.settings);\n\n\tif(this.settings.hidden) {\n\t\tthis.wrapper = this.wrap(this.container);\n\t}\n\n}\n\n/**\n* Creates an element to render to.\n* Resizes to passed width and height or to the elements size\n*/\nStage.prototype.create = function(options){\n\tvar height = options.height;// !== false ? options.height : \"100%\";\n\tvar width = options.width;// !== false ? options.width : \"100%\";\n\tvar overflow = options.overflow || false;\n\tvar axis = options.axis || \"vertical\";\n\n\tif(options.height && core.isNumber(options.height)) {\n\t\theight = options.height + \"px\";\n\t}\n\n\tif(options.width && core.isNumber(options.width)) {\n\t\twidth = options.width + \"px\";\n\t}\n\n\t// Create new container element\n\tcontainer = document.createElement(\"div\");\n\n\tcontainer.id = this.id;\n\tcontainer.classList.add(\"epub-container\");\n\n\t// Style Element\n\t// container.style.fontSize = \"0\";\n\tcontainer.style.wordSpacing = \"0\";\n\tcontainer.style.lineHeight = \"0\";\n\tcontainer.style.verticalAlign = \"top\";\n\n\tif(axis === \"horizontal\") {\n\t\tcontainer.style.whiteSpace = \"nowrap\";\n\t}\n\n\tif(width){\n\t\tcontainer.style.width = width;\n\t}\n\n\tif(height){\n\t\tcontainer.style.height = height;\n\t}\n\n\tif (overflow) {\n\t\tcontainer.style.overflow = overflow;\n\t}\n\n\treturn container;\n};\n\nStage.wrap = function(container) {\n\tvar wrapper = document.createElement(\"div\");\n\n\twrapper.style.visibility = \"hidden\";\n\twrapper.style.overflow = \"hidden\";\n\twrapper.style.width = \"0\";\n\twrapper.style.height = \"0\";\n\n\twrapper.appendChild(container);\n\treturn wrapper;\n};\n\n\nStage.prototype.getElement = function(_element){\n\tvar element;\n\n\tif(core.isElement(_element)) {\n\t\telement = _element;\n\t} else if (typeof _element === \"string\") {\n\t\telement = document.getElementById(_element);\n\t}\n\n\tif(!element){\n\t\tconsole.error(\"Not an Element\");\n\t\treturn;\n\t}\n\n\treturn element;\n};\n\nStage.prototype.attachTo = function(what){\n\n\tvar element = this.getElement(what);\n\tvar base;\n\n\tif(!element){\n\t\treturn;\n\t}\n\n\tif(this.settings.hidden) {\n\t\tbase = this.wrapper;\n\t} else {\n\t\tbase = this.container;\n\t}\n\n\telement.appendChild(base);\n\n\tthis.element = element;\n\n\treturn element;\n\n};\n\nStage.prototype.getContainer = function() {\n\treturn this.container;\n};\n\nStage.prototype.onResize = function(func){\n\t// Only listen to window for resize event if width and height are not fixed.\n\t// This applies if it is set to a percent or auto.\n\tif(!core.isNumber(this.settings.width) ||\n\t\t !core.isNumber(this.settings.height) ) {\n\t\twindow.addEventListener(\"resize\", func, false);\n\t}\n\n};\n\nStage.prototype.size = function(width, height){\n\tvar bounds;\n\t// var width = _width || this.settings.width;\n\t// var height = _height || this.settings.height;\n\n\t// If width or height are set to false, inherit them from containing element\n\tif(width === null) {\n\t\tbounds = this.element.getBoundingClientRect();\n\n\t\tif(bounds.width) {\n\t\t\twidth = bounds.width;\n\t\t\tthis.container.style.width = bounds.width + \"px\";\n\t\t}\n\t}\n\n\tif(height === null) {\n\t\tbounds = bounds || this.element.getBoundingClientRect();\n\n\t\tif(bounds.height) {\n\t\t\theight = bounds.height;\n\t\t\tthis.container.style.height = bounds.height + \"px\";\n\t\t}\n\n\t}\n\n\tif(!core.isNumber(width)) {\n\t\tbounds = this.container.getBoundingClientRect();\n\t\twidth = bounds.width;\n\t\t//height = bounds.height;\n\t}\n\n\tif(!core.isNumber(height)) {\n\t\tbounds = bounds || this.container.getBoundingClientRect();\n\t\t//width = bounds.width;\n\t\theight = bounds.height;\n\t}\n\n\n\tthis.containerStyles = window.getComputedStyle(this.container);\n\n\tthis.containerPadding = {\n\t\tleft: parseFloat(this.containerStyles[\"padding-left\"]) || 0,\n\t\tright: parseFloat(this.containerStyles[\"padding-right\"]) || 0,\n\t\ttop: parseFloat(this.containerStyles[\"padding-top\"]) || 0,\n\t\tbottom: parseFloat(this.containerStyles[\"padding-bottom\"]) || 0\n\t};\n\n\treturn {\n\t\twidth: width -\n\t\t\t\t\t\tthis.containerPadding.left -\n\t\t\t\t\t\tthis.containerPadding.right,\n\t\theight: height -\n\t\t\t\t\t\tthis.containerPadding.top -\n\t\t\t\t\t\tthis.containerPadding.bottom\n\t};\n\n};\n\nStage.prototype.bounds = function(){\n\n\tif(!this.container) {\n\t\treturn core.windowBounds();\n\t} else {\n\t\treturn this.container.getBoundingClientRect();\n\t}\n\n}\n\nStage.prototype.getSheet = function(){\n\tvar style = document.createElement(\"style\");\n\n\t// WebKit hack --> https://davidwalsh.name/add-rules-stylesheets\n\tstyle.appendChild(document.createTextNode(\"\"));\n\n\tdocument.head.appendChild(style);\n\n\treturn style.sheet;\n}\n\nStage.prototype.addStyleRules = function(selector, rulesArray){\n\tvar scope = \"#\" + this.id + \" \";\n\tvar rules = \"\";\n\n\tif(!this.sheet){\n\t\tthis.sheet = this.getSheet();\n\t}\n\n\trulesArray.forEach(function(set) {\n\t\tfor (var prop in set) {\n\t\t\tif(set.hasOwnProperty(prop)) {\n\t\t\t\trules += prop + \":\" + set[prop] + \";\";\n\t\t\t}\n\t\t}\n\t})\n\n\tthis.sheet.insertRule(scope + selector + \" {\" + rules + \"}\", 0);\n}\n\n\n\nmodule.exports = Stage;\n","function Views(container) {\n\tthis.container = container;\n\tthis._views = [];\n\tthis.length = 0;\n\tthis.hidden = false;\n};\n\nViews.prototype.all = function() {\n\treturn this._views;\n};\n\nViews.prototype.first = function() {\n\treturn this._views[0];\n};\n\nViews.prototype.last = function() {\n\treturn this._views[this._views.length-1];\n};\n\nViews.prototype.indexOf = function(view) {\n\treturn this._views.indexOf(view);\n};\n\nViews.prototype.slice = function() {\n\treturn this._views.slice.apply(this._views, arguments);\n};\n\nViews.prototype.get = function(i) {\n\treturn this._views[i];\n};\n\nViews.prototype.append = function(view){\n\tthis._views.push(view);\n\tif(this.container){\n\t\tthis.container.appendChild(view.element);\n\t}\n\tthis.length++;\n\treturn view;\n};\n\nViews.prototype.prepend = function(view){\n\tthis._views.unshift(view);\n\tif(this.container){\n\t\tthis.container.insertBefore(view.element, this.container.firstChild);\n\t}\n\tthis.length++;\n\treturn view;\n};\n\nViews.prototype.insert = function(view, index) {\n\tthis._views.splice(index, 0, view);\n\n\tif(this.container){\n\t\tif(index < this.container.children.length){\n\t\t\tthis.container.insertBefore(view.element, this.container.children[index]);\n\t\t} else {\n\t\t\tthis.container.appendChild(view.element);\n\t\t}\n\t}\n\n\tthis.length++;\n\treturn view;\n};\n\nViews.prototype.remove = function(view) {\n\tvar index = this._views.indexOf(view);\n\n\tif(index > -1) {\n\t\tthis._views.splice(index, 1);\n\t}\n\n\n\tthis.destroy(view);\n\n\tthis.length--;\n};\n\nViews.prototype.destroy = function(view) {\n\tview.off(\"resized\");\n\n\tif(view.displayed){\n\t\tview.destroy();\n\t}\n\n\tif(this.container){\n\t\t this.container.removeChild(view.element);\n\t}\n\tview = null;\n};\n\n// Iterators\n\nViews.prototype.each = function() {\n\treturn this._views.forEach.apply(this._views, arguments);\n};\n\nViews.prototype.clear = function(){\n\t// Remove all views\n\tvar view;\n\tvar len = this.length;\n\n\tif(!this.length) return;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tthis.destroy(view);\n\t}\n\n\tthis._views = [];\n\tthis.length = 0;\n};\n\nViews.prototype.find = function(section){\n\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed && view.section.index == section.index) {\n\t\t\treturn view;\n\t\t}\n\t}\n\n};\n\nViews.prototype.displayed = function(){\n\tvar displayed = [];\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed){\n\t\t\tdisplayed.push(view);\n\t\t}\n\t}\n\treturn displayed;\n};\n\nViews.prototype.show = function(){\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed){\n\t\t\tview.show();\n\t\t}\n\t}\n\tthis.hidden = false;\n};\n\nViews.prototype.hide = function(){\n\tvar view;\n\tvar len = this.length;\n\n\tfor (var i = 0; i < len; i++) {\n\t\tview = this._views[i];\n\t\tif(view.displayed){\n\t\t\tview.hide();\n\t\t}\n\t}\n\tthis.hidden = true;\n};\n\nmodule.exports = Views;\n","var RSVP = require('rsvp');\nvar core = require('../core');\nvar EpubCFI = require('../epubcfi');\n// var Layout = require('../layout');\nvar Mapping = require('../mapping');\nvar Queue = require('../queue');\nvar Stage = require('./helpers/stage');\nvar Views = require('./helpers/views');\n\nfunction SingleViewManager(options) {\n\n\tthis.name = \"single\";\n\tthis.View = options.view;\n\tthis.request = options.request;\n\tthis.renditionQueue = options.queue;\n\tthis.q = new Queue(this);\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\tinfinite: true,\n\t\thidden: false,\n\t\twidth: undefined,\n\t\theight: undefined,\n\t\t// globalLayoutProperties : { layout: 'reflowable', spread: 'auto', orientation: 'auto'},\n\t\t// layout: null,\n\t\taxis: \"vertical\",\n\t\tignoreClass: ''\n\t});\n\n\tcore.extend(this.settings, options.settings || {});\n\n\tthis.viewSettings = {\n\t\tignoreClass: this.settings.ignoreClass,\n\t\taxis: this.settings.axis,\n\t\tlayout: this.layout,\n\t\twidth: 0,\n\t\theight: 0\n\t};\n\n}\n\nSingleViewManager.prototype.render = function(element, size){\n\n\t// Save the stage\n\tthis.stage = new Stage({\n\t\twidth: size.width,\n\t\theight: size.height,\n\t\toverflow: this.settings.overflow,\n\t\thidden: this.settings.hidden,\n\t\taxis: this.settings.axis\n\t});\n\n\tthis.stage.attachTo(element);\n\n\t// Get this stage container div\n\tthis.container = this.stage.getContainer();\n\n\t// Views array methods\n\tthis.views = new Views(this.container);\n\n\t// Calculate Stage Size\n\tthis._bounds = this.bounds();\n\tthis._stageSize = this.stage.size();\n\n\t// Set the dimensions for views\n\tthis.viewSettings.width = this._stageSize.width;\n\tthis.viewSettings.height = this._stageSize.height;\n\n\t// Function to handle a resize event.\n\t// Will only attach if width and height are both fixed.\n\tthis.stage.onResize(this.onResized.bind(this));\n\n\t// Add Event Listeners\n\tthis.addEventListeners();\n\n\t// Add Layout method\n\t// this.applyLayoutMethod();\n\tif (this.layout) {\n\t\tthis.updateLayout();\n\t}\n};\n\nSingleViewManager.prototype.addEventListeners = function(){\n\twindow.addEventListener('unload', function(e){\n\t\tthis.destroy();\n\t}.bind(this));\n};\n\nSingleViewManager.prototype.destroy = function(){\n\t// this.views.each(function(view){\n\t// \tview.destroy();\n\t// });\n\n\t/*\n\n\t\tclearTimeout(this.trimTimeout);\n\t\tif(this.settings.hidden) {\n\t\t\tthis.element.removeChild(this.wrapper);\n\t\t} else {\n\t\t\tthis.element.removeChild(this.container);\n\t\t}\n\t*/\n};\n\nSingleViewManager.prototype.onResized = function(e) {\n\tclearTimeout(this.resizeTimeout);\n\tthis.resizeTimeout = setTimeout(function(){\n\t\tthis.resize();\n\t}.bind(this), 150);\n};\n\nSingleViewManager.prototype.resize = function(width, height){\n\n\t// Clear the queue\n\tthis.q.clear();\n\n\tthis._stageSize = this.stage.size(width, height);\n\tthis._bounds = this.bounds();\n\n\t// Update for new views\n\tthis.viewSettings.width = this._stageSize.width;\n\tthis.viewSettings.height = this._stageSize.height;\n\n\t// Update for existing views\n\tthis.views.each(function(view) {\n\t\tview.size(this._stageSize.width, this._stageSize.height);\n\t}.bind(this));\n\n\tthis.updateLayout();\n\n\tthis.trigger(\"resized\", {\n\t\twidth: this.stage.width,\n\t\theight: this.stage.height\n\t});\n\n};\n\nSingleViewManager.prototype.createView = function(section) {\n\treturn new this.View(section, this.viewSettings);\n};\n\nSingleViewManager.prototype.display = function(section, target){\n\n\tvar displaying = new RSVP.defer();\n\tvar displayed = displaying.promise;\n\n\t// Check to make sure the section we want isn't already shown\n\tvar visible = this.views.find(section);\n\n\t// View is already shown, just move to correct location\n\tif(visible && target) {\n\t\toffset = visible.locationOf(target);\n\t\tthis.moveTo(offset);\n\t\tdisplaying.resolve();\n\t\treturn displayed;\n\t}\n\n\t// Hide all current views\n\tthis.views.hide();\n\n\tthis.views.clear();\n\n\tthis.add(section)\n\t\t.then(function(){\n\t\t\tvar next;\n\t\t\tif (this.layout.name === \"pre-paginated\" &&\n\t\t\t\t\tthis.layout.divisor > 1) {\n\t\t\t\tnext = section.next();\n\t\t\t\tif (next) {\n\t\t\t\t\treturn this.add(next);\n\t\t\t\t}\n\t\t\t}\n\t\t}.bind(this))\n\t\t.then(function(view){\n\n\t\t\t// Move to correct place within the section, if needed\n\t\t\tif(target) {\n\t\t\t\toffset = view.locationOf(target);\n\t\t\t\tthis.moveTo(offset);\n\t\t\t}\n\n\t\t\tthis.views.show();\n\n\t\t\tdisplaying.resolve();\n\n\t\t}.bind(this))\n\t\t// .then(function(){\n\t\t// \treturn this.hooks.display.trigger(view);\n\t\t// }.bind(this))\n\t\t// .then(function(){\n\t\t// \tthis.views.show();\n\t\t// }.bind(this));\n\t\treturn displayed;\n};\n\nSingleViewManager.prototype.afterDisplayed = function(view){\n\tthis.trigger(\"added\", view);\n};\n\nSingleViewManager.prototype.afterResized = function(view){\n\tthis.trigger(\"resize\", view.section);\n};\n\n// SingleViewManager.prototype.moveTo = function(offset){\n// \tthis.scrollTo(offset.left, offset.top);\n// };\n\nSingleViewManager.prototype.moveTo = function(offset){\n\tvar distX = 0,\n\t\t\tdistY = 0;\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tdistY = offset.top;\n\t} else {\n\t\tdistX = Math.floor(offset.left / this.layout.delta) * this.layout.delta;\n\n\t\tif (distX + this.layout.delta > this.container.scrollWidth) {\n\t\t\tdistX = this.container.scrollWidth - this.layout.delta;\n\t\t}\n\t}\n\n\tthis.scrollTo(distX, distY);\n};\n\nSingleViewManager.prototype.add = function(section){\n\tvar view = this.createView(section);\n\n\tthis.views.append(view);\n\n\t// view.on(\"shown\", this.afterDisplayed.bind(this));\n\tview.onDisplayed = this.afterDisplayed.bind(this);\n\tview.onResize = this.afterResized.bind(this);\n\n\treturn view.display(this.request);\n\n};\n\nSingleViewManager.prototype.append = function(section){\n\tvar view = this.createView(section);\n\tthis.views.append(view);\n\treturn view.display(this.request);\n};\n\nSingleViewManager.prototype.prepend = function(section){\n\tvar view = this.createView(section);\n\n\tthis.views.prepend(view);\n\treturn view.display(this.request);\n};\n// SingleViewManager.prototype.resizeView = function(view) {\n//\n// \tif(this.settings.globalLayoutProperties.layout === \"pre-paginated\") {\n// \t\tview.lock(\"both\", this.bounds.width, this.bounds.height);\n// \t} else {\n// \t\tview.lock(\"width\", this.bounds.width, this.bounds.height);\n// \t}\n//\n// };\n\nSingleViewManager.prototype.next = function(){\n\tvar next;\n\tvar view;\n\tvar left;\n\n\tif(!this.views.length) return;\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\n\t\tleft = this.container.scrollLeft + this.container.offsetWidth + this.layout.delta;\n\n\t\tif(left < this.container.scrollWidth) {\n\t\t\tthis.scrollBy(this.layout.delta, 0);\n\t\t} else if (left - this.layout.columnWidth === this.container.scrollWidth) {\n\t\t\tthis.scrollTo(this.container.scrollWidth - this.layout.delta, 0);\n\t\t} else {\n\t\t\tnext = this.views.last().section.next();\n\t\t}\n\n\n\t} else {\n\n\t\tnext = this.views.last().section.next();\n\n\t}\n\n\tif(next) {\n\t\tthis.views.clear();\n\n\t\treturn this.append(next)\n\t\t\t.then(function(){\n\t\t\t\tvar right;\n\t\t\t\tif (this.layout.name && this.layout.divisor > 1) {\n\t\t\t\t\tright = next.next();\n\t\t\t\t\tif (right) {\n\t\t\t\t\t\treturn this.append(right);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}.bind(this))\n\t\t\t.then(function(){\n\t\t\t\tthis.views.show();\n\t\t\t}.bind(this));\n\t}\n\n\n};\n\nSingleViewManager.prototype.prev = function(){\n\tvar prev;\n\tvar view;\n\tvar left;\n\n\tif(!this.views.length) return;\n\n\tif(this.settings.axis === \"horizontal\") {\n\n\t\tthis.scrollLeft = this.container.scrollLeft;\n\n\t\tleft = this.container.scrollLeft;\n\n\t\tif(left > 0) {\n\t\t\tthis.scrollBy(-this.layout.delta, 0);\n\t\t} else {\n\t\t\tprev = this.views.first().section.prev();\n\t\t}\n\n\n\t} else {\n\n\t\tprev = this.views.first().section.prev();\n\n\t}\n\n\tif(prev) {\n\t\tthis.views.clear();\n\n\t\treturn this.prepend(prev)\n\t\t\t.then(function(){\n\t\t\t\tvar left;\n\t\t\t\tif (this.layout.name && this.layout.divisor > 1) {\n\t\t\t\t\tleft = prev.prev();\n\t\t\t\t\tif (left) {\n\t\t\t\t\t\treturn this.prepend(left);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}.bind(this))\n\t\t\t.then(function(){\n\t\t\t\tif(this.settings.axis === \"horizontal\") {\n\t\t\t\t\tthis.scrollTo(this.container.scrollWidth - this.layout.delta, 0);\n\t\t\t\t}\n\t\t\t\tthis.views.show();\n\t\t\t}.bind(this));\n\t}\n};\n\nSingleViewManager.prototype.current = function(){\n\tvar visible = this.visible();\n\tif(visible.length){\n\t\t// Current is the last visible view\n\t\treturn visible[visible.length-1];\n\t}\n\treturn null;\n};\n\nSingleViewManager.prototype.currentLocation = function(){\n\tvar view;\n\tvar start, end;\n\n\tif(this.views.length) {\n\t\tview = this.views.first();\n\t\tstart = container.left - view.position().left;\n\t\tend = start + this.layout.spread;\n\n\t\treturn this.mapping.page(view, view.section.cfiBase);\n\t}\n\n};\n\nSingleViewManager.prototype.isVisible = function(view, offsetPrev, offsetNext, _container){\n\tvar position = view.position();\n\tvar container = _container || this.bounds();\n\n\tif(this.settings.axis === \"horizontal\" &&\n\t\tposition.right > container.left - offsetPrev &&\n\t\tposition.left < container.right + offsetNext) {\n\n\t\treturn true;\n\n\t} else if(this.settings.axis === \"vertical\" &&\n\t\tposition.bottom > container.top - offsetPrev &&\n\t\tposition.top < container.bottom + offsetNext) {\n\n\t\treturn true;\n\t}\n\n\treturn false;\n\n};\n\nSingleViewManager.prototype.visible = function(){\n\t// return this.views.displayed();\n\tvar container = this.bounds();\n\tvar views = this.views.displayed();\n\tvar viewsLength = views.length;\n\tvar visible = [];\n\tvar isVisible;\n\tvar view;\n\n\tfor (var i = 0; i < viewsLength; i++) {\n\t\tview = views[i];\n\t\tisVisible = this.isVisible(view, 0, 0, container);\n\n\t\tif(isVisible === true) {\n\t\t\tvisible.push(view);\n\t\t}\n\n\t}\n\treturn visible;\n};\n\nSingleViewManager.prototype.scrollBy = function(x, y, silent){\n\tif(silent) {\n\t\tthis.ignore = true;\n\t}\n\n\tif(this.settings.height) {\n\n\t\tif(x) this.container.scrollLeft += x;\n\t\tif(y) this.container.scrollTop += y;\n\n\t} else {\n\t\twindow.scrollBy(x,y);\n\t}\n\t// console.log(\"scrollBy\", x, y);\n\tthis.scrolled = true;\n\tthis.onScroll();\n};\n\nSingleViewManager.prototype.scrollTo = function(x, y, silent){\n\tif(silent) {\n\t\tthis.ignore = true;\n\t}\n\n\tif(this.settings.height) {\n\t\tthis.container.scrollLeft = x;\n\t\tthis.container.scrollTop = y;\n\t} else {\n\t\twindow.scrollTo(x,y);\n\t}\n\t// console.log(\"scrollTo\", x, y);\n\tthis.scrolled = true;\n\tthis.onScroll();\n\t// if(this.container.scrollLeft != x){\n\t// setTimeout(function() {\n\t// this.scrollTo(x, y, silent);\n\t// }.bind(this), 10);\n\t// return;\n\t// };\n };\n\nSingleViewManager.prototype.onScroll = function(){\n\n};\n\nSingleViewManager.prototype.bounds = function() {\n\tvar bounds;\n\n\tbounds = this.stage.bounds();\n\n\treturn bounds;\n};\n\nSingleViewManager.prototype.applyLayout = function(layout) {\n\n\tthis.layout = layout;\n\tthis.updateLayout();\n\n\tthis.mapping = new Mapping(this.layout);\n\t // this.manager.layout(this.layout.format);\n};\n\nSingleViewManager.prototype.updateLayout = function() {\n\tif (!this.stage) {\n\t\treturn;\n\t}\n\n\tthis._stageSize = this.stage.size();\n\n\tif(this.settings.axis === \"vertical\") {\n\t\tthis.layout.calculate(this._stageSize.width, this._stageSize.height);\n\t} else {\n\t\tthis.layout.calculate(\n\t\t\tthis._stageSize.width,\n\t\t\tthis._stageSize.height,\n\t\t\tthis.settings.gap\n\t\t);\n\n\t\t// Set the look ahead offset for what is visible\n\t\tthis.settings.offset = this.layout.delta;\n\n\t\tthis.stage.addStyleRules(\"iframe\", [{\"margin-right\" : this.layout.gap + \"px\"}]);\n\n\t}\n\n\t// Set the dimensions for views\n\tthis.viewSettings.width = this.layout.width;\n\tthis.viewSettings.height = this.layout.height;\n\n\tthis.setLayout(this.layout);\n\n};\n\nSingleViewManager.prototype.setLayout = function(layout){\n\n\tthis.viewSettings.layout = layout;\n\n\tif(this.views) {\n\n\t\tthis.views.each(function(view){\n\t\t\tview.setLayout(layout);\n\t\t});\n\n\t}\n\n};\n\nSingleViewManager.prototype.updateFlow = function(flow){\n\tvar axis = (flow === \"paginated\") ? \"horizontal\" : \"vertical\";\n\n\tthis.settings.axis = axis;\n\n\tthis.viewSettings.axis = axis;\n\n\tthis.settings.overflow = (flow === \"paginated\") ? \"hidden\" : \"auto\";\n\t// this.views.each(function(view){\n\t// \tview.setAxis(axis);\n\t// });\n\n};\n\n //-- Enable binding events to Manager\n RSVP.EventTarget.mixin(SingleViewManager.prototype);\n\n module.exports = SingleViewManager;\n","var RSVP = require('rsvp');\nvar core = require('../../core');\nvar EpubCFI = require('../../epubcfi');\nvar Contents = require('../../contents');\n\nfunction IframeView(section, options) {\n\tthis.settings = core.extend({\n\t\tignoreClass : '',\n\t\taxis: 'vertical',\n\t\twidth: 0,\n\t\theight: 0,\n\t\tlayout: undefined,\n\t\tglobalLayoutProperties: {},\n\t}, options || {});\n\n\tthis.id = \"epubjs-view-\" + core.uuid();\n\tthis.section = section;\n\tthis.index = section.index;\n\n\tthis.element = this.container(this.settings.axis);\n\n\tthis.added = false;\n\tthis.displayed = false;\n\tthis.rendered = false;\n\n\tthis.width = this.settings.width;\n\tthis.height = this.settings.height;\n\n\tthis.fixedWidth = 0;\n\tthis.fixedHeight = 0;\n\n\t// Blank Cfi for Parsing\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.layout = this.settings.layout;\n\t// Dom events to listen for\n\t// this.listenedEvents = [\"keydown\", \"keyup\", \"keypressed\", \"mouseup\", \"mousedown\", \"click\", \"touchend\", \"touchstart\"];\n};\n\nIframeView.prototype.container = function(axis) {\n\tvar element = document.createElement('div');\n\n\telement.classList.add(\"epub-view\");\n\n\t// this.element.style.minHeight = \"100px\";\n\telement.style.height = \"0px\";\n\telement.style.width = \"0px\";\n\telement.style.overflow = \"hidden\";\n\n\tif(axis && axis == \"horizontal\"){\n\t\telement.style.display = \"inline-block\";\n\t} else {\n\t\telement.style.display = \"block\";\n\t}\n\n\treturn element;\n};\n\nIframeView.prototype.create = function() {\n\n\tif(this.iframe) {\n\t\treturn this.iframe;\n\t}\n\n\tif(!this.element) {\n\t\tthis.element = this.createContainer();\n\t}\n\n\tthis.iframe = document.createElement('iframe');\n\tthis.iframe.id = this.id;\n\tthis.iframe.scrolling = \"no\"; // Might need to be removed: breaks ios width calculations\n\tthis.iframe.style.overflow = \"hidden\";\n\tthis.iframe.seamless = \"seamless\";\n\t// Back up if seamless isn't supported\n\tthis.iframe.style.border = \"none\";\n\n\tthis.resizing = true;\n\n\t// this.iframe.style.display = \"none\";\n\tthis.element.style.visibility = \"hidden\";\n\tthis.iframe.style.visibility = \"hidden\";\n\n\tthis.iframe.style.width = \"0\";\n\tthis.iframe.style.height = \"0\";\n\tthis._width = 0;\n\tthis._height = 0;\n\n\tthis.element.appendChild(this.iframe);\n\tthis.added = true;\n\n\tthis.elementBounds = core.bounds(this.element);\n\n\t// if(width || height){\n\t// this.resize(width, height);\n\t// } else if(this.width && this.height){\n\t// this.resize(this.width, this.height);\n\t// } else {\n\t// this.iframeBounds = core.bounds(this.iframe);\n\t// }\n\n\t// Firefox has trouble with baseURI and srcdoc\n\t// TODO: Disable for now in firefox\n\n\tif(!!(\"srcdoc\" in this.iframe)) {\n\t\tthis.supportsSrcdoc = true;\n\t} else {\n\t\tthis.supportsSrcdoc = false;\n\t}\n\n\treturn this.iframe;\n};\n\nIframeView.prototype.render = function(request, show) {\n\n\t// view.onLayout = this.layout.format.bind(this.layout);\n\tthis.create();\n\n\t// Fit to size of the container, apply padding\n\tthis.size();\n\n\tif(!this.sectionRender) {\n\t\tthis.sectionRender = this.section.render(request);\n\t}\n\n\t// Render Chain\n\treturn this.sectionRender\n\t\t.then(function(contents){\n\t\t\treturn this.load(contents);\n\t\t}.bind(this))\n\t\t// .then(function(doc){\n\t\t// \treturn this.hooks.content.trigger(view, this);\n\t\t// }.bind(this))\n\t\t.then(function(){\n\t\t\t// this.settings.layout.format(view.contents);\n\t\t\t// return this.hooks.layout.trigger(view, this);\n\t\t}.bind(this))\n\t\t// .then(function(){\n\t\t// \treturn this.display();\n\t\t// }.bind(this))\n\t\t// .then(function(){\n\t\t// \treturn this.hooks.render.trigger(view, this);\n\t\t// }.bind(this))\n\t\t.then(function(){\n\n\t\t\t// apply the layout function to the contents\n\t\t\tthis.settings.layout.format(this.contents);\n\n\t\t\t// Expand the iframe to the full size of the content\n\t\t\tthis.expand();\n\n\t\t\t// Listen for events that require an expansion of the iframe\n\t\t\tthis.addListeners();\n\n\t\t\tif(show !== false) {\n\t\t\t\t//this.q.enqueue(function(view){\n\t\t\t\t\t// this.show();\n\t\t\t\t//}, view);\n\t\t\t}\n\t\t\t// this.map = new Map(view, this.layout);\n\t\t\t//this.hooks.show.trigger(view, this);\n\t\t\tthis.trigger(\"rendered\", this.section);\n\n\t\t}.bind(this))\n\t\t.catch(function(e){\n\t\t\tthis.trigger(\"loaderror\", e);\n\t\t}.bind(this));\n\n};\n\n// Determine locks base on settings\nIframeView.prototype.size = function(_width, _height) {\n\tvar width = _width || this.settings.width;\n\tvar height = _height || this.settings.height;\n\n\tif(this.layout.name === \"pre-paginated\") {\n\t\tthis.lock(\"both\", width, height);\n\t} else if(this.settings.axis === \"horizontal\") {\n\t\tthis.lock(\"height\", width, height);\n\t} else {\n\t\tthis.lock(\"width\", width, height);\n\t}\n\n};\n\n// Lock an axis to element dimensions, taking borders into account\nIframeView.prototype.lock = function(what, width, height) {\n\tvar elBorders = core.borders(this.element);\n\tvar iframeBorders;\n\n\tif(this.iframe) {\n\t\tiframeBorders = core.borders(this.iframe);\n\t} else {\n\t\tiframeBorders = {width: 0, height: 0};\n\t}\n\n\tif(what == \"width\" && core.isNumber(width)){\n\t\tthis.lockedWidth = width - elBorders.width - iframeBorders.width;\n\t\tthis.resize(this.lockedWidth, width); // width keeps ratio correct\n\t}\n\n\tif(what == \"height\" && core.isNumber(height)){\n\t\tthis.lockedHeight = height - elBorders.height - iframeBorders.height;\n\t\tthis.resize(width, this.lockedHeight);\n\t}\n\n\tif(what === \"both\" &&\n\t\t core.isNumber(width) &&\n\t\t core.isNumber(height)){\n\n\t\tthis.lockedWidth = width - elBorders.width - iframeBorders.width;\n\t\tthis.lockedHeight = height - elBorders.height - iframeBorders.height;\n\n\t\tthis.resize(this.lockedWidth, this.lockedHeight);\n\t}\n\n\tif(this.displayed && this.iframe) {\n\n\t\t\t// this.contents.layout();\n\t\t\tthis.expand();\n\n\t}\n\n\n\n};\n\n// Resize a single axis based on content dimensions\nIframeView.prototype.expand = function(force) {\n\tvar width = this.lockedWidth;\n\tvar height = this.lockedHeight;\n\tvar columns;\n\n\tvar textWidth, textHeight;\n\n\tif(!this.iframe || this._expanding) return;\n\n\tthis._expanding = true;\n\n\t// Expand Horizontally\n\t// if(height && !width) {\n\tif(this.settings.axis === \"horizontal\") {\n\t\t// Get the width of the text\n\t\ttextWidth = this.contents.textWidth();\n\t\t// Check if the textWidth has changed\n\t\tif(textWidth != this._textWidth){\n\t\t\t// Get the contentWidth by resizing the iframe\n\t\t\t// Check with a min reset of the textWidth\n\t\t\twidth = this.contentWidth(textWidth);\n\n\t\t\tcolumns = Math.ceil(width / (this.settings.layout.columnWidth + this.settings.layout.gap));\n\n\t\t\tif ( this.settings.layout.divisor > 1 &&\n\t\t\t\t\t this.settings.layout.name === \"reflowable\" &&\n\t\t\t\t\t(columns % 2 > 0)) {\n\t\t\t\t\t// add a blank page\n\t\t\t\t\twidth += this.settings.layout.gap + this.settings.layout.columnWidth;\n\t\t\t}\n\n\t\t\t// Save the textWdith\n\t\t\tthis._textWidth = textWidth;\n\t\t\t// Save the contentWidth\n\t\t\tthis._contentWidth = width;\n\t\t} else {\n\t\t\t// Otherwise assume content height hasn't changed\n\t\t\twidth = this._contentWidth;\n\t\t}\n\t} // Expand Vertically\n\telse if(this.settings.axis === \"vertical\") {\n\t\ttextHeight = this.contents.textHeight();\n\t\tif(textHeight != this._textHeight){\n\t\t\theight = this.contentHeight(textHeight);\n\t\t\tthis._textHeight = textHeight;\n\t\t\tthis._contentHeight = height;\n\t\t} else {\n\t\t\theight = this._contentHeight;\n\t\t}\n\n\t}\n\n\t// Only Resize if dimensions have changed or\n\t// if Frame is still hidden, so needs reframing\n\tif(this._needsReframe || width != this._width || height != this._height){\n\t\tthis.resize(width, height);\n\t}\n\n\tthis._expanding = false;\n};\n\nIframeView.prototype.contentWidth = function(min) {\n\tvar prev;\n\tvar width;\n\n\t// Save previous width\n\tprev = this.iframe.style.width;\n\t// Set the iframe size to min, width will only ever be greater\n\t// Will preserve the aspect ratio\n\tthis.iframe.style.width = (min || 0) + \"px\";\n\t// Get the scroll overflow width\n\twidth = this.contents.scrollWidth();\n\t// Reset iframe size back\n\tthis.iframe.style.width = prev;\n\treturn width;\n};\n\nIframeView.prototype.contentHeight = function(min) {\n\tvar prev;\n\tvar height;\n\n\tprev = this.iframe.style.height;\n\tthis.iframe.style.height = (min || 0) + \"px\";\n\theight = this.contents.scrollHeight();\n\n\tthis.iframe.style.height = prev;\n\treturn height;\n};\n\n\nIframeView.prototype.resize = function(width, height) {\n\n\tif(!this.iframe) return;\n\n\tif(core.isNumber(width)){\n\t\tthis.iframe.style.width = width + \"px\";\n\t\tthis._width = width;\n\t}\n\n\tif(core.isNumber(height)){\n\t\tthis.iframe.style.height = height + \"px\";\n\t\tthis._height = height;\n\t}\n\n\tthis.iframeBounds = core.bounds(this.iframe);\n\n\tthis.reframe(this.iframeBounds.width, this.iframeBounds.height);\n\n};\n\nIframeView.prototype.reframe = function(width, height) {\n\tvar size;\n\n\t// if(!this.displayed) {\n\t// this._needsReframe = true;\n\t// return;\n\t// }\n\tif(core.isNumber(width)){\n\t\tthis.element.style.width = width + \"px\";\n\t}\n\n\tif(core.isNumber(height)){\n\t\tthis.element.style.height = height + \"px\";\n\t}\n\n\tthis.prevBounds = this.elementBounds;\n\n\tthis.elementBounds = core.bounds(this.element);\n\n\tsize = {\n\t\twidth: this.elementBounds.width,\n\t\theight: this.elementBounds.height,\n\t\twidthDelta: this.elementBounds.width - this.prevBounds.width,\n\t\theightDelta: this.elementBounds.height - this.prevBounds.height,\n\t};\n\n\tthis.onResize(this, size);\n\n\tthis.trigger(\"resized\", size);\n\n};\n\n\nIframeView.prototype.load = function(contents) {\n\tvar loading = new RSVP.defer();\n\tvar loaded = loading.promise;\n\n\tif(!this.iframe) {\n\t\tloading.reject(new Error(\"No Iframe Available\"));\n\t\treturn loaded;\n\t}\n\n\tthis.iframe.onload = function(event) {\n\n\t\tthis.onLoad(event, loading);\n\n\t}.bind(this);\n\n\tif(this.supportsSrcdoc){\n\t\tthis.iframe.srcdoc = contents;\n\t} else {\n\n\t\tthis.document = this.iframe.contentDocument;\n\n\t\tif(!this.document) {\n\t\t\tloading.reject(new Error(\"No Document Available\"));\n\t\t\treturn loaded;\n\t\t}\n\n\t\tthis.iframe.contentDocument.open();\n\t\tthis.iframe.contentDocument.write(contents);\n\t\tthis.iframe.contentDocument.close();\n\n\t}\n\n\treturn loaded;\n};\n\nIframeView.prototype.onLoad = function(event, promise) {\n\n\t\tthis.window = this.iframe.contentWindow;\n\t\tthis.document = this.iframe.contentDocument;\n\n\t\tthis.contents = new Contents(this.document, this.document.body, this.section.cfiBase);\n\n\t\tthis.rendering = false;\n\n\t\tvar link = this.document.querySelector(\"link[rel='canonical']\");\n\t\tif (link) {\n\t\t\tlink.setAttribute(\"href\", this.section.url);\n\t\t} else {\n\t\t\tlink = this.document.createElement(\"link\");\n\t\t\tlink.setAttribute(\"rel\", \"canonical\");\n\t\t\tlink.setAttribute(\"href\", this.section.url);\n\t\t\tthis.document.querySelector(\"head\").appendChild(link);\n\t\t}\n\n\t\tthis.contents.on(\"expand\", function () {\n\t\t\tif(this.displayed && this.iframe) {\n\t\t\t\t\tthis.expand();\n\t\t\t}\n\t\t});\n\n\t\tpromise.resolve(this.contents);\n};\n\n\n\n// IframeView.prototype.layout = function(layoutFunc) {\n//\n// this.iframe.style.display = \"inline-block\";\n//\n// // Reset Body Styles\n// // this.document.body.style.margin = \"0\";\n// //this.document.body.style.display = \"inline-block\";\n// //this.document.documentElement.style.width = \"auto\";\n//\n// if(layoutFunc){\n// this.layoutFunc = layoutFunc;\n// }\n//\n// this.contents.layout(this.layoutFunc);\n//\n// };\n//\n// IframeView.prototype.onLayout = function(view) {\n// // stub\n// };\n\nIframeView.prototype.setLayout = function(layout) {\n\tthis.layout = layout;\n};\n\nIframeView.prototype.setAxis = function(axis) {\n\tthis.settings.axis = axis;\n};\n\nIframeView.prototype.resizeListenters = function() {\n\t// Test size again\n\tclearTimeout(this.expanding);\n\tthis.expanding = setTimeout(this.expand.bind(this), 350);\n};\n\nIframeView.prototype.addListeners = function() {\n\t//TODO: Add content listeners for expanding\n};\n\nIframeView.prototype.removeListeners = function(layoutFunc) {\n\t//TODO: remove content listeners for expanding\n};\n\nIframeView.prototype.display = function(request) {\n\tvar displayed = new RSVP.defer();\n\n\tif (!this.displayed) {\n\n\t\tthis.render(request).then(function () {\n\n\t\t\tthis.trigger(\"displayed\", this);\n\t\t\tthis.onDisplayed(this);\n\n\t\t\tthis.displayed = true;\n\t\t\tdisplayed.resolve(this);\n\n\t\t}.bind(this));\n\n\t} else {\n\t\tdisplayed.resolve(this);\n\t}\n\n\n\treturn displayed.promise;\n};\n\nIframeView.prototype.show = function() {\n\n\tthis.element.style.visibility = \"visible\";\n\n\tif(this.iframe){\n\t\tthis.iframe.style.visibility = \"visible\";\n\t}\n\n\tthis.trigger(\"shown\", this);\n};\n\nIframeView.prototype.hide = function() {\n\t// this.iframe.style.display = \"none\";\n\tthis.element.style.visibility = \"hidden\";\n\tthis.iframe.style.visibility = \"hidden\";\n\n\tthis.stopExpanding = true;\n\tthis.trigger(\"hidden\", this);\n};\n\nIframeView.prototype.position = function() {\n\treturn this.element.getBoundingClientRect();\n};\n\nIframeView.prototype.locationOf = function(target) {\n\tvar parentPos = this.iframe.getBoundingClientRect();\n\tvar targetPos = this.contents.locationOf(target, this.settings.ignoreClass);\n\n\treturn {\n\t\t\"left\": window.scrollX + parentPos.left + targetPos.left,\n\t\t\"top\": window.scrollY + parentPos.top + targetPos.top\n\t};\n};\n\nIframeView.prototype.onDisplayed = function(view) {\n\t// Stub, override with a custom functions\n};\n\nIframeView.prototype.onResize = function(view, e) {\n\t// Stub, override with a custom functions\n};\n\nIframeView.prototype.bounds = function() {\n\tif(!this.elementBounds) {\n\t\tthis.elementBounds = core.bounds(this.element);\n\t}\n\treturn this.elementBounds;\n};\n\nIframeView.prototype.destroy = function() {\n\n\tif(this.displayed){\n\t\tthis.displayed = false;\n\n\t\tthis.removeListeners();\n\n\t\tthis.stopExpanding = true;\n\t\tthis.element.removeChild(this.iframe);\n\t\tthis.displayed = false;\n\t\tthis.iframe = null;\n\n\t\tthis._textWidth = null;\n\t\tthis._textHeight = null;\n\t\tthis._width = null;\n\t\tthis._height = null;\n\t}\n\t// this.element.style.height = \"0px\";\n\t// this.element.style.width = \"0px\";\n};\n\nRSVP.EventTarget.mixin(IframeView.prototype);\n\nmodule.exports = IframeView;\n","var EpubCFI = require('./epubcfi');\n\nfunction Mapping(layout){\n\tthis.layout = layout;\n};\n\nMapping.prototype.section = function(view) {\n\tvar ranges = this.findRanges(view);\n\tvar map = this.rangeListToCfiList(view.section.cfiBase, ranges);\n\n\treturn map;\n};\n\nMapping.prototype.page = function(contents, cfiBase, start, end) {\n\tvar root = contents && contents.document ? contents.document.body : false;\n\n\tif (!root) {\n\t\treturn;\n\t}\n\n\treturn this.rangePairToCfiPair(cfiBase, {\n\t\tstart: this.findStart(root, start, end),\n\t\tend: this.findEnd(root, start, end)\n\t});\n};\n\nMapping.prototype.walk = function(root, func) {\n\t//var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT + NodeFilter.SHOW_TEXT, null, false);\n\tvar treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {\n\t\t\tacceptNode: function (node) {\n\t\t\t\t\tif ( node.data.trim().length > 0 ) {\n\t\t\t\t\t\treturn NodeFilter.FILTER_ACCEPT;\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn NodeFilter.FILTER_REJECT;\n\t\t\t\t\t}\n\t\t\t}\n\t}, false);\n\tvar node;\n\tvar result;\n\twhile ((node = treeWalker.nextNode())) {\n\t\tresult = func(node);\n\t\tif(result) break;\n\t}\n\n\treturn result;\n};\n\nMapping.prototype.findRanges = function(view){\n\tvar columns = [];\n\tvar scrollWidth = view.contents.scrollWidth();\n\tvar count = this.layout.count(scrollWidth);\n\tvar column = this.layout.column;\n\tvar gap = this.layout.gap;\n\tvar start, end;\n\n\tfor (var i = 0; i < count.pages; i++) {\n\t\tstart = (column + gap) * i;\n\t\tend = (column * (i+1)) + (gap * i);\n\t\tcolumns.push({\n\t\t\tstart: this.findStart(view.document.body, start, end),\n\t\t\tend: this.findEnd(view.document.body, start, end)\n\t\t});\n\t}\n\n\treturn columns;\n};\n\nMapping.prototype.findStart = function(root, start, end){\n\tvar stack = [root];\n\tvar $el;\n\tvar found;\n\tvar $prev = root;\n\twhile (stack.length) {\n\n\t\t$el = stack.shift();\n\n\t\tfound = this.walk($el, function(node){\n\t\t\tvar left, right;\n\t\t\tvar elPos;\n\t\t\tvar elRange;\n\n\n\t\t\tif(node.nodeType == Node.TEXT_NODE){\n\t\t\t\telRange = document.createRange();\n\t\t\t\telRange.selectNodeContents(node);\n\t\t\t\telPos = elRange.getBoundingClientRect();\n\t\t\t} else {\n\t\t\t\telPos = node.getBoundingClientRect();\n\t\t\t}\n\n\t\t\tleft = elPos.left;\n\t\t\tright = elPos.right;\n\n\t\t\tif( left >= start && left <= end ) {\n\t\t\t\treturn node;\n\t\t\t} else if (right > start) {\n\t\t\t\treturn node;\n\t\t\t} else {\n\t\t\t\t$prev = node;\n\t\t\t\tstack.push(node);\n\t\t\t}\n\n\t\t});\n\n\t\tif(found) {\n\t\t\treturn this.findTextStartRange(found, start, end);\n\t\t}\n\n\t}\n\n\t// Return last element\n\treturn this.findTextStartRange($prev, start, end);\n};\n\nMapping.prototype.findEnd = function(root, start, end){\n\tvar stack = [root];\n\tvar $el;\n\tvar $prev = root;\n\tvar found;\n\n\twhile (stack.length) {\n\n\t\t$el = stack.shift();\n\n\t\tfound = this.walk($el, function(node){\n\n\t\t\tvar left, right;\n\t\t\tvar elPos;\n\t\t\tvar elRange;\n\n\n\t\t\tif(node.nodeType == Node.TEXT_NODE){\n\t\t\t\telRange = document.createRange();\n\t\t\t\telRange.selectNodeContents(node);\n\t\t\t\telPos = elRange.getBoundingClientRect();\n\t\t\t} else {\n\t\t\t\telPos = node.getBoundingClientRect();\n\t\t\t}\n\n\t\t\tleft = elPos.left;\n\t\t\tright = elPos.right;\n\n\t\t\tif(left > end && $prev) {\n\t\t\t\treturn $prev;\n\t\t\t} else if(right > end) {\n\t\t\t\treturn node;\n\t\t\t} else {\n\t\t\t\t$prev = node;\n\t\t\t\tstack.push(node);\n\t\t\t}\n\n\t\t});\n\n\n\t\tif(found){\n\t\t\treturn this.findTextEndRange(found, start, end);\n\t\t}\n\n\t}\n\n\t// end of chapter\n\treturn this.findTextEndRange($prev, start, end);\n};\n\n\nMapping.prototype.findTextStartRange = function(node, start, end){\n\tvar ranges = this.splitTextNodeIntoRanges(node);\n\tvar prev;\n\tvar range;\n\tvar pos;\n\n\tfor (var i = 0; i < ranges.length; i++) {\n\t\trange = ranges[i];\n\n\t\tpos = range.getBoundingClientRect();\n\n\t\tif( pos.left >= start ) {\n\t\t\treturn range;\n\t\t}\n\n\t\tprev = range;\n\n\t}\n\n\treturn ranges[0];\n};\n\nMapping.prototype.findTextEndRange = function(node, start, end){\n\tvar ranges = this.splitTextNodeIntoRanges(node);\n\tvar prev;\n\tvar range;\n\tvar pos;\n\n\tfor (var i = 0; i < ranges.length; i++) {\n\t\trange = ranges[i];\n\n\t\tpos = range.getBoundingClientRect();\n\n\t\tif(pos.left > end && prev) {\n\t\t\treturn prev;\n\t\t} else if(pos.right > end) {\n\t\t\treturn range;\n\t\t}\n\n\t\tprev = range;\n\n\t}\n\n\t// Ends before limit\n\treturn ranges[ranges.length-1];\n\n};\n\nMapping.prototype.splitTextNodeIntoRanges = function(node, _splitter){\n\tvar ranges = [];\n\tvar textContent = node.textContent || \"\";\n\tvar text = textContent.trim();\n\tvar range;\n\tvar rect;\n\tvar list;\n\tvar doc = node.ownerDocument;\n\tvar splitter = _splitter || \" \";\n\n\tpos = text.indexOf(splitter);\n\n\tif(pos === -1 || node.nodeType != Node.TEXT_NODE) {\n\t\trange = doc.createRange();\n\t\trange.selectNodeContents(node);\n\t\treturn [range];\n\t}\n\n\trange = doc.createRange();\n\trange.setStart(node, 0);\n\trange.setEnd(node, pos);\n\tranges.push(range);\n\trange = false;\n\n\twhile ( pos != -1 ) {\n\n\t\tpos = text.indexOf(splitter, pos + 1);\n\t\tif(pos > 0) {\n\n\t\t\tif(range) {\n\t\t\t\trange.setEnd(node, pos);\n\t\t\t\tranges.push(range);\n\t\t\t}\n\n\t\t\trange = doc.createRange();\n\t\t\trange.setStart(node, pos+1);\n\t\t}\n\t}\n\n\tif(range) {\n\t\trange.setEnd(node, text.length);\n\t\tranges.push(range);\n\t}\n\n\treturn ranges;\n};\n\n\n\nMapping.prototype.rangePairToCfiPair = function(cfiBase, rangePair){\n\n\tvar startRange = rangePair.start;\n\tvar endRange = rangePair.end;\n\n\tstartRange.collapse(true);\n\tendRange.collapse(true);\n\n\t// startCfi = section.cfiFromRange(startRange);\n\t// endCfi = section.cfiFromRange(endRange);\n\tstartCfi = new EpubCFI(startRange, cfiBase).toString();\n\tendCfi = new EpubCFI(endRange, cfiBase).toString();\n\n\treturn {\n\t\tstart: startCfi,\n\t\tend: endCfi\n\t};\n\n};\n\nMapping.prototype.rangeListToCfiList = function(cfiBase, columns){\n\tvar map = [];\n\tvar rangePair, cifPair;\n\n\tfor (var i = 0; i < columns.length; i++) {\n\t\tcifPair = this.rangePairToCfiPair(cfiBase, columns[i]);\n\n\t\tmap.push(cifPair);\n\n\t}\n\n\treturn map;\n};\n\nmodule.exports = Mapping;\n","var core = require('./core');\nvar Parser = require('./parser');\nvar RSVP = require('rsvp');\nvar URI = require('urijs');\n\nfunction Navigation(_package, _request){\n\tvar navigation = this;\n\tvar parse = new Parser();\n\tvar request = _request || require('./request');\n\n\tthis.package = _package;\n\tthis.toc = [];\n\tthis.tocByHref = {};\n\tthis.tocById = {};\n\n\tif(_package.navPath) {\n\t\tthis.navUrl = URI(_package.navPath).absoluteTo(_package.baseUrl).toString();\n\t\tthis.nav = {};\n\n\t\tthis.nav.load = function(_request){\n\t\t\tvar loading = new RSVP.defer();\n\t\t\tvar loaded = loading.promise;\n\n\t\t\trequest(navigation.navUrl, 'xml').then(function(xml){\n\t\t\t\tnavigation.toc = parse.nav(xml);\n\t\t\t\tnavigation.loaded(navigation.toc);\n\t\t\t\tloading.resolve(navigation.toc);\n\t\t\t});\n\n\t\t\treturn loaded;\n\t\t};\n\n\t}\n\n\tif(_package.ncxPath) {\n\t\tthis.ncxUrl = URI(_package.ncxPath).absoluteTo(_package.baseUrl).toString();\n\t\tthis.ncx = {};\n\n\t\tthis.ncx.load = function(_request){\n\t\t\tvar loading = new RSVP.defer();\n\t\t\tvar loaded = loading.promise;\n\n\t\t\trequest(navigation.ncxUrl, 'xml').then(function(xml){\n\t\t\t\tnavigation.toc = parse.toc(xml);\n\t\t\t\tnavigation.loaded(navigation.toc);\n\t\t\t\tloading.resolve(navigation.toc);\n\t\t\t});\n\n\t\t\treturn loaded;\n\t\t};\n\n\t}\n};\n\n// Load the navigation\nNavigation.prototype.load = function(_request) {\n\tvar request = _request || require('./request');\n\tvar loading, loaded;\n\n\tif(this.nav) {\n\t\tloading = this.nav.load();\n\t} else if(this.ncx) {\n\t\tloading = this.ncx.load();\n\t} else {\n\t\tloaded = new RSVP.defer();\n\t\tloaded.resolve([]);\n\t\tloading = loaded.promise;\n\t}\n\n\treturn loading;\n\n};\n\nNavigation.prototype.loaded = function(toc) {\n\tvar item;\n\n\tfor (var i = 0; i < toc.length; i++) {\n\t\titem = toc[i];\n\t\tthis.tocByHref[item.href] = i;\n\t\tthis.tocById[item.id] = i;\n\t}\n\n};\n\n// Get an item from the navigation\nNavigation.prototype.get = function(target) {\n\tvar index;\n\n\tif(!target) {\n\t\treturn this.toc;\n\t}\n\n\tif(target.indexOf(\"#\") === 0) {\n\t\tindex = this.tocById[target.substring(1)];\n\t} else if(target in this.tocByHref){\n\t\tindex = this.tocByHref[target];\n\t}\n\n\treturn this.toc[index];\n};\n\nmodule.exports = Navigation;\n","var URI = require('urijs');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\n\n\nfunction Parser(){};\n\nParser.prototype.container = function(containerXml){\n\t\t//-- \n\t\tvar rootfile, fullpath, folder, encoding;\n\n\t\tif(!containerXml) {\n\t\t\tconsole.error(\"Container File Not Found\");\n\t\t\treturn;\n\t\t}\n\n\t\trootfile = core.qs(containerXml, \"rootfile\");\n\n\t\tif(!rootfile) {\n\t\t\tconsole.error(\"No RootFile Found\");\n\t\t\treturn;\n\t\t}\n\n\t\tfullpath = rootfile.getAttribute('full-path');\n\t\tfolder = URI(fullpath).directory();\n\t\tencoding = containerXml.xmlEncoding;\n\n\t\t//-- Now that we have the path we can parse the contents\n\t\treturn {\n\t\t\t'packagePath' : fullpath,\n\t\t\t'basePath' : folder,\n\t\t\t'encoding' : encoding\n\t\t};\n};\n\nParser.prototype.identifier = function(packageXml){\n\tvar metadataNode;\n\n\tif(!packageXml) {\n\t\tconsole.error(\"Package File Not Found\");\n\t\treturn;\n\t}\n\n\tmetadataNode = core.qs(packageXml, \"metadata\");\n\n\tif(!metadataNode) {\n\t\tconsole.error(\"No Metadata Found\");\n\t\treturn;\n\t}\n\n\treturn this.getElementText(metadataNode, \"identifier\");\n};\n\nParser.prototype.packageContents = function(packageXml){\n\tvar parse = this;\n\tvar metadataNode, manifestNode, spineNode;\n\tvar manifest, navPath, ncxPath, coverPath;\n\tvar spineNodeIndex;\n\tvar spine;\n\tvar spineIndexByURL;\n\tvar metadata;\n\n\tif(!packageXml) {\n\t\tconsole.error(\"Package File Not Found\");\n\t\treturn;\n\t}\n\n\tmetadataNode = core.qs(packageXml, \"metadata\");\n\tif(!metadataNode) {\n\t\tconsole.error(\"No Metadata Found\");\n\t\treturn;\n\t}\n\n\tmanifestNode = core.qs(packageXml, \"manifest\");\n\tif(!manifestNode) {\n\t\tconsole.error(\"No Manifest Found\");\n\t\treturn;\n\t}\n\n\tspineNode = core.qs(packageXml, \"spine\");\n\tif(!spineNode) {\n\t\tconsole.error(\"No Spine Found\");\n\t\treturn;\n\t}\n\n\tmanifest = parse.manifest(manifestNode);\n\tnavPath = parse.findNavPath(manifestNode);\n\tncxPath = parse.findNcxPath(manifestNode, spineNode);\n\tcoverPath = parse.findCoverPath(packageXml);\n\n\tspineNodeIndex = Array.prototype.indexOf.call(spineNode.parentNode.childNodes, spineNode);\n\n\tspine = parse.spine(spineNode, manifest);\n\n\tmetadata = parse.metadata(metadataNode);\n\n\tmetadata.direction = spineNode.getAttribute(\"page-progression-direction\");\n\n\treturn {\n\t\t'metadata' : metadata,\n\t\t'spine' : spine,\n\t\t'manifest' : manifest,\n\t\t'navPath' : navPath,\n\t\t'ncxPath' : ncxPath,\n\t\t'coverPath': coverPath,\n\t\t'spineNodeIndex' : spineNodeIndex\n\t};\n};\n\n//-- Find TOC NAV\nParser.prototype.findNavPath = function(manifestNode){\n\t// Find item with property 'nav'\n\t// Should catch nav irregardless of order\n\t// var node = manifestNode.querySelector(\"item[properties$='nav'], item[properties^='nav '], item[properties*=' nav ']\");\n\tvar node = core.qsp(manifestNode, \"item\", {\"properties\":\"nav\"});\n\treturn node ? node.getAttribute('href') : false;\n};\n\n//-- Find TOC NCX: media-type=\"application/x-dtbncx+xml\" href=\"toc.ncx\"\nParser.prototype.findNcxPath = function(manifestNode, spineNode){\n\t// var node = manifestNode.querySelector(\"item[media-type='application/x-dtbncx+xml']\");\n\tvar node = core.qsp(manifestNode, \"item\", {\"media-type\":\"application/x-dtbncx+xml\"});\n\tvar tocId;\n\n\t// If we can't find the toc by media-type then try to look for id of the item in the spine attributes as\n\t// according to http://www.idpf.org/epub/20/spec/OPF_2.0.1_draft.htm#Section2.4.1.2,\n\t// \"The item that describes the NCX must be referenced by the spine toc attribute.\"\n\tif (!node) {\n\t\ttocId = spineNode.getAttribute(\"toc\");\n\t\tif(tocId) {\n\t\t\t// node = manifestNode.querySelector(\"item[id='\" + tocId + \"']\");\n\t\t\tnode = manifestNode.getElementById(tocId);\n\t\t}\n\t}\n\n\treturn node ? node.getAttribute('href') : false;\n};\n\n//-- Expanded to match Readium web components\nParser.prototype.metadata = function(xml){\n\tvar metadata = {},\n\t\t\tp = this;\n\n\tmetadata.title = p.getElementText(xml, 'title');\n\tmetadata.creator = p.getElementText(xml, 'creator');\n\tmetadata.description = p.getElementText(xml, 'description');\n\n\tmetadata.pubdate = p.getElementText(xml, 'date');\n\n\tmetadata.publisher = p.getElementText(xml, 'publisher');\n\n\tmetadata.identifier = p.getElementText(xml, \"identifier\");\n\tmetadata.language = p.getElementText(xml, \"language\");\n\tmetadata.rights = p.getElementText(xml, \"rights\");\n\n\tmetadata.modified_date = p.getPropertyText(xml, 'dcterms:modified');\n\n\tmetadata.layout = p.getPropertyText(xml, \"rendition:layout\");\n\tmetadata.orientation = p.getPropertyText(xml, 'rendition:orientation');\n\tmetadata.flow = p.getPropertyText(xml, 'rendition:flow');\n\tmetadata.viewport = p.getPropertyText(xml, 'rendition:viewport');\n\t// metadata.page_prog_dir = packageXml.querySelector(\"spine\").getAttribute(\"page-progression-direction\");\n\n\treturn metadata;\n};\n\n//-- Find Cover: \n//-- Fallback for Epub 2.0\nParser.prototype.findCoverPath = function(packageXml){\n\tvar pkg = core.qs(packageXml, \"package\");\n\tvar epubVersion = pkg.getAttribute('version');\n\n\tif (epubVersion === '2.0') {\n\t\tvar metaCover = core.qsp(packageXml, 'meta', {'name':'cover'});\n\t\tif (metaCover) {\n\t\t\tvar coverId = metaCover.getAttribute('content');\n\t\t\t// var cover = packageXml.querySelector(\"item[id='\" + coverId + \"']\");\n\t\t\tvar cover = packageXml.getElementById(coverId);\n\t\t\treturn cover ? cover.getAttribute('href') : false;\n\t\t}\n\t\telse {\n\t\t\treturn false;\n\t\t}\n\t}\n\telse {\n\t\t// var node = packageXml.querySelector(\"item[properties='cover-image']\");\n\t\tvar node = core.qsp(packageXml, 'item', {'properties':'cover-image'});\n\t\treturn node ? node.getAttribute('href') : false;\n\t}\n};\n\nParser.prototype.getElementText = function(xml, tag){\n\tvar found = xml.getElementsByTagNameNS(\"http://purl.org/dc/elements/1.1/\", tag),\n\t\tel;\n\n\tif(!found || found.length === 0) return '';\n\n\tel = found[0];\n\n\tif(el.childNodes.length){\n\t\treturn el.childNodes[0].nodeValue;\n\t}\n\n\treturn '';\n\n};\n\nParser.prototype.getPropertyText = function(xml, property){\n\tvar el = core.qsp(xml, \"meta\", {\"property\":property});\n\n\tif(el && el.childNodes.length){\n\t\treturn el.childNodes[0].nodeValue;\n\t}\n\n\treturn '';\n};\n\nParser.prototype.querySelectorText = function(xml, q){\n\tvar el = xml.querySelector(q);\n\n\tif(el && el.childNodes.length){\n\t\treturn el.childNodes[0].nodeValue;\n\t}\n\n\treturn '';\n};\n\nParser.prototype.manifest = function(manifestXml){\n\tvar manifest = {};\n\n\t//-- Turn items into an array\n\t// var selected = manifestXml.querySelectorAll(\"item\");\n\tvar selected = core.qsa(manifestXml, \"item\");\n\tvar items = Array.prototype.slice.call(selected);\n\n\t//-- Create an object with the id as key\n\titems.forEach(function(item){\n\t\tvar id = item.getAttribute('id'),\n\t\t\t\thref = item.getAttribute('href') || '',\n\t\t\t\ttype = item.getAttribute('media-type') || '',\n\t\t\t\tproperties = item.getAttribute('properties') || '';\n\n\t\tmanifest[id] = {\n\t\t\t'href' : href,\n\t\t\t// 'url' : href,\n\t\t\t'type' : type,\n\t\t\t'properties' : properties.length ? properties.split(' ') : []\n\t\t};\n\n\t});\n\n\treturn manifest;\n\n};\n\nParser.prototype.spine = function(spineXml, manifest){\n\tvar spine = [];\n\n\tvar selected = spineXml.getElementsByTagName(\"itemref\"),\n\t\t\titems = Array.prototype.slice.call(selected);\n\n\tvar epubcfi = new EpubCFI();\n\n\t//-- Add to array to mantain ordering and cross reference with manifest\n\titems.forEach(function(item, index){\n\t\tvar idref = item.getAttribute('idref');\n\t\t// var cfiBase = epubcfi.generateChapterComponent(spineNodeIndex, index, Id);\n\t\tvar props = item.getAttribute('properties') || '';\n\t\tvar propArray = props.length ? props.split(' ') : [];\n\t\t// var manifestProps = manifest[Id].properties;\n\t\t// var manifestPropArray = manifestProps.length ? manifestProps.split(' ') : [];\n\n\t\tvar itemref = {\n\t\t\t'idref' : idref,\n\t\t\t'linear' : item.getAttribute('linear') || '',\n\t\t\t'properties' : propArray,\n\t\t\t// 'href' : manifest[Id].href,\n\t\t\t// 'url' : manifest[Id].url,\n\t\t\t'index' : index\n\t\t\t// 'cfiBase' : cfiBase\n\t\t};\n\t\tspine.push(itemref);\n\t});\n\n\treturn spine;\n};\n\nParser.prototype.querySelectorByType = function(html, element, type){\n\tvar query;\n\tif (typeof html.querySelector != \"undefined\") {\n\t\tquery = html.querySelector(element+'[*|type=\"'+type+'\"]');\n\t}\n\t// Handle IE not supporting namespaced epub:type in querySelector\n\tif(!query || query.length === 0) {\n\t\tquery = core.qsa(html, element);\n\t\tfor (var i = 0; i < query.length; i++) {\n\t\t\tif(query[i].getAttributeNS(\"http://www.idpf.org/2007/ops\", \"type\") === type) {\n\t\t\t\treturn query[i];\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn query;\n\t}\n};\n\nParser.prototype.nav = function(navHtml, spineIndexByURL, bookSpine){\n\tvar navElement = this.querySelectorByType(navHtml, \"nav\", \"toc\");\n\t// var navItems = navElement ? navElement.querySelectorAll(\"ol li\") : [];\n\tvar navItems = navElement ? core.qsa(navElement, \"li\") : [];\n\tvar length = navItems.length;\n\tvar i;\n\tvar toc = {};\n\tvar list = [];\n\tvar item, parent;\n\n\tif(!navItems || length === 0) return list;\n\n\tfor (i = 0; i < length; ++i) {\n\t\titem = this.navItem(navItems[i], spineIndexByURL, bookSpine);\n\t\ttoc[item.id] = item;\n\t\tif(!item.parent) {\n\t\t\tlist.push(item);\n\t\t} else {\n\t\t\tparent = toc[item.parent];\n\t\t\tparent.subitems.push(item);\n\t\t}\n\t}\n\n\treturn list;\n};\n\nParser.prototype.navItem = function(item, spineIndexByURL, bookSpine){\n\tvar id = item.getAttribute('id') || false,\n\t\t\t// content = item.querySelector(\"a, span\"),\n\t\t\tcontent = core.qs(item, \"a\"),\n\t\t\tsrc = content.getAttribute('href') || '',\n\t\t\ttext = content.textContent || \"\",\n\t\t\t// split = src.split(\"#\"),\n\t\t\t// baseUrl = split[0],\n\t\t\t// spinePos = spineIndexByURL[baseUrl],\n\t\t\t// spineItem = bookSpine[spinePos],\n\t\t\tsubitems = [],\n\t\t\tparentNode = item.parentNode,\n\t\t\tparent;\n\t\t\t// cfi = spineItem ? spineItem.cfi : '';\n\n\tif(parentNode && parentNode.nodeName === \"navPoint\") {\n\t\tparent = parentNode.getAttribute('id');\n\t}\n\n\t/*\n\tif(!id) {\n\t\tif(spinePos) {\n\t\t\tspineItem = bookSpine[spinePos];\n\t\t\tid = spineItem.id;\n\t\t\tcfi = spineItem.cfi;\n\t\t} else {\n\t\t\tid = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid();\n\t\t\titem.setAttribute('id', id);\n\t\t}\n\t}\n\t*/\n\n\treturn {\n\t\t\"id\": id,\n\t\t\"href\": src,\n\t\t\"label\": text,\n\t\t\"subitems\" : subitems,\n\t\t\"parent\" : parent\n\t};\n};\n\nParser.prototype.ncx = function(tocXml, spineIndexByURL, bookSpine){\n\t// var navPoints = tocXml.querySelectorAll(\"navMap navPoint\");\n\tvar navPoints = core.qsa(tocXml, \"navPoint\");\n\tvar length = navPoints.length;\n\tvar i;\n\tvar toc = {};\n\tvar list = [];\n\tvar item, parent;\n\n\tif(!navPoints || length === 0) return list;\n\n\tfor (i = 0; i < length; ++i) {\n\t\titem = this.ncxItem(navPoints[i], spineIndexByURL, bookSpine);\n\t\ttoc[item.id] = item;\n\t\tif(!item.parent) {\n\t\t\tlist.push(item);\n\t\t} else {\n\t\t\tparent = toc[item.parent];\n\t\t\tparent.subitems.push(item);\n\t\t}\n\t}\n\n\treturn list;\n};\n\nParser.prototype.ncxItem = function(item, spineIndexByURL, bookSpine){\n\tvar id = item.getAttribute('id') || false,\n\t\t\t// content = item.querySelector(\"content\"),\n\t\t\tcontent = core.qs(item, \"content\"),\n\t\t\tsrc = content.getAttribute('src'),\n\t\t\t// navLabel = item.querySelector(\"navLabel\"),\n\t\t\tnavLabel = core.qs(item, \"navLabel\"),\n\t\t\ttext = navLabel.textContent ? navLabel.textContent : \"\",\n\t\t\t// split = src.split(\"#\"),\n\t\t\t// baseUrl = split[0],\n\t\t\t// spinePos = spineIndexByURL[baseUrl],\n\t\t\t// spineItem = bookSpine[spinePos],\n\t\t\tsubitems = [],\n\t\t\tparentNode = item.parentNode,\n\t\t\tparent;\n\t\t\t// cfi = spineItem ? spineItem.cfi : '';\n\n\tif(parentNode && parentNode.nodeName === \"navPoint\") {\n\t\tparent = parentNode.getAttribute('id');\n\t}\n\n\t/*\n\tif(!id) {\n\t\tif(spinePos) {\n\t\t\tspineItem = bookSpine[spinePos];\n\t\t\tid = spineItem.id;\n\t\t\tcfi = spineItem.cfi;\n\t\t} else {\n\t\t\tid = 'epubjs-autogen-toc-id-' + EPUBJS.core.uuid();\n\t\t\titem.setAttribute('id', id);\n\t\t}\n\t}\n\t*/\n\n\treturn {\n\t\t\"id\": id,\n\t\t\"href\": src,\n\t\t\"label\": text,\n\t\t\"subitems\" : subitems,\n\t\t\"parent\" : parent\n\t};\n};\n\nParser.prototype.pageList = function(navHtml, spineIndexByURL, bookSpine){\n\tvar navElement = this.querySelectorByType(navHtml, \"nav\", \"page-list\");\n\t// var navItems = navElement ? navElement.querySelectorAll(\"ol li\") : [];\n\tvar navItems = navElement ? core.qsa(navElement, \"li\") : [];\n\tvar length = navItems.length;\n\tvar i;\n\tvar toc = {};\n\tvar list = [];\n\tvar item;\n\n\tif(!navItems || length === 0) return list;\n\n\tfor (i = 0; i < length; ++i) {\n\t\titem = this.pageListItem(navItems[i], spineIndexByURL, bookSpine);\n\t\tlist.push(item);\n\t}\n\n\treturn list;\n};\n\nParser.prototype.pageListItem = function(item, spineIndexByURL, bookSpine){\n\tvar id = item.getAttribute('id') || false,\n\t\t// content = item.querySelector(\"a\"),\n\t\tcontent = core.qs(item, \"a\"),\n\t\thref = content.getAttribute('href') || '',\n\t\ttext = content.textContent || \"\",\n\t\tpage = parseInt(text),\n\t\tisCfi = href.indexOf(\"epubcfi\"),\n\t\tsplit,\n\t\tpackageUrl,\n\t\tcfi;\n\n\tif(isCfi != -1) {\n\t\tsplit = href.split(\"#\");\n\t\tpackageUrl = split[0];\n\t\tcfi = split.length > 1 ? split[1] : false;\n\t\treturn {\n\t\t\t\"cfi\" : cfi,\n\t\t\t\"href\" : href,\n\t\t\t\"packageUrl\" : packageUrl,\n\t\t\t\"page\" : page\n\t\t};\n\t} else {\n\t\treturn {\n\t\t\t\"href\" : href,\n\t\t\t\"page\" : page\n\t\t};\n\t}\n};\n\nmodule.exports = Parser;\n","var RSVP = require('rsvp');\nvar core = require('./core');\n\nfunction Queue(_context){\n\tthis._q = [];\n\tthis.context = _context;\n\tthis.tick = core.requestAnimationFrame;\n\tthis.running = false;\n\tthis.paused = false;\n};\n\n// Add an item to the queue\nQueue.prototype.enqueue = function() {\n\tvar deferred, promise;\n\tvar queued;\n\tvar task = [].shift.call(arguments);\n\tvar args = arguments;\n\n\t// Handle single args without context\n\t// if(args && !Array.isArray(args)) {\n\t// args = [args];\n\t// }\n\tif(!task) {\n\t\treturn console.error(\"No Task Provided\");\n\t}\n\n\tif(typeof task === \"function\"){\n\n\t\tdeferred = new RSVP.defer();\n\t\tpromise = deferred.promise;\n\n\t\tqueued = {\n\t\t\t\"task\" : task,\n\t\t\t\"args\" : args,\n\t\t\t//\"context\" : context,\n\t\t\t\"deferred\" : deferred,\n\t\t\t\"promise\" : promise\n\t\t};\n\n\t} else {\n\t\t// Task is a promise\n\t\tqueued = {\n\t\t\t\"promise\" : task\n\t\t};\n\n\t}\n\n\tthis._q.push(queued);\n\n\t// Wait to start queue flush\n\tif (this.paused == false && !this.running) {\n\t\t// setTimeout(this.flush.bind(this), 0);\n\t\t// this.tick.call(window, this.run.bind(this));\n\t\tthis.run();\n\t}\n\n\treturn queued.promise;\n};\n\n// Run one item\nQueue.prototype.dequeue = function(){\n\tvar inwait, task, result;\n\n\tif(this._q.length) {\n\t\tinwait = this._q.shift();\n\t\ttask = inwait.task;\n\t\tif(task){\n\t\t\t// console.log(task)\n\n\t\t\tresult = task.apply(this.context, inwait.args);\n\n\t\t\tif(result && typeof result[\"then\"] === \"function\") {\n\t\t\t\t// Task is a function that returns a promise\n\t\t\t\treturn result.then(function(){\n\t\t\t\t\tinwait.deferred.resolve.apply(this.context, arguments);\n\t\t\t\t}.bind(this));\n\t\t\t} else {\n\t\t\t\t// Task resolves immediately\n\t\t\t\tinwait.deferred.resolve.apply(this.context, result);\n\t\t\t\treturn inwait.promise;\n\t\t\t}\n\n\n\n\t\t} else if(inwait.promise) {\n\t\t\t// Task is a promise\n\t\t\treturn inwait.promise;\n\t\t}\n\n\t} else {\n\t\tinwait = new RSVP.defer();\n\t\tinwait.deferred.resolve();\n\t\treturn inwait.promise;\n\t}\n\n};\n\n// Run All Immediately\nQueue.prototype.dump = function(){\n\twhile(this._q.length) {\n\t\tthis.dequeue();\n\t}\n};\n\n// Run all sequentially, at convince\n\nQueue.prototype.run = function(){\n\n\tif(!this.running){\n\t\tthis.running = true;\n\t\tthis.defered = new RSVP.defer();\n\t}\n\n\tthis.tick.call(window, function() {\n\n\t\tif(this._q.length) {\n\n\t\t\tthis.dequeue()\n\t\t\t\t.then(function(){\n\t\t\t\t\tthis.run();\n\t\t\t\t}.bind(this));\n\n\t\t} else {\n\t\t\tthis.defered.resolve();\n\t\t\tthis.running = undefined;\n\t\t}\n\n\t}.bind(this));\n\n\t// Unpause\n\tif(this.paused == true) {\n\t\tthis.paused = false;\n\t}\n\n\treturn this.defered.promise;\n};\n\n// Flush all, as quickly as possible\nQueue.prototype.flush = function(){\n\n\tif(this.running){\n\t\treturn this.running;\n\t}\n\n\tif(this._q.length) {\n\t\tthis.running = this.dequeue()\n\t\t\t.then(function(){\n\t\t\t\tthis.running = undefined;\n\t\t\t\treturn this.flush();\n\t\t\t}.bind(this));\n\n\t\treturn this.running;\n\t}\n\n};\n\n// Clear all items in wait\nQueue.prototype.clear = function(){\n\tthis._q = [];\n\tthis.running = false;\n};\n\nQueue.prototype.length = function(){\n\treturn this._q.length;\n};\n\nQueue.prototype.pause = function(){\n\tthis.paused = true;\n};\n\n// Create a new task from a callback\nfunction Task(task, args, context){\n\n\treturn function(){\n\t\tvar toApply = arguments || [];\n\n\t\treturn new RSVP.Promise(function(resolve, reject) {\n\t\t\tvar callback = function(value){\n\t\t\t\tresolve(value);\n\t\t\t};\n\t\t\t// Add the callback to the arguments list\n\t\t\ttoApply.push(callback);\n\n\t\t\t// Apply all arguments to the functions\n\t\t\ttask.apply(this, toApply);\n\n\t}.bind(this));\n\n\t};\n\n};\n\nmodule.exports = Queue;\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar replace = require('./replacements');\nvar Hook = require('./hook');\nvar EpubCFI = require('./epubcfi');\nvar Queue = require('./queue');\nvar Layout = require('./layout');\nvar Mapping = require('./mapping');\n\nfunction Rendition(book, options) {\n\n\tthis.settings = core.extend(this.settings || {}, {\n\t\twidth: null,\n\t\theight: null,\n\t\tignoreClass: '',\n\t\tmanager: \"single\",\n\t\tview: \"iframe\",\n\t\tflow: null,\n\t\tlayout: null,\n\t\tspread: null,\n\t\tminSpreadWidth: 800, //-- overridden by spread: none (never) / both (always),\n\t\tuseBase64: true\n\t});\n\n\tcore.extend(this.settings, options);\n\n\tthis.viewSettings = {\n\t\tignoreClass: this.settings.ignoreClass\n\t};\n\n\tthis.book = book;\n\n\tthis.views = null;\n\n\t//-- Adds Hook methods to the Rendition prototype\n\tthis.hooks = {};\n\tthis.hooks.display = new Hook(this);\n\tthis.hooks.serialize = new Hook(this);\n\tthis.hooks.content = new Hook(this);\n\tthis.hooks.layout = new Hook(this);\n\tthis.hooks.render = new Hook(this);\n\tthis.hooks.show = new Hook(this);\n\n\tthis.hooks.content.register(replace.links.bind(this));\n\tthis.hooks.content.register(this.passViewEvents.bind(this));\n\n\t// this.hooks.display.register(this.afterDisplay.bind(this));\n\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.q = new Queue(this);\n\n\tthis.q.enqueue(this.book.opened);\n\n\t// Block the queue until rendering is started\n\t// this.starting = new RSVP.defer();\n\t// this.started = this.starting.promise;\n\tthis.q.enqueue(this.start);\n\n\tif(this.book.unarchived) {\n\t\tthis.q.enqueue(this.replacements.bind(this));\n\t}\n\n};\n\nRendition.prototype.setManager = function(manager) {\n\tthis.manager = manager;\n};\n\nRendition.prototype.requireManager = function(manager) {\n\tvar viewManager;\n\n\t// If manager is a string, try to load from register managers,\n\t// or require included managers directly\n\tif (typeof manager === \"string\") {\n\t\t// Use global or require\n\t\tviewManager = typeof ePub != \"undefined\" ? ePub.ViewManagers[manager] : undefined; //require('./managers/'+manager);\n\t} else {\n\t\t// otherwise, assume we were passed a function\n\t\tviewManager = manager\n\t}\n\n\treturn viewManager;\n};\n\nRendition.prototype.requireView = function(view) {\n\tvar View;\n\n\tif (typeof view == \"string\") {\n\t\tView = typeof ePub != \"undefined\" ? ePub.Views[view] : undefined; //require('./views/'+view);\n\t} else {\n\t\t// otherwise, assume we were passed a function\n\t\tView = view\n\t}\n\n\treturn View;\n};\n\nRendition.prototype.start = function(){\n\n\tif(!this.manager) {\n\t\tthis.ViewManager = this.requireManager(this.settings.manager);\n\t\tthis.View = this.requireView(this.settings.view);\n\n\t\tthis.manager = new this.ViewManager({\n\t\t\tview: this.View,\n\t\t\tqueue: this.q,\n\t\t\trequest: this.book.request,\n\t\t\tsettings: this.settings\n\t\t});\n\t}\n\n\t// Parse metadata to get layout props\n\tthis.settings.globalLayoutProperties = this.determineLayoutProperties(this.book.package.metadata);\n\n\tthis.flow(this.settings.globalLayoutProperties.flow);\n\n\tthis.layout(this.settings.globalLayoutProperties);\n\n\t// Listen for displayed views\n\tthis.manager.on(\"added\", this.afterDisplayed.bind(this));\n\n\t// Listen for resizing\n\tthis.manager.on(\"resized\", this.onResized.bind(this));\n\n\t// Listen for scroll changes\n\tthis.manager.on(\"scroll\", this.reportLocation.bind(this));\n\n\n\tthis.on('displayed', this.reportLocation.bind(this));\n\n\t// Trigger that rendering has started\n\tthis.trigger(\"started\");\n\n\t// Start processing queue\n\t// this.starting.resolve();\n};\n\n// Call to attach the container to an element in the dom\n// Container must be attached before rendering can begin\nRendition.prototype.attachTo = function(element){\n\n\treturn this.q.enqueue(function () {\n\n\t\t// Start rendering\n\t\tthis.manager.render(element, {\n\t\t\t\"width\" : this.settings.width,\n\t\t\t\"height\" : this.settings.height\n\t\t});\n\n\t\t// Trigger Attached\n\t\tthis.trigger(\"attached\");\n\n\t}.bind(this));\n\n};\n\nRendition.prototype.display = function(target){\n\n\t// if (!this.book.spine.spineItems.length > 0) {\n\t\t// Book isn't open yet\n\t\t// return this.q.enqueue(this.display, target);\n\t// }\n\n\treturn this.q.enqueue(this._display, target);\n\n};\n\nRendition.prototype._display = function(target){\n\tvar isCfiString = this.epubcfi.isCfiString(target);\n\tvar displaying = new RSVP.defer();\n\tvar displayed = displaying.promise;\n\tvar section;\n\tvar moveTo;\n\n\tsection = this.book.spine.get(target);\n\n\tif(!section){\n\t\tdisplaying.reject(new Error(\"No Section Found\"));\n\t\treturn displayed;\n\t}\n\n\t// Trim the target fragment\n\t// removing the chapter\n\tif(!isCfiString && typeof target === \"string\" &&\n\t\ttarget.indexOf(\"#\") > -1) {\n\t\t\tmoveTo = target.substring(target.indexOf(\"#\")+1);\n\t}\n\n\tif (isCfiString) {\n\t\tmoveTo = target;\n\t}\n\n\treturn this.manager.display(section, moveTo)\n\t\t.then(function(){\n\t\t\tthis.trigger(\"displayed\", section);\n\t\t}.bind(this));\n\n};\n\n/*\nRendition.prototype.render = function(view, show) {\n\n\t// view.onLayout = this.layout.format.bind(this.layout);\n\tview.create();\n\n\t// Fit to size of the container, apply padding\n\tthis.manager.resizeView(view);\n\n\t// Render Chain\n\treturn view.section.render(this.book.request)\n\t\t.then(function(contents){\n\t\t\treturn view.load(contents);\n\t\t}.bind(this))\n\t\t.then(function(doc){\n\t\t\treturn this.hooks.content.trigger(view, this);\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\tthis.layout.format(view.contents);\n\t\t\treturn this.hooks.layout.trigger(view, this);\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\treturn view.display();\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\treturn this.hooks.render.trigger(view, this);\n\t\t}.bind(this))\n\t\t.then(function(){\n\t\t\tif(show !== false) {\n\t\t\t\tthis.q.enqueue(function(view){\n\t\t\t\t\tview.show();\n\t\t\t\t}, view);\n\t\t\t}\n\t\t\t// this.map = new Map(view, this.layout);\n\t\t\tthis.hooks.show.trigger(view, this);\n\t\t\tthis.trigger(\"rendered\", view.section);\n\n\t\t}.bind(this))\n\t\t.catch(function(e){\n\t\t\tthis.trigger(\"loaderror\", e);\n\t\t}.bind(this));\n\n};\n*/\n\nRendition.prototype.afterDisplayed = function(view){\n\tthis.hooks.content.trigger(view, this);\n\tthis.trigger(\"rendered\", view.section);\n\tthis.reportLocation();\n};\n\nRendition.prototype.onResized = function(size){\n\n\tif(this.location) {\n\t\tthis.display(this.location.start);\n\t}\n\n\tthis.trigger(\"resized\", {\n\t\twidth: size.width,\n\t\theight: size.height\n\t});\n\n};\n\nRendition.prototype.moveTo = function(offset){\n\tthis.manager.moveTo(offset);\n};\n\nRendition.prototype.next = function(){\n\treturn this.q.enqueue(this.manager.next.bind(this.manager))\n\t\t.then(this.reportLocation.bind(this));\n};\n\nRendition.prototype.prev = function(){\n\treturn this.q.enqueue(this.manager.prev.bind(this.manager))\n\t\t.then(this.reportLocation.bind(this));\n};\n\n//-- http://www.idpf.org/epub/301/spec/epub-publications.html#meta-properties-rendering\nRendition.prototype.determineLayoutProperties = function(metadata){\n\tvar settings;\n\tvar layout = this.settings.layout || metadata.layout || \"reflowable\";\n\tvar spread = this.settings.spread || metadata.spread || \"auto\";\n\tvar orientation = this.settings.orientation || metadata.orientation || \"auto\";\n\tvar flow = this.settings.flow || metadata.flow || \"auto\";\n\tvar viewport = metadata.viewport || \"\";\n\tvar minSpreadWidth = this.settings.minSpreadWidth || metadata.minSpreadWidth || 800;\n\n\tif (this.settings.width >= 0 && this.settings.height >= 0) {\n\t\tviewport = \"width=\"+this.settings.width+\", height=\"+this.settings.height+\"\";\n\t}\n\n\tsettings = {\n\t\tlayout : layout,\n\t\tspread : spread,\n\t\torientation : orientation,\n\t\tflow : flow,\n\t\tviewport : viewport,\n\t\tminSpreadWidth : minSpreadWidth\n\t};\n\n\treturn settings;\n};\n\n// Rendition.prototype.applyLayoutProperties = function(){\n// \tvar settings = this.determineLayoutProperties(this.book.package.metadata);\n//\n// \tthis.flow(settings.flow);\n//\n// \tthis.layout(settings);\n// };\n\n// paginated | scrolled\n// (scrolled-continuous vs scrolled-doc are handled by different view managers)\nRendition.prototype.flow = function(_flow){\n\tvar flow;\n\tif (_flow === \"scrolled-doc\" || _flow === \"scrolled-continuous\") {\n\t\tflow = \"scrolled\";\n\t}\n\n\tif (_flow === \"auto\" || _flow === \"paginated\") {\n\t\tflow = \"paginated\";\n\t}\n\n\tif (this._layout) {\n\t\tthis._layout.flow(flow);\n\t}\n\n\tif (this.manager) {\n\t\tthis.manager.updateFlow(flow);\n\t}\n};\n\n// reflowable | pre-paginated\nRendition.prototype.layout = function(settings){\n\tif (settings) {\n\t\tthis._layout = new Layout(settings);\n\t\tthis._layout.spread(settings.spread, this.settings.minSpreadWidth);\n\n\t\tthis.mapping = new Mapping(this._layout);\n\t}\n\n\tif (this.manager && this._layout) {\n\t\tthis.manager.applyLayout(this._layout);\n\t}\n\n\treturn this._layout;\n};\n\n// none | auto (TODO: implement landscape, portrait, both)\nRendition.prototype.spread = function(spread, min){\n\n\tthis._layout.spread(spread, min);\n\n\tif (this.manager.isRendered()) {\n\t\tthis.manager.updateLayout();\n\t}\n};\n\n\nRendition.prototype.reportLocation = function(){\n\treturn this.q.enqueue(function(){\n\t\tvar location = this.manager.currentLocation();\n\t\tif (location && location.then && typeof location.then === 'function') {\n\t\t\tlocation.then(function(result) {\n\t\t\t\tthis.location = result;\n\t\t\t\tthis.trigger(\"locationChanged\", this.location);\n\t\t\t}.bind(this));\n\t\t} else if (location) {\n\t\t\tthis.location = location;\n\t\t\tthis.trigger(\"locationChanged\", this.location);\n\t\t}\n\n\t}.bind(this));\n};\n\n\nRendition.prototype.destroy = function(){\n\t// Clear the queue\n\tthis.q.clear();\n\n\tthis.manager.destroy();\n};\n\nRendition.prototype.passViewEvents = function(view){\n\tview.contents.listenedEvents.forEach(function(e){\n\t\tview.on(e, this.triggerViewEvent.bind(this));\n\t}.bind(this));\n\n\tview.on(\"selected\", this.triggerSelectedEvent.bind(this));\n};\n\nRendition.prototype.triggerViewEvent = function(e){\n\tthis.trigger(e.type, e);\n};\n\nRendition.prototype.triggerSelectedEvent = function(cfirange){\n\tthis.trigger(\"selected\", cfirange);\n};\n\nRendition.prototype.replacements = function(){\n\t// Wait for loading\n\t// return this.q.enqueue(function () {\n\t\t// Get thes books manifest\n\t\tvar manifest = this.book.package.manifest;\n\t\tvar manifestArray = Object.keys(manifest).\n\t\t\tmap(function (key){\n\t\t\t\treturn manifest[key];\n\t\t\t});\n\n\t\t// Exclude HTML\n\t\tvar items = manifestArray.\n\t\t\tfilter(function (item){\n\t\t\t\tif (item.type != \"application/xhtml+xml\" &&\n\t\t\t\t\t\titem.type != \"text/html\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Only CSS\n\t\tvar css = items.\n\t\t\tfilter(function (item){\n\t\t\t\tif (item.type === \"text/css\") {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Css Urls\n\t\tvar cssUrls = css.map(function(item) {\n\t\t\treturn item.href;\n\t\t});\n\n\t\t// All Assets Urls\n\t\tvar urls = items.\n\t\t\tmap(function(item) {\n\t\t\t\treturn item.href;\n\t\t\t}.bind(this));\n\n\t\t// Create blob urls for all the assets\n\t\tvar processing = urls.\n\t\t\tmap(function(url) {\n\t\t\t\tvar absolute = URI(url).absoluteTo(this.book.baseUrl).toString();\n\t\t\t\t// Full url from archive base\n\t\t\t\treturn this.book.unarchived.createUrl(absolute, {\"base64\": this.settings.useBase64});\n\t\t\t}.bind(this));\n\n\t\tvar replacementUrls;\n\n\t\t// After all the urls are created\n\t\treturn RSVP.all(processing)\n\t\t\t.then(function(_replacementUrls) {\n\t\t\t\tvar replaced = [];\n\n\t\t\t\treplacementUrls = _replacementUrls;\n\n\t\t\t\t// Replace Asset Urls in the text of all css files\n\t\t\t\tcssUrls.forEach(function(href) {\n\t\t\t\t\treplaced.push(this.replaceCss(href, urls, replacementUrls));\n\t\t\t\t}.bind(this));\n\n\t\t\t\treturn RSVP.all(replaced);\n\n\t\t\t}.bind(this))\n\t\t\t.then(function () {\n\t\t\t\t// Replace Asset Urls in chapters\n\t\t\t\t// by registering a hook after the sections contents has been serialized\n\t\t\t\tthis.book.spine.hooks.serialize.register(function(output, section) {\n\n\t\t\t\t\tthis.replaceAssets(section, urls, replacementUrls);\n\n\t\t\t\t}.bind(this));\n\n\t\t\t}.bind(this))\n\t\t\t.catch(function(reason){\n\t\t\t\tconsole.error(reason);\n\t\t\t});\n\t// }.bind(this));\n};\n\nRendition.prototype.replaceCss = function(href, urls, replacementUrls){\n\t\tvar newUrl;\n\t\tvar indexInUrls;\n\n\t\t// Find the absolute url of the css file\n\t\tvar fileUri = URI(href);\n\t\tvar absolute = fileUri.absoluteTo(this.book.baseUrl).toString();\n\t\t// Get the text of the css file from the archive\n\t\tvar textResponse = this.book.unarchived.getText(absolute);\n\t\t// Get asset links relative to css file\n\t\tvar relUrls = urls.\n\t\t\tmap(function(assetHref) {\n\t\t\t\tvar assetUri = URI(assetHref).absoluteTo(this.book.baseUrl);\n\t\t\t\tvar relative = assetUri.relativeTo(absolute).toString();\n\t\t\t\treturn relative;\n\t\t\t}.bind(this));\n\n\t\treturn textResponse.then(function (text) {\n\t\t\t// Replacements in the css text\n\t\t\ttext = replace.substitute(text, relUrls, replacementUrls);\n\n\t\t\t// Get the new url\n\t\t\tif (this.settings.useBase64) {\n\t\t\t\tnewUrl = core.createBase64Url(text, 'text/css');\n\t\t\t} else {\n\t\t\t\tnewUrl = core.createBlobUrl(text, 'text/css');\n\t\t\t}\n\n\t\t\t// switch the url in the replacementUrls\n\t\t\tindexInUrls = urls.indexOf(href);\n\t\t\tif (indexInUrls > -1) {\n\t\t\t\treplacementUrls[indexInUrls] = newUrl;\n\t\t\t}\n\n\t\t\treturn new RSVP.Promise(function(resolve, reject){\n\t\t\t\tresolve(urls, replacementUrls);\n\t\t\t});\n\n\t\t}.bind(this));\n\n};\n\nRendition.prototype.replaceAssets = function(section, urls, replacementUrls){\n\tvar fileUri = URI(section.url);\n\t// Get Urls relative to current sections\n\tvar relUrls = urls.\n\t\tmap(function(href) {\n\t\t\tvar assetUri = URI(href).absoluteTo(this.book.baseUrl);\n\t\t\tvar relative = assetUri.relativeTo(fileUri).toString();\n\t\t\treturn relative;\n\t\t}.bind(this));\n\n\n\tsection.output = replace.substitute(section.output, relUrls, replacementUrls);\n};\n\nRendition.prototype.range = function(_cfi, ignoreClass){\n\tvar cfi = new EpubCFI(_cfi);\n\tvar found = this.visible().filter(function (view) {\n\t\tif(cfi.spinePos === view.index) return true;\n\t});\n\n\t// Should only every return 1 item\n\tif (found.length) {\n\t\treturn found[0].range(cfi, ignoreClass);\n\t}\n};\n\nRendition.prototype.adjustImages = function(view) {\n\n\tview.addStylesheetRules([\n\t\t\t[\"img\",\n\t\t\t\t[\"max-width\", (view.layout.spreadWidth) + \"px\"],\n\t\t\t\t[\"max-height\", (view.layout.height) + \"px\"]\n\t\t\t]\n\t]);\n\treturn new RSVP.Promise(function(resolve, reject){\n\t\t// Wait to apply\n\t\tsetTimeout(function() {\n\t\t\tresolve();\n\t\t}, 1);\n\t});\n};\n\n//-- Enable binding events to Renderer\nRSVP.EventTarget.mixin(Rendition.prototype);\n\nmodule.exports = Rendition;\n","var URI = require('urijs');\nvar core = require('./core');\n\nfunction base(doc, section){\n\tvar base;\n\tvar head;\n\n\tif(!doc){\n\t\treturn;\n\t}\n\n\t// head = doc.querySelector(\"head\");\n\t// base = head.querySelector(\"base\");\n\thead = core.qs(doc, \"head\");\n\tbase = core.qs(head, \"base\");\n\n\tif(!base) {\n\t\tbase = doc.createElement(\"base\");\n\t\thead.insertBefore(base, head.firstChild);\n\t}\n\n\tbase.setAttribute(\"href\", section.url);\n}\n\nfunction canonical(doc, section){\n\tvar head;\n\tvar link;\n\tvar url = section.url; // window.location.origin + window.location.pathname + \"?loc=\" + encodeURIComponent(section.url);\n\n\tif(!doc){\n\t\treturn;\n\t}\n\n\thead = core.qs(doc, \"head\");\n\tlink = core.qs(head, \"link[rel='canonical']\");\n\n\tif (link) {\n\t\tlink.setAttribute(\"href\", url);\n\t} else {\n\t\tlink = doc.createElement(\"link\");\n\t\tlink.setAttribute(\"rel\", \"canonical\");\n\t\tlink.setAttribute(\"href\", url);\n\t\thead.appendChild(link);\n\t}\n}\n\nfunction links(view, renderer) {\n\n\tvar links = view.document.querySelectorAll(\"a[href]\");\n\tvar replaceLinks = function(link){\n\t\tvar href = link.getAttribute(\"href\");\n\n\t\tif(href.indexOf(\"mailto:\") === 0){\n\t\t\treturn;\n\t\t}\n\n\t\tvar linkUri = URI(href);\n\t\tvar absolute = linkUri.absoluteTo(view.section.url);\n\t\tvar relative = absolute.relativeTo(this.book.baseUrl).toString();\n\n\t\tif(linkUri.protocol()){\n\n\t\t\tlink.setAttribute(\"target\", \"_blank\");\n\n\t\t}else{\n\t\t\t/*\n\t\t\tif(baseDirectory) {\n\t\t\t\t// We must ensure that the file:// protocol is preserved for\n\t\t\t\t// local file links, as in certain contexts (such as under\n\t\t\t\t// Titanium), file links without the file:// protocol will not\n\t\t\t\t// work\n\t\t\t\tif (baseUri.protocol === \"file\") {\n\t\t\t\t\trelative = core.resolveUrl(baseUri.base, href);\n\t\t\t\t} else {\n\t\t\t\t\trelative = core.resolveUrl(baseDirectory, href);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trelative = href;\n\t\t\t}\n\t\t\t*/\n\n\t\t\tif(linkUri.fragment()) {\n\t\t\t\t// do nothing with fragment yet\n\t\t\t} else {\n\t\t\t\tlink.onclick = function(){\n\t\t\t\t\trenderer.display(relative);\n\t\t\t\t\treturn false;\n\t\t\t\t};\n\t\t\t}\n\n\t\t}\n\t}.bind(this);\n\n\tfor (var i = 0; i < links.length; i++) {\n\t\treplaceLinks(links[i]);\n\t}\n\n\n};\n\nfunction substitute(content, urls, replacements) {\n\turls.forEach(function(url, i){\n\t\tif (url && replacements[i]) {\n\t\t\tcontent = content.replace(new RegExp(url, 'g'), replacements[i]);\n\t\t}\n\t});\n\treturn content;\n}\nmodule.exports = {\n\t'base': base,\n\t'canonical' : canonical,\n\t'links': links,\n\t'substitute': substitute\n};\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\n\nfunction request(url, type, withCredentials, headers) {\n\tvar supportsURL = (typeof window != \"undefined\") ? window.URL : false; // TODO: fallback for url if window isn't defined\n\tvar BLOB_RESPONSE = supportsURL ? \"blob\" : \"arraybuffer\";\n\tvar uri;\n\n\tvar deferred = new RSVP.defer();\n\n\tvar xhr = new XMLHttpRequest();\n\n\t//-- Check from PDF.js:\n\t// https://github.com/mozilla/pdf.js/blob/master/web/compatibility.js\n\tvar xhrPrototype = XMLHttpRequest.prototype;\n\n\tvar header;\n\n\tif (!('overrideMimeType' in xhrPrototype)) {\n\t\t// IE10 might have response, but not overrideMimeType\n\t\tObject.defineProperty(xhrPrototype, 'overrideMimeType', {\n\t\t\tvalue: function xmlHttpRequestOverrideMimeType(mimeType) {}\n\t\t});\n\t}\n\tif(withCredentials) {\n\t\txhr.withCredentials = true;\n\t}\n\n\txhr.onreadystatechange = handler;\n\txhr.onerror = err;\n\n\txhr.open(\"GET\", url, true);\n\n\tfor(header in headers) {\n\t\txhr.setRequestHeader(header, headers[header]);\n\t}\n\n\tif(type == \"json\") {\n\t\txhr.setRequestHeader(\"Accept\", \"application/json\");\n\t}\n\n\t// If type isn't set, determine it from the file extension\n\tif(!type) {\n\t\turi = URI(url);\n\t\ttype = uri.suffix();\n\t}\n\n\tif(type == 'blob'){\n\t\txhr.responseType = BLOB_RESPONSE;\n\t}\n\n\n\tif(core.isXml(type)) {\n\t\t// xhr.responseType = \"document\";\n\t\txhr.overrideMimeType('text/xml'); // for OPF parsing\n\t}\n\n\tif(type == 'xhtml') {\n\t\t// xhr.responseType = \"document\";\n\t}\n\n\tif(type == 'html' || type == 'htm') {\n\t\t// xhr.responseType = \"document\";\n\t }\n\n\tif(type == \"binary\") {\n\t\txhr.responseType = \"arraybuffer\";\n\t}\n\n\txhr.send();\n\n\tfunction err(e) {\n\t\tconsole.error(e);\n\t\tdeferred.reject(e);\n\t}\n\n\tfunction handler() {\n\t\tif (this.readyState === XMLHttpRequest.DONE) {\n\n\t\t\tif (this.status === 200 || this.responseXML ) { //-- Firefox is reporting 0 for blob urls\n\t\t\t\tvar r;\n\n\t\t\t\tif (!this.response && !this.responseXML) {\n\t\t\t\t\tdeferred.reject({\n\t\t\t\t\t\tstatus: this.status,\n\t\t\t\t\t\tmessage : \"Empty Response\",\n\t\t\t\t\t\tstack : new Error().stack\n\t\t\t\t\t});\n\t\t\t\t\treturn deferred.promise;\n\t\t\t\t}\n\n\t\t\t\tif (this.status === 403) {\n\t\t\t\t\tdeferred.reject({\n\t\t\t\t\t\tstatus: this.status,\n\t\t\t\t\t\tresponse: this.response,\n\t\t\t\t\t\tmessage : \"Forbidden\",\n\t\t\t\t\t\tstack : new Error().stack\n\t\t\t\t\t});\n\t\t\t\t\treturn deferred.promise;\n\t\t\t\t}\n\n\t\t\t\tif((this.responseType == '' || this.responseType == 'document')\n\t\t\t\t\t\t&& this.responseXML){\n\t\t\t\t\tr = this.responseXML;\n\t\t\t\t} else\n\t\t\t\tif(core.isXml(type)){\n\t\t\t\t\t// xhr.overrideMimeType('text/xml'); // for OPF parsing\n\t\t\t\t\t// If this.responseXML wasn't set, try to parse using a DOMParser from text\n\t\t\t\t\tr = core.parse(this.response, \"text/xml\");\n\t\t\t\t}else\n\t\t\t\tif(type == 'xhtml'){\n\t\t\t\t\tr = core.parse(this.response, \"application/xhtml+xml\");\n\t\t\t\t}else\n\t\t\t\tif(type == 'html' || type == 'htm'){\n\t\t\t\t\tr = core.parse(this.response, \"text/html\");\n\t\t\t\t}else\n\t\t\t\tif(type == 'json'){\n\t\t\t\t\tr = JSON.parse(this.response);\n\t\t\t\t}else\n\t\t\t\tif(type == 'blob'){\n\n\t\t\t\t\tif(supportsURL) {\n\t\t\t\t\t\tr = this.response;\n\t\t\t\t\t} else {\n\t\t\t\t\t\t//-- Safari doesn't support responseType blob, so create a blob from arraybuffer\n\t\t\t\t\t\tr = new Blob([this.response]);\n\t\t\t\t\t}\n\n\t\t\t\t}else{\n\t\t\t\t\tr = this.response;\n\t\t\t\t}\n\n\t\t\t\tdeferred.resolve(r);\n\t\t\t} else {\n\n\t\t\t\tdeferred.reject({\n\t\t\t\t\tstatus: this.status,\n\t\t\t\t\tmessage : this.response,\n\t\t\t\t\tstack : new Error().stack\n\t\t\t\t});\n\n\t\t\t}\n\t\t}\n\t}\n\n\treturn deferred.promise;\n};\n\nmodule.exports = request;\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\nvar Hook = require('./hook');\n\nfunction Section(item, hooks){\n\t\tthis.idref = item.idref;\n\t\tthis.linear = item.linear;\n\t\tthis.properties = item.properties;\n\t\tthis.index = item.index;\n\t\tthis.href = item.href;\n\t\tthis.url = item.url;\n\t\tthis.next = item.next;\n\t\tthis.prev = item.prev;\n\n\t\tthis.cfiBase = item.cfiBase;\n\n\t\tif (hooks) {\n\t\t\tthis.hooks = hooks;\n\t\t} else {\n\t\t\tthis.hooks = {};\n\t\t\tthis.hooks.serialize = new Hook(this);\n\t\t\tthis.hooks.content = new Hook(this);\n\t\t}\n\n};\n\n\nSection.prototype.load = function(_request){\n\tvar request = _request || this.request || require('./request');\n\tvar loading = new RSVP.defer();\n\tvar loaded = loading.promise;\n\n\tif(this.contents) {\n\t\tloading.resolve(this.contents);\n\t} else {\n\t\trequest(this.url)\n\t\t\t.then(function(xml){\n\t\t\t\tvar base;\n\t\t\t\tvar directory = URI(this.url).directory();\n\n\t\t\t\tthis.document = xml;\n\t\t\t\tthis.contents = xml.documentElement;\n\n\t\t\t\treturn this.hooks.content.trigger(this.document, this);\n\t\t\t}.bind(this))\n\t\t\t.then(function(){\n\t\t\t\tloading.resolve(this.contents);\n\t\t\t}.bind(this))\n\t\t\t.catch(function(error){\n\t\t\t\tloading.reject(error);\n\t\t\t});\n\t}\n\n\treturn loaded;\n};\n\nSection.prototype.base = function(_document){\n\t\tvar task = new RSVP.defer();\n\t\tvar base = _document.createElement(\"base\"); // TODO: check if exists\n\t\tvar head;\n\t\tconsole.log(window.location.origin + \"/\" +this.url);\n\n\t\tbase.setAttribute(\"href\", window.location.origin + \"/\" +this.url);\n\n\t\tif(_document) {\n\t\t\thead = _document.querySelector(\"head\");\n\t\t}\n\t\tif(head) {\n\t\t\thead.insertBefore(base, head.firstChild);\n\t\t\ttask.resolve();\n\t\t} else {\n\t\t\ttask.reject(new Error(\"No head to insert into\"));\n\t\t}\n\n\n\t\treturn task.promise;\n};\n\nSection.prototype.beforeSectionLoad = function(){\n\t// Stub for a hook - replace me for now\n};\n\nSection.prototype.render = function(_request){\n\tvar rendering = new RSVP.defer();\n\tvar rendered = rendering.promise;\n\tthis.output; // TODO: better way to return this from hooks?\n\n\tthis.load(_request).\n\t\tthen(function(contents){\n\t\t\tvar serializer;\n\n\t\t\tif (typeof XMLSerializer === \"undefined\") {\n\t\t\t\tXMLSerializer = require('xmldom').XMLSerializer;\n\t\t\t}\n\t\t\tserializer = new XMLSerializer();\n\t\t\tthis.output = serializer.serializeToString(contents);\n\t\t\treturn this.output;\n\t\t}.bind(this)).\n\t\tthen(function(){\n\t\t\treturn this.hooks.serialize.trigger(this.output, this);\n\t\t}.bind(this)).\n\t\tthen(function(){\n\t\t\trendering.resolve(this.output);\n\t\t}.bind(this))\n\t\t.catch(function(error){\n\t\t\trendering.reject(error);\n\t\t});\n\n\treturn rendered;\n};\n\nSection.prototype.find = function(_query){\n\n};\n\n/**\n* Reconciles the current chapters layout properies with\n* the global layout properities.\n* Takes: global layout settings object, chapter properties string\n* Returns: Object with layout properties\n*/\nSection.prototype.reconcileLayoutSettings = function(global){\n\t//-- Get the global defaults\n\tvar settings = {\n\t\tlayout : global.layout,\n\t\tspread : global.spread,\n\t\torientation : global.orientation\n\t};\n\n\t//-- Get the chapter's display type\n\tthis.properties.forEach(function(prop){\n\t\tvar rendition = prop.replace(\"rendition:\", '');\n\t\tvar split = rendition.indexOf(\"-\");\n\t\tvar property, value;\n\n\t\tif(split != -1){\n\t\t\tproperty = rendition.slice(0, split);\n\t\t\tvalue = rendition.slice(split+1);\n\n\t\t\tsettings[property] = value;\n\t\t}\n\t});\n return settings;\n};\n\nSection.prototype.cfiFromRange = function(_range) {\n\treturn new EpubCFI(_range, this.cfiBase).toString();\n};\n\nSection.prototype.cfiFromElement = function(el) {\n\treturn new EpubCFI(el, this.cfiBase).toString();\n};\n\nmodule.exports = Section;\n","var RSVP = require('rsvp');\nvar core = require('./core');\nvar EpubCFI = require('./epubcfi');\nvar Hook = require('./hook');\nvar Section = require('./section');\nvar replacements = require('./replacements');\n\nfunction Spine(_request){\n\tthis.request = _request;\n\tthis.spineItems = [];\n\tthis.spineByHref = {};\n\tthis.spineById = {};\n\n\tthis.hooks = {};\n\tthis.hooks.serialize = new Hook();\n\tthis.hooks.content = new Hook();\n\n\t// Register replacements\n\tthis.hooks.content.register(replacements.base);\n\tthis.hooks.content.register(replacements.canonical);\n\n\tthis.epubcfi = new EpubCFI();\n\n\tthis.loaded = false;\n};\n\nSpine.prototype.load = function(_package) {\n\n\tthis.items = _package.spine;\n\tthis.manifest = _package.manifest;\n\tthis.spineNodeIndex = _package.spineNodeIndex;\n\tthis.baseUrl = _package.baseUrl || '';\n\tthis.length = this.items.length;\n\n\tthis.items.forEach(function(item, index){\n\t\tvar href, url;\n\t\tvar manifestItem = this.manifest[item.idref];\n\t\tvar spineItem;\n\n\t\titem.cfiBase = this.epubcfi.generateChapterComponent(this.spineNodeIndex, item.index, item.idref);\n\n\t\tif(manifestItem) {\n\t\t\titem.href = manifestItem.href;\n\t\t\titem.url = this.baseUrl + item.href;\n\n\t\t\tif(manifestItem.properties.length){\n\t\t\t\titem.properties.push.apply(item.properties, manifestItem.properties);\n\t\t\t}\n\t\t}\n\n\t\t// if(index > 0) {\n\t\t\titem.prev = function(){ return this.get(index-1); }.bind(this);\n\t\t// }\n\n\t\t// if(index+1 < this.items.length) {\n\t\t\titem.next = function(){ return this.get(index+1); }.bind(this);\n\t\t// }\n\n\t\tspineItem = new Section(item, this.hooks);\n\n\t\tthis.append(spineItem);\n\n\n\t}.bind(this));\n\n\tthis.loaded = true;\n};\n\n// book.spine.get();\n// book.spine.get(1);\n// book.spine.get(\"chap1.html\");\n// book.spine.get(\"#id1234\");\nSpine.prototype.get = function(target) {\n\tvar index = 0;\n\n\tif(this.epubcfi.isCfiString(target)) {\n\t\tcfi = new EpubCFI(target);\n\t\tindex = cfi.spinePos;\n\t} else if(target && (typeof target === \"number\" || isNaN(target) === false)){\n\t\tindex = target;\n\t} else if(target && target.indexOf(\"#\") === 0) {\n\t\tindex = this.spineById[target.substring(1)];\n\t} else if(target) {\n\t\t// Remove fragments\n\t\ttarget = target.split(\"#\")[0];\n\t\tindex = this.spineByHref[target];\n\t}\n\n\treturn this.spineItems[index] || null;\n};\n\nSpine.prototype.append = function(section) {\n\tvar index = this.spineItems.length;\n\tsection.index = index;\n\n\tthis.spineItems.push(section);\n\n\tthis.spineByHref[section.href] = index;\n\tthis.spineById[section.idref] = index;\n\n\treturn index;\n};\n\nSpine.prototype.prepend = function(section) {\n\tvar index = this.spineItems.unshift(section);\n\tthis.spineByHref[section.href] = 0;\n\tthis.spineById[section.idref] = 0;\n\n\t// Re-index\n\tthis.spineItems.forEach(function(item, index){\n\t\titem.index = index;\n\t});\n\n\treturn 0;\n};\n\nSpine.prototype.insert = function(section, index) {\n\n};\n\nSpine.prototype.remove = function(section) {\n\tvar index = this.spineItems.indexOf(section);\n\n\tif(index > -1) {\n\t\tdelete this.spineByHref[section.href];\n\t\tdelete this.spineById[section.idref];\n\n\t\treturn this.spineItems.splice(index, 1);\n\t}\n};\n\nSpine.prototype.each = function() {\n\treturn this.spineItems.forEach.apply(this.spineItems, arguments);\n};\n\nmodule.exports = Spine;\n","var RSVP = require('rsvp');\nvar URI = require('urijs');\nvar core = require('./core');\nvar request = require('./request');\nvar mime = require('../libs/mime/mime');\n\nfunction Unarchive() {\n\n\tthis.checkRequirements();\n\tthis.urlCache = {};\n\n}\n\nUnarchive.prototype.checkRequirements = function(callback){\n\ttry {\n\t\tif (typeof JSZip !== 'undefined') {\n\t\t\tthis.zip = new JSZip();\n\t\t} else {\n\t\t\tJSZip = require('jszip');\n\t\t\tthis.zip = new JSZip();\n\t\t}\n\t} catch (e) {\n\t\tconsole.error(\"JSZip lib not loaded\");\n\t}\n};\n\nUnarchive.prototype.open = function(zipUrl, isBase64){\n\tif (zipUrl instanceof ArrayBuffer || isBase64) {\n\t\treturn this.zip.loadAsync(zipUrl, {\"base64\": isBase64});\n\t} else {\n\t\treturn request(zipUrl, \"binary\")\n\t\t\t.then(function(data){\n\t\t\t\treturn this.zip.loadAsync(data);\n\t\t\t}.bind(this));\n\t}\n};\n\nUnarchive.prototype.request = function(url, type){\n\tvar deferred = new RSVP.defer();\n\tvar response;\n\tvar r;\n\n\t// If type isn't set, determine it from the file extension\n\tif(!type) {\n\t\turi = URI(url);\n\t\ttype = uri.suffix();\n\t}\n\n\tif(type == 'blob'){\n\t\tresponse = this.getBlob(url);\n\t} else {\n\t\tresponse = this.getText(url);\n\t}\n\n\tif (response) {\n\t\tresponse.then(function (r) {\n\t\t\tresult = this.handleResponse(r, type);\n\t\t\tdeferred.resolve(result);\n\t\t}.bind(this));\n\t} else {\n\t\tdeferred.reject({\n\t\t\tmessage : \"File not found in the epub: \" + url,\n\t\t\tstack : new Error().stack\n\t\t});\n\t}\n\treturn deferred.promise;\n};\n\nUnarchive.prototype.handleResponse = function(response, type){\n\tvar r;\n\n\tif(type == \"json\") {\n\t\tr = JSON.parse(response);\n\t}\n\telse\n\tif(core.isXml(type)) {\n\t\tr = core.parse(response, \"text/xml\");\n\t}\n\telse\n\tif(type == 'xhtml') {\n\t\tr = core.parse(response, \"application/xhtml+xml\");\n\t}\n\telse\n\tif(type == 'html' || type == 'htm') {\n\t\tr = core.parse(response, \"text/html\");\n\t } else {\n\t\t r = response;\n\t }\n\n\treturn r;\n};\n\nUnarchive.prototype.getBlob = function(url, _mimeType){\n\tvar decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash\n\tvar entry = this.zip.file(decodededUrl);\n\tvar mimeType;\n\n\tif(entry) {\n\t\tmimeType = _mimeType || mime.lookup(entry.name);\n\t\treturn entry.async(\"uint8array\").then(function(uint8array) {\n\t\t\treturn new Blob([uint8array], {type : mimeType});\n\t\t});\n\t}\n};\n\nUnarchive.prototype.getText = function(url, encoding){\n\tvar decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash\n\tvar entry = this.zip.file(decodededUrl);\n\n\tif(entry) {\n\t\treturn entry.async(\"string\").then(function(text) {\n\t\t\treturn text;\n\t\t});\n\t}\n};\n\nUnarchive.prototype.getBase64 = function(url, _mimeType){\n\tvar decodededUrl = window.decodeURIComponent(url.substr(1)); // Remove first slash\n\tvar entry = this.zip.file(decodededUrl);\n\tvar mimeType;\n\n\tif(entry) {\n\t\tmimeType = _mimeType || mime.lookup(entry.name);\n\t\treturn entry.async(\"base64\").then(function(data) {\n\t\t\treturn \"data:\" + mimeType + \";base64,\" + data;\n\t\t});\n\t}\n};\n\nUnarchive.prototype.createUrl = function(url, options){\n\tvar deferred = new RSVP.defer();\n\tvar _URL = window.URL || window.webkitURL || window.mozURL;\n\tvar tempUrl;\n\tvar blob;\n\tvar response;\n\tvar useBase64 = options && options.base64;\n\n\tif(url in this.urlCache) {\n\t\tdeferred.resolve(this.urlCache[url]);\n\t\treturn deferred.promise;\n\t}\n\n\tif (useBase64) {\n\t\tresponse = this.getBase64(url);\n\n\t\tif (response) {\n\t\t\tresponse.then(function(tempUrl) {\n\n\t\t\t\tthis.urlCache[url] = tempUrl;\n\t\t\t\tdeferred.resolve(tempUrl);\n\n\t\t\t}.bind(this));\n\n\t\t}\n\n\t} else {\n\n\t\tresponse = this.getBlob(url);\n\n\t\tif (response) {\n\t\t\tresponse.then(function(blob) {\n\n\t\t\t\ttempUrl = _URL.createObjectURL(blob);\n\t\t\t\tthis.urlCache[url] = tempUrl;\n\t\t\t\tdeferred.resolve(tempUrl);\n\n\t\t\t}.bind(this));\n\n\t\t}\n\t}\n\n\n\tif (!response) {\n\t\tdeferred.reject({\n\t\t\tmessage : \"File not found in the epub: \" + url,\n\t\t\tstack : new Error().stack\n\t\t});\n\t}\n\n\treturn deferred.promise;\n};\n\nUnarchive.prototype.revokeUrl = function(url){\n\tvar _URL = window.URL || window.webkitURL || window.mozURL;\n\tvar fromCache = this.urlCache[url];\n\tif(fromCache) _URL.revokeObjectURL(fromCache);\n};\n\nmodule.exports = Unarchive;\n","var Book = require('./book');\nvar EpubCFI = require('./epubcfi');\nvar Rendition = require('./rendition');\nvar Contents = require('./contents');\nvar RSVP = require('rsvp');\n\nfunction ePub(_url) {\n\treturn new Book(_url);\n};\n\nePub.VERSION = \"0.3.0\";\n\nePub.CFI = EpubCFI;\nePub.Rendition = Rendition;\nePub.Contents = Contents;\nePub.RSVP = RSVP;\n\nePub.ViewManagers = {};\nePub.Views = {};\nePub.register = {\n\tmanager : function(name, manager){\n\t\treturn ePub.ViewManagers[name] = manager;\n\t},\n\tview : function(name, view){\n\t\treturn ePub.Views[name] = view;\n\t}\n};\n\n// Default Views\nePub.register.view(\"iframe\", require('./managers/views/iframe'));\n// ePub.register.view(\"inline\", require('./managers/views/inline'));\n\n// Default View Managers\nePub.register.manager(\"single\", require('./managers/single'));\nePub.register.manager(\"continuous\", require('./managers/continuous'));\n\nmodule.exports = ePub;\n"]} \ No newline at end of file diff --git a/src/epub.js b/src/epub.js index 161017f..1ab7d9b 100644 --- a/src/epub.js +++ b/src/epub.js @@ -27,8 +27,8 @@ ePub.register = { }; // Default Views -ePub.register.view("iframe", require('./views/iframe')); -// ePub.register.view("inline", require('./views/inline')); +ePub.register.view("iframe", require('./managers/views/iframe')); +// ePub.register.view("inline", require('./managers/views/inline')); // Default View Managers ePub.register.manager("single", require('./managers/single')); diff --git a/src/stage.js b/src/managers/helpers/stage.js similarity index 99% rename from src/stage.js rename to src/managers/helpers/stage.js index 2e167ba..fb3d2fe 100644 --- a/src/stage.js +++ b/src/managers/helpers/stage.js @@ -1,4 +1,4 @@ -var core = require('./core'); +var core = require('../../core'); function Stage(_options) { this.settings = _options || {}; diff --git a/src/views.js b/src/managers/helpers/views.js similarity index 100% rename from src/views.js rename to src/managers/helpers/views.js diff --git a/src/managers/single.js b/src/managers/single.js index 11f034b..81a1dd5 100644 --- a/src/managers/single.js +++ b/src/managers/single.js @@ -1,11 +1,11 @@ var RSVP = require('rsvp'); var core = require('../core'); -var Stage = require('../stage'); -var Views = require('../views'); var EpubCFI = require('../epubcfi'); // var Layout = require('../layout'); var Mapping = require('../mapping'); var Queue = require('../queue'); +var Stage = require('./helpers/stage'); +var Views = require('./helpers/views'); function SingleViewManager(options) { @@ -89,6 +89,16 @@ SingleViewManager.prototype.destroy = function(){ // this.views.each(function(view){ // view.destroy(); // }); + + /* + + clearTimeout(this.trimTimeout); + if(this.settings.hidden) { + this.element.removeChild(this.wrapper); + } else { + this.element.removeChild(this.container); + } + */ }; SingleViewManager.prototype.onResized = function(e) { diff --git a/src/views/iframe.js b/src/managers/views/iframe.js similarity index 99% rename from src/views/iframe.js rename to src/managers/views/iframe.js index 4bf59ab..f470715 100644 --- a/src/views/iframe.js +++ b/src/managers/views/iframe.js @@ -1,7 +1,7 @@ var RSVP = require('rsvp'); -var core = require('../core'); -var EpubCFI = require('../epubcfi'); -var Contents = require('../contents'); +var core = require('../../core'); +var EpubCFI = require('../../epubcfi'); +var Contents = require('../../contents'); function IframeView(section, options) { this.settings = core.extend({ diff --git a/src/views/inline.js b/src/managers/views/inline.js similarity index 98% rename from src/views/inline.js rename to src/managers/views/inline.js index ade5a04..0ad3a42 100644 --- a/src/views/inline.js +++ b/src/managers/views/inline.js @@ -1,7 +1,7 @@ var RSVP = require('rsvp'); -var core = require('../core'); -var EpubCFI = require('../epubcfi'); -var Contents = require('../contents'); +var core = require('../../core'); +var EpubCFI = require('../../epubcfi'); +var Contents = require('../../contents'); var URI = require('urijs'); function InlineView(section, options) { diff --git a/src/rendition.js b/src/rendition.js index d27e0b8..fe321a0 100644 --- a/src/rendition.js +++ b/src/rendition.js @@ -5,8 +5,6 @@ var replace = require('./replacements'); var Hook = require('./hook'); var EpubCFI = require('./epubcfi'); var Queue = require('./queue'); -// var View = require('./view'); -var Views = require('./views'); var Layout = require('./layout'); var Mapping = require('./mapping'); @@ -382,15 +380,7 @@ Rendition.prototype.destroy = function(){ // Clear the queue this.q.clear(); - this.views.clear(); - - clearTimeout(this.trimTimeout); - if(this.settings.hidden) { - this.element.removeChild(this.wrapper); - } else { - this.element.removeChild(this.container); - } - + this.manager.destroy(); }; Rendition.prototype.passViewEvents = function(view){