diff --git a/minerva_analysis/client/.gitignore b/minerva_analysis/client/.gitignore index adbb97d2d..56668cac3 100644 --- a/minerva_analysis/client/.gitignore +++ b/minerva_analysis/client/.gitignore @@ -1 +1,5 @@ -data/ \ No newline at end of file +data/ +.editorconfig +.eslintignore +.eslintrc.json +tsconfig.json diff --git a/minerva_analysis/client/dist/vendor_bundle.js b/minerva_analysis/client/dist/vendor_bundle.js index 446d2e167..14c312ba2 100644 --- a/minerva_analysis/client/dist/vendor_bundle.js +++ b/minerva_analysis/client/dist/vendor_bundle.js @@ -7121,7 +7121,7 @@ eval("/*\nobject-assign\n(c) Sindre Sorhus\n@license MIT\n*/\n\n\n/* eslint-disa /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { -eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;//! openseadragon 2.3.1\n//! Built on 2021-08-24\n//! Git commit: --88a3858\n//! http://openseadragon.github.io\n//! License: http://openseadragon.github.io/license/\n\n/*\n * OpenSeadragon\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Portions of this source file taken from jQuery:\n *\n * Copyright 2011 John Resig\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/*\n * Portions of this source file taken from mattsnider.com:\n *\n * Copyright (c) 2006-2013 Matt Snider\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT\n * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR\n * THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n\n/**\n * @namespace OpenSeadragon\n * @version openseadragon 2.3.1\n * @classdesc The root namespace for OpenSeadragon. All utility methods\n * and classes are defined on or below this namespace.\n *\n */\n\n\n// Typedefs\n\n /**\n * All required and optional settings for instantiating a new instance of an OpenSeadragon image viewer.\n *\n * @typedef {Object} Options\n * @memberof OpenSeadragon\n *\n * @property {String} id\n * Id of the element to append the viewer's container element to. If not provided, the 'element' property must be provided.\n * If both the element and id properties are specified, the viewer is appended to the element provided in the element property.\n *\n * @property {Element} element\n * The element to append the viewer's container element to. If not provided, the 'id' property must be provided.\n * If both the element and id properties are specified, the viewer is appended to the element provided in the element property.\n *\n * @property {Array|String|Function|Object} [tileSources=null]\n * Tile source(s) to open initially. This is a complex parameter; see\n * {@link OpenSeadragon.Viewer#open} for details.\n *\n * @property {Number} [tabIndex=0]\n * Tabbing order index to assign to the viewer element. Positive values are selected in increasing order. When tabIndex is 0\n * source order is used. A negative value omits the viewer from the tabbing order.\n *\n * @property {Array} overlays Array of objects defining permanent overlays of\n * the viewer. The overlays added via this option and later removed with\n * {@link OpenSeadragon.Viewer#removeOverlay} will be added back when a new\n * image is opened.\n * To add overlays which can be definitively removed, one must use\n * {@link OpenSeadragon.Viewer#addOverlay}\n * If displaying a sequence of images, the overlays can be associated\n * with a specific page by passing the overlays array to the page's\n * tile source configuration.\n * Expected properties:\n * * x, y, (or px, py for pixel coordinates) to define the location.\n * * width, height in point if using x,y or in pixels if using px,py. If width\n * and height are specified, the overlay size is adjusted when zooming,\n * otherwise the size stays the size of the content (or the size defined by CSS).\n * * className to associate a class to the overlay\n * * id to set the overlay element. If an element with this id already exists,\n * it is reused, otherwise it is created. If not specified, a new element is\n * created.\n * * placement a string to define the relative position to the viewport.\n * Only used if no width and height are specified. Default: 'TOP_LEFT'.\n * See {@link OpenSeadragon.Placement} for possible values.\n *\n * @property {String} [xmlPath=null]\n * DEPRECATED. A relative path to load a DZI file from the server.\n * Prefer the newer Options.tileSources.\n *\n * @property {String} [prefixUrl='/images/']\n * Prepends the prefixUrl to navImages paths, which is very useful\n * since the default paths are rarely useful for production\n * environments.\n *\n * @property {OpenSeadragon.NavImages} [navImages]\n * An object with a property for each button or other built-in navigation\n * control, eg the current 'zoomIn', 'zoomOut', 'home', and 'fullpage'.\n * Each of those in turn provides an image path for each state of the button\n * or navigation control, eg 'REST', 'GROUP', 'HOVER', 'PRESS'. Finally the\n * image paths, by default assume there is a folder on the servers root path\n * called '/images', eg '/images/zoomin_rest.png'. If you need to adjust\n * these paths, prefer setting the option.prefixUrl rather than overriding\n * every image path directly through this setting.\n *\n * @property {Boolean} [debugMode=false]\n * TODO: provide an in-screen panel providing event detail feedback.\n *\n * @property {String} [debugGridColor=['#437AB2', '#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E', '#E6AB02', '#A6761D', '#666666']]\n * The colors of grids in debug mode. Each tiled image's grid uses a consecutive color.\n * If there are more tiled images than provided colors, the color vector is recycled.\n *\n * @property {Number} [blendTime=0]\n * Specifies the duration of animation as higher or lower level tiles are\n * replacing the existing tile.\n *\n * @property {Boolean} [alwaysBlend=false]\n * Forces the tile to always blend. By default the tiles skip blending\n * when the blendTime is surpassed and the current animation frame would\n * not complete the blend.\n *\n * @property {Boolean} [autoHideControls=true]\n * If the user stops interacting with the viewport, fade the navigation\n * controls. Useful for presentation since the controls are by default\n * floated on top of the image the user is viewing.\n *\n * @property {Boolean} [immediateRender=false]\n * Render the best closest level first, ignoring the lowering levels which\n * provide the effect of very blurry to sharp. It is recommended to change\n * setting to true for mobile devices.\n *\n * @property {Number} [defaultZoomLevel=0]\n * Zoom level to use when image is first opened or the home button is clicked.\n * If 0, adjusts to fit viewer.\n *\n * @property {Number} [opacity=1]\n * Default proportional opacity of the tiled images (1=opaque, 0=hidden)\n * Hidden images do not draw and only load when preloading is allowed.\n *\n * @property {Boolean} [preload=false]\n * Default switch for loading hidden images (true loads, false blocks)\n *\n * @property {String} [compositeOperation=null]\n * Valid values are 'source-over', 'source-atop', 'source-in', 'source-out',\n * 'destination-over', 'destination-atop', 'destination-in',\n * 'destination-out', 'lighter', 'copy' or 'xor'\n *\n * @property {String|CanvasGradient|CanvasPattern|Function} [placeholderFillStyle=null]\n * Draws a colored rectangle behind the tile if it is not loaded yet.\n * You can pass a CSS color value like \"#FF8800\".\n * When passing a function the tiledImage and canvas context are available as argument which is useful when you draw a gradient or pattern.\n *\n * @property {Number} [degrees=0]\n * Initial rotation.\n *\n * @property {Boolean} [flipped=false]\n * Initial flip state.\n *\n * @property {Number} [minZoomLevel=null]\n *\n * @property {Number} [maxZoomLevel=null]\n *\n * @property {Boolean} [homeFillsViewer=false]\n * Make the 'home' button fill the viewer and clip the image, instead\n * of fitting the image to the viewer and letterboxing.\n *\n * @property {Boolean} [panHorizontal=true]\n * Allow horizontal pan.\n *\n * @property {Boolean} [panVertical=true]\n * Allow vertical pan.\n *\n * @property {Boolean} [constrainDuringPan=false]\n *\n * @property {Boolean} [wrapHorizontal=false]\n * Set to true to force the image to wrap horizontally within the viewport.\n * Useful for maps or images representing the surface of a sphere or cylinder.\n *\n * @property {Boolean} [wrapVertical=false]\n * Set to true to force the image to wrap vertically within the viewport.\n * Useful for maps or images representing the surface of a sphere or cylinder.\n *\n * @property {Number} [minZoomImageRatio=0.9]\n * The minimum percentage ( expressed as a number between 0 and 1 ) of\n * the viewport height or width at which the zoom out will be constrained.\n * Setting it to 0, for example will allow you to zoom out infinity.\n *\n * @property {Number} [maxZoomPixelRatio=1.1]\n * The maximum ratio to allow a zoom-in to affect the highest level pixel\n * ratio. This can be set to Infinity to allow 'infinite' zooming into the\n * image though it is less effective visually if the HTML5 Canvas is not\n * availble on the viewing device.\n *\n * @property {Number} [smoothTileEdgesMinZoom=1.1]\n * A zoom percentage ( where 1 is 100% ) of the highest resolution level.\n * When zoomed in beyond this value alternative compositing will be used to\n * smooth out the edges between tiles. This will have a performance impact.\n * Can be set to Infinity to turn it off.\n * Note: This setting is ignored on iOS devices due to a known bug (See {@link https://github.com/openseadragon/openseadragon/issues/952})\n *\n * @property {Boolean} [iOSDevice=?]\n * True if running on an iOS device, false otherwise.\n * Used to disable certain features that behave differently on iOS devices.\n *\n * @property {Boolean} [autoResize=true]\n * Set to false to prevent polling for viewer size changes. Useful for providing custom resize behavior.\n *\n * @property {Boolean} [preserveImageSizeOnResize=false]\n * Set to true to have the image size preserved when the viewer is resized. This requires autoResize=true (default).\n *\n * @property {Number} [minScrollDeltaTime=50]\n * Number of milliseconds between canvas-scroll events. This value helps normalize the rate of canvas-scroll\n * events between different devices, causing the faster devices to slow down enough to make the zoom control\n * more manageable.\n *\n * @property {Number} [pixelsPerWheelLine=40]\n * For pixel-resolution scrolling devices, the number of pixels equal to one scroll line.\n *\n * @property {Number} [pixelsPerArrowPress=40]\n * The number of pixels viewport moves when an arrow key is pressed.\n *\n * @property {Number} [visibilityRatio=0.5]\n * The percentage ( as a number from 0 to 1 ) of the source image which\n * must be kept within the viewport. If the image is dragged beyond that\n * limit, it will 'bounce' back until the minimum visibility ratio is\n * achieved. Setting this to 0 and wrapHorizontal ( or wrapVertical ) to\n * true will provide the effect of an infinitely scrolling viewport.\n *\n * @property {Object} [viewportMargins={}]\n * Pushes the \"home\" region in from the sides by the specified amounts.\n * Possible subproperties (Numbers, in screen coordinates): left, top, right, bottom.\n *\n * @property {Number} [imageLoaderLimit=0]\n * The maximum number of image requests to make concurrently. By default\n * it is set to 0 allowing the browser to make the maximum number of\n * image requests in parallel as allowed by the browsers policy.\n *\n * @property {Number} [clickTimeThreshold=300]\n * The number of milliseconds within which a pointer down-up event combination\n * will be treated as a click gesture.\n *\n * @property {Number} [clickDistThreshold=5]\n * The maximum distance allowed between a pointer down event and a pointer up event\n * to be treated as a click gesture.\n *\n * @property {Number} [dblClickTimeThreshold=300]\n * The number of milliseconds within which two pointer down-up event combinations\n * will be treated as a double-click gesture.\n *\n * @property {Number} [dblClickDistThreshold=20]\n * The maximum distance allowed between two pointer click events\n * to be treated as a double-click gesture.\n *\n * @property {Number} [springStiffness=6.5]\n *\n * @property {Number} [animationTime=1.2]\n * Specifies the animation duration per each {@link OpenSeadragon.Spring}\n * which occur when the image is dragged or zoomed.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsMouse]\n * Settings for gestures generated by a mouse pointer device. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsMouse.scrollToZoom=true] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsMouse.clickToZoom=true] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsMouse.dblClickToZoom=false] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsMouse.pinchToZoom=false] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsMouse.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsMouse.flickEnabled=false] - Enable flick gesture\n * @property {Number} [gestureSettingsMouse.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsMouse.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsMouse.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsTouch]\n * Settings for gestures generated by a touch pointer device. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsTouch.scrollToZoom=false] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsTouch.clickToZoom=false] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsTouch.dblClickToZoom=true] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsTouch.pinchToZoom=true] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsTouch.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsTouch.flickEnabled=true] - Enable flick gesture\n * @property {Number} [gestureSettingsTouch.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsTouch.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsTouch.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsPen]\n * Settings for gestures generated by a pen pointer device. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsPen.scrollToZoom=false] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsPen.clickToZoom=true] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsPen.dblClickToZoom=false] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsPen.pinchToZoom=false] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsPan.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsPen.flickEnabled=false] - Enable flick gesture\n * @property {Number} [gestureSettingsPen.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsPen.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsPen.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsUnknown]\n * Settings for gestures generated by unknown pointer devices. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsUnknown.scrollToZoom=true] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsUnknown.clickToZoom=false] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsUnknown.dblClickToZoom=true] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsUnknown.pinchToZoom=true] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsUnknown.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsUnknown.flickEnabled=true] - Enable flick gesture\n * @property {Number} [gestureSettingsUnknown.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsUnknown.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsUnknown.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {Number} [zoomPerClick=2.0]\n * The \"zoom distance\" per mouse click or touch tap. Note: Setting this to 1.0 effectively disables the click-to-zoom feature (also see gestureSettings[Mouse|Touch|Pen].clickToZoom/dblClickToZoom).\n *\n * @property {Number} [zoomPerScroll=1.2]\n * The \"zoom distance\" per mouse scroll or touch pinch. Note: Setting this to 1.0 effectively disables the mouse-wheel zoom feature (also see gestureSettings[Mouse|Touch|Pen].scrollToZoom}).\n *\n * @property {Number} [zoomPerSecond=1.0]\n * The number of seconds to animate a single zoom event over.\n *\n * @property {Boolean} [showNavigator=false]\n * Set to true to make the navigator minimap appear.\n *\n * @property {String} [navigatorId=navigator-GENERATED DATE]\n * The ID of a div to hold the navigator minimap.\n * If an ID is specified, the navigatorPosition, navigatorSizeRatio, navigatorMaintainSizeRatio, navigator[Top|Left|Height|Width] and navigatorAutoFade options will be ignored.\n * If an ID is not specified, a div element will be generated and placed on top of the main image.\n *\n * @property {String} [navigatorPosition='TOP_RIGHT']\n * Valid values are 'TOP_LEFT', 'TOP_RIGHT', 'BOTTOM_LEFT', 'BOTTOM_RIGHT', or 'ABSOLUTE'.
\n * If 'ABSOLUTE' is specified, then navigator[Top|Left|Height|Width] determines the size and position of the navigator minimap in the viewer, and navigatorSizeRatio and navigatorMaintainSizeRatio are ignored.
\n * For 'TOP_LEFT', 'TOP_RIGHT', 'BOTTOM_LEFT', and 'BOTTOM_RIGHT', the navigatorSizeRatio or navigator[Height|Width] values determine the size of the navigator minimap.\n *\n * @property {Number} [navigatorSizeRatio=0.2]\n * Ratio of navigator size to viewer size. Ignored if navigator[Height|Width] are specified.\n *\n * @property {Boolean} [navigatorMaintainSizeRatio=false]\n * If true, the navigator minimap is resized (using navigatorSizeRatio) when the viewer size changes.\n *\n * @property {Number|String} [navigatorTop=null]\n * Specifies the location of the navigator minimap (see navigatorPosition).\n *\n * @property {Number|String} [navigatorLeft=null]\n * Specifies the location of the navigator minimap (see navigatorPosition).\n *\n * @property {Number|String} [navigatorHeight=null]\n * Specifies the size of the navigator minimap (see navigatorPosition).\n * If specified, navigatorSizeRatio and navigatorMaintainSizeRatio are ignored.\n *\n * @property {Number|String} [navigatorWidth=null]\n * Specifies the size of the navigator minimap (see navigatorPosition).\n * If specified, navigatorSizeRatio and navigatorMaintainSizeRatio are ignored.\n *\n * @property {Boolean} [navigatorAutoResize=true]\n * Set to false to prevent polling for navigator size changes. Useful for providing custom resize behavior.\n * Setting to false can also improve performance when the navigator is configured to a fixed size.\n *\n * @property {Boolean} [navigatorAutoFade=true]\n * If the user stops interacting with the viewport, fade the navigator minimap.\n * Setting to false will make the navigator minimap always visible.\n *\n * @property {Boolean} [navigatorRotate=true]\n * If true, the navigator will be rotated together with the viewer.\n *\n * @property {Number} [controlsFadeDelay=2000]\n * The number of milliseconds to wait once the user has stopped interacting\n * with the interface before begining to fade the controls. Assumes\n * showNavigationControl and autoHideControls are both true.\n *\n * @property {Number} [controlsFadeLength=1500]\n * The number of milliseconds to animate the controls fading out.\n *\n * @property {Number} [maxImageCacheCount=200]\n * The max number of images we should keep in memory (per drawer).\n *\n * @property {Number} [timeout=30000]\n * The max number of milliseconds that an image job may take to complete.\n *\n * @property {Boolean} [useCanvas=true]\n * Set to false to not use an HTML canvas element for image rendering even if canvas is supported.\n *\n * @property {Number} [minPixelRatio=0.5]\n * The higher the minPixelRatio, the lower the quality of the image that\n * is considered sufficient to stop rendering a given zoom level. For\n * example, if you are targeting mobile devices with less bandwith you may\n * try setting this to 1.5 or higher.\n *\n * @property {Boolean} [mouseNavEnabled=true]\n * Is the user able to interact with the image via mouse or touch. Default\n * interactions include draging the image in a plane, and zooming in toward\n * and away from the image.\n *\n * @property {Boolean} [showNavigationControl=true]\n * Set to false to prevent the appearance of the default navigation controls.
\n * Note that if set to false, the customs buttons set by the options\n * zoomInButton, zoomOutButton etc, are rendered inactive.\n *\n * @property {OpenSeadragon.ControlAnchor} [navigationControlAnchor=TOP_LEFT]\n * Placement of the default navigation controls.\n * To set the placement of the sequence controls, see the\n * sequenceControlAnchor option.\n *\n * @property {Boolean} [showZoomControl=true]\n * If true then + and - buttons to zoom in and out are displayed.
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showHomeControl=true]\n * If true then the 'Go home' button is displayed to go back to the original\n * zoom and pan.
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showFullPageControl=true]\n * If true then the 'Toggle full page' button is displayed to switch\n * between full page and normal mode.
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showRotationControl=false]\n * If true then the rotate left/right controls will be displayed as part of the\n * standard controls. This is also subject to the browser support for rotate\n * (e.g. viewer.drawer.canRotate()).
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showFlipControl=false]\n * If true then the flip controls will be displayed as part of the\n * standard controls.\n *\n * @property {Boolean} [showSequenceControl=true]\n * If sequenceMode is true, then provide buttons for navigating forward and\n * backward through the images.\n *\n * @property {OpenSeadragon.ControlAnchor} [sequenceControlAnchor=TOP_LEFT]\n * Placement of the default sequence controls.\n *\n * @property {Boolean} [navPrevNextWrap=false]\n * If true then the 'previous' button will wrap to the last image when\n * viewing the first image and the 'next' button will wrap to the first\n * image when viewing the last image.\n *\n * @property {String} zoomInButton\n * Set the id of the custom 'Zoom in' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} zoomOutButton\n * Set the id of the custom 'Zoom out' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} homeButton\n * Set the id of the custom 'Go home' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} fullPageButton\n * Set the id of the custom 'Toggle full page' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} rotateLeftButton\n * Set the id of the custom 'Rotate left' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} rotateRightButton\n * Set the id of the custom 'Rotate right' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} previousButton\n * Set the id of the custom 'Previous page' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} nextButton\n * Set the id of the custom 'Next page' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {Boolean} [sequenceMode=false]\n * Set to true to have the viewer treat your tilesources as a sequence of images to\n * be opened one at a time rather than all at once.\n *\n * @property {Number} [initialPage=0]\n * If sequenceMode is true, display this page initially.\n *\n * @property {Boolean} [preserveViewport=false]\n * If sequenceMode is true, then normally navigating through each image resets the\n * viewport to 'home' position. If preserveViewport is set to true, then the viewport\n * position is preserved when navigating between images in the sequence.\n *\n * @property {Boolean} [preserveOverlays=false]\n * If sequenceMode is true, then normally navigating through each image\n * resets the overlays.\n * If preserveOverlays is set to true, then the overlays added with {@link OpenSeadragon.Viewer#addOverlay}\n * are preserved when navigating between images in the sequence.\n * Note: setting preserveOverlays overrides any overlays specified in the global\n * \"overlays\" option for the Viewer. It's also not compatible with specifying\n * per-tileSource overlays via the options, as those overlays will persist\n * even after the tileSource is closed.\n *\n * @property {Boolean} [showReferenceStrip=false]\n * If sequenceMode is true, then display a scrolling strip of image thumbnails for\n * navigating through the images.\n *\n * @property {String} [referenceStripScroll='horizontal']\n *\n * @property {Element} [referenceStripElement=null]\n *\n * @property {Number} [referenceStripHeight=null]\n *\n * @property {Number} [referenceStripWidth=null]\n *\n * @property {String} [referenceStripPosition='BOTTOM_LEFT']\n *\n * @property {Number} [referenceStripSizeRatio=0.2]\n *\n * @property {Boolean} [collectionMode=false]\n * Set to true to have the viewer arrange your TiledImages in a grid or line.\n *\n * @property {Number} [collectionRows=3]\n * If collectionMode is true, specifies how many rows the grid should have. Use 1 to make a line.\n * If collectionLayout is 'vertical', specifies how many columns instead.\n *\n * @property {Number} [collectionColumns=0]\n * If collectionMode is true, specifies how many columns the grid should have. Use 1 to make a line.\n * If collectionLayout is 'vertical', specifies how many rows instead. Ignored if collectionRows is not set to a falsy value.\n *\n * @property {String} [collectionLayout='horizontal']\n * If collectionMode is true, specifies whether to arrange vertically or horizontally.\n *\n * @property {Number} [collectionTileSize=800]\n * If collectionMode is true, specifies the size, in viewport coordinates, for each TiledImage to fit into.\n * The TiledImage will be centered within a square of the specified size.\n *\n * @property {Number} [collectionTileMargin=80]\n * If collectionMode is true, specifies the margin, in viewport coordinates, between each TiledImage.\n *\n * @property {String|Boolean} [crossOriginPolicy=false]\n * Valid values are 'Anonymous', 'use-credentials', and false. If false, canvas requests will\n * not use CORS, and the canvas will be tainted.\n *\n * @property {Boolean} [ajaxWithCredentials=false]\n * Whether to set the withCredentials XHR flag for AJAX requests.\n * Note that this can be overridden at the {@link OpenSeadragon.TileSource} level.\n *\n * @property {Boolean} [loadTilesWithAjax=false]\n * Whether to load tile data using AJAX requests.\n * Note that this can be overridden at the {@link OpenSeadragon.TileSource} level.\n *\n * @property {Object} [ajaxHeaders={}]\n * A set of headers to include when making AJAX requests for tile sources or tiles.\n *\n */\n\n /**\n * Settings for gestures generated by a pointer device.\n *\n * @typedef {Object} GestureSettings\n * @memberof OpenSeadragon\n *\n * @property {Boolean} scrollToZoom\n * Set to false to disable zooming on scroll gestures.\n *\n * @property {Boolean} clickToZoom\n * Set to false to disable zooming on click gestures.\n *\n * @property {Boolean} dblClickToZoom\n * Set to false to disable zooming on double-click gestures. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n *\n * @property {Boolean} pinchToZoom\n * Set to false to disable zooming on pinch gestures.\n *\n * @property {Boolean} flickEnabled\n * Set to false to disable the kinetic panning effect (flick) at the end of a drag gesture.\n *\n * @property {Number} flickMinSpeed\n * If flickEnabled is true, the minimum speed (in pixels-per-second) required to cause the kinetic panning effect (flick) at the end of a drag gesture.\n *\n * @property {Number} flickMomentum\n * If flickEnabled is true, a constant multiplied by the velocity to determine the distance of the kinetic panning effect (flick) at the end of a drag gesture.\n * A larger value will make the flick feel \"lighter\", while a smaller value will make the flick feel \"heavier\".\n * Note: springStiffness and animationTime also affect the \"spring\" used to stop the flick animation.\n *\n */\n\n/**\n * The names for the image resources used for the image navigation buttons.\n *\n * @typedef {Object} NavImages\n * @memberof OpenSeadragon\n *\n * @property {Object} zoomIn - Images for the zoom-in button.\n * @property {String} zoomIn.REST\n * @property {String} zoomIn.GROUP\n * @property {String} zoomIn.HOVER\n * @property {String} zoomIn.DOWN\n *\n * @property {Object} zoomOut - Images for the zoom-out button.\n * @property {String} zoomOut.REST\n * @property {String} zoomOut.GROUP\n * @property {String} zoomOut.HOVER\n * @property {String} zoomOut.DOWN\n *\n * @property {Object} home - Images for the home button.\n * @property {String} home.REST\n * @property {String} home.GROUP\n * @property {String} home.HOVER\n * @property {String} home.DOWN\n *\n * @property {Object} fullpage - Images for the full-page button.\n * @property {String} fullpage.REST\n * @property {String} fullpage.GROUP\n * @property {String} fullpage.HOVER\n * @property {String} fullpage.DOWN\n *\n * @property {Object} rotateleft - Images for the rotate left button.\n * @property {String} rotateleft.REST\n * @property {String} rotateleft.GROUP\n * @property {String} rotateleft.HOVER\n * @property {String} rotateleft.DOWN\n *\n * @property {Object} rotateright - Images for the rotate right button.\n * @property {String} rotateright.REST\n * @property {String} rotateright.GROUP\n * @property {String} rotateright.HOVER\n * @property {String} rotateright.DOWN\n *\n * @property {Object} flip - Images for the flip button.\n * @property {String} flip.REST\n * @property {String} flip.GROUP\n * @property {String} flip.HOVER\n * @property {String} flip.DOWN\n *\n * @property {Object} previous - Images for the previous button.\n * @property {String} previous.REST\n * @property {String} previous.GROUP\n * @property {String} previous.HOVER\n * @property {String} previous.DOWN\n *\n * @property {Object} next - Images for the next button.\n * @property {String} next.REST\n * @property {String} next.GROUP\n * @property {String} next.HOVER\n * @property {String} next.DOWN\n *\n */\n\n\nfunction OpenSeadragon( options ){\n return new OpenSeadragon.Viewer( options );\n}\n\n(function( $ ){\n\n\n /**\n * The OpenSeadragon version.\n *\n * @member {Object} OpenSeadragon.version\n * @property {String} versionStr - The version number as a string ('major.minor.revision').\n * @property {Number} major - The major version number.\n * @property {Number} minor - The minor version number.\n * @property {Number} revision - The revision number.\n * @since 1.0.0\n */\n $.version = {\n versionStr: '2.3.1',\n major: parseInt('2', 10),\n minor: parseInt('3', 10),\n revision: parseInt('1', 10)\n };\n\n\n /**\n * Taken from jquery 1.6.1\n * [[Class]] -> type pairs\n * @private\n */\n var class2type = {\n '[object Boolean]': 'boolean',\n '[object Number]': 'number',\n '[object String]': 'string',\n '[object Function]': 'function',\n '[object Array]': 'array',\n '[object Date]': 'date',\n '[object RegExp]': 'regexp',\n '[object Object]': 'object'\n },\n // Save a reference to some core methods\n toString = Object.prototype.toString,\n hasOwn = Object.prototype.hasOwnProperty;\n\n /**\n * Taken from jQuery 1.6.1\n * @function isFunction\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isFunction = function( obj ) {\n return $.type(obj) === \"function\";\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function isArray\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isArray = Array.isArray || function( obj ) {\n return $.type(obj) === \"array\";\n };\n\n\n /**\n * A crude way of determining if an object is a window.\n * Taken from jQuery 1.6.1\n * @function isWindow\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isWindow = function( obj ) {\n return obj && typeof obj === \"object\" && \"setInterval\" in obj;\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function type\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.type = function( obj ) {\n return ( obj === null ) || ( obj === undefined ) ?\n String( obj ) :\n class2type[ toString.call(obj) ] || \"object\";\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function isPlainObject\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isPlainObject = function( obj ) {\n // Must be an Object.\n // Because of IE, we also have to check the presence of the constructor property.\n // Make sure that DOM nodes and window objects don't pass through, as well\n if ( !obj || OpenSeadragon.type(obj) !== \"object\" || obj.nodeType || $.isWindow( obj ) ) {\n return false;\n }\n\n // Not own constructor property must be Object\n if ( obj.constructor &&\n !hasOwn.call(obj, \"constructor\") &&\n !hasOwn.call(obj.constructor.prototype, \"isPrototypeOf\") ) {\n return false;\n }\n\n // Own properties are enumerated firstly, so to speed up,\n // if last one is own, then all properties are own.\n\n var lastKey;\n for (var key in obj ) {\n lastKey = key;\n }\n\n return lastKey === undefined || hasOwn.call( obj, lastKey );\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function isEmptyObject\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isEmptyObject = function( obj ) {\n for ( var name in obj ) {\n return false;\n }\n return true;\n };\n\n /**\n * Shim around Object.freeze. Does nothing if Object.freeze is not supported.\n * @param {Object} obj The object to freeze.\n * @return {Object} obj The frozen object.\n */\n $.freezeObject = function(obj) {\n if (Object.freeze) {\n $.freezeObject = Object.freeze;\n } else {\n $.freezeObject = function(obj) {\n return obj;\n };\n }\n return $.freezeObject(obj);\n };\n\n /**\n * True if the browser supports the HTML5 canvas element\n * @member {Boolean} supportsCanvas\n * @memberof OpenSeadragon\n */\n $.supportsCanvas = (function () {\n var canvasElement = document.createElement( 'canvas' );\n return !!( $.isFunction( canvasElement.getContext ) &&\n canvasElement.getContext( '2d' ) );\n }());\n\n /**\n * Test whether the submitted canvas is tainted or not.\n * @argument {Canvas} canvas The canvas to test.\n * @returns {Boolean} True if the canvas is tainted.\n */\n $.isCanvasTainted = function(canvas) {\n var isTainted = false;\n try {\n // We test if the canvas is tainted by retrieving data from it.\n // An exception will be raised if the canvas is tainted.\n canvas.getContext('2d').getImageData(0, 0, 1, 1);\n } catch (e) {\n isTainted = true;\n }\n return isTainted;\n };\n\n /**\n * A ratio comparing the device screen's pixel density to the canvas's backing store pixel density,\n * clamped to a minimum of 1. Defaults to 1 if canvas isn't supported by the browser.\n * @member {Number} pixelDensityRatio\n * @memberof OpenSeadragon\n */\n $.pixelDensityRatio = (function () {\n if ( $.supportsCanvas ) {\n var context = document.createElement('canvas').getContext('2d');\n var devicePixelRatio = window.devicePixelRatio || 1;\n var backingStoreRatio = context.webkitBackingStorePixelRatio ||\n context.mozBackingStorePixelRatio ||\n context.msBackingStorePixelRatio ||\n context.oBackingStorePixelRatio ||\n context.backingStorePixelRatio || 1;\n return Math.max(devicePixelRatio, 1) / backingStoreRatio;\n } else {\n return 1;\n }\n }());\n\n}( OpenSeadragon ));\n\n/**\n * This closure defines all static methods available to the OpenSeadragon\n * namespace. Many, if not most, are taked directly from jQuery for use\n * to simplify and reduce common programming patterns. More static methods\n * from jQuery may eventually make their way into this though we are\n * attempting to avoid an explicit dependency on jQuery only because\n * OpenSeadragon is a broadly useful code base and would be made less broad\n * by requiring jQuery fully.\n *\n * Some static methods have also been refactored from the original OpenSeadragon\n * project.\n */\n(function( $ ){\n\n /**\n * Taken from jQuery 1.6.1\n * @function extend\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.extend = function() {\n var options,\n name,\n src,\n copy,\n copyIsArray,\n clone,\n target = arguments[ 0 ] || {},\n length = arguments.length,\n deep = false,\n i = 1;\n\n // Handle a deep copy situation\n if ( typeof target === \"boolean\" ) {\n deep = target;\n target = arguments[ 1 ] || {};\n // skip the boolean and the target\n i = 2;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if ( typeof target !== \"object\" && !OpenSeadragon.isFunction( target ) ) {\n target = {};\n }\n\n // extend jQuery itself if only one argument is passed\n if ( length === i ) {\n target = this;\n --i;\n }\n\n for ( ; i < length; i++ ) {\n // Only deal with non-null/undefined values\n options = arguments[ i ];\n if ( options !== null || options !== undefined ) {\n // Extend the base object\n for ( name in options ) {\n src = target[ name ];\n copy = options[ name ];\n\n // Prevent never-ending loop\n if ( target === copy ) {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays\n if ( deep && copy && ( OpenSeadragon.isPlainObject( copy ) || ( copyIsArray = OpenSeadragon.isArray( copy ) ) ) ) {\n if ( copyIsArray ) {\n copyIsArray = false;\n clone = src && OpenSeadragon.isArray( src ) ? src : [];\n\n } else {\n clone = src && OpenSeadragon.isPlainObject( src ) ? src : {};\n }\n\n // Never move original objects, clone them\n target[ name ] = OpenSeadragon.extend( deep, clone, copy );\n\n // Don't bring in undefined values\n } else if ( copy !== undefined ) {\n target[ name ] = copy;\n }\n }\n }\n }\n\n // Return the modified object\n return target;\n };\n\n var isIOSDevice = function () {\n if (typeof navigator !== 'object') {\n return false;\n }\n var userAgent = navigator.userAgent;\n if (typeof userAgent !== 'string') {\n return false;\n }\n return userAgent.indexOf('iPhone') !== -1 ||\n userAgent.indexOf('iPad') !== -1 ||\n userAgent.indexOf('iPod') !== -1;\n };\n\n $.extend( $, /** @lends OpenSeadragon */{\n /**\n * The default values for the optional settings documented at {@link OpenSeadragon.Options}.\n * @static\n * @type {Object}\n */\n DEFAULT_SETTINGS: {\n //DATA SOURCE DETAILS\n xmlPath: null,\n tileSources: null,\n tileHost: null,\n initialPage: 0,\n crossOriginPolicy: false,\n ajaxWithCredentials: false,\n loadTilesWithAjax: false,\n ajaxHeaders: {},\n\n //PAN AND ZOOM SETTINGS AND CONSTRAINTS\n panHorizontal: true,\n panVertical: true,\n constrainDuringPan: false,\n wrapHorizontal: false,\n wrapVertical: false,\n visibilityRatio: 0.5, //-> how much of the viewer can be negative space\n minPixelRatio: 0.5, //->closer to 0 draws tiles meant for a higher zoom at this zoom\n defaultZoomLevel: 0,\n minZoomLevel: null,\n maxZoomLevel: null,\n homeFillsViewer: false,\n\n //UI RESPONSIVENESS AND FEEL\n clickTimeThreshold: 300,\n clickDistThreshold: 5,\n dblClickTimeThreshold: 300,\n dblClickDistThreshold: 20,\n springStiffness: 6.5,\n animationTime: 1.2,\n gestureSettingsMouse: {\n scrollToZoom: true,\n clickToZoom: true,\n dblClickToZoom: false,\n pinchToZoom: false,\n zoomToRefPoint: true,\n flickEnabled: false,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n gestureSettingsTouch: {\n scrollToZoom: false,\n clickToZoom: false,\n dblClickToZoom: true,\n pinchToZoom: true,\n zoomToRefPoint: true,\n flickEnabled: true,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n gestureSettingsPen: {\n scrollToZoom: false,\n clickToZoom: true,\n dblClickToZoom: false,\n pinchToZoom: false,\n zoomToRefPoint: true,\n flickEnabled: false,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n gestureSettingsUnknown: {\n scrollToZoom: false,\n clickToZoom: false,\n dblClickToZoom: true,\n pinchToZoom: true,\n zoomToRefPoint: true,\n flickEnabled: true,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n zoomPerClick: 2,\n zoomPerScroll: 1.2,\n zoomPerSecond: 1.0,\n blendTime: 0,\n alwaysBlend: false,\n autoHideControls: true,\n immediateRender: false,\n minZoomImageRatio: 0.9, //-> closer to 0 allows zoom out to infinity\n maxZoomPixelRatio: 1.1, //-> higher allows 'over zoom' into pixels\n smoothTileEdgesMinZoom: 1.1, //-> higher than maxZoomPixelRatio disables it\n iOSDevice: isIOSDevice(),\n pixelsPerWheelLine: 40,\n pixelsPerArrowPress: 40,\n autoResize: true,\n preserveImageSizeOnResize: false, // requires autoResize=true\n minScrollDeltaTime: 50,\n\n //DEFAULT CONTROL SETTINGS\n showSequenceControl: true, //SEQUENCE\n sequenceControlAnchor: null, //SEQUENCE\n preserveViewport: false, //SEQUENCE\n preserveOverlays: false, //SEQUENCE\n navPrevNextWrap: false, //SEQUENCE\n showNavigationControl: true, //ZOOM/HOME/FULL/ROTATION\n navigationControlAnchor: null, //ZOOM/HOME/FULL/ROTATION\n showZoomControl: true, //ZOOM\n showHomeControl: true, //HOME\n showFullPageControl: true, //FULL\n showRotationControl: false, //ROTATION\n showFlipControl: false, //FLIP\n controlsFadeDelay: 2000, //ZOOM/HOME/FULL/SEQUENCE\n controlsFadeLength: 1500, //ZOOM/HOME/FULL/SEQUENCE\n mouseNavEnabled: true, //GENERAL MOUSE INTERACTIVITY\n\n //VIEWPORT NAVIGATOR SETTINGS\n showNavigator: false,\n navigatorId: null,\n navigatorPosition: null,\n navigatorSizeRatio: 0.2,\n navigatorMaintainSizeRatio: false,\n navigatorTop: null,\n navigatorLeft: null,\n navigatorHeight: null,\n navigatorWidth: null,\n navigatorAutoResize: true,\n navigatorAutoFade: true,\n navigatorRotate: true,\n\n // INITIAL ROTATION\n degrees: 0,\n\n // INITIAL FLIP STATE\n flipped: false,\n\n // APPEARANCE\n opacity: 1,\n preload: false,\n compositeOperation: null,\n placeholderFillStyle: null,\n\n //REFERENCE STRIP SETTINGS\n showReferenceStrip: false,\n referenceStripScroll: 'horizontal',\n referenceStripElement: null,\n referenceStripHeight: null,\n referenceStripWidth: null,\n referenceStripPosition: 'BOTTOM_LEFT',\n referenceStripSizeRatio: 0.2,\n\n //COLLECTION VISUALIZATION SETTINGS\n collectionRows: 3, //or columns depending on layout\n collectionColumns: 0, //columns in horizontal layout, rows in vertical layout\n collectionLayout: 'horizontal', //vertical\n collectionMode: false,\n collectionTileSize: 800,\n collectionTileMargin: 80,\n\n //PERFORMANCE SETTINGS\n imageLoaderLimit: 0,\n maxImageCacheCount: 200,\n timeout: 30000,\n useCanvas: true, // Use canvas element for drawing if available\n\n //INTERFACE RESOURCE SETTINGS\n prefixUrl: \"/images/\",\n navImages: {\n zoomIn: {\n REST: 'zoomin_rest.png',\n GROUP: 'zoomin_grouphover.png',\n HOVER: 'zoomin_hover.png',\n DOWN: 'zoomin_pressed.png'\n },\n zoomOut: {\n REST: 'zoomout_rest.png',\n GROUP: 'zoomout_grouphover.png',\n HOVER: 'zoomout_hover.png',\n DOWN: 'zoomout_pressed.png'\n },\n home: {\n REST: 'home_rest.png',\n GROUP: 'home_grouphover.png',\n HOVER: 'home_hover.png',\n DOWN: 'home_pressed.png'\n },\n fullpage: {\n REST: 'fullpage_rest.png',\n GROUP: 'fullpage_grouphover.png',\n HOVER: 'fullpage_hover.png',\n DOWN: 'fullpage_pressed.png'\n },\n rotateleft: {\n REST: 'rotateleft_rest.png',\n GROUP: 'rotateleft_grouphover.png',\n HOVER: 'rotateleft_hover.png',\n DOWN: 'rotateleft_pressed.png'\n },\n rotateright: {\n REST: 'rotateright_rest.png',\n GROUP: 'rotateright_grouphover.png',\n HOVER: 'rotateright_hover.png',\n DOWN: 'rotateright_pressed.png'\n },\n flip: { // Flip icon designed by Yaroslav Samoylov from the Noun Project and modified by Nelson Campos ncampos@criteriamarathon.com, https://thenounproject.com/term/flip/136289/\n REST: 'flip_rest.png',\n GROUP: 'flip_grouphover.png',\n HOVER: 'flip_hover.png',\n DOWN: 'flip_pressed.png'\n },\n previous: {\n REST: 'previous_rest.png',\n GROUP: 'previous_grouphover.png',\n HOVER: 'previous_hover.png',\n DOWN: 'previous_pressed.png'\n },\n next: {\n REST: 'next_rest.png',\n GROUP: 'next_grouphover.png',\n HOVER: 'next_hover.png',\n DOWN: 'next_pressed.png'\n }\n },\n\n //DEVELOPER SETTINGS\n debugMode: false,\n debugGridColor: ['#437AB2', '#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E', '#E6AB02', '#A6761D', '#666666']\n },\n\n\n /**\n * TODO: get rid of this. I can't see how it's required at all. Looks\n * like an early legacy code artifact.\n * @static\n * @ignore\n */\n SIGNAL: \"----seadragon----\",\n\n\n /**\n * Returns a function which invokes the method as if it were a method belonging to the object.\n * @function\n * @param {Object} object\n * @param {Function} method\n * @returns {Function}\n */\n delegate: function( object, method ) {\n return function(){\n var args = arguments;\n if ( args === undefined ){\n args = [];\n }\n return method.apply( object, args );\n };\n },\n\n\n /**\n * An enumeration of Browser vendors.\n * @static\n * @type {Object}\n * @property {Number} UNKNOWN\n * @property {Number} IE\n * @property {Number} FIREFOX\n * @property {Number} SAFARI\n * @property {Number} CHROME\n * @property {Number} OPERA\n */\n BROWSERS: {\n UNKNOWN: 0,\n IE: 1,\n FIREFOX: 2,\n SAFARI: 3,\n CHROME: 4,\n OPERA: 5\n },\n\n\n /**\n * Returns a DOM Element for the given id or element.\n * @function\n * @param {String|Element} element Accepts an id or element.\n * @returns {Element} The element with the given id, null, or the element itself.\n */\n getElement: function( element ) {\n if ( typeof ( element ) == \"string\" ) {\n element = document.getElementById( element );\n }\n return element;\n },\n\n\n /**\n * Determines the position of the upper-left corner of the element.\n * @function\n * @param {Element|String} element - the elemenet we want the position for.\n * @returns {OpenSeadragon.Point} - the position of the upper left corner of the element.\n */\n getElementPosition: function( element ) {\n var result = new $.Point(),\n isFixed,\n offsetParent;\n\n element = $.getElement( element );\n isFixed = $.getElementStyle( element ).position == \"fixed\";\n offsetParent = getOffsetParent( element, isFixed );\n\n while ( offsetParent ) {\n\n result.x += element.offsetLeft;\n result.y += element.offsetTop;\n\n if ( isFixed ) {\n result = result.plus( $.getPageScroll() );\n }\n\n element = offsetParent;\n isFixed = $.getElementStyle( element ).position == \"fixed\";\n offsetParent = getOffsetParent( element, isFixed );\n }\n\n return result;\n },\n\n\n /**\n * Determines the position of the upper-left corner of the element adjusted for current page and/or element scroll.\n * @function\n * @param {Element|String} element - the element we want the position for.\n * @returns {OpenSeadragon.Point} - the position of the upper left corner of the element adjusted for current page and/or element scroll.\n */\n getElementOffset: function( element ) {\n element = $.getElement( element );\n\n var doc = element && element.ownerDocument,\n docElement,\n win,\n boundingRect = { top: 0, left: 0 };\n\n if ( !doc ) {\n return new $.Point();\n }\n\n docElement = doc.documentElement;\n\n if ( typeof element.getBoundingClientRect !== typeof undefined ) {\n boundingRect = element.getBoundingClientRect();\n }\n\n win = ( doc == doc.window ) ?\n doc :\n ( doc.nodeType === 9 ) ?\n doc.defaultView || doc.parentWindow :\n false;\n\n return new $.Point(\n boundingRect.left + ( win.pageXOffset || docElement.scrollLeft ) - ( docElement.clientLeft || 0 ),\n boundingRect.top + ( win.pageYOffset || docElement.scrollTop ) - ( docElement.clientTop || 0 )\n );\n },\n\n\n /**\n * Determines the height and width of the given element.\n * @function\n * @param {Element|String} element\n * @returns {OpenSeadragon.Point}\n */\n getElementSize: function( element ) {\n element = $.getElement( element );\n\n return new $.Point(\n element.clientWidth,\n element.clientHeight\n );\n },\n\n\n /**\n * Returns the CSSStyle object for the given element.\n * @function\n * @param {Element|String} element\n * @returns {CSSStyle}\n */\n getElementStyle:\n document.documentElement.currentStyle ?\n function( element ) {\n element = $.getElement( element );\n return element.currentStyle;\n } :\n function( element ) {\n element = $.getElement( element );\n return window.getComputedStyle( element, \"\" );\n },\n\n /**\n * Returns the property with the correct vendor prefix appended.\n * @param {String} property the property name\n * @returns {String} the property with the correct prefix or null if not\n * supported.\n */\n getCssPropertyWithVendorPrefix: function(property) {\n var memo = {};\n\n $.getCssPropertyWithVendorPrefix = function(property) {\n if (memo[property] !== undefined) {\n return memo[property];\n }\n var style = document.createElement('div').style;\n var result = null;\n if (style[property] !== undefined) {\n result = property;\n } else {\n var prefixes = ['Webkit', 'Moz', 'MS', 'O',\n 'webkit', 'moz', 'ms', 'o'];\n var suffix = $.capitalizeFirstLetter(property);\n for (var i = 0; i < prefixes.length; i++) {\n var prop = prefixes[i] + suffix;\n if (style[prop] !== undefined) {\n result = prop;\n break;\n }\n }\n }\n memo[property] = result;\n return result;\n };\n return $.getCssPropertyWithVendorPrefix(property);\n },\n\n /**\n * Capitalizes the first letter of a string\n * @param {String} string\n * @returns {String} The string with the first letter capitalized\n */\n capitalizeFirstLetter: function(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n },\n\n /**\n * Compute the modulo of a number but makes sure to always return\n * a positive value.\n * @param {Number} number the number to computes the modulo of\n * @param {Number} modulo the modulo\n * @returns {Number} the result of the modulo of number\n */\n positiveModulo: function(number, modulo) {\n var result = number % modulo;\n if (result < 0) {\n result += modulo;\n }\n return result;\n },\n\n /**\n * Determines if a point is within the bounding rectangle of the given element (hit-test).\n * @function\n * @param {Element|String} element\n * @param {OpenSeadragon.Point} point\n * @returns {Boolean}\n */\n pointInElement: function( element, point ) {\n element = $.getElement( element );\n var offset = $.getElementOffset( element ),\n size = $.getElementSize( element );\n return point.x >= offset.x && point.x < offset.x + size.x && point.y < offset.y + size.y && point.y >= offset.y;\n },\n\n\n /**\n * Gets the latest event, really only useful internally since its\n * specific to IE behavior.\n * @function\n * @param {Event} [event]\n * @returns {Event}\n * @deprecated For internal use only\n * @private\n */\n getEvent: function( event ) {\n if( event ){\n $.getEvent = function( event ) {\n return event;\n };\n } else {\n $.getEvent = function() {\n return window.event;\n };\n }\n return $.getEvent( event );\n },\n\n\n /**\n * Gets the position of the mouse on the screen for a given event.\n * @function\n * @param {Event} [event]\n * @returns {OpenSeadragon.Point}\n */\n getMousePosition: function( event ) {\n\n if ( typeof ( event.pageX ) == \"number\" ) {\n $.getMousePosition = function( event ){\n var result = new $.Point();\n\n event = $.getEvent( event );\n result.x = event.pageX;\n result.y = event.pageY;\n\n return result;\n };\n } else if ( typeof ( event.clientX ) == \"number\" ) {\n $.getMousePosition = function( event ){\n var result = new $.Point();\n\n event = $.getEvent( event );\n result.x =\n event.clientX +\n document.body.scrollLeft +\n document.documentElement.scrollLeft;\n result.y =\n event.clientY +\n document.body.scrollTop +\n document.documentElement.scrollTop;\n\n return result;\n };\n } else {\n throw new Error(\n \"Unknown event mouse position, no known technique.\"\n );\n }\n\n return $.getMousePosition( event );\n },\n\n\n /**\n * Determines the page's current scroll position.\n * @function\n * @returns {OpenSeadragon.Point}\n */\n getPageScroll: function() {\n var docElement = document.documentElement || {},\n body = document.body || {};\n\n if ( typeof ( window.pageXOffset ) == \"number\" ) {\n $.getPageScroll = function(){\n return new $.Point(\n window.pageXOffset,\n window.pageYOffset\n );\n };\n } else if ( body.scrollLeft || body.scrollTop ) {\n $.getPageScroll = function(){\n return new $.Point(\n document.body.scrollLeft,\n document.body.scrollTop\n );\n };\n } else if ( docElement.scrollLeft || docElement.scrollTop ) {\n $.getPageScroll = function(){\n return new $.Point(\n document.documentElement.scrollLeft,\n document.documentElement.scrollTop\n );\n };\n } else {\n // We can't reassign the function yet, as there was no scroll.\n return new $.Point(0, 0);\n }\n\n return $.getPageScroll();\n },\n\n /**\n * Set the page scroll position.\n * @function\n * @returns {OpenSeadragon.Point}\n */\n setPageScroll: function( scroll ) {\n if ( typeof ( window.scrollTo ) !== \"undefined\" ) {\n $.setPageScroll = function( scroll ) {\n window.scrollTo( scroll.x, scroll.y );\n };\n } else {\n var originalScroll = $.getPageScroll();\n if ( originalScroll.x === scroll.x &&\n originalScroll.y === scroll.y ) {\n // We are already correctly positioned and there\n // is no way to detect the correct method.\n return;\n }\n\n document.body.scrollLeft = scroll.x;\n document.body.scrollTop = scroll.y;\n var currentScroll = $.getPageScroll();\n if ( currentScroll.x !== originalScroll.x &&\n currentScroll.y !== originalScroll.y ) {\n $.setPageScroll = function( scroll ) {\n document.body.scrollLeft = scroll.x;\n document.body.scrollTop = scroll.y;\n };\n return;\n }\n\n document.documentElement.scrollLeft = scroll.x;\n document.documentElement.scrollTop = scroll.y;\n currentScroll = $.getPageScroll();\n if ( currentScroll.x !== originalScroll.x &&\n currentScroll.y !== originalScroll.y ) {\n $.setPageScroll = function( scroll ) {\n document.documentElement.scrollLeft = scroll.x;\n document.documentElement.scrollTop = scroll.y;\n };\n return;\n }\n\n // We can't find anything working, so we do nothing.\n $.setPageScroll = function( scroll ) {\n };\n }\n\n return $.setPageScroll( scroll );\n },\n\n /**\n * Determines the size of the browsers window.\n * @function\n * @returns {OpenSeadragon.Point}\n */\n getWindowSize: function() {\n var docElement = document.documentElement || {},\n body = document.body || {};\n\n if ( typeof ( window.innerWidth ) == 'number' ) {\n $.getWindowSize = function(){\n return new $.Point(\n window.innerWidth,\n window.innerHeight\n );\n };\n } else if ( docElement.clientWidth || docElement.clientHeight ) {\n $.getWindowSize = function(){\n return new $.Point(\n document.documentElement.clientWidth,\n document.documentElement.clientHeight\n );\n };\n } else if ( body.clientWidth || body.clientHeight ) {\n $.getWindowSize = function(){\n return new $.Point(\n document.body.clientWidth,\n document.body.clientHeight\n );\n };\n } else {\n throw new Error(\"Unknown window size, no known technique.\");\n }\n\n return $.getWindowSize();\n },\n\n\n /**\n * Wraps the given element in a nest of divs so that the element can\n * be easily centered using CSS tables\n * @function\n * @param {Element|String} element\n * @returns {Element} outermost wrapper element\n */\n makeCenteredNode: function( element ) {\n // Convert a possible ID to an actual HTMLElement\n element = $.getElement( element );\n\n /*\n CSS tables require you to have a display:table/row/cell hierarchy so we need to create\n three nested wrapper divs:\n */\n\n var wrappers = [\n $.makeNeutralElement( 'div' ),\n $.makeNeutralElement( 'div' ),\n $.makeNeutralElement( 'div' )\n ];\n\n // It feels like we should be able to pass style dicts to makeNeutralElement:\n $.extend(wrappers[0].style, {\n display: \"table\",\n height: \"100%\",\n width: \"100%\"\n });\n\n $.extend(wrappers[1].style, {\n display: \"table-row\"\n });\n\n $.extend(wrappers[2].style, {\n display: \"table-cell\",\n verticalAlign: \"middle\",\n textAlign: \"center\"\n });\n\n wrappers[0].appendChild(wrappers[1]);\n wrappers[1].appendChild(wrappers[2]);\n wrappers[2].appendChild(element);\n\n return wrappers[0];\n },\n\n\n /**\n * Creates an easily positionable element of the given type that therefor\n * serves as an excellent container element.\n * @function\n * @param {String} tagName\n * @returns {Element}\n */\n makeNeutralElement: function( tagName ) {\n var element = document.createElement( tagName ),\n style = element.style;\n\n style.background = \"transparent none\";\n style.border = \"none\";\n style.margin = \"0px\";\n style.padding = \"0px\";\n style.position = \"static\";\n\n return element;\n },\n\n\n /**\n * Returns the current milliseconds, using Date.now() if available\n * @function\n */\n now: function( ) {\n if (Date.now) {\n $.now = Date.now;\n } else {\n $.now = function() {\n return new Date().getTime();\n };\n }\n\n return $.now();\n },\n\n\n /**\n * Ensures an image is loaded correctly to support alpha transparency.\n * Generally only IE has issues doing this correctly for formats like\n * png.\n * @function\n * @param {String} src\n * @returns {Element}\n */\n makeTransparentImage: function( src ) {\n\n $.makeTransparentImage = function( src ){\n var img = $.makeNeutralElement( \"img\" );\n\n img.src = src;\n\n return img;\n };\n\n if ( $.Browser.vendor == $.BROWSERS.IE && $.Browser.version < 7 ) {\n\n $.makeTransparentImage = function( src ){\n var img = $.makeNeutralElement( \"img\" ),\n element = null;\n\n element = $.makeNeutralElement(\"span\");\n element.style.display = \"inline-block\";\n\n img.onload = function() {\n element.style.width = element.style.width || img.width + \"px\";\n element.style.height = element.style.height || img.height + \"px\";\n\n img.onload = null;\n img = null; // to prevent memory leaks in IE\n };\n\n img.src = src;\n element.style.filter =\n \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='\" +\n src +\n \"', sizingMethod='scale')\";\n\n return element;\n };\n\n }\n\n return $.makeTransparentImage( src );\n },\n\n\n /**\n * Sets the opacity of the specified element.\n * @function\n * @param {Element|String} element\n * @param {Number} opacity\n * @param {Boolean} [usesAlpha]\n */\n setElementOpacity: function( element, opacity, usesAlpha ) {\n\n var ieOpacity,\n ieFilter;\n\n element = $.getElement( element );\n\n if ( usesAlpha && !$.Browser.alpha ) {\n opacity = Math.round( opacity );\n }\n\n if ( $.Browser.opacity ) {\n element.style.opacity = opacity < 1 ? opacity : \"\";\n } else {\n if ( opacity < 1 ) {\n ieOpacity = Math.round( 100 * opacity );\n ieFilter = \"alpha(opacity=\" + ieOpacity + \")\";\n element.style.filter = ieFilter;\n } else {\n element.style.filter = \"\";\n }\n }\n },\n\n\n /**\n * Sets the specified element's touch-action style attribute to 'none'.\n * @function\n * @param {Element|String} element\n */\n setElementTouchActionNone: function( element ) {\n element = $.getElement( element );\n if ( typeof element.style.touchAction !== 'undefined' ) {\n element.style.touchAction = 'none';\n } else if ( typeof element.style.msTouchAction !== 'undefined' ) {\n element.style.msTouchAction = 'none';\n }\n },\n\n\n /**\n * Add the specified CSS class to the element if not present.\n * @function\n * @param {Element|String} element\n * @param {String} className\n */\n addClass: function( element, className ) {\n element = $.getElement( element );\n\n if (!element.className) {\n element.className = className;\n } else if ( ( ' ' + element.className + ' ' ).\n indexOf( ' ' + className + ' ' ) === -1 ) {\n element.className += ' ' + className;\n }\n },\n\n /**\n * Find the first index at which an element is found in an array or -1\n * if not present.\n *\n * Code taken and adapted from\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility\n *\n * @function\n * @param {Array} array The array from which to find the element\n * @param {Object} searchElement The element to find\n * @param {Number} [fromIndex=0] Index to start research.\n * @returns {Number} The index of the element in the array.\n */\n indexOf: function( array, searchElement, fromIndex ) {\n if ( Array.prototype.indexOf ) {\n this.indexOf = function( array, searchElement, fromIndex ) {\n return array.indexOf( searchElement, fromIndex );\n };\n } else {\n this.indexOf = function( array, searchElement, fromIndex ) {\n var i,\n pivot = ( fromIndex ) ? fromIndex : 0,\n length;\n if ( !array ) {\n throw new TypeError( );\n }\n\n length = array.length;\n if ( length === 0 || pivot >= length ) {\n return -1;\n }\n\n if ( pivot < 0 ) {\n pivot = length - Math.abs( pivot );\n }\n\n for ( i = pivot; i < length; i++ ) {\n if ( array[i] === searchElement ) {\n return i;\n }\n }\n return -1;\n };\n }\n return this.indexOf( array, searchElement, fromIndex );\n },\n\n /**\n * Remove the specified CSS class from the element.\n * @function\n * @param {Element|String} element\n * @param {String} className\n */\n removeClass: function( element, className ) {\n var oldClasses,\n newClasses = [],\n i;\n\n element = $.getElement( element );\n oldClasses = element.className.split( /\\s+/ );\n for ( i = 0; i < oldClasses.length; i++ ) {\n if ( oldClasses[ i ] && oldClasses[ i ] !== className ) {\n newClasses.push( oldClasses[ i ] );\n }\n }\n element.className = newClasses.join(' ');\n },\n\n\n /**\n * Adds an event listener for the given element, eventName and handler.\n * @function\n * @param {Element|String} element\n * @param {String} eventName\n * @param {Function} handler\n * @param {Boolean} [useCapture]\n */\n addEvent: (function () {\n if ( window.addEventListener ) {\n return function ( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.addEventListener( eventName, handler, useCapture );\n };\n } else if ( window.attachEvent ) {\n return function ( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.attachEvent( 'on' + eventName, handler );\n };\n } else {\n throw new Error( \"No known event model.\" );\n }\n }()),\n\n\n /**\n * Remove a given event listener for the given element, event type and\n * handler.\n * @function\n * @param {Element|String} element\n * @param {String} eventName\n * @param {Function} handler\n * @param {Boolean} [useCapture]\n */\n removeEvent: (function () {\n if ( window.removeEventListener ) {\n return function ( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.removeEventListener( eventName, handler, useCapture );\n };\n } else if ( window.detachEvent ) {\n return function( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.detachEvent( 'on' + eventName, handler );\n };\n } else {\n throw new Error( \"No known event model.\" );\n }\n }()),\n\n\n /**\n * Cancels the default browser behavior had the event propagated all\n * the way up the DOM to the window object.\n * @function\n * @param {Event} [event]\n */\n cancelEvent: function( event ) {\n event = $.getEvent( event );\n\n if ( event.preventDefault ) {\n $.cancelEvent = function( event ){\n // W3C for preventing default\n event.preventDefault();\n };\n } else {\n $.cancelEvent = function( event ){\n event = $.getEvent( event );\n // legacy for preventing default\n event.cancel = true;\n // IE for preventing default\n event.returnValue = false;\n };\n }\n $.cancelEvent( event );\n },\n\n\n /**\n * Stops the propagation of the event up the DOM.\n * @function\n * @param {Event} [event]\n */\n stopEvent: function( event ) {\n event = $.getEvent( event );\n\n if ( event.stopPropagation ) {\n // W3C for stopping propagation\n $.stopEvent = function( event ){\n event.stopPropagation();\n };\n } else {\n // IE for stopping propagation\n $.stopEvent = function( event ){\n event = $.getEvent( event );\n event.cancelBubble = true;\n };\n\n }\n\n $.stopEvent( event );\n },\n\n\n /**\n * Similar to OpenSeadragon.delegate, but it does not immediately call\n * the method on the object, returning a function which can be called\n * repeatedly to delegate the method. It also allows additonal arguments\n * to be passed during construction which will be added during each\n * invocation, and each invocation can add additional arguments as well.\n *\n * @function\n * @param {Object} object\n * @param {Function} method\n * @param [args] any additional arguments are passed as arguments to the\n * created callback\n * @returns {Function}\n */\n createCallback: function( object, method ) {\n //TODO: This pattern is painful to use and debug. It's much cleaner\n // to use pinning plus anonymous functions. Get rid of this\n // pattern!\n var initialArgs = [],\n i;\n for ( i = 2; i < arguments.length; i++ ) {\n initialArgs.push( arguments[ i ] );\n }\n\n return function() {\n var args = initialArgs.concat( [] ),\n i;\n for ( i = 0; i < arguments.length; i++ ) {\n args.push( arguments[ i ] );\n }\n\n return method.apply( object, args );\n };\n },\n\n\n /**\n * Retreives the value of a url parameter from the window.location string.\n * @function\n * @param {String} key\n * @returns {String} The value of the url parameter or null if no param matches.\n */\n getUrlParameter: function( key ) {\n // eslint-disable-next-line no-use-before-define\n var value = URLPARAMS[ key ];\n return value ? value : null;\n },\n\n /**\n * Retrieves the protocol used by the url. The url can either be absolute\n * or relative.\n * @function\n * @private\n * @param {String} url The url to retrieve the protocol from.\n * @return {String} The protocol (http:, https:, file:, ftp: ...)\n */\n getUrlProtocol: function( url ) {\n var match = url.match(/^([a-z]+:)\\/\\//i);\n if ( match === null ) {\n // Relative URL, retrive the protocol from window.location\n return window.location.protocol;\n }\n return match[1].toLowerCase();\n },\n\n /**\n * Create an XHR object\n * @private\n * @param {type} [local] If set to true, the XHR will be file: protocol\n * compatible if possible (but may raise a warning in the browser).\n * @returns {XMLHttpRequest}\n */\n createAjaxRequest: function( local ) {\n // IE11 does not support window.ActiveXObject so we just try to\n // create one to see if it is supported.\n // See: http://msdn.microsoft.com/en-us/library/ie/dn423948%28v=vs.85%29.aspx\n var supportActiveX;\n try {\n /* global ActiveXObject:true */\n supportActiveX = !!new ActiveXObject( \"Microsoft.XMLHTTP\" );\n } catch( e ) {\n supportActiveX = false;\n }\n\n if ( supportActiveX ) {\n if ( window.XMLHttpRequest ) {\n $.createAjaxRequest = function( local ) {\n if ( local ) {\n return new ActiveXObject( \"Microsoft.XMLHTTP\" );\n }\n return new XMLHttpRequest();\n };\n } else {\n $.createAjaxRequest = function() {\n return new ActiveXObject( \"Microsoft.XMLHTTP\" );\n };\n }\n } else if ( window.XMLHttpRequest ) {\n $.createAjaxRequest = function() {\n return new XMLHttpRequest();\n };\n } else {\n throw new Error( \"Browser doesn't support XMLHttpRequest.\" );\n }\n return $.createAjaxRequest( local );\n },\n\n /**\n * Makes an AJAX request.\n * @param {Object} options\n * @param {String} options.url - the url to request\n * @param {Function} options.success - a function to call on a successful response\n * @param {Function} options.error - a function to call on when an error occurs\n * @param {Object} options.headers - headers to add to the AJAX request\n * @param {String} options.responseType - the response type of the the AJAX request\n * @param {Boolean} [options.withCredentials=false] - whether to set the XHR's withCredentials\n * @throws {Error}\n * @returns {XMLHttpRequest}\n */\n makeAjaxRequest: function( url, onSuccess, onError ) {\n var withCredentials;\n var headers;\n var responseType;\n\n // Note that our preferred API is that you pass in a single object; the named\n // arguments are for legacy support.\n if( $.isPlainObject( url ) ){\n onSuccess = url.success;\n onError = url.error;\n withCredentials = url.withCredentials;\n headers = url.headers;\n responseType = url.responseType || null;\n url = url.url;\n }\n\n var protocol = $.getUrlProtocol( url );\n var request = $.createAjaxRequest( protocol === \"file:\" );\n\n if ( !$.isFunction( onSuccess ) ) {\n throw new Error( \"makeAjaxRequest requires a success callback\" );\n }\n\n request.onreadystatechange = function() {\n // 4 = DONE (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties)\n if ( request.readyState == 4 ) {\n request.onreadystatechange = function(){};\n\n // With protocols other than http/https, a successful request status is in\n // the 200's on Firefox and 0 on other browsers\n if ( (request.status >= 200 && request.status < 300) ||\n ( request.status === 0 &&\n protocol !== \"http:\" &&\n protocol !== \"https:\" )) {\n onSuccess( request );\n } else {\n $.console.log( \"AJAX request returned %d: %s\", request.status, url );\n\n if ( $.isFunction( onError ) ) {\n onError( request );\n }\n }\n }\n };\n\n try {\n request.open( \"GET\", url, true );\n\n if (responseType) {\n request.responseType = responseType;\n }\n\n if (headers) {\n for (var headerName in headers) {\n if (headers.hasOwnProperty(headerName) && headers[headerName]) {\n request.setRequestHeader(headerName, headers[headerName]);\n }\n }\n }\n\n if (withCredentials) {\n request.withCredentials = true;\n }\n\n request.send(null);\n } catch (e) {\n var msg = e.message;\n\n /*\n IE < 10 does not support CORS and an XHR request to a different origin will fail as soon\n as send() is called. This is particularly easy to miss during development and appear in\n production if you use a CDN or domain sharding and the security policy is likely to break\n exception handlers since any attempt to access a property of the request object will\n raise an access denied TypeError inside the catch block.\n\n To be friendlier, we'll check for this specific error and add a documentation pointer\n to point developers in the right direction. We test the exception number because IE's\n error messages are localized.\n */\n var oldIE = $.Browser.vendor == $.BROWSERS.IE && $.Browser.version < 10;\n if ( oldIE && typeof ( e.number ) != \"undefined\" && e.number == -2147024891 ) {\n msg += \"\\nSee http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx#xdomain\";\n }\n\n $.console.log( \"%s while making AJAX request: %s\", e.name, msg );\n\n request.onreadystatechange = function(){};\n\n if (window.XDomainRequest) { // IE9 or IE8 might as well try to use XDomainRequest\n var xdr = new XDomainRequest();\n if (xdr) {\n xdr.onload = function (e) {\n if ( $.isFunction( onSuccess ) ) {\n onSuccess({ // Faking an xhr object\n responseText: xdr.responseText,\n status: 200, // XDomainRequest doesn't support status codes, so we just fake one! :/\n statusText: 'OK'\n });\n }\n };\n xdr.onerror = function (e) {\n if ($.isFunction(onError)) {\n onError({ // Faking an xhr object\n responseText: xdr.responseText,\n status: 444, // 444 No Response\n statusText: 'An error happened. Due to an XDomainRequest deficiency we can not extract any information about this error. Upgrade your browser.'\n });\n }\n };\n try {\n xdr.open('GET', url);\n xdr.send();\n } catch (e2) {\n if ( $.isFunction( onError ) ) {\n onError( request, e );\n }\n }\n }\n } else {\n if ( $.isFunction( onError ) ) {\n onError( request, e );\n }\n }\n }\n\n return request;\n },\n\n /**\n * Taken from jQuery 1.6.1\n * @function\n * @param {Object} options\n * @param {String} options.url\n * @param {Function} options.callback\n * @param {String} [options.param='callback'] The name of the url parameter\n * to request the jsonp provider with.\n * @param {String} [options.callbackName=] The name of the callback to\n * request the jsonp provider with.\n */\n jsonp: function( options ){\n var script,\n url = options.url,\n head = document.head ||\n document.getElementsByTagName( \"head\" )[ 0 ] ||\n document.documentElement,\n jsonpCallback = options.callbackName || 'openseadragon' + $.now(),\n previous = window[ jsonpCallback ],\n replace = \"$1\" + jsonpCallback + \"$2\",\n callbackParam = options.param || 'callback',\n callback = options.callback;\n\n url = url.replace( /(\\=)\\?(&|$)|\\?\\?/i, replace );\n // Add callback manually\n url += (/\\?/.test( url ) ? \"&\" : \"?\") + callbackParam + \"=\" + jsonpCallback;\n\n // Install callback\n window[ jsonpCallback ] = function( response ) {\n if ( !previous ){\n try{\n delete window[ jsonpCallback ];\n }catch(e){\n //swallow\n }\n } else {\n window[ jsonpCallback ] = previous;\n }\n if( callback && $.isFunction( callback ) ){\n callback( response );\n }\n };\n\n script = document.createElement( \"script\" );\n\n //TODO: having an issue with async info requests\n if( undefined !== options.async || false !== options.async ){\n script.async = \"async\";\n }\n\n if ( options.scriptCharset ) {\n script.charset = options.scriptCharset;\n }\n\n script.src = url;\n\n // Attach handlers for all browsers\n script.onload = script.onreadystatechange = function( _, isAbort ) {\n\n if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {\n\n // Handle memory leak in IE\n script.onload = script.onreadystatechange = null;\n\n // Remove the script\n if ( head && script.parentNode ) {\n head.removeChild( script );\n }\n\n // Dereference the script\n script = undefined;\n }\n };\n // Use insertBefore instead of appendChild to circumvent an IE6 bug.\n // This arises when a base node is used (#2709 and #4378).\n head.insertBefore( script, head.firstChild );\n\n },\n\n\n /**\n * Fully deprecated. Will throw an error.\n * @function\n * @deprecated use {@link OpenSeadragon.Viewer#open}\n */\n createFromDZI: function() {\n throw \"OpenSeadragon.createFromDZI is deprecated, use Viewer.open.\";\n },\n\n /**\n * Parses an XML string into a DOM Document.\n * @function\n * @param {String} string\n * @returns {Document}\n */\n parseXml: function( string ) {\n if ( window.DOMParser ) {\n\n $.parseXml = function( string ) {\n var xmlDoc = null,\n parser;\n\n parser = new DOMParser();\n xmlDoc = parser.parseFromString( string, \"text/xml\" );\n return xmlDoc;\n };\n\n } else if ( window.ActiveXObject ) {\n\n $.parseXml = function( string ) {\n var xmlDoc = null;\n\n xmlDoc = new ActiveXObject( \"Microsoft.XMLDOM\" );\n xmlDoc.async = false;\n xmlDoc.loadXML( string );\n return xmlDoc;\n };\n\n } else {\n throw new Error( \"Browser doesn't support XML DOM.\" );\n }\n\n return $.parseXml( string );\n },\n\n /**\n * Parses a JSON string into a Javascript object.\n * @function\n * @param {String} string\n * @returns {Object}\n */\n parseJSON: function(string) {\n if (window.JSON && window.JSON.parse) {\n $.parseJSON = window.JSON.parse;\n } else {\n // Should only be used by IE8 in non standards mode\n $.parseJSON = function(string) {\n /*jshint evil:true*/\n //eslint-disable-next-line no-eval\n return eval('(' + string + ')');\n };\n }\n return $.parseJSON(string);\n },\n\n /**\n * Reports whether the image format is supported for tiling in this\n * version.\n * @function\n * @param {String} [extension]\n * @returns {Boolean}\n */\n imageFormatSupported: function( extension ) {\n extension = extension ? extension : \"\";\n // eslint-disable-next-line no-use-before-define\n return !!FILEFORMATS[ extension.toLowerCase() ];\n }\n\n });\n\n\n /**\n * The current browser vendor, version, and related information regarding detected features.\n * @member {Object} Browser\n * @memberof OpenSeadragon\n * @static\n * @type {Object}\n * @property {OpenSeadragon.BROWSERS} vendor - One of the {@link OpenSeadragon.BROWSERS} enumeration values.\n * @property {Number} version\n * @property {Boolean} alpha - Does the browser support image alpha transparency.\n */\n $.Browser = {\n vendor: $.BROWSERS.UNKNOWN,\n version: 0,\n alpha: true\n };\n\n\n var FILEFORMATS = {\n \"bmp\": false,\n \"jpeg\": true,\n \"jpg\": true,\n \"png\": true,\n \"tif\": false,\n \"wdp\": false\n },\n URLPARAMS = {};\n\n (function() {\n //A small auto-executing routine to determine the browser vendor,\n //version and supporting feature sets.\n var ver = navigator.appVersion,\n ua = navigator.userAgent,\n regex;\n\n //console.error( 'appName: ' + navigator.appName );\n //console.error( 'appVersion: ' + navigator.appVersion );\n //console.error( 'userAgent: ' + navigator.userAgent );\n\n switch( navigator.appName ){\n case \"Microsoft Internet Explorer\":\n if( !!window.attachEvent &&\n !!window.ActiveXObject ) {\n\n $.Browser.vendor = $.BROWSERS.IE;\n $.Browser.version = parseFloat(\n ua.substring(\n ua.indexOf( \"MSIE\" ) + 5,\n ua.indexOf( \";\", ua.indexOf( \"MSIE\" ) ) )\n );\n }\n break;\n case \"Netscape\":\n if (window.addEventListener) {\n if ( ua.indexOf( \"Firefox\" ) >= 0 ) {\n $.Browser.vendor = $.BROWSERS.FIREFOX;\n $.Browser.version = parseFloat(\n ua.substring( ua.indexOf( \"Firefox\" ) + 8 )\n );\n } else if ( ua.indexOf( \"Safari\" ) >= 0 ) {\n $.Browser.vendor = ua.indexOf( \"Chrome\" ) >= 0 ?\n $.BROWSERS.CHROME :\n $.BROWSERS.SAFARI;\n $.Browser.version = parseFloat(\n ua.substring(\n ua.substring( 0, ua.indexOf( \"Safari\" ) ).lastIndexOf( \"/\" ) + 1,\n ua.indexOf( \"Safari\" )\n )\n );\n } else {\n regex = new RegExp( \"Trident/.*rv:([0-9]{1,}[.0-9]{0,})\");\n if ( regex.exec( ua ) !== null ) {\n $.Browser.vendor = $.BROWSERS.IE;\n $.Browser.version = parseFloat( RegExp.$1 );\n }\n }\n }\n break;\n case \"Opera\":\n $.Browser.vendor = $.BROWSERS.OPERA;\n $.Browser.version = parseFloat( ver );\n break;\n }\n\n // ignore '?' portion of query string\n var query = window.location.search.substring( 1 ),\n parts = query.split('&'),\n part,\n sep,\n i;\n\n for ( i = 0; i < parts.length; i++ ) {\n part = parts[ i ];\n sep = part.indexOf( '=' );\n\n if ( sep > 0 ) {\n URLPARAMS[ part.substring( 0, sep ) ] =\n decodeURIComponent( part.substring( sep + 1 ) );\n }\n }\n\n //determine if this browser supports image alpha transparency\n $.Browser.alpha = !(\n (\n $.Browser.vendor == $.BROWSERS.IE &&\n $.Browser.version < 9\n ) || (\n $.Browser.vendor == $.BROWSERS.CHROME &&\n $.Browser.version < 2\n )\n );\n\n //determine if this browser supports element.style.opacity\n $.Browser.opacity = !(\n $.Browser.vendor == $.BROWSERS.IE &&\n $.Browser.version < 9\n );\n\n })();\n\n\n //TODO: $.console is often used inside a try/catch block which generally\n // prevents allowings errors to occur with detection until a debugger\n // is attached. Although I've been guilty of the same anti-pattern\n // I eventually was convinced that errors should naturally propogate in\n // all but the most special cases.\n /**\n * A convenient alias for console when available, and a simple null\n * function when console is unavailable.\n * @static\n * @private\n */\n var nullfunction = function( msg ){\n //document.location.hash = msg;\n };\n\n $.console = window.console || {\n log: nullfunction,\n debug: nullfunction,\n info: nullfunction,\n warn: nullfunction,\n error: nullfunction,\n assert: nullfunction\n };\n\n\n // Adding support for HTML5's requestAnimationFrame as suggested by acdha.\n // Implementation taken from matt synder's post here:\n // http://mattsnider.com/cross-browser-and-legacy-supported-requestframeanimation/\n (function( w ) {\n\n // most browsers have an implementation\n var requestAnimationFrame = w.requestAnimationFrame ||\n w.mozRequestAnimationFrame ||\n w.webkitRequestAnimationFrame ||\n w.msRequestAnimationFrame;\n\n var cancelAnimationFrame = w.cancelAnimationFrame ||\n w.mozCancelAnimationFrame ||\n w.webkitCancelAnimationFrame ||\n w.msCancelAnimationFrame;\n\n // polyfill, when necessary\n if ( requestAnimationFrame && cancelAnimationFrame ) {\n // We can't assign these window methods directly to $ because they\n // expect their \"this\" to be \"window\", so we call them in wrappers.\n $.requestAnimationFrame = function(){\n return requestAnimationFrame.apply( w, arguments );\n };\n $.cancelAnimationFrame = function(){\n return cancelAnimationFrame.apply( w, arguments );\n };\n } else {\n var aAnimQueue = [],\n processing = [],\n iRequestId = 0,\n iIntervalId;\n\n // create a mock requestAnimationFrame function\n $.requestAnimationFrame = function( callback ) {\n aAnimQueue.push( [ ++iRequestId, callback ] );\n\n if ( !iIntervalId ) {\n iIntervalId = setInterval( function() {\n if ( aAnimQueue.length ) {\n var time = $.now();\n // Process all of the currently outstanding frame\n // requests, but none that get added during the\n // processing.\n // Swap the arrays so we don't have to create a new\n // array every frame.\n var temp = processing;\n processing = aAnimQueue;\n aAnimQueue = temp;\n while ( processing.length ) {\n processing.shift()[ 1 ]( time );\n }\n } else {\n // don't continue the interval, if unnecessary\n clearInterval( iIntervalId );\n iIntervalId = undefined;\n }\n }, 1000 / 50); // estimating support for 50 frames per second\n }\n\n return iRequestId;\n };\n\n // create a mock cancelAnimationFrame function\n $.cancelAnimationFrame = function( requestId ) {\n // find the request ID and remove it\n var i, j;\n for ( i = 0, j = aAnimQueue.length; i < j; i += 1 ) {\n if ( aAnimQueue[ i ][ 0 ] === requestId ) {\n aAnimQueue.splice( i, 1 );\n return;\n }\n }\n\n // If it's not in the queue, it may be in the set we're currently\n // processing (if cancelAnimationFrame is called from within a\n // requestAnimationFrame callback).\n for ( i = 0, j = processing.length; i < j; i += 1 ) {\n if ( processing[ i ][ 0 ] === requestId ) {\n processing.splice( i, 1 );\n return;\n }\n }\n };\n }\n })( window );\n\n /**\n * @private\n * @inner\n * @function\n * @param {Element} element\n * @param {Boolean} [isFixed]\n * @returns {Element}\n */\n function getOffsetParent( element, isFixed ) {\n if ( isFixed && element != document.body ) {\n return document.body;\n } else {\n return element.offsetParent;\n }\n }\n\n}(OpenSeadragon));\n\n\n// Universal Module Definition, supports CommonJS, AMD and simple script tag\n(function (root, factory) {\n if (true) {\n // expose as amd module\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n}(this, function () {\n return OpenSeadragon;\n}));\n\n/*\n * OpenSeadragon - full-screen support functions\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ) {\n /**\n * Determine native full screen support we can get from the browser.\n * @member fullScreenApi\n * @memberof OpenSeadragon\n * @type {object}\n * @property {Boolean} supportsFullScreen Return true if full screen API is supported.\n * @property {Function} isFullScreen Return true if currently in full screen mode.\n * @property {Function} getFullScreenElement Return the element currently in full screen mode.\n * @property {Function} requestFullScreen Make a request to go in full screen mode.\n * @property {Function} exitFullScreen Make a request to exit full screen mode.\n * @property {Function} cancelFullScreen Deprecated, use exitFullScreen instead.\n * @property {String} fullScreenEventName Event fired when the full screen mode change.\n * @property {String} fullScreenErrorEventName Event fired when a request to go\n * in full screen mode failed.\n */\n var fullScreenApi = {\n supportsFullScreen: false,\n isFullScreen: function() { return false; },\n getFullScreenElement: function() { return null; },\n requestFullScreen: function() {},\n exitFullScreen: function() {},\n cancelFullScreen: function() {},\n fullScreenEventName: '',\n fullScreenErrorEventName: ''\n };\n\n // check for native support\n if ( document.exitFullscreen ) {\n // W3C standard\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.fullscreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.requestFullscreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.exitFullscreen();\n };\n fullScreenApi.fullScreenEventName = \"fullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"fullscreenerror\";\n } else if ( document.msExitFullscreen ) {\n // IE 11\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.msFullscreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.msRequestFullscreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.msExitFullscreen();\n };\n fullScreenApi.fullScreenEventName = \"MSFullscreenChange\";\n fullScreenApi.fullScreenErrorEventName = \"MSFullscreenError\";\n } else if ( document.webkitExitFullscreen ) {\n // Recent webkit\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.webkitFullscreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.webkitRequestFullscreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.webkitExitFullscreen();\n };\n fullScreenApi.fullScreenEventName = \"webkitfullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"webkitfullscreenerror\";\n } else if ( document.webkitCancelFullScreen ) {\n // Old webkit\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.webkitCurrentFullScreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.webkitRequestFullScreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.webkitCancelFullScreen();\n };\n fullScreenApi.fullScreenEventName = \"webkitfullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"webkitfullscreenerror\";\n } else if ( document.mozCancelFullScreen ) {\n // Firefox\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.mozFullScreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.mozRequestFullScreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.mozCancelFullScreen();\n };\n fullScreenApi.fullScreenEventName = \"mozfullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"mozfullscreenerror\";\n }\n fullScreenApi.isFullScreen = function() {\n return fullScreenApi.getFullScreenElement() !== null;\n };\n fullScreenApi.cancelFullScreen = function() {\n $.console.error(\"cancelFullScreen is deprecated. Use exitFullScreen instead.\");\n fullScreenApi.exitFullScreen();\n };\n\n // export api\n $.extend( $, fullScreenApi );\n\n})( OpenSeadragon );\n\n/*\n * OpenSeadragon - EventSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($){\n\n/**\n * Event handler method signature used by all OpenSeadragon events.\n *\n * @callback EventHandler\n * @memberof OpenSeadragon\n * @param {Object} event - See individual events for event-specific properties.\n */\n\n\n/**\n * @class EventSource\n * @classdesc For use by classes which want to support custom, non-browser events.\n *\n * @memberof OpenSeadragon\n */\n$.EventSource = function() {\n this.events = {};\n};\n\n/** @lends OpenSeadragon.EventSource.prototype */\n$.EventSource.prototype = {\n\n /**\n * Add an event handler to be triggered only once (or a given number of times)\n * for a given event.\n * @function\n * @param {String} eventName - Name of event to register.\n * @param {OpenSeadragon.EventHandler} handler - Function to call when event\n * is triggered.\n * @param {Object} [userData=null] - Arbitrary object to be passed unchanged\n * to the handler.\n * @param {Number} [times=1] - The number of times to handle the event\n * before removing it.\n */\n addOnceHandler: function(eventName, handler, userData, times) {\n var self = this;\n times = times || 1;\n var count = 0;\n var onceHandler = function(event) {\n count++;\n if (count === times) {\n self.removeHandler(eventName, onceHandler);\n }\n handler(event);\n };\n this.addHandler(eventName, onceHandler, userData);\n },\n\n /**\n * Add an event handler for a given event.\n * @function\n * @param {String} eventName - Name of event to register.\n * @param {OpenSeadragon.EventHandler} handler - Function to call when event is triggered.\n * @param {Object} [userData=null] - Arbitrary object to be passed unchanged to the handler.\n */\n addHandler: function ( eventName, handler, userData ) {\n var events = this.events[ eventName ];\n if ( !events ) {\n this.events[ eventName ] = events = [];\n }\n if ( handler && $.isFunction( handler ) ) {\n events[ events.length ] = { handler: handler, userData: userData || null };\n }\n },\n\n /**\n * Remove a specific event handler for a given event.\n * @function\n * @param {String} eventName - Name of event for which the handler is to be removed.\n * @param {OpenSeadragon.EventHandler} handler - Function to be removed.\n */\n removeHandler: function ( eventName, handler ) {\n var events = this.events[ eventName ],\n handlers = [],\n i;\n if ( !events ) {\n return;\n }\n if ( $.isArray( events ) ) {\n for ( i = 0; i < events.length; i++ ) {\n if ( events[i].handler !== handler ) {\n handlers.push( events[ i ] );\n }\n }\n this.events[ eventName ] = handlers;\n }\n },\n\n\n /**\n * Remove all event handlers for a given event type. If no type is given all\n * event handlers for every event type are removed.\n * @function\n * @param {String} eventName - Name of event for which all handlers are to be removed.\n */\n removeAllHandlers: function( eventName ) {\n if ( eventName ){\n this.events[ eventName ] = [];\n } else{\n for ( var eventType in this.events ) {\n this.events[ eventType ] = [];\n }\n }\n },\n\n /**\n * Get a function which iterates the list of all handlers registered for a given event, calling the handler for each.\n * @function\n * @param {String} eventName - Name of event to get handlers for.\n */\n getHandler: function ( eventName ) {\n var events = this.events[ eventName ];\n if ( !events || !events.length ) {\n return null;\n }\n events = events.length === 1 ?\n [ events[ 0 ] ] :\n Array.apply( null, events );\n return function ( source, args ) {\n var i,\n length = events.length;\n for ( i = 0; i < length; i++ ) {\n if ( events[ i ] ) {\n args.eventSource = source;\n args.userData = events[ i ].userData;\n events[ i ].handler( args );\n }\n }\n };\n },\n\n /**\n * Trigger an event, optionally passing additional information.\n * @function\n * @param {String} eventName - Name of event to register.\n * @param {Object} eventArgs - Event-specific data.\n */\n raiseEvent: function( eventName, eventArgs ) {\n //uncomment if you want to get a log of all events\n //$.console.log( eventName );\n var handler = this.getHandler( eventName );\n\n if ( handler ) {\n if ( !eventArgs ) {\n eventArgs = {};\n }\n\n handler( this, eventArgs );\n }\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - MouseTracker\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function ( $ ) {\n\n // All MouseTracker instances\n var MOUSETRACKERS = [];\n\n // dictionary from hash to private properties\n var THIS = {};\n\n\n /**\n * @class MouseTracker\n * @classdesc Provides simplified handling of common pointer device (mouse, touch, pen, etc.) gestures\n * and keyboard events on a specified element.\n * @memberof OpenSeadragon\n * @param {Object} options\n * Allows configurable properties to be entirely specified by passing\n * an options object to the constructor. The constructor also supports\n * the original positional arguments 'element', 'clickTimeThreshold',\n * and 'clickDistThreshold' in that order.\n * @param {Element|String} options.element\n * A reference to an element or an element id for which the pointer/key\n * events will be monitored.\n * @param {Boolean} [options.startDisabled=false]\n * If true, event tracking on the element will not start until\n * {@link OpenSeadragon.MouseTracker.setTracking|setTracking} is called.\n * @param {Number} options.clickTimeThreshold\n * The number of milliseconds within which a pointer down-up event combination\n * will be treated as a click gesture.\n * @param {Number} options.clickDistThreshold\n * The maximum distance allowed between a pointer down event and a pointer up event\n * to be treated as a click gesture.\n * @param {Number} options.dblClickTimeThreshold\n * The number of milliseconds within which two pointer down-up event combinations\n * will be treated as a double-click gesture.\n * @param {Number} options.dblClickDistThreshold\n * The maximum distance allowed between two pointer click events\n * to be treated as a click gesture.\n * @param {Number} [options.stopDelay=50]\n * The number of milliseconds without pointer move before the stop\n * event is fired.\n * @param {OpenSeadragon.EventHandler} [options.enterHandler=null]\n * An optional handler for pointer enter.\n * @param {OpenSeadragon.EventHandler} [options.exitHandler=null]\n * An optional handler for pointer exit.\n * @param {OpenSeadragon.EventHandler} [options.pressHandler=null]\n * An optional handler for pointer press.\n * @param {OpenSeadragon.EventHandler} [options.nonPrimaryPressHandler=null]\n * An optional handler for pointer non-primary button press.\n * @param {OpenSeadragon.EventHandler} [options.releaseHandler=null]\n * An optional handler for pointer release.\n * @param {OpenSeadragon.EventHandler} [options.nonPrimaryReleaseHandler=null]\n * An optional handler for pointer non-primary button release.\n * @param {OpenSeadragon.EventHandler} [options.moveHandler=null]\n * An optional handler for pointer move.\n * @param {OpenSeadragon.EventHandler} [options.scrollHandler=null]\n * An optional handler for mouse wheel scroll.\n * @param {OpenSeadragon.EventHandler} [options.clickHandler=null]\n * An optional handler for pointer click.\n * @param {OpenSeadragon.EventHandler} [options.dblClickHandler=null]\n * An optional handler for pointer double-click.\n * @param {OpenSeadragon.EventHandler} [options.dragHandler=null]\n * An optional handler for the drag gesture.\n * @param {OpenSeadragon.EventHandler} [options.dragEndHandler=null]\n * An optional handler for after a drag gesture.\n * @param {OpenSeadragon.EventHandler} [options.pinchHandler=null]\n * An optional handler for the pinch gesture.\n * @param {OpenSeadragon.EventHandler} [options.keyDownHandler=null]\n * An optional handler for keydown.\n * @param {OpenSeadragon.EventHandler} [options.keyUpHandler=null]\n * An optional handler for keyup.\n * @param {OpenSeadragon.EventHandler} [options.keyHandler=null]\n * An optional handler for keypress.\n * @param {OpenSeadragon.EventHandler} [options.focusHandler=null]\n * An optional handler for focus.\n * @param {OpenSeadragon.EventHandler} [options.blurHandler=null]\n * An optional handler for blur.\n * @param {Object} [options.userData=null]\n * Arbitrary object to be passed unchanged to any attached handler methods.\n */\n $.MouseTracker = function ( options ) {\n\n MOUSETRACKERS.push( this );\n\n var args = arguments;\n\n if ( !$.isPlainObject( options ) ) {\n options = {\n element: args[ 0 ],\n clickTimeThreshold: args[ 1 ],\n clickDistThreshold: args[ 2 ]\n };\n }\n\n this.hash = Math.random(); // An unique hash for this tracker.\n /**\n * The element for which pointer events are being monitored.\n * @member {Element} element\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.element = $.getElement( options.element );\n /**\n * The number of milliseconds within which a pointer down-up event combination\n * will be treated as a click gesture.\n * @member {Number} clickTimeThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.clickTimeThreshold = options.clickTimeThreshold || $.DEFAULT_SETTINGS.clickTimeThreshold;\n /**\n * The maximum distance allowed between a pointer down event and a pointer up event\n * to be treated as a click gesture.\n * @member {Number} clickDistThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.clickDistThreshold = options.clickDistThreshold || $.DEFAULT_SETTINGS.clickDistThreshold;\n /**\n * The number of milliseconds within which two pointer down-up event combinations\n * will be treated as a double-click gesture.\n * @member {Number} dblClickTimeThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.dblClickTimeThreshold = options.dblClickTimeThreshold || $.DEFAULT_SETTINGS.dblClickTimeThreshold;\n /**\n * The maximum distance allowed between two pointer click events\n * to be treated as a click gesture.\n * @member {Number} clickDistThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.dblClickDistThreshold = options.dblClickDistThreshold || $.DEFAULT_SETTINGS.dblClickDistThreshold;\n /*eslint-disable no-multi-spaces*/\n this.userData = options.userData || null;\n this.stopDelay = options.stopDelay || 50;\n\n this.enterHandler = options.enterHandler || null;\n this.exitHandler = options.exitHandler || null;\n this.pressHandler = options.pressHandler || null;\n this.nonPrimaryPressHandler = options.nonPrimaryPressHandler || null;\n this.releaseHandler = options.releaseHandler || null;\n this.nonPrimaryReleaseHandler = options.nonPrimaryReleaseHandler || null;\n this.moveHandler = options.moveHandler || null;\n this.scrollHandler = options.scrollHandler || null;\n this.clickHandler = options.clickHandler || null;\n this.dblClickHandler = options.dblClickHandler || null;\n this.dragHandler = options.dragHandler || null;\n this.dragEndHandler = options.dragEndHandler || null;\n this.pinchHandler = options.pinchHandler || null;\n this.stopHandler = options.stopHandler || null;\n this.keyDownHandler = options.keyDownHandler || null;\n this.keyUpHandler = options.keyUpHandler || null;\n this.keyHandler = options.keyHandler || null;\n this.focusHandler = options.focusHandler || null;\n this.blurHandler = options.blurHandler || null;\n /*eslint-enable no-multi-spaces*/\n\n //Store private properties in a scope sealed hash map\n var _this = this;\n\n /**\n * @private\n * @property {Boolean} tracking\n * Are we currently tracking pointer events for this element.\n */\n THIS[ this.hash ] = {\n click: function ( event ) { onClick( _this, event ); },\n dblclick: function ( event ) { onDblClick( _this, event ); },\n keydown: function ( event ) { onKeyDown( _this, event ); },\n keyup: function ( event ) { onKeyUp( _this, event ); },\n keypress: function ( event ) { onKeyPress( _this, event ); },\n focus: function ( event ) { onFocus( _this, event ); },\n blur: function ( event ) { onBlur( _this, event ); },\n\n wheel: function ( event ) { onWheel( _this, event ); },\n mousewheel: function ( event ) { onMouseWheel( _this, event ); },\n DOMMouseScroll: function ( event ) { onMouseWheel( _this, event ); },\n MozMousePixelScroll: function ( event ) { onMouseWheel( _this, event ); },\n\n mouseenter: function ( event ) { onMouseEnter( _this, event ); }, // Used on IE8 only\n mouseleave: function ( event ) { onMouseLeave( _this, event ); }, // Used on IE8 only\n mouseover: function ( event ) { onMouseOver( _this, event ); },\n mouseout: function ( event ) { onMouseOut( _this, event ); },\n mousedown: function ( event ) { onMouseDown( _this, event ); },\n mouseup: function ( event ) { onMouseUp( _this, event ); },\n mouseupcaptured: function ( event ) { onMouseUpCaptured( _this, event ); },\n mousemove: function ( event ) { onMouseMove( _this, event ); },\n mousemovecaptured: function ( event ) { onMouseMoveCaptured( _this, event ); },\n\n touchstart: function ( event ) { onTouchStart( _this, event ); },\n touchend: function ( event ) { onTouchEnd( _this, event ); },\n touchendcaptured: function ( event ) { onTouchEndCaptured( _this, event ); },\n touchmove: function ( event ) { onTouchMove( _this, event ); },\n touchmovecaptured: function ( event ) { onTouchMoveCaptured( _this, event ); },\n touchcancel: function ( event ) { onTouchCancel( _this, event ); },\n\n gesturestart: function ( event ) { onGestureStart( _this, event ); },\n gesturechange: function ( event ) { onGestureChange( _this, event ); },\n\n pointerover: function ( event ) { onPointerOver( _this, event ); },\n MSPointerOver: function ( event ) { onPointerOver( _this, event ); },\n pointerout: function ( event ) { onPointerOut( _this, event ); },\n MSPointerOut: function ( event ) { onPointerOut( _this, event ); },\n pointerdown: function ( event ) { onPointerDown( _this, event ); },\n MSPointerDown: function ( event ) { onPointerDown( _this, event ); },\n pointerup: function ( event ) { onPointerUp( _this, event ); },\n MSPointerUp: function ( event ) { onPointerUp( _this, event ); },\n pointermove: function ( event ) { onPointerMove( _this, event ); },\n MSPointerMove: function ( event ) { onPointerMove( _this, event ); },\n pointercancel: function ( event ) { onPointerCancel( _this, event ); },\n MSPointerCancel: function ( event ) { onPointerCancel( _this, event ); },\n pointerupcaptured: function ( event ) { onPointerUpCaptured( _this, event ); },\n pointermovecaptured: function ( event ) { onPointerMoveCaptured( _this, event ); },\n\n tracking: false,\n\n // Active pointers lists. Array of GesturePointList objects, one for each pointer device type.\n // GesturePointList objects are added each time a pointer is tracked by a new pointer device type (see getActivePointersListByType()).\n // Active pointers are any pointer being tracked for this element which are in the hit-test area\n // of the element (for hover-capable devices) and/or have contact or a button press initiated in the element.\n activePointersLists: [],\n\n // Tracking for double-click gesture\n lastClickPos: null,\n dblClickTimeOut: null,\n\n // Tracking for pinch gesture\n pinchGPoints: [],\n lastPinchDist: 0,\n currentPinchDist: 0,\n lastPinchCenter: null,\n currentPinchCenter: null\n };\n\n if ( !options.startDisabled ) {\n this.setTracking( true );\n }\n };\n\n /** @lends OpenSeadragon.MouseTracker.prototype */\n $.MouseTracker.prototype = {\n\n /**\n * Clean up any events or objects created by the tracker.\n * @function\n */\n destroy: function () {\n var i;\n\n stopTracking( this );\n this.element = null;\n\n for ( i = 0; i < MOUSETRACKERS.length; i++ ) {\n if ( MOUSETRACKERS[ i ] === this ) {\n MOUSETRACKERS.splice( i, 1 );\n break;\n }\n }\n\n THIS[ this.hash ] = null;\n delete THIS[ this.hash ];\n },\n\n /**\n * Are we currently tracking events on this element.\n * @deprecated Just use this.tracking\n * @function\n * @returns {Boolean} Are we currently tracking events on this element.\n */\n isTracking: function () {\n return THIS[ this.hash ].tracking;\n },\n\n /**\n * Enable or disable whether or not we are tracking events on this element.\n * @function\n * @param {Boolean} track True to start tracking, false to stop tracking.\n * @returns {OpenSeadragon.MouseTracker} Chainable.\n */\n setTracking: function ( track ) {\n if ( track ) {\n startTracking( this );\n } else {\n stopTracking( this );\n }\n //chain\n return this;\n },\n\n /**\n * Returns the {@link OpenSeadragon.MouseTracker.GesturePointList|GesturePointList} for all but the given pointer device type.\n * @function\n * @param {String} type - The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @returns {Array.}\n */\n getActivePointersListsExceptType: function ( type ) {\n var delegate = THIS[ this.hash ];\n var listArray = [];\n\n for (var i = 0; i < delegate.activePointersLists.length; ++i) {\n if (delegate.activePointersLists[i].type !== type) {\n listArray.push(delegate.activePointersLists[i]);\n }\n }\n\n return listArray;\n },\n\n /**\n * Returns the {@link OpenSeadragon.MouseTracker.GesturePointList|GesturePointList} for the given pointer device type,\n * creating and caching a new {@link OpenSeadragon.MouseTracker.GesturePointList|GesturePointList} if one doesn't already exist for the type.\n * @function\n * @param {String} type - The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @returns {OpenSeadragon.MouseTracker.GesturePointList}\n */\n getActivePointersListByType: function ( type ) {\n var delegate = THIS[ this.hash ],\n i,\n len = delegate.activePointersLists.length,\n list;\n\n for ( i = 0; i < len; i++ ) {\n if ( delegate.activePointersLists[ i ].type === type ) {\n return delegate.activePointersLists[ i ];\n }\n }\n\n list = new $.MouseTracker.GesturePointList( type );\n delegate.activePointersLists.push( list );\n return list;\n },\n\n /**\n * Returns the total number of pointers currently active on the tracked element.\n * @function\n * @returns {Number}\n */\n getActivePointerCount: function () {\n var delegate = THIS[ this.hash ],\n i,\n len = delegate.activePointersLists.length,\n count = 0;\n\n for ( i = 0; i < len; i++ ) {\n count += delegate.activePointersLists[ i ].getLength();\n }\n\n return count;\n },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Number} event.pointers\n * Number of pointers (all types) active in the tracked element.\n * @param {Boolean} event.insideElementPressed\n * True if the left mouse button is currently being pressed and was\n * initiated inside the tracked element, otherwise false.\n * @param {Boolean} event.buttonDownAny\n * Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n enterHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Number} event.pointers\n * Number of pointers (all types) active in the tracked element.\n * @param {Boolean} event.insideElementPressed\n * True if the left mouse button is currently being pressed and was\n * initiated inside the tracked element, otherwise false.\n * @param {Boolean} event.buttonDownAny\n * Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n exitHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n pressHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.button\n * Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n nonPrimaryPressHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.insideElementPressed\n * True if the left mouse button is currently being pressed and was\n * initiated inside the tracked element, otherwise false.\n * @param {Boolean} event.insideElementReleased\n * True if the cursor inside the tracked element when the button was released.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n releaseHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.button\n * Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n nonPrimaryReleaseHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n moveHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.scroll\n * The scroll delta for the event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead. Touch devices no longer generate scroll event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n scrollHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Boolean} event.quick\n * True only if the clickDistThreshold and clickTimeThreshold are both passed. Useful for ignoring drag events.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n clickHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n dblClickHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {OpenSeadragon.Point} event.delta\n * The x,y components of the difference between the current position and the last drag event position. Useful for ignoring or weighting the events.\n * @param {Number} event.speed\n * Current computed speed, in pixels per second.\n * @param {Number} event.direction\n * Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n dragHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.speed\n * Speed at the end of a drag gesture, in pixels per second.\n * @param {Number} event.direction\n * Direction at the end of a drag gesture, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n dragEndHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {Array.} event.gesturePoints\n * Gesture points associated with the gesture. Velocity data can be found here.\n * @param {OpenSeadragon.Point} event.lastCenter\n * The previous center point of the two pinch contact points relative to the tracked element.\n * @param {OpenSeadragon.Point} event.center\n * The center point of the two pinch contact points relative to the tracked element.\n * @param {Number} event.lastDistance\n * The previous distance between the two pinch contact points in CSS pixels.\n * @param {Number} event.distance\n * The distance between the two pinch contact points in CSS pixels.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n pinchHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n stopHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Number} event.keyCode\n * The key code that was pressed.\n * @param {Boolean} event.ctrl\n * True if the ctrl key was pressed during this event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.alt\n * True if the alt key was pressed during this event.\n * @param {Boolean} event.meta\n * True if the meta key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n keyDownHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Number} event.keyCode\n * The key code that was pressed.\n * @param {Boolean} event.ctrl\n * True if the ctrl key was pressed during this event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.alt\n * True if the alt key was pressed during this event.\n * @param {Boolean} event.meta\n * True if the meta key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n keyUpHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Number} event.keyCode\n * The key code that was pressed.\n * @param {Boolean} event.ctrl\n * True if the ctrl key was pressed during this event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.alt\n * True if the alt key was pressed during this event.\n * @param {Boolean} event.meta\n * True if the meta key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n keyHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n focusHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n blurHandler: function () { }\n };\n\n /**\n * Resets all active mousetrakers. (Added to patch issue #697 \"Mouse up outside map will cause \"canvas-drag\" event to stick\")\n *\n * @private\n * @member resetAllMouseTrackers\n * @memberof OpenSeadragon.MouseTracker\n */\n $.MouseTracker.resetAllMouseTrackers = function(){\n for(var i = 0; i < MOUSETRACKERS.length; i++){\n if (MOUSETRACKERS[i].isTracking()){\n MOUSETRACKERS[i].setTracking(false);\n MOUSETRACKERS[i].setTracking(true);\n }\n }\n };\n\n /**\n * Provides continuous computation of velocity (speed and direction) of active pointers.\n * This is a singleton, used by all MouseTracker instances, as it is unlikely there will ever be more than\n * two active gesture pointers at a time.\n *\n * @private\n * @member gesturePointVelocityTracker\n * @memberof OpenSeadragon.MouseTracker\n */\n $.MouseTracker.gesturePointVelocityTracker = (function () {\n var trackerPoints = [],\n intervalId = 0,\n lastTime = 0;\n\n // Generates a unique identifier for a tracked gesture point\n var _generateGuid = function ( tracker, gPoint ) {\n return tracker.hash.toString() + gPoint.type + gPoint.id.toString();\n };\n\n // Interval timer callback. Computes velocity for all tracked gesture points.\n var _doTracking = function () {\n var i,\n len = trackerPoints.length,\n trackPoint,\n gPoint,\n now = $.now(),\n elapsedTime,\n distance,\n speed;\n\n elapsedTime = now - lastTime;\n lastTime = now;\n\n for ( i = 0; i < len; i++ ) {\n trackPoint = trackerPoints[ i ];\n gPoint = trackPoint.gPoint;\n // Math.atan2 gives us just what we need for a velocity vector, as we can simply\n // use cos()/sin() to extract the x/y velocity components.\n gPoint.direction = Math.atan2( gPoint.currentPos.y - trackPoint.lastPos.y, gPoint.currentPos.x - trackPoint.lastPos.x );\n // speed = distance / elapsed time\n distance = trackPoint.lastPos.distanceTo( gPoint.currentPos );\n trackPoint.lastPos = gPoint.currentPos;\n speed = 1000 * distance / ( elapsedTime + 1 );\n // Simple biased average, favors the most recent speed computation. Smooths out erratic gestures a bit.\n gPoint.speed = 0.75 * speed + 0.25 * gPoint.speed;\n }\n };\n\n // Public. Add a gesture point to be tracked\n var addPoint = function ( tracker, gPoint ) {\n var guid = _generateGuid( tracker, gPoint );\n\n trackerPoints.push(\n {\n guid: guid,\n gPoint: gPoint,\n lastPos: gPoint.currentPos\n } );\n\n // Only fire up the interval timer when there's gesture pointers to track\n if ( trackerPoints.length === 1 ) {\n lastTime = $.now();\n intervalId = window.setInterval( _doTracking, 50 );\n }\n };\n\n // Public. Stop tracking a gesture point\n var removePoint = function ( tracker, gPoint ) {\n var guid = _generateGuid( tracker, gPoint ),\n i,\n len = trackerPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( trackerPoints[ i ].guid === guid ) {\n trackerPoints.splice( i, 1 );\n // Only run the interval timer if theres gesture pointers to track\n len--;\n if ( len === 0 ) {\n window.clearInterval( intervalId );\n }\n break;\n }\n }\n };\n\n return {\n addPoint: addPoint,\n removePoint: removePoint\n };\n } )();\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Pointer event model and feature detection\n///////////////////////////////////////////////////////////////////////////////\n\n $.MouseTracker.captureElement = document;\n\n /**\n * Detect available mouse wheel event name.\n */\n $.MouseTracker.wheelEventName = ( $.Browser.vendor == $.BROWSERS.IE && $.Browser.version > 8 ) ||\n ( 'onwheel' in document.createElement( 'div' ) ) ? 'wheel' : // Modern browsers support 'wheel'\n document.onmousewheel !== undefined ? 'mousewheel' : // Webkit and IE support at least 'mousewheel'\n 'DOMMouseScroll'; // Assume old Firefox\n\n /**\n * Detect legacy mouse capture support.\n */\n $.MouseTracker.supportsMouseCapture = (function () {\n var divElement = document.createElement( 'div' );\n return $.isFunction( divElement.setCapture ) && $.isFunction( divElement.releaseCapture );\n }());\n\n /**\n * Detect browser pointer device event model(s) and build appropriate list of events to subscribe to.\n */\n $.MouseTracker.subscribeEvents = [ \"click\", \"dblclick\", \"keydown\", \"keyup\", \"keypress\", \"focus\", \"blur\", $.MouseTracker.wheelEventName ];\n\n if( $.MouseTracker.wheelEventName == \"DOMMouseScroll\" ) {\n // Older Firefox\n $.MouseTracker.subscribeEvents.push( \"MozMousePixelScroll\" );\n }\n\n // Note: window.navigator.pointerEnable is deprecated on IE 11 and not part of W3C spec.\n if ( window.PointerEvent && ( window.navigator.pointerEnabled || $.Browser.vendor !== $.BROWSERS.IE ) ) {\n // IE11 and other W3C Pointer Event implementations (see http://www.w3.org/TR/pointerevents)\n $.MouseTracker.havePointerEvents = true;\n $.MouseTracker.subscribeEvents.push( \"pointerover\", \"pointerout\", \"pointerdown\", \"pointerup\", \"pointermove\", \"pointercancel\" );\n $.MouseTracker.unprefixedPointerEvents = true;\n if( navigator.maxTouchPoints ) {\n $.MouseTracker.maxTouchPoints = navigator.maxTouchPoints;\n } else {\n $.MouseTracker.maxTouchPoints = 0;\n }\n $.MouseTracker.haveMouseEnter = false;\n } else if ( window.MSPointerEvent && window.navigator.msPointerEnabled ) {\n // IE10\n $.MouseTracker.havePointerEvents = true;\n $.MouseTracker.subscribeEvents.push( \"MSPointerOver\", \"MSPointerOut\", \"MSPointerDown\", \"MSPointerUp\", \"MSPointerMove\", \"MSPointerCancel\" );\n $.MouseTracker.unprefixedPointerEvents = false;\n if( navigator.msMaxTouchPoints ) {\n $.MouseTracker.maxTouchPoints = navigator.msMaxTouchPoints;\n } else {\n $.MouseTracker.maxTouchPoints = 0;\n }\n $.MouseTracker.haveMouseEnter = false;\n } else {\n // Legacy W3C mouse events\n $.MouseTracker.havePointerEvents = false;\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n $.MouseTracker.subscribeEvents.push( \"mouseenter\", \"mouseleave\" );\n $.MouseTracker.haveMouseEnter = true;\n } else {\n $.MouseTracker.subscribeEvents.push( \"mouseover\", \"mouseout\" );\n $.MouseTracker.haveMouseEnter = false;\n }\n $.MouseTracker.subscribeEvents.push( \"mousedown\", \"mouseup\", \"mousemove\" );\n if ( 'ontouchstart' in window ) {\n // iOS, Android, and other W3c Touch Event implementations\n // (see http://www.w3.org/TR/touch-events/)\n // (see https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)\n // (see https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)\n $.MouseTracker.subscribeEvents.push( \"touchstart\", \"touchend\", \"touchmove\", \"touchcancel\" );\n }\n if ( 'ongesturestart' in window ) {\n // iOS (see https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)\n // Subscribe to these to prevent default gesture handling\n $.MouseTracker.subscribeEvents.push( \"gesturestart\", \"gesturechange\" );\n }\n $.MouseTracker.mousePointerId = \"legacy-mouse\";\n $.MouseTracker.maxTouchPoints = 10;\n }\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Classes and typedefs\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * Represents a point of contact on the screen made by a mouse cursor, pen, touch, or other pointer device.\n *\n * @typedef {Object} GesturePoint\n * @memberof OpenSeadragon.MouseTracker\n *\n * @property {Number} id\n * Identifier unique from all other active GesturePoints for a given pointer device.\n * @property {String} type\n * The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @property {Boolean} captured\n * True if events for the gesture point are captured to the tracked element.\n * @property {Boolean} isPrimary\n * True if the gesture point is a master pointer amongst the set of active pointers for each pointer type. True for mouse and primary (first) touch/pen pointers.\n * @property {Boolean} insideElementPressed\n * True if button pressed or contact point initiated inside the screen area of the tracked element.\n * @property {Boolean} insideElement\n * True if pointer or contact point is currently inside the bounds of the tracked element.\n * @property {Number} speed\n * Current computed speed, in pixels per second.\n * @property {Number} direction\n * Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @property {OpenSeadragon.Point} contactPos\n * The initial pointer contact position, relative to the page including any scrolling. Only valid if the pointer has contact (pressed, touch contact, pen contact).\n * @property {Number} contactTime\n * The initial pointer contact time, in milliseconds. Only valid if the pointer has contact (pressed, touch contact, pen contact).\n * @property {OpenSeadragon.Point} lastPos\n * The last pointer position, relative to the page including any scrolling.\n * @property {Number} lastTime\n * The last pointer contact time, in milliseconds.\n * @property {OpenSeadragon.Point} currentPos\n * The current pointer position, relative to the page including any scrolling.\n * @property {Number} currentTime\n * The current pointer contact time, in milliseconds.\n */\n\n\n /**\n * @class GesturePointList\n * @classdesc Provides an abstraction for a set of active {@link OpenSeadragon.MouseTracker.GesturePoint|GesturePoint} objects for a given pointer device type.\n * Active pointers are any pointer being tracked for this element which are in the hit-test area\n * of the element (for hover-capable devices) and/or have contact or a button press initiated in the element.\n * @memberof OpenSeadragon.MouseTracker\n * @param {String} type - The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n */\n $.MouseTracker.GesturePointList = function ( type ) {\n this._gPoints = [];\n /**\n * The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @member {String} type\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.type = type;\n /**\n * Current buttons pressed for the device.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @member {Number} buttons\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.buttons = 0;\n /**\n * Current number of contact points (touch points, mouse down, etc.) for the device.\n * @member {Number} contacts\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.contacts = 0;\n /**\n * Current number of clicks for the device. Used for multiple click gesture tracking.\n * @member {Number} clicks\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.clicks = 0;\n /**\n * Current number of captured pointers for the device.\n * @member {Number} captureCount\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.captureCount = 0;\n };\n\n /** @lends OpenSeadragon.MouseTracker.GesturePointList.prototype */\n $.MouseTracker.GesturePointList.prototype = {\n /**\n * @function\n * @returns {Number} Number of gesture points in the list.\n */\n getLength: function () {\n return this._gPoints.length;\n },\n /**\n * @function\n * @returns {Array.} The list of gesture points in the list as an array (read-only).\n */\n asArray: function () {\n return this._gPoints;\n },\n /**\n * @function\n * @param {OpenSeadragon.MouseTracker.GesturePoint} gesturePoint - A gesture point to add to the list.\n * @returns {Number} Number of gesture points in the list.\n */\n add: function ( gp ) {\n return this._gPoints.push( gp );\n },\n /**\n * @function\n * @param {Number} id - The id of the gesture point to remove from the list.\n * @returns {Number} Number of gesture points in the list.\n */\n removeById: function ( id ) {\n var i,\n len = this._gPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( this._gPoints[ i ].id === id ) {\n this._gPoints.splice( i, 1 );\n break;\n }\n }\n return this._gPoints.length;\n },\n /**\n * @function\n * @param {Number} index - The index of the gesture point to retrieve from the list.\n * @returns {OpenSeadragon.MouseTracker.GesturePoint|null} The gesture point at the given index, or null if not found.\n */\n getByIndex: function ( index ) {\n if ( index < this._gPoints.length) {\n return this._gPoints[ index ];\n }\n\n return null;\n },\n /**\n * @function\n * @param {Number} id - The id of the gesture point to retrieve from the list.\n * @returns {OpenSeadragon.MouseTracker.GesturePoint|null} The gesture point with the given id, or null if not found.\n */\n getById: function ( id ) {\n var i,\n len = this._gPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( this._gPoints[ i ].id === id ) {\n return this._gPoints[ i ];\n }\n }\n return null;\n },\n /**\n * @function\n * @returns {OpenSeadragon.MouseTracker.GesturePoint|null} The primary gesture point in the list, or null if not found.\n */\n getPrimary: function ( id ) {\n var i,\n len = this._gPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( this._gPoints[ i ].isPrimary ) {\n return this._gPoints[ i ];\n }\n }\n return null;\n },\n\n /**\n * Increment this pointer's contact count.\n * It will evaluate whether this pointer type is allowed to have multiple contacts.\n * @function\n */\n addContact: function() {\n ++this.contacts;\n\n if (this.contacts > 1 && (this.type === \"mouse\" || this.type === \"pen\")) {\n this.contacts = 1;\n }\n },\n\n /**\n * Decrement this pointer's contact count.\n * It will make sure the count does not go below 0.\n * @function\n */\n removeContact: function() {\n --this.contacts;\n\n if (this.contacts < 0) {\n this.contacts = 0;\n }\n }\n };\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Utility functions\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * Removes all tracked pointers.\n * @private\n * @inner\n */\n function clearTrackedPointers( tracker ) {\n var delegate = THIS[ tracker.hash ],\n i,\n pointerListCount = delegate.activePointersLists.length;\n\n for ( i = 0; i < pointerListCount; i++ ) {\n if ( delegate.activePointersLists[ i ].captureCount > 0 ) {\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'mousemove',\n delegate.mousemovecaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'mouseup',\n delegate.mouseupcaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n $.MouseTracker.unprefixedPointerEvents ? 'pointermove' : 'MSPointerMove',\n delegate.pointermovecaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n $.MouseTracker.unprefixedPointerEvents ? 'pointerup' : 'MSPointerUp',\n delegate.pointerupcaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'touchmove',\n delegate.touchmovecaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'touchend',\n delegate.touchendcaptured,\n true\n );\n\n delegate.activePointersLists[ i ].captureCount = 0;\n }\n }\n\n for ( i = 0; i < pointerListCount; i++ ) {\n delegate.activePointersLists.pop();\n }\n }\n\n /**\n * Starts tracking pointer events on the tracked element.\n * @private\n * @inner\n */\n function startTracking( tracker ) {\n var delegate = THIS[ tracker.hash ],\n event,\n i;\n\n if ( !delegate.tracking ) {\n for ( i = 0; i < $.MouseTracker.subscribeEvents.length; i++ ) {\n event = $.MouseTracker.subscribeEvents[ i ];\n $.addEvent(\n tracker.element,\n event,\n delegate[ event ],\n false\n );\n }\n\n clearTrackedPointers( tracker );\n\n delegate.tracking = true;\n }\n }\n\n /**\n * Stops tracking pointer events on the tracked element.\n * @private\n * @inner\n */\n function stopTracking( tracker ) {\n var delegate = THIS[ tracker.hash ],\n event,\n i;\n\n if ( delegate.tracking ) {\n for ( i = 0; i < $.MouseTracker.subscribeEvents.length; i++ ) {\n event = $.MouseTracker.subscribeEvents[ i ];\n $.removeEvent(\n tracker.element,\n event,\n delegate[ event ],\n false\n );\n }\n\n clearTrackedPointers( tracker );\n\n delegate.tracking = false;\n }\n }\n\n /**\n * @private\n * @inner\n */\n function getCaptureEventParams( tracker, pointerType ) {\n var delegate = THIS[ tracker.hash ];\n\n if ( pointerType === 'pointerevent' ) {\n return {\n upName: $.MouseTracker.unprefixedPointerEvents ? 'pointerup' : 'MSPointerUp',\n upHandler: delegate.pointerupcaptured,\n moveName: $.MouseTracker.unprefixedPointerEvents ? 'pointermove' : 'MSPointerMove',\n moveHandler: delegate.pointermovecaptured\n };\n } else if ( pointerType === 'mouse' ) {\n return {\n upName: 'mouseup',\n upHandler: delegate.mouseupcaptured,\n moveName: 'mousemove',\n moveHandler: delegate.mousemovecaptured\n };\n } else if ( pointerType === 'touch' ) {\n return {\n upName: 'touchend',\n upHandler: delegate.touchendcaptured,\n moveName: 'touchmove',\n moveHandler: delegate.touchmovecaptured\n };\n } else {\n throw new Error( \"MouseTracker.getCaptureEventParams: Unknown pointer type.\" );\n }\n }\n\n /**\n * Begin capturing pointer events to the tracked element.\n * @private\n * @inner\n */\n function capturePointer( tracker, pointerType, pointerCount ) {\n var pointsList = tracker.getActivePointersListByType( pointerType ),\n eventParams;\n\n pointsList.captureCount += (pointerCount || 1);\n\n if ( pointsList.captureCount === 1 ) {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n tracker.element.setCapture( true );\n } else {\n eventParams = getCaptureEventParams( tracker, $.MouseTracker.havePointerEvents ? 'pointerevent' : pointerType );\n // We emulate mouse capture by hanging listeners on the document object.\n // (Note we listen on the capture phase so the captured handlers will get called first)\n // eslint-disable-next-line no-use-before-define\n if (isInIframe && canAccessEvents(window.top)) {\n $.addEvent(\n window.top,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n }\n $.addEvent(\n $.MouseTracker.captureElement,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n $.addEvent(\n $.MouseTracker.captureElement,\n eventParams.moveName,\n eventParams.moveHandler,\n true\n );\n }\n }\n }\n\n\n /**\n * Stop capturing pointer events to the tracked element.\n * @private\n * @inner\n */\n function releasePointer( tracker, pointerType, pointerCount ) {\n var pointsList = tracker.getActivePointersListByType( pointerType ),\n eventParams;\n\n pointsList.captureCount -= (pointerCount || 1);\n\n if ( pointsList.captureCount === 0 ) {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n tracker.element.releaseCapture();\n } else {\n eventParams = getCaptureEventParams( tracker, $.MouseTracker.havePointerEvents ? 'pointerevent' : pointerType );\n // We emulate mouse capture by hanging listeners on the document object.\n // (Note we listen on the capture phase so the captured handlers will get called first)\n // eslint-disable-next-line no-use-before-define\n if (isInIframe && canAccessEvents(window.top)) {\n $.removeEvent(\n window.top,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n }\n $.removeEvent(\n $.MouseTracker.captureElement,\n eventParams.moveName,\n eventParams.moveHandler,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n }\n }\n }\n\n\n /**\n * Gets a W3C Pointer Events model compatible pointer type string from a DOM pointer event.\n * IE10 used a long integer value, but the W3C specification (and IE11+) use a string \"mouse\", \"touch\", \"pen\", etc.\n * @private\n * @inner\n */\n function getPointerType( event ) {\n var pointerTypeStr;\n if ( $.MouseTracker.unprefixedPointerEvents ) {\n pointerTypeStr = event.pointerType;\n } else {\n // IE10\n // MSPOINTER_TYPE_TOUCH: 0x00000002\n // MSPOINTER_TYPE_PEN: 0x00000003\n // MSPOINTER_TYPE_MOUSE: 0x00000004\n switch( event.pointerType )\n {\n case 0x00000002:\n pointerTypeStr = 'touch';\n break;\n case 0x00000003:\n pointerTypeStr = 'pen';\n break;\n case 0x00000004:\n pointerTypeStr = 'mouse';\n break;\n default:\n pointerTypeStr = '';\n }\n }\n return pointerTypeStr;\n }\n\n\n /**\n * @private\n * @inner\n */\n function getMouseAbsolute( event ) {\n return $.getMousePosition( event );\n }\n\n /**\n * @private\n * @inner\n */\n function getMouseRelative( event, element ) {\n return getPointRelativeToAbsolute( getMouseAbsolute( event ), element );\n }\n\n /**\n * @private\n * @inner\n */\n function getPointRelativeToAbsolute( point, element ) {\n var offset = $.getElementOffset( element );\n return point.minus( offset );\n }\n\n /**\n * @private\n * @inner\n */\n function getCenterPoint( point1, point2 ) {\n return new $.Point( ( point1.x + point2.x ) / 2, ( point1.y + point2.y ) / 2 );\n }\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Device-specific DOM event handlers\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * @private\n * @inner\n */\n function onClick( tracker, event ) {\n if ( tracker.clickHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onDblClick( tracker, event ) {\n if ( tracker.dblClickHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onKeyDown( tracker, event ) {\n //$.console.log( \"keydown %s %s %s %s %s\", event.keyCode, event.charCode, event.ctrlKey, event.shiftKey, event.altKey );\n var propagate;\n if ( tracker.keyDownHandler ) {\n event = $.getEvent( event );\n propagate = tracker.keyDownHandler(\n {\n eventSource: tracker,\n keyCode: event.keyCode ? event.keyCode : event.charCode,\n ctrl: event.ctrlKey,\n shift: event.shiftKey,\n alt: event.altKey,\n meta: event.metaKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( !propagate ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onKeyUp( tracker, event ) {\n //$.console.log( \"keyup %s %s %s %s %s\", event.keyCode, event.charCode, event.ctrlKey, event.shiftKey, event.altKey );\n var propagate;\n if ( tracker.keyUpHandler ) {\n event = $.getEvent( event );\n propagate = tracker.keyUpHandler(\n {\n eventSource: tracker,\n keyCode: event.keyCode ? event.keyCode : event.charCode,\n ctrl: event.ctrlKey,\n shift: event.shiftKey,\n alt: event.altKey,\n meta: event.metaKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( !propagate ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onKeyPress( tracker, event ) {\n //$.console.log( \"keypress %s %s %s %s %s\", event.keyCode, event.charCode, event.ctrlKey, event.shiftKey, event.altKey );\n var propagate;\n if ( tracker.keyHandler ) {\n event = $.getEvent( event );\n propagate = tracker.keyHandler(\n {\n eventSource: tracker,\n keyCode: event.keyCode ? event.keyCode : event.charCode,\n ctrl: event.ctrlKey,\n shift: event.shiftKey,\n alt: event.altKey,\n meta: event.metaKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( !propagate ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onFocus( tracker, event ) {\n //console.log( \"focus %s\", event );\n var propagate;\n if ( tracker.focusHandler ) {\n event = $.getEvent( event );\n propagate = tracker.focusHandler(\n {\n eventSource: tracker,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onBlur( tracker, event ) {\n //console.log( \"blur %s\", event );\n var propagate;\n if ( tracker.blurHandler ) {\n event = $.getEvent( event );\n propagate = tracker.blurHandler(\n {\n eventSource: tracker,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * Handler for 'wheel' events\n *\n * @private\n * @inner\n */\n function onWheel( tracker, event ) {\n handleWheelEvent( tracker, event, event );\n }\n\n\n /**\n * Handler for 'mousewheel', 'DOMMouseScroll', and 'MozMousePixelScroll' events\n *\n * @private\n * @inner\n */\n function onMouseWheel( tracker, event ) {\n event = $.getEvent( event );\n\n // Simulate a 'wheel' event\n var simulatedEvent = {\n target: event.target || event.srcElement,\n type: \"wheel\",\n shiftKey: event.shiftKey || false,\n clientX: event.clientX,\n clientY: event.clientY,\n pageX: event.pageX ? event.pageX : event.clientX,\n pageY: event.pageY ? event.pageY : event.clientY,\n deltaMode: event.type == \"MozMousePixelScroll\" ? 0 : 1, // 0=pixel, 1=line, 2=page\n deltaX: 0,\n deltaZ: 0\n };\n\n // Calculate deltaY\n if ( $.MouseTracker.wheelEventName == \"mousewheel\" ) {\n simulatedEvent.deltaY = -event.wheelDelta / $.DEFAULT_SETTINGS.pixelsPerWheelLine;\n } else {\n simulatedEvent.deltaY = event.detail;\n }\n\n handleWheelEvent( tracker, simulatedEvent, event );\n }\n\n\n /**\n * Handles 'wheel' events.\n * The event may be simulated by the legacy mouse wheel event handler (onMouseWheel()).\n *\n * @private\n * @inner\n */\n function handleWheelEvent( tracker, event, originalEvent ) {\n var nDelta = 0,\n propagate;\n\n // The nDelta variable is gated to provide smooth z-index scrolling\n // since the mouse wheel allows for substantial deltas meant for rapid\n // y-index scrolling.\n // event.deltaMode: 0=pixel, 1=line, 2=page\n // TODO: Deltas in pixel mode should be accumulated then a scroll value computed after $.DEFAULT_SETTINGS.pixelsPerWheelLine threshold reached\n nDelta = event.deltaY < 0 ? 1 : -1;\n\n if ( tracker.scrollHandler ) {\n propagate = tracker.scrollHandler(\n {\n eventSource: tracker,\n pointerType: 'mouse',\n position: getMouseRelative( event, tracker.element ),\n scroll: nDelta,\n shift: event.shiftKey,\n isTouchEvent: false,\n originalEvent: originalEvent,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( originalEvent );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function isParentChild( parent, child )\n {\n if ( parent === child ) {\n return false;\n }\n while ( child && child !== parent ) {\n child = child.parentNode;\n }\n return child === parent;\n }\n\n\n /**\n * Only used on IE 8\n *\n * @private\n * @inner\n */\n function onMouseEnter( tracker, event ) {\n event = $.getEvent( event );\n\n handleMouseEnter( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseOver( tracker, event ) {\n event = $.getEvent( event );\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n handleMouseEnter( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseEnter( tracker, event ) {\n var gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersEnter( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * Only used on IE 8\n *\n * @private\n * @inner\n */\n function onMouseLeave( tracker, event ) {\n event = $.getEvent( event );\n\n handleMouseExit( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseOut( tracker, event ) {\n event = $.getEvent( event );\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n handleMouseExit( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseExit( tracker, event ) {\n var gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersExit( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * Returns a W3C DOM level 3 standard button value given an event.button property:\n * -1 == none, 0 == primary/left, 1 == middle, 2 == secondary/right, 3 == X1/back, 4 == X2/forward, 5 == eraser (pen)\n * @private\n * @inner\n */\n function getStandardizedButton( button ) {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n // On IE 8, 0 == none, 1 == left, 2 == right, 3 == left and right, 4 == middle, 5 == left and middle, 6 == right and middle, 7 == all three\n // TODO: Support chorded (multiple) button presses on IE 8?\n if ( button === 1 ) {\n return 0;\n } else if ( button === 2 ) {\n return 2;\n } else if ( button === 4 ) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return button;\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseDown( tracker, event ) {\n var gPoint;\n\n event = $.getEvent( event );\n\n gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersDown( tracker, event, [ gPoint ], getStandardizedButton( event.button ) ) ) {\n $.stopEvent( event );\n capturePointer( tracker, 'mouse' );\n }\n\n if ( tracker.clickHandler || tracker.dblClickHandler || tracker.pressHandler || tracker.dragHandler || tracker.dragEndHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseUp( tracker, event ) {\n handleMouseUp( tracker, event );\n }\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onMouseUp is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onMouseUpCaptured( tracker, event ) {\n handleMouseUp( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseUp( tracker, event ) {\n var gPoint;\n\n event = $.getEvent( event );\n\n gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersUp( tracker, event, [ gPoint ], getStandardizedButton( event.button ) ) ) {\n releasePointer( tracker, 'mouse' );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseMove( tracker, event ) {\n handleMouseMove( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onMouseMove is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onMouseMoveCaptured( tracker, event ) {\n handleMouseMove( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseMove( tracker, event ) {\n var gPoint;\n\n event = $.getEvent( event );\n\n gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersMove( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function abortContacts( tracker, event, pointsList ) {\n var i,\n gPointCount = pointsList.getLength(),\n abortGPoints = [];\n\n // Check contact count for hoverable pointer types before aborting\n if (pointsList.type === 'touch' || pointsList.contacts > 0) {\n for ( i = 0; i < gPointCount; i++ ) {\n abortGPoints.push( pointsList.getByIndex( i ) );\n }\n\n if ( abortGPoints.length > 0 ) {\n // simulate touchend/mouseup\n updatePointersUp( tracker, event, abortGPoints, 0 ); // 0 means primary button press/release or touch contact\n // release pointer capture\n pointsList.captureCount = 1;\n releasePointer( tracker, pointsList.type );\n // simulate touchleave/mouseout\n updatePointersExit( tracker, event, abortGPoints );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchStart( tracker, event ) {\n var time,\n i,\n j,\n touchCount = event.changedTouches.length,\n gPoints = [],\n parentGPoints,\n pointsList = tracker.getActivePointersListByType( 'touch' );\n\n time = $.now();\n\n if ( pointsList.getLength() > event.touches.length - touchCount ) {\n $.console.warn('Tracked touch contact count doesn\\'t match event.touches.length. Removing all tracked touch pointers.');\n abortContacts( tracker, event, pointsList );\n }\n\n for ( i = 0; i < touchCount; i++ ) {\n gPoints.push( {\n id: event.changedTouches[ i ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ i ] ),\n currentTime: time\n } );\n }\n\n // simulate touchenter on our tracked element\n updatePointersEnter( tracker, event, gPoints );\n\n // simulate touchenter on our tracked element's tracked ancestor elements\n for ( i = 0; i < MOUSETRACKERS.length; i++ ) {\n if ( MOUSETRACKERS[ i ] !== tracker && MOUSETRACKERS[ i ].isTracking() && isParentChild( MOUSETRACKERS[ i ].element, tracker.element ) ) {\n parentGPoints = [];\n for ( j = 0; j < touchCount; j++ ) {\n parentGPoints.push( {\n id: event.changedTouches[ j ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ j ] ),\n currentTime: time\n } );\n }\n updatePointersEnter( MOUSETRACKERS[ i ], event, parentGPoints );\n }\n }\n\n if ( updatePointersDown( tracker, event, gPoints, 0 ) ) { // 0 means primary button press/release or touch contact\n $.stopEvent( event );\n capturePointer( tracker, 'touch', touchCount );\n }\n\n $.cancelEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchEnd( tracker, event ) {\n handleTouchEnd( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate pointer capture.\n * onTouchEnd is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onTouchEndCaptured( tracker, event ) {\n handleTouchEnd( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleTouchEnd( tracker, event ) {\n var time,\n i,\n j,\n touchCount = event.changedTouches.length,\n gPoints = [],\n parentGPoints;\n\n time = $.now();\n\n for ( i = 0; i < touchCount; i++ ) {\n gPoints.push( {\n id: event.changedTouches[ i ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ i ] ),\n currentTime: time\n } );\n }\n\n if ( updatePointersUp( tracker, event, gPoints, 0 ) ) {\n releasePointer( tracker, 'touch', touchCount );\n }\n\n // simulate touchleave on our tracked element\n updatePointersExit( tracker, event, gPoints );\n\n // simulate touchleave on our tracked element's tracked ancestor elements\n for ( i = 0; i < MOUSETRACKERS.length; i++ ) {\n if ( MOUSETRACKERS[ i ] !== tracker && MOUSETRACKERS[ i ].isTracking() && isParentChild( MOUSETRACKERS[ i ].element, tracker.element ) ) {\n parentGPoints = [];\n for ( j = 0; j < touchCount; j++ ) {\n parentGPoints.push( {\n id: event.changedTouches[ j ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ j ] ),\n currentTime: time\n } );\n }\n updatePointersExit( MOUSETRACKERS[ i ], event, parentGPoints );\n }\n }\n\n $.cancelEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchMove( tracker, event ) {\n handleTouchMove( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate pointer capture.\n * onTouchMove is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onTouchMoveCaptured( tracker, event ) {\n handleTouchMove( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleTouchMove( tracker, event ) {\n var i,\n touchCount = event.changedTouches.length,\n gPoints = [];\n\n for ( i = 0; i < touchCount; i++ ) {\n gPoints.push( {\n id: event.changedTouches[ i ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ i ] ),\n currentTime: $.now()\n } );\n }\n\n updatePointersMove( tracker, event, gPoints );\n\n $.cancelEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchCancel( tracker, event ) {\n var pointsList = tracker.getActivePointersListByType('touch');\n\n abortContacts( tracker, event, pointsList );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onGestureStart( tracker, event ) {\n event.stopPropagation();\n event.preventDefault();\n return false;\n }\n\n\n /**\n * @private\n * @inner\n */\n function onGestureChange( tracker, event ) {\n event.stopPropagation();\n event.preventDefault();\n return false;\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerOver( tracker, event ) {\n var gPoint;\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersEnter( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerOut( tracker, event ) {\n var gPoint;\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersExit( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerDown( tracker, event ) {\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersDown( tracker, event, [ gPoint ], event.button ) ) {\n $.stopEvent( event );\n capturePointer( tracker, gPoint.type );\n }\n\n if ( tracker.clickHandler || tracker.dblClickHandler || tracker.pressHandler || tracker.dragHandler || tracker.dragEndHandler || tracker.pinchHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerUp( tracker, event ) {\n handlePointerUp( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onPointerUp is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onPointerUpCaptured( tracker, event ) {\n var pointsList = tracker.getActivePointersListByType( getPointerType( event ) );\n if ( pointsList.getById( event.pointerId ) ) {\n handlePointerUp( tracker, event );\n }\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handlePointerUp( tracker, event ) {\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersUp( tracker, event, [ gPoint ], event.button ) ) {\n releasePointer( tracker, gPoint.type );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerMove( tracker, event ) {\n handlePointerMove( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onPointerMove is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onPointerMoveCaptured( tracker, event ) {\n var pointsList = tracker.getActivePointersListByType( getPointerType( event ) );\n if ( pointsList.getById( event.pointerId ) ) {\n handlePointerMove( tracker, event );\n }\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handlePointerMove( tracker, event ) {\n // Pointer changed coordinates, button state, pressure, tilt, or contact geometry (e.g. width and height)\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersMove( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerCancel( tracker, event ) {\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event )\n };\n\n updatePointersCancel( tracker, event, [ gPoint ] );\n }\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Device-agnostic DOM event handlers\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker.GesturePointList} pointsList\n * The GesturePointList to track the pointer in.\n * @param {OpenSeadragon.MouseTracker.GesturePoint} gPoint\n * Gesture point to track.\n * @returns {Number} Number of gesture points in pointsList.\n */\n function startTrackingPointer( pointsList, gPoint ) {\n\n // If isPrimary is not known for the pointer then set it according to our rules:\n // true if the first pointer in the gesture, otherwise false\n if ( !gPoint.hasOwnProperty( 'isPrimary' ) ) {\n if ( pointsList.getLength() === 0 ) {\n gPoint.isPrimary = true;\n } else {\n gPoint.isPrimary = false;\n }\n }\n gPoint.speed = 0;\n gPoint.direction = 0;\n gPoint.contactPos = gPoint.currentPos;\n gPoint.contactTime = gPoint.currentTime;\n gPoint.lastPos = gPoint.currentPos;\n gPoint.lastTime = gPoint.currentTime;\n\n return pointsList.add( gPoint );\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker.GesturePointList} pointsList\n * The GesturePointList to stop tracking the pointer on.\n * @param {OpenSeadragon.MouseTracker.GesturePoint} gPoint\n * Gesture point to stop tracking.\n * @returns {Number} Number of gesture points in pointsList.\n */\n function stopTrackingPointer( pointsList, gPoint ) {\n var listLength,\n primaryPoint;\n\n if ( pointsList.getById( gPoint.id ) ) {\n listLength = pointsList.removeById( gPoint.id );\n\n // If isPrimary is not known for the pointer and we just removed the primary pointer from the list then we need to set another pointer as primary\n if ( !gPoint.hasOwnProperty( 'isPrimary' ) ) {\n primaryPoint = pointsList.getPrimary();\n if ( !primaryPoint ) {\n primaryPoint = pointsList.getByIndex( 0 );\n if ( primaryPoint ) {\n primaryPoint.isPrimary = true;\n }\n }\n }\n } else {\n listLength = pointsList.getLength();\n }\n\n return listLength;\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersEnter( tracker, event, gPoints ) {\n var pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n propagate;\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer...update it\n updateGPoint.insideElement = true;\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n\n curGPoint = updateGPoint;\n } else {\n // Initialize for tracking and add to the tracking list\n curGPoint.captured = false;\n curGPoint.insideElementPressed = false;\n curGPoint.insideElement = true;\n startTrackingPointer( pointsList, curGPoint );\n }\n\n // Enter\n if ( tracker.enterHandler ) {\n propagate = tracker.enterHandler(\n {\n eventSource: tracker,\n pointerType: curGPoint.type,\n position: getPointRelativeToAbsolute( curGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n pointers: tracker.getActivePointerCount(),\n insideElementPressed: curGPoint.insideElementPressed,\n buttonDownAny: pointsList.buttons !== 0,\n isTouchEvent: curGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersExit( tracker, event, gPoints ) {\n var pointsList = tracker.getActivePointersListByType(gPoints[0].type),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n propagate;\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer. If captured then update it, else stop tracking it\n if ( updateGPoint.captured ) {\n updateGPoint.insideElement = false;\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n } else {\n stopTrackingPointer( pointsList, updateGPoint );\n }\n\n curGPoint = updateGPoint;\n }\n\n // Exit\n if ( tracker.exitHandler ) {\n propagate = tracker.exitHandler(\n {\n eventSource: tracker,\n pointerType: curGPoint.type,\n position: getPointRelativeToAbsolute( curGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n pointers: tracker.getActivePointerCount(),\n insideElementPressed: updateGPoint ? updateGPoint.insideElementPressed : false,\n buttonDownAny: pointsList.buttons !== 0,\n isTouchEvent: curGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n * @param {Number} buttonChanged\n * The button involved in the event: -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * Note on chorded button presses (a button pressed when another button is already pressed): In the W3C Pointer Events model,\n * only one pointerdown/pointerup event combo is fired. Chorded button state changes instead fire pointermove events.\n *\n * @returns {Boolean} True if pointers should be captured to the tracked element, otherwise false.\n */\n function updatePointersDown( tracker, event, gPoints, buttonChanged ) {\n var delegate = THIS[ tracker.hash ],\n propagate,\n pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint;\n\n if ( typeof event.buttons !== 'undefined' ) {\n pointsList.buttons = event.buttons;\n } else {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons += 1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons += 4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons += 2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons += 8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons += 16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons += 32;\n }\n } else {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons |= 1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons |= 4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons |= 2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons |= 8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons |= 16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons |= 32;\n }\n }\n }\n\n // Some pointers may steal control from another pointer without firing the appropriate release events\n // e.g. Touching a screen while click-dragging with certain mice.\n var otherPointsLists = tracker.getActivePointersListsExceptType(gPoints[ 0 ].type);\n for (i = 0; i < otherPointsLists.length; i++) {\n //If another pointer has contact, simulate the release\n abortContacts(tracker, event, otherPointsLists[i]); // No-op if no active pointer\n }\n\n // Only capture and track primary button, pen, and touch contacts\n if ( buttonChanged !== 0 ) {\n // Aux Press\n if ( tracker.nonPrimaryPressHandler ) {\n propagate = tracker.nonPrimaryPressHandler(\n {\n eventSource: tracker,\n pointerType: gPoints[ 0 ].type,\n position: getPointRelativeToAbsolute( gPoints[ 0 ].currentPos, tracker.element ),\n button: buttonChanged,\n buttons: pointsList.buttons,\n isTouchEvent: gPoints[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n return false;\n }\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer...update it\n updateGPoint.captured = true;\n updateGPoint.insideElementPressed = true;\n updateGPoint.insideElement = true;\n updateGPoint.contactPos = curGPoint.currentPos;\n updateGPoint.contactTime = curGPoint.currentTime;\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n\n curGPoint = updateGPoint;\n } else {\n // Initialize for tracking and add to the tracking list (no pointerover or pointermove event occurred before this)\n curGPoint.captured = true;\n curGPoint.insideElementPressed = true;\n curGPoint.insideElement = true;\n startTrackingPointer( pointsList, curGPoint );\n }\n\n pointsList.addContact();\n //$.console.log('contacts++ ', pointsList.contacts);\n\n if ( tracker.dragHandler || tracker.dragEndHandler || tracker.pinchHandler ) {\n $.MouseTracker.gesturePointVelocityTracker.addPoint( tracker, curGPoint );\n }\n\n if ( pointsList.contacts === 1 ) {\n // Press\n if ( tracker.pressHandler ) {\n propagate = tracker.pressHandler(\n {\n eventSource: tracker,\n pointerType: curGPoint.type,\n position: getPointRelativeToAbsolute( curGPoint.contactPos, tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: curGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n } else if ( pointsList.contacts === 2 ) {\n if ( tracker.pinchHandler && curGPoint.type === 'touch' ) {\n // Initialize for pinch\n delegate.pinchGPoints = pointsList.asArray();\n delegate.lastPinchDist = delegate.currentPinchDist = delegate.pinchGPoints[ 0 ].currentPos.distanceTo( delegate.pinchGPoints[ 1 ].currentPos );\n delegate.lastPinchCenter = delegate.currentPinchCenter = getCenterPoint( delegate.pinchGPoints[ 0 ].currentPos, delegate.pinchGPoints[ 1 ].currentPos );\n }\n }\n }\n\n return true;\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n * @param {Number} buttonChanged\n * The button involved in the event: -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * Note on chorded button presses (a button pressed when another button is already pressed): In the W3C Pointer Events model,\n * only one pointerdown/pointerup event combo is fired. Chorded button state changes instead fire pointermove events.\n *\n * @returns {Boolean} True if pointer capture should be released from the tracked element, otherwise false.\n */\n function updatePointersUp( tracker, event, gPoints, buttonChanged ) {\n var delegate = THIS[ tracker.hash ],\n pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n propagate,\n releasePoint,\n releaseTime,\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n releaseCapture = false,\n wasCaptured = false,\n quick;\n\n if ( typeof event.buttons !== 'undefined' ) {\n pointsList.buttons = event.buttons;\n } else {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons -= 1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons -= 4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons -= 2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons -= 8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons -= 16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons -= 32;\n }\n } else {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons ^= ~1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons ^= ~4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons ^= ~2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons ^= ~8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons ^= ~16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons ^= ~32;\n }\n }\n }\n\n // Only capture and track primary button, pen, and touch contacts\n if ( buttonChanged !== 0 ) {\n // Aux Release\n if ( tracker.nonPrimaryReleaseHandler ) {\n propagate = tracker.nonPrimaryReleaseHandler(\n {\n eventSource: tracker,\n pointerType: gPoints[ 0 ].type,\n position: getPointRelativeToAbsolute(gPoints[0].currentPos, tracker.element),\n button: buttonChanged,\n buttons: pointsList.buttons,\n isTouchEvent: gPoints[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // A primary mouse button may have been released while the non-primary button was down\n var otherPointsList = tracker.getActivePointersListByType(\"mouse\");\n // Stop tracking the mouse; see https://github.com/openseadragon/openseadragon/pull/1223\n abortContacts(tracker, event, otherPointsList); // No-op if no active pointer\n\n return false;\n }\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Update the pointer, stop tracking it if not still in this element\n if ( updateGPoint.captured ) {\n updateGPoint.captured = false;\n releaseCapture = true;\n wasCaptured = true;\n }\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n if ( !updateGPoint.insideElement ) {\n stopTrackingPointer( pointsList, updateGPoint );\n }\n\n releasePoint = updateGPoint.currentPos;\n releaseTime = updateGPoint.currentTime;\n\n if ( wasCaptured ) {\n // Pointer was activated in our element but could have been removed in any element since events are captured to our element\n\n pointsList.removeContact();\n //$.console.log('contacts-- ', pointsList.contacts);\n\n if ( tracker.dragHandler || tracker.dragEndHandler || tracker.pinchHandler ) {\n $.MouseTracker.gesturePointVelocityTracker.removePoint( tracker, updateGPoint );\n }\n\n if ( pointsList.contacts === 0 ) {\n\n // Release (pressed in our element)\n if ( tracker.releaseHandler ) {\n propagate = tracker.releaseHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( releasePoint, tracker.element ),\n buttons: pointsList.buttons,\n insideElementPressed: updateGPoint.insideElementPressed,\n insideElementReleased: updateGPoint.insideElement,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Drag End\n if ( tracker.dragEndHandler && !updateGPoint.currentPos.equals( updateGPoint.contactPos ) ) {\n propagate = tracker.dragEndHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n speed: updateGPoint.speed,\n direction: updateGPoint.direction,\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Click / Double-Click\n if ( ( tracker.clickHandler || tracker.dblClickHandler ) && updateGPoint.insideElement ) {\n quick = releaseTime - updateGPoint.contactTime <= tracker.clickTimeThreshold &&\n updateGPoint.contactPos.distanceTo( releasePoint ) <= tracker.clickDistThreshold;\n\n // Click\n if ( tracker.clickHandler ) {\n propagate = tracker.clickHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n quick: quick,\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Double-Click\n if ( tracker.dblClickHandler && quick ) {\n pointsList.clicks++;\n if ( pointsList.clicks === 1 ) {\n delegate.lastClickPos = releasePoint;\n /*jshint loopfunc:true*/\n delegate.dblClickTimeOut = setTimeout( function() {\n pointsList.clicks = 0;\n }, tracker.dblClickTimeThreshold );\n /*jshint loopfunc:false*/\n } else if ( pointsList.clicks === 2 ) {\n clearTimeout( delegate.dblClickTimeOut );\n pointsList.clicks = 0;\n if ( delegate.lastClickPos.distanceTo( releasePoint ) <= tracker.dblClickDistThreshold ) {\n propagate = tracker.dblClickHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n delegate.lastClickPos = null;\n }\n }\n }\n } else if ( pointsList.contacts === 2 ) {\n if ( tracker.pinchHandler && updateGPoint.type === 'touch' ) {\n // Reset for pinch\n delegate.pinchGPoints = pointsList.asArray();\n delegate.lastPinchDist = delegate.currentPinchDist = delegate.pinchGPoints[ 0 ].currentPos.distanceTo( delegate.pinchGPoints[ 1 ].currentPos );\n delegate.lastPinchCenter = delegate.currentPinchCenter = getCenterPoint( delegate.pinchGPoints[ 0 ].currentPos, delegate.pinchGPoints[ 1 ].currentPos );\n }\n }\n } else {\n // Pointer was activated in another element but removed in our element\n\n // Release (pressed in another element)\n if ( tracker.releaseHandler ) {\n propagate = tracker.releaseHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( releasePoint, tracker.element ),\n buttons: pointsList.buttons,\n insideElementPressed: updateGPoint.insideElementPressed,\n insideElementReleased: updateGPoint.insideElement,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n }\n\n return releaseCapture;\n }\n\n\n /**\n * Call when pointer(s) change coordinates, button state, pressure, tilt, or contact geometry (e.g. width and height)\n *\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersMove( tracker, event, gPoints ) {\n var delegate = THIS[ tracker.hash ],\n pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n gPointArray,\n delta,\n propagate;\n\n if ( typeof event.buttons !== 'undefined' ) {\n pointsList.buttons = event.buttons;\n }\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer...update it\n if ( curGPoint.hasOwnProperty( 'isPrimary' ) ) {\n updateGPoint.isPrimary = curGPoint.isPrimary;\n }\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n } else {\n // Initialize for tracking and add to the tracking list (no pointerover or pointerdown event occurred before this)\n curGPoint.captured = false;\n curGPoint.insideElementPressed = false;\n curGPoint.insideElement = true;\n startTrackingPointer( pointsList, curGPoint );\n }\n }\n\n // Stop (mouse only)\n if ( tracker.stopHandler && gPoints[ 0 ].type === 'mouse' ) {\n clearTimeout( tracker.stopTimeOut );\n tracker.stopTimeOut = setTimeout( function() {\n handlePointerStop( tracker, event, gPoints[ 0 ].type );\n }, tracker.stopDelay );\n }\n\n if ( pointsList.contacts === 0 ) {\n // Move (no contacts: hovering mouse or other hover-capable device)\n if ( tracker.moveHandler ) {\n propagate = tracker.moveHandler(\n {\n eventSource: tracker,\n pointerType: gPoints[ 0 ].type,\n position: getPointRelativeToAbsolute( gPoints[ 0 ].currentPos, tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: gPoints[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n } else if ( pointsList.contacts === 1 ) {\n // Move (1 contact)\n if ( tracker.moveHandler ) {\n updateGPoint = pointsList.asArray()[ 0 ];\n propagate = tracker.moveHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Drag\n if ( tracker.dragHandler ) {\n updateGPoint = pointsList.asArray()[ 0 ];\n delta = updateGPoint.currentPos.minus( updateGPoint.lastPos );\n propagate = tracker.dragHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n delta: delta,\n speed: updateGPoint.speed,\n direction: updateGPoint.direction,\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n } else if ( pointsList.contacts === 2 ) {\n // Move (2 contacts, use center)\n if ( tracker.moveHandler ) {\n gPointArray = pointsList.asArray();\n propagate = tracker.moveHandler(\n {\n eventSource: tracker,\n pointerType: gPointArray[ 0 ].type,\n position: getPointRelativeToAbsolute( getCenterPoint( gPointArray[ 0 ].currentPos, gPointArray[ 1 ].currentPos ), tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: gPointArray[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Pinch\n if ( tracker.pinchHandler && gPoints[ 0 ].type === 'touch' ) {\n delta = delegate.pinchGPoints[ 0 ].currentPos.distanceTo( delegate.pinchGPoints[ 1 ].currentPos );\n if ( delta != delegate.currentPinchDist ) {\n delegate.lastPinchDist = delegate.currentPinchDist;\n delegate.currentPinchDist = delta;\n delegate.lastPinchCenter = delegate.currentPinchCenter;\n delegate.currentPinchCenter = getCenterPoint( delegate.pinchGPoints[ 0 ].currentPos, delegate.pinchGPoints[ 1 ].currentPos );\n propagate = tracker.pinchHandler(\n {\n eventSource: tracker,\n pointerType: 'touch',\n gesturePoints: delegate.pinchGPoints,\n lastCenter: getPointRelativeToAbsolute( delegate.lastPinchCenter, tracker.element ),\n center: getPointRelativeToAbsolute( delegate.currentPinchCenter, tracker.element ),\n lastDistance: delegate.lastPinchDist,\n distance: delegate.currentPinchDist,\n shift: event.shiftKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersCancel( tracker, event, gPoints ) {\n updatePointersUp( tracker, event, gPoints, 0 );\n updatePointersExit( tracker, event, gPoints );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handlePointerStop( tracker, originalMoveEvent, pointerType ) {\n if ( tracker.stopHandler ) {\n tracker.stopHandler( {\n eventSource: tracker,\n pointerType: pointerType,\n position: getMouseRelative( originalMoveEvent, tracker.element ),\n buttons: tracker.getActivePointersListByType( pointerType ).buttons,\n isTouchEvent: pointerType === 'touch',\n originalEvent: originalMoveEvent,\n preventDefaultAction: false,\n userData: tracker.userData\n } );\n }\n }\n\n /**\n * True if inside an iframe, otherwise false.\n * @member {Boolean} isInIframe\n * @private\n * @inner\n */\n var isInIframe = (function() {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n })();\n\n /**\n * @function\n * @private\n * @inner\n * @returns {Boolean} True if the target has access rights to events, otherwise false.\n */\n function canAccessEvents (target) {\n try {\n return target.addEventListener && target.removeEventListener;\n } catch (e) {\n return false;\n }\n }\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Control\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * An enumeration of supported locations where controls can be anchored.\n * The anchoring is always relative to the container.\n * @member ControlAnchor\n * @memberof OpenSeadragon\n * @static\n * @type {Object}\n * @property {Number} NONE\n * @property {Number} TOP_LEFT\n * @property {Number} TOP_RIGHT\n * @property {Number} BOTTOM_LEFT\n * @property {Number} BOTTOM_RIGHT\n * @property {Number} ABSOLUTE\n */\n$.ControlAnchor = {\n NONE: 0,\n TOP_LEFT: 1,\n TOP_RIGHT: 2,\n BOTTOM_RIGHT: 3,\n BOTTOM_LEFT: 4,\n ABSOLUTE: 5\n};\n\n/**\n * @class Control\n * @classdesc A Control represents any interface element which is meant to allow the user\n * to interact with the zoomable interface. Any control can be anchored to any\n * element.\n *\n * @memberof OpenSeadragon\n * @param {Element} element - the control element to be anchored in the container.\n * @param {Object } options - All required and optional settings for configuring a control element.\n * @param {OpenSeadragon.ControlAnchor} [options.anchor=OpenSeadragon.ControlAnchor.NONE] - the position of the control\n * relative to the container.\n * @param {Boolean} [options.attachToViewer=true] - Whether the control should be added directly to the viewer, or\n * directly to the container\n * @param {Boolean} [options.autoFade=true] - Whether the control should have the autofade behavior\n * @param {Element} container - the element to control will be anchored too.\n */\n$.Control = function ( element, options, container ) {\n var parent = element.parentNode;\n if (typeof options === 'number')\n {\n $.console.error(\"Passing an anchor directly into the OpenSeadragon.Control constructor is deprecated; \" +\n \"please use an options object instead. \" +\n \"Support for this deprecated variant is scheduled for removal in December 2013\");\n options = {anchor: options};\n }\n options.attachToViewer = (typeof options.attachToViewer === 'undefined') ? true : options.attachToViewer;\n /**\n * True if the control should have autofade behavior.\n * @member {Boolean} autoFade\n * @memberof OpenSeadragon.Control#\n */\n this.autoFade = (typeof options.autoFade === 'undefined') ? true : options.autoFade;\n /**\n * The element providing the user interface with some type of control (e.g. a zoom-in button).\n * @member {Element} element\n * @memberof OpenSeadragon.Control#\n */\n this.element = element;\n /**\n * The position of the Control relative to its container.\n * @member {OpenSeadragon.ControlAnchor} anchor\n * @memberof OpenSeadragon.Control#\n */\n this.anchor = options.anchor;\n /**\n * The Control's containing element.\n * @member {Element} container\n * @memberof OpenSeadragon.Control#\n */\n this.container = container;\n /**\n * A neutral element surrounding the control element.\n * @member {Element} wrapper\n * @memberof OpenSeadragon.Control#\n */\n if ( this.anchor == $.ControlAnchor.ABSOLUTE ) {\n this.wrapper = $.makeNeutralElement( \"div\" );\n this.wrapper.style.position = \"absolute\";\n this.wrapper.style.top = typeof (options.top) == \"number\" ? (options.top + 'px') : options.top;\n this.wrapper.style.left = typeof (options.left) == \"number\" ? (options.left + 'px') : options.left;\n this.wrapper.style.height = typeof (options.height) == \"number\" ? (options.height + 'px') : options.height;\n this.wrapper.style.width = typeof (options.width) == \"number\" ? (options.width + 'px') : options.width;\n this.wrapper.style.margin = \"0px\";\n this.wrapper.style.padding = \"0px\";\n\n this.element.style.position = \"relative\";\n this.element.style.top = \"0px\";\n this.element.style.left = \"0px\";\n this.element.style.height = \"100%\";\n this.element.style.width = \"100%\";\n } else {\n this.wrapper = $.makeNeutralElement( \"div\" );\n this.wrapper.style.display = \"inline-block\";\n if ( this.anchor == $.ControlAnchor.NONE ) {\n // IE6 fix\n this.wrapper.style.width = this.wrapper.style.height = \"100%\";\n }\n }\n this.wrapper.appendChild( this.element );\n\n if (options.attachToViewer ) {\n if ( this.anchor == $.ControlAnchor.TOP_RIGHT ||\n this.anchor == $.ControlAnchor.BOTTOM_RIGHT ) {\n this.container.insertBefore(\n this.wrapper,\n this.container.firstChild\n );\n } else {\n this.container.appendChild( this.wrapper );\n }\n } else {\n parent.appendChild( this.wrapper );\n }\n};\n\n/** @lends OpenSeadragon.Control.prototype */\n$.Control.prototype = {\n\n /**\n * Removes the control from the container.\n * @function\n */\n destroy: function() {\n this.wrapper.removeChild( this.element );\n this.container.removeChild( this.wrapper );\n },\n\n /**\n * Determines if the control is currently visible.\n * @function\n * @return {Boolean} true if currenly visible, false otherwise.\n */\n isVisible: function() {\n return this.wrapper.style.display != \"none\";\n },\n\n /**\n * Toggles the visibility of the control.\n * @function\n * @param {Boolean} visible - true to make visible, false to hide.\n */\n setVisible: function( visible ) {\n this.wrapper.style.display = visible ?\n ( this.anchor == $.ControlAnchor.ABSOLUTE ? 'block' : 'inline-block' ) :\n \"none\";\n },\n\n /**\n * Sets the opacity level for the control.\n * @function\n * @param {Number} opactiy - a value between 1 and 0 inclusively.\n */\n setOpacity: function( opacity ) {\n if ( this.element[ $.SIGNAL ] && $.Browser.vendor == $.BROWSERS.IE ) {\n $.setElementOpacity( this.element, opacity, true );\n } else {\n $.setElementOpacity( this.wrapper, opacity, true );\n }\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ControlDock\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n /**\n * @class ControlDock\n * @classdesc Provides a container element (a <form> element) with support for the layout of control elements.\n *\n * @memberof OpenSeadragon\n */\n $.ControlDock = function( options ){\n var layouts = [ 'topleft', 'topright', 'bottomright', 'bottomleft'],\n layout,\n i;\n\n $.extend( true, this, {\n id: 'controldock-' + $.now() + '-' + Math.floor(Math.random() * 1000000),\n container: $.makeNeutralElement( 'div' ),\n controls: []\n }, options );\n\n // Disable the form's submit; otherwise button clicks and return keys\n // can trigger it.\n this.container.onsubmit = function() {\n return false;\n };\n\n if( this.element ){\n this.element = $.getElement( this.element );\n this.element.appendChild( this.container );\n this.element.style.position = 'relative';\n this.container.style.width = '100%';\n this.container.style.height = '100%';\n }\n\n for( i = 0; i < layouts.length; i++ ){\n layout = layouts[ i ];\n this.controls[ layout ] = $.makeNeutralElement( \"div\" );\n this.controls[ layout ].style.position = 'absolute';\n if ( layout.match( 'left' ) ){\n this.controls[ layout ].style.left = '0px';\n }\n if ( layout.match( 'right' ) ){\n this.controls[ layout ].style.right = '0px';\n }\n if ( layout.match( 'top' ) ){\n this.controls[ layout ].style.top = '0px';\n }\n if ( layout.match( 'bottom' ) ){\n this.controls[ layout ].style.bottom = '0px';\n }\n }\n\n this.container.appendChild( this.controls.topleft );\n this.container.appendChild( this.controls.topright );\n this.container.appendChild( this.controls.bottomright );\n this.container.appendChild( this.controls.bottomleft );\n };\n\n /** @lends OpenSeadragon.ControlDock.prototype */\n $.ControlDock.prototype = {\n\n /**\n * @function\n */\n addControl: function ( element, controlOptions ) {\n element = $.getElement( element );\n var div = null;\n\n if ( getControlIndex( this, element ) >= 0 ) {\n return; // they're trying to add a duplicate control\n }\n\n switch ( controlOptions.anchor ) {\n case $.ControlAnchor.TOP_RIGHT:\n div = this.controls.topright;\n element.style.position = \"relative\";\n element.style.paddingRight = \"0px\";\n element.style.paddingTop = \"0px\";\n break;\n case $.ControlAnchor.BOTTOM_RIGHT:\n div = this.controls.bottomright;\n element.style.position = \"relative\";\n element.style.paddingRight = \"0px\";\n element.style.paddingBottom = \"0px\";\n break;\n case $.ControlAnchor.BOTTOM_LEFT:\n div = this.controls.bottomleft;\n element.style.position = \"relative\";\n element.style.paddingLeft = \"0px\";\n element.style.paddingBottom = \"0px\";\n break;\n case $.ControlAnchor.TOP_LEFT:\n div = this.controls.topleft;\n element.style.position = \"relative\";\n element.style.paddingLeft = \"0px\";\n element.style.paddingTop = \"0px\";\n break;\n case $.ControlAnchor.ABSOLUTE:\n div = this.container;\n element.style.margin = \"0px\";\n element.style.padding = \"0px\";\n break;\n default:\n case $.ControlAnchor.NONE:\n div = this.container;\n element.style.margin = \"0px\";\n element.style.padding = \"0px\";\n break;\n }\n\n this.controls.push(\n new $.Control( element, controlOptions, div )\n );\n element.style.display = \"inline-block\";\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.ControlDock} Chainable.\n */\n removeControl: function ( element ) {\n element = $.getElement( element );\n var i = getControlIndex( this, element );\n\n if ( i >= 0 ) {\n this.controls[ i ].destroy();\n this.controls.splice( i, 1 );\n }\n\n return this;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.ControlDock} Chainable.\n */\n clearControls: function () {\n while ( this.controls.length > 0 ) {\n this.controls.pop().destroy();\n }\n\n return this;\n },\n\n\n /**\n * @function\n * @return {Boolean}\n */\n areControlsEnabled: function () {\n var i;\n\n for ( i = this.controls.length - 1; i >= 0; i-- ) {\n if ( this.controls[ i ].isVisible() ) {\n return true;\n }\n }\n\n return false;\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.ControlDock} Chainable.\n */\n setControlsEnabled: function( enabled ) {\n var i;\n\n for ( i = this.controls.length - 1; i >= 0; i-- ) {\n this.controls[ i ].setVisible( enabled );\n }\n\n return this;\n }\n\n };\n\n\n ///////////////////////////////////////////////////////////////////////////////\n // Utility methods\n ///////////////////////////////////////////////////////////////////////////////\n function getControlIndex( dock, element ) {\n var controls = dock.controls,\n i;\n\n for ( i = controls.length - 1; i >= 0; i-- ) {\n if ( controls[ i ].element == element ) {\n return i;\n }\n }\n\n return -1;\n }\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Placement\n *\n * Copyright (C) 2010-2016 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n /**\n * An enumeration of positions to anchor an element.\n * @member Placement\n * @memberOf OpenSeadragon\n * @static\n * @readonly\n * @property {OpenSeadragon.Placement} CENTER\n * @property {OpenSeadragon.Placement} TOP_LEFT\n * @property {OpenSeadragon.Placement} TOP\n * @property {OpenSeadragon.Placement} TOP_RIGHT\n * @property {OpenSeadragon.Placement} RIGHT\n * @property {OpenSeadragon.Placement} BOTTOM_RIGHT\n * @property {OpenSeadragon.Placement} BOTTOM\n * @property {OpenSeadragon.Placement} BOTTOM_LEFT\n * @property {OpenSeadragon.Placement} LEFT\n */\n $.Placement = $.freezeObject({\n CENTER: 0,\n TOP_LEFT: 1,\n TOP: 2,\n TOP_RIGHT: 3,\n RIGHT: 4,\n BOTTOM_RIGHT: 5,\n BOTTOM: 6,\n BOTTOM_LEFT: 7,\n LEFT: 8,\n properties: {\n 0: {\n isLeft: false,\n isHorizontallyCentered: true,\n isRight: false,\n isTop: false,\n isVerticallyCentered: true,\n isBottom: false\n },\n 1: {\n isLeft: true,\n isHorizontallyCentered: false,\n isRight: false,\n isTop: true,\n isVerticallyCentered: false,\n isBottom: false\n },\n 2: {\n isLeft: false,\n isHorizontallyCentered: true,\n isRight: false,\n isTop: true,\n isVerticallyCentered: false,\n isBottom: false\n },\n 3: {\n isLeft: false,\n isHorizontallyCentered: false,\n isRight: true,\n isTop: true,\n isVerticallyCentered: false,\n isBottom: false\n },\n 4: {\n isLeft: false,\n isHorizontallyCentered: false,\n isRight: true,\n isTop: false,\n isVerticallyCentered: true,\n isBottom: false\n },\n 5: {\n isLeft: false,\n isHorizontallyCentered: false,\n isRight: true,\n isTop: false,\n isVerticallyCentered: false,\n isBottom: true\n },\n 6: {\n isLeft: false,\n isHorizontallyCentered: true,\n isRight: false,\n isTop: false,\n isVerticallyCentered: false,\n isBottom: true\n },\n 7: {\n isLeft: true,\n isHorizontallyCentered: false,\n isRight: false,\n isTop: false,\n isVerticallyCentered: false,\n isBottom: true\n },\n 8: {\n isLeft: true,\n isHorizontallyCentered: false,\n isRight: false,\n isTop: false,\n isVerticallyCentered: true,\n isBottom: false\n }\n }\n });\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Viewer\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n// dictionary from hash to private properties\nvar THIS = {};\nvar nextHash = 1;\n\n/**\n *\n * The main point of entry into creating a zoomable image on the page.
\n *
\n * We have provided an idiomatic javascript constructor which takes\n * a single object, but still support the legacy positional arguments.
\n *
\n * The options below are given in order that they appeared in the constructor\n * as arguments and we translate a positional call into an idiomatic call.
\n *
\n * To create a viewer, you can use either of this methods:
\n *
    \n *
  • var viewer = new OpenSeadragon.Viewer(options);
  • \n *
  • var viewer = OpenSeadragon(options);
  • \n *
\n * @class Viewer\n * @classdesc The main OpenSeadragon viewer class.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @extends OpenSeadragon.ControlDock\n * @param {OpenSeadragon.Options} options - Viewer options.\n *\n **/\n$.Viewer = function( options ) {\n\n var args = arguments,\n _this = this,\n i;\n\n\n //backward compatibility for positional args while prefering more\n //idiomatic javascript options object as the only argument\n if( !$.isPlainObject( options ) ){\n options = {\n id: args[ 0 ],\n xmlPath: args.length > 1 ? args[ 1 ] : undefined,\n prefixUrl: args.length > 2 ? args[ 2 ] : undefined,\n controls: args.length > 3 ? args[ 3 ] : undefined,\n overlays: args.length > 4 ? args[ 4 ] : undefined\n };\n }\n\n //options.config and the general config argument are deprecated\n //in favor of the more direct specification of optional settings\n //being pass directly on the options object\n if ( options.config ){\n $.extend( true, options, options.config );\n delete options.config;\n }\n\n //Public properties\n //Allow the options object to override global defaults\n $.extend( true, this, {\n\n //internal state and dom identifiers\n id: options.id,\n hash: options.hash || nextHash++,\n /**\n * Index for page to be shown first next time open() is called (only used in sequenceMode).\n * @member {Number} initialPage\n * @memberof OpenSeadragon.Viewer#\n */\n initialPage: 0,\n\n //dom nodes\n /**\n * The parent element of this Viewer instance, passed in when the Viewer was created.\n * @member {Element} element\n * @memberof OpenSeadragon.Viewer#\n */\n element: null,\n /**\n * A <div> element (provided by {@link OpenSeadragon.ControlDock}), the base element of this Viewer instance.

\n * Child element of {@link OpenSeadragon.Viewer#element}.\n * @member {Element} container\n * @memberof OpenSeadragon.Viewer#\n */\n container: null,\n /**\n * A <div> element, the element where user-input events are handled for panning and zooming.

\n * Child element of {@link OpenSeadragon.Viewer#container},\n * positioned on top of {@link OpenSeadragon.Viewer#keyboardCommandArea}.

\n * The parent of {@link OpenSeadragon.Drawer#canvas} instances.\n * @member {Element} canvas\n * @memberof OpenSeadragon.Viewer#\n */\n canvas: null,\n\n // Overlays list. An overlay allows to add html on top of the viewer.\n overlays: [],\n // Container inside the canvas where overlays are drawn.\n overlaysContainer: null,\n\n //private state properties\n previousBody: [],\n\n //This was originally initialized in the constructor and so could never\n //have anything in it. now it can because we allow it to be specified\n //in the options and is only empty by default if not specified. Also\n //this array was returned from get_controls which I find confusing\n //since this object has a controls property which is treated in other\n //functions like clearControls. I'm removing the accessors.\n customControls: [],\n\n //These are originally not part options but declared as members\n //in initialize. It's still considered idiomatic to put them here\n source: null,\n /**\n * Handles rendering of tiles in the viewer. Created for each TileSource opened.\n * @member {OpenSeadragon.Drawer} drawer\n * @memberof OpenSeadragon.Viewer#\n */\n drawer: null,\n world: null,\n /**\n * Handles coordinate-related functionality - zoom, pan, rotation, etc. Created for each TileSource opened.\n * @member {OpenSeadragon.Viewport} viewport\n * @memberof OpenSeadragon.Viewer#\n */\n viewport: null,\n /**\n * @member {OpenSeadragon.Navigator} navigator\n * @memberof OpenSeadragon.Viewer#\n */\n navigator: null,\n\n //A collection viewport is a separate viewport used to provide\n //simultaneous rendering of sets of tiles\n collectionViewport: null,\n collectionDrawer: null,\n\n //UI image resources\n //TODO: rename navImages to uiImages\n navImages: null,\n\n //interface button controls\n buttons: null,\n\n //TODO: this is defunct so safely remove it\n profiler: null\n\n }, $.DEFAULT_SETTINGS, options );\n\n if ( typeof ( this.hash) === \"undefined\" ) {\n throw new Error(\"A hash must be defined, either by specifying options.id or options.hash.\");\n }\n if ( typeof ( THIS[ this.hash ] ) !== \"undefined\" ) {\n // We don't want to throw an error here, as the user might have discarded\n // the previous viewer with the same hash and now want to recreate it.\n $.console.warn(\"Hash \" + this.hash + \" has already been used.\");\n }\n\n //Private state properties\n THIS[ this.hash ] = {\n \"fsBoundsDelta\": new $.Point( 1, 1 ),\n \"prevContainerSize\": null,\n \"animating\": false,\n \"forceRedraw\": false,\n \"mouseInside\": false,\n \"group\": null,\n // whether we should be continuously zooming\n \"zooming\": false,\n // how much we should be continuously zooming by\n \"zoomFactor\": null,\n \"lastZoomTime\": null,\n \"fullPage\": false,\n \"onfullscreenchange\": null\n };\n\n this._sequenceIndex = 0;\n this._firstOpen = true;\n this._updateRequestId = null;\n this._loadQueue = [];\n this.currentOverlays = [];\n\n this._lastScrollTime = $.now(); // variable used to help normalize the scroll event speed of different devices\n\n //Inherit some behaviors and properties\n $.EventSource.call( this );\n\n this.addHandler( 'open-failed', function ( event ) {\n var msg = $.getString( \"Errors.OpenFailed\", event.eventSource, event.message);\n _this._showMessage( msg );\n });\n\n $.ControlDock.call( this, options );\n\n //Deal with tile sources\n if (this.xmlPath) {\n //Deprecated option. Now it is preferred to use the tileSources option\n this.tileSources = [ this.xmlPath ];\n }\n\n this.element = this.element || document.getElementById( this.id );\n this.canvas = $.makeNeutralElement( \"div\" );\n\n this.canvas.className = \"openseadragon-canvas\";\n (function( style ){\n style.width = \"100%\";\n style.height = \"100%\";\n style.overflow = \"hidden\";\n style.position = \"absolute\";\n style.top = \"0px\";\n style.left = \"0px\";\n }(this.canvas.style));\n $.setElementTouchActionNone( this.canvas );\n if (options.tabIndex !== \"\") {\n this.canvas.tabIndex = (options.tabIndex === undefined ? 0 : options.tabIndex);\n }\n\n //the container is created through applying the ControlDock constructor above\n this.container.className = \"openseadragon-container\";\n (function( style ){\n style.width = \"100%\";\n style.height = \"100%\";\n style.position = \"relative\";\n style.overflow = \"hidden\";\n style.left = \"0px\";\n style.top = \"0px\";\n style.textAlign = \"left\"; // needed to protect against\n }( this.container.style ));\n\n this.container.insertBefore( this.canvas, this.container.firstChild );\n this.element.appendChild( this.container );\n\n //Used for toggling between fullscreen and default container size\n //TODO: these can be closure private and shared across Viewer\n // instances.\n this.bodyWidth = document.body.style.width;\n this.bodyHeight = document.body.style.height;\n this.bodyOverflow = document.body.style.overflow;\n this.docOverflow = document.documentElement.style.overflow;\n\n this.innerTracker = new $.MouseTracker({\n element: this.canvas,\n startDisabled: !this.mouseNavEnabled,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n dblClickTimeThreshold: this.dblClickTimeThreshold,\n dblClickDistThreshold: this.dblClickDistThreshold,\n keyDownHandler: $.delegate( this, onCanvasKeyDown ),\n keyHandler: $.delegate( this, onCanvasKeyPress ),\n clickHandler: $.delegate( this, onCanvasClick ),\n dblClickHandler: $.delegate( this, onCanvasDblClick ),\n dragHandler: $.delegate( this, onCanvasDrag ),\n dragEndHandler: $.delegate( this, onCanvasDragEnd ),\n enterHandler: $.delegate( this, onCanvasEnter ),\n exitHandler: $.delegate( this, onCanvasExit ),\n pressHandler: $.delegate( this, onCanvasPress ),\n releaseHandler: $.delegate( this, onCanvasRelease ),\n nonPrimaryPressHandler: $.delegate( this, onCanvasNonPrimaryPress ),\n nonPrimaryReleaseHandler: $.delegate( this, onCanvasNonPrimaryRelease ),\n scrollHandler: $.delegate( this, onCanvasScroll ),\n pinchHandler: $.delegate( this, onCanvasPinch )\n });\n\n this.outerTracker = new $.MouseTracker({\n element: this.container,\n startDisabled: !this.mouseNavEnabled,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n dblClickTimeThreshold: this.dblClickTimeThreshold,\n dblClickDistThreshold: this.dblClickDistThreshold,\n enterHandler: $.delegate( this, onContainerEnter ),\n exitHandler: $.delegate( this, onContainerExit )\n });\n\n if( this.toolbar ){\n this.toolbar = new $.ControlDock({ element: this.toolbar });\n }\n\n this.bindStandardControls();\n\n THIS[ this.hash ].prevContainerSize = _getSafeElemSize( this.container );\n\n // Create the world\n this.world = new $.World({\n viewer: this\n });\n\n this.world.addHandler('add-item', function(event) {\n // For backwards compatibility, we maintain the source property\n _this.source = _this.world.getItemAt(0).source;\n\n THIS[ _this.hash ].forceRedraw = true;\n\n if (!_this._updateRequestId) {\n _this._updateRequestId = scheduleUpdate( _this, updateMulti );\n }\n });\n\n this.world.addHandler('remove-item', function(event) {\n // For backwards compatibility, we maintain the source property\n if (_this.world.getItemCount()) {\n _this.source = _this.world.getItemAt(0).source;\n } else {\n _this.source = null;\n }\n\n THIS[ _this.hash ].forceRedraw = true;\n });\n\n this.world.addHandler('metrics-change', function(event) {\n if (_this.viewport) {\n _this.viewport._setContentBounds(_this.world.getHomeBounds(), _this.world.getContentFactor());\n }\n });\n\n this.world.addHandler('item-index-change', function(event) {\n // For backwards compatibility, we maintain the source property\n _this.source = _this.world.getItemAt(0).source;\n });\n\n // Create the viewport\n this.viewport = new $.Viewport({\n containerSize: THIS[ this.hash ].prevContainerSize,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime,\n minZoomImageRatio: this.minZoomImageRatio,\n maxZoomPixelRatio: this.maxZoomPixelRatio,\n visibilityRatio: this.visibilityRatio,\n wrapHorizontal: this.wrapHorizontal,\n wrapVertical: this.wrapVertical,\n defaultZoomLevel: this.defaultZoomLevel,\n minZoomLevel: this.minZoomLevel,\n maxZoomLevel: this.maxZoomLevel,\n viewer: this,\n degrees: this.degrees,\n flipped: this.flipped,\n navigatorRotate: this.navigatorRotate,\n homeFillsViewer: this.homeFillsViewer,\n margins: this.viewportMargins\n });\n\n this.viewport._setContentBounds(this.world.getHomeBounds(), this.world.getContentFactor());\n\n // Create the image loader\n this.imageLoader = new $.ImageLoader({\n jobLimit: this.imageLoaderLimit,\n timeout: options.timeout\n });\n\n // Create the tile cache\n this.tileCache = new $.TileCache({\n maxImageCacheCount: this.maxImageCacheCount\n });\n\n // Create the drawer\n this.drawer = new $.Drawer({\n viewer: this,\n viewport: this.viewport,\n element: this.canvas,\n debugGridColor: this.debugGridColor\n });\n\n // Overlay container\n this.overlaysContainer = $.makeNeutralElement( \"div\" );\n this.canvas.appendChild( this.overlaysContainer );\n\n // Now that we have a drawer, see if it supports rotate. If not we need to remove the rotate buttons\n if (!this.drawer.canRotate()) {\n // Disable/remove the rotate left/right buttons since they aren't supported\n if (this.rotateLeft) {\n i = this.buttons.buttons.indexOf(this.rotateLeft);\n this.buttons.buttons.splice(i, 1);\n this.buttons.element.removeChild(this.rotateLeft.element);\n }\n if (this.rotateRight) {\n i = this.buttons.buttons.indexOf(this.rotateRight);\n this.buttons.buttons.splice(i, 1);\n this.buttons.element.removeChild(this.rotateRight.element);\n }\n }\n\n //Instantiate a navigator if configured\n if ( this.showNavigator){\n this.navigator = new $.Navigator({\n id: this.navigatorId,\n position: this.navigatorPosition,\n sizeRatio: this.navigatorSizeRatio,\n maintainSizeRatio: this.navigatorMaintainSizeRatio,\n top: this.navigatorTop,\n left: this.navigatorLeft,\n width: this.navigatorWidth,\n height: this.navigatorHeight,\n autoResize: this.navigatorAutoResize,\n autoFade: this.navigatorAutoFade,\n prefixUrl: this.prefixUrl,\n viewer: this,\n navigatorRotate: this.navigatorRotate,\n crossOriginPolicy: this.crossOriginPolicy\n });\n }\n\n // Sequence mode\n if (this.sequenceMode) {\n this.bindSequenceControls();\n }\n\n // Open initial tilesources\n if (this.tileSources) {\n this.open( this.tileSources );\n }\n\n // Add custom controls\n for ( i = 0; i < this.customControls.length; i++ ) {\n this.addControl(\n this.customControls[ i ].id,\n {anchor: this.customControls[ i ].anchor}\n );\n }\n\n // Initial fade out\n $.requestAnimationFrame( function(){\n beginControlsAutoHide( _this );\n } );\n};\n\n$.extend( $.Viewer.prototype, $.EventSource.prototype, $.ControlDock.prototype, /** @lends OpenSeadragon.Viewer.prototype */{\n\n\n /**\n * @function\n * @return {Boolean}\n */\n isOpen: function () {\n return !!this.world.getItemCount();\n },\n\n // deprecated\n openDzi: function ( dzi ) {\n $.console.error( \"[Viewer.openDzi] this function is deprecated; use Viewer.open() instead.\" );\n return this.open( dzi );\n },\n\n // deprecated\n openTileSource: function ( tileSource ) {\n $.console.error( \"[Viewer.openTileSource] this function is deprecated; use Viewer.open() instead.\" );\n return this.open( tileSource );\n },\n\n /**\n * Open tiled images into the viewer, closing any others.\n * To get the TiledImage instance created by open, add an event listener for\n * {@link OpenSeadragon.Viewer.html#.event:open}, which when fired can be used to get access\n * to the instance, i.e., viewer.world.getItemAt(0).\n * @function\n * @param {Array|String|Object|Function} tileSources - This can be a TiledImage\n * specifier, a TileSource specifier, or an array of either. A TiledImage specifier\n * is the same as the options parameter for {@link OpenSeadragon.Viewer#addTiledImage},\n * except for the index property; images are added in sequence.\n * A TileSource specifier is anything you could pass as the tileSource property\n * of the options parameter for {@link OpenSeadragon.Viewer#addTiledImage}.\n * @param {Number} initialPage - If sequenceMode is true, display this page initially\n * for the given tileSources. If specified, will overwrite the Viewer's existing initialPage property.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:open\n * @fires OpenSeadragon.Viewer.event:open-failed\n */\n open: function (tileSources, initialPage) {\n var _this = this;\n\n this.close();\n\n if (!tileSources) {\n return;\n }\n\n if (this.sequenceMode && $.isArray(tileSources)) {\n if (this.referenceStrip) {\n this.referenceStrip.destroy();\n this.referenceStrip = null;\n }\n\n if (typeof initialPage != 'undefined' && !isNaN(initialPage)) {\n this.initialPage = initialPage;\n }\n\n this.tileSources = tileSources;\n this._sequenceIndex = Math.max(0, Math.min(this.tileSources.length - 1, this.initialPage));\n if (this.tileSources.length) {\n this.open(this.tileSources[this._sequenceIndex]);\n\n if ( this.showReferenceStrip ){\n this.addReferenceStrip();\n }\n }\n\n this._updateSequenceButtons( this._sequenceIndex );\n return;\n }\n\n if (!$.isArray(tileSources)) {\n tileSources = [tileSources];\n }\n\n if (!tileSources.length) {\n return;\n }\n\n this._opening = true;\n\n var expected = tileSources.length;\n var successes = 0;\n var failures = 0;\n var failEvent;\n\n var checkCompletion = function() {\n if (successes + failures === expected) {\n if (successes) {\n if (_this._firstOpen || !_this.preserveViewport) {\n _this.viewport.goHome( true );\n _this.viewport.update();\n }\n\n _this._firstOpen = false;\n\n var source = tileSources[0];\n if (source.tileSource) {\n source = source.tileSource;\n }\n\n // Global overlays\n if( _this.overlays && !_this.preserveOverlays ){\n for ( var i = 0; i < _this.overlays.length; i++ ) {\n _this.currentOverlays[ i ] = getOverlayObject( _this, _this.overlays[ i ] );\n }\n }\n\n _this._drawOverlays();\n _this._opening = false;\n\n /**\n * Raised when the viewer has opened and loaded one or more TileSources.\n *\n * @event open\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TileSource} source - The tile source that was opened.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n // TODO: what if there are multiple sources?\n _this.raiseEvent( 'open', { source: source } );\n } else {\n _this._opening = false;\n\n /**\n * Raised when an error occurs loading a TileSource.\n *\n * @event open-failed\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {String} message - Information about what failed.\n * @property {String} source - The tile source that failed.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'open-failed', failEvent );\n }\n }\n };\n\n var doOne = function(options) {\n if (!$.isPlainObject(options) || !options.tileSource) {\n options = {\n tileSource: options\n };\n }\n\n if (options.index !== undefined) {\n $.console.error('[Viewer.open] setting indexes here is not supported; use addTiledImage instead');\n delete options.index;\n }\n\n if (options.collectionImmediately === undefined) {\n options.collectionImmediately = true;\n }\n\n var originalSuccess = options.success;\n options.success = function(event) {\n successes++;\n\n // TODO: now that options has other things besides tileSource, the overlays\n // should probably be at the options level, not the tileSource level.\n if (options.tileSource.overlays) {\n for (var i = 0; i < options.tileSource.overlays.length; i++) {\n _this.addOverlay(options.tileSource.overlays[i]);\n }\n }\n\n if (originalSuccess) {\n originalSuccess(event);\n }\n\n checkCompletion();\n };\n\n var originalError = options.error;\n options.error = function(event) {\n failures++;\n\n if (!failEvent) {\n failEvent = event;\n }\n\n if (originalError) {\n originalError(event);\n }\n\n checkCompletion();\n };\n\n _this.addTiledImage(options);\n };\n\n // TileSources\n for (var i = 0; i < tileSources.length; i++) {\n doOne(tileSources[i]);\n }\n\n return this;\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:close\n */\n close: function ( ) {\n if ( !THIS[ this.hash ] ) {\n //this viewer has already been destroyed: returning immediately\n return this;\n }\n\n this._opening = false;\n\n if ( this.navigator ) {\n this.navigator.close();\n }\n\n if (!this.preserveOverlays) {\n this.clearOverlays();\n this.overlaysContainer.innerHTML = \"\";\n }\n\n THIS[ this.hash ].animating = false;\n this.world.removeAll();\n this.imageLoader.clear();\n\n /**\n * Raised when the viewer is closed (see {@link OpenSeadragon.Viewer#close}).\n *\n * @event close\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'close' );\n\n return this;\n },\n\n\n /**\n * Function to destroy the viewer and clean up everything created by OpenSeadragon.\n *\n * Example:\n * var viewer = OpenSeadragon({\n * [...]\n * });\n *\n * //when you are done with the viewer:\n * viewer.destroy();\n * viewer = null; //important\n *\n * @function\n */\n destroy: function( ) {\n if ( !THIS[ this.hash ] ) {\n //this viewer has already been destroyed: returning immediately\n return;\n }\n\n this.close();\n\n this.clearOverlays();\n this.overlaysContainer.innerHTML = \"\";\n\n //TODO: implement this...\n //this.unbindSequenceControls()\n //this.unbindStandardControls()\n\n if (this.referenceStrip) {\n this.referenceStrip.destroy();\n this.referenceStrip = null;\n }\n\n if ( this._updateRequestId !== null ) {\n $.cancelAnimationFrame( this._updateRequestId );\n this._updateRequestId = null;\n }\n\n if ( this.drawer ) {\n this.drawer.destroy();\n }\n\n this.removeAllHandlers();\n\n // Go through top element (passed to us) and remove all children\n // Use removeChild to make sure it handles SVG or any non-html\n // also it performs better - http://jsperf.com/innerhtml-vs-removechild/15\n if (this.element){\n while (this.element.firstChild) {\n this.element.removeChild(this.element.firstChild);\n }\n }\n\n // destroy the mouse trackers\n if (this.innerTracker){\n this.innerTracker.destroy();\n }\n if (this.outerTracker){\n this.outerTracker.destroy();\n }\n\n THIS[ this.hash ] = null;\n delete THIS[ this.hash ];\n\n // clear all our references to dom objects\n this.canvas = null;\n this.container = null;\n\n // clear our reference to the main element - they will need to pass it in again, creating a new viewer\n this.element = null;\n },\n\n /**\n * @function\n * @return {Boolean}\n */\n isMouseNavEnabled: function () {\n return this.innerTracker.isTracking();\n },\n\n /**\n * @function\n * @param {Boolean} enabled - true to enable, false to disable\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:mouse-enabled\n */\n setMouseNavEnabled: function( enabled ){\n this.innerTracker.setTracking( enabled );\n this.outerTracker.setTracking( enabled );\n /**\n * Raised when mouse/touch navigation is enabled or disabled (see {@link OpenSeadragon.Viewer#setMouseNavEnabled}).\n *\n * @event mouse-enabled\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} enabled\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'mouse-enabled', { enabled: enabled } );\n return this;\n },\n\n\n /**\n * @function\n * @return {Boolean}\n */\n areControlsEnabled: function () {\n var enabled = this.controls.length,\n i;\n for( i = 0; i < this.controls.length; i++ ){\n enabled = enabled && this.controls[ i ].isVisibile();\n }\n return enabled;\n },\n\n\n /**\n * Shows or hides the controls (e.g. the default navigation buttons).\n *\n * @function\n * @param {Boolean} true to show, false to hide.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:controls-enabled\n */\n setControlsEnabled: function( enabled ) {\n if( enabled ){\n abortControlsAutoHide( this );\n } else {\n beginControlsAutoHide( this );\n }\n /**\n * Raised when the navigation controls are shown or hidden (see {@link OpenSeadragon.Viewer#setControlsEnabled}).\n *\n * @event controls-enabled\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} enabled\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'controls-enabled', { enabled: enabled } );\n return this;\n },\n\n /**\n * Turns debugging mode on or off for this viewer.\n *\n * @function\n * @param {Boolean} true to turn debug on, false to turn debug off.\n */\n setDebugMode: function(debugMode){\n\n for (var i = 0; i < this.world.getItemCount(); i++) {\n this.world.getItemAt(i).debugMode = debugMode;\n }\n\n this.debugMode = debugMode;\n this.forceRedraw();\n },\n\n /**\n * @function\n * @return {Boolean}\n */\n isFullPage: function () {\n return THIS[ this.hash ].fullPage;\n },\n\n\n /**\n * Toggle full page mode.\n * @function\n * @param {Boolean} fullPage\n * If true, enter full page mode. If false, exit full page mode.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:pre-full-page\n * @fires OpenSeadragon.Viewer.event:full-page\n */\n setFullPage: function( fullPage ) {\n\n var body = document.body,\n bodyStyle = body.style,\n docStyle = document.documentElement.style,\n _this = this,\n nodes,\n i;\n\n //dont bother modifying the DOM if we are already in full page mode.\n if ( fullPage == this.isFullPage() ) {\n return this;\n }\n\n var fullPageEventArgs = {\n fullPage: fullPage,\n preventDefaultAction: false\n };\n /**\n * Raised when the viewer is about to change to/from full-page mode (see {@link OpenSeadragon.Viewer#setFullPage}).\n *\n * @event pre-full-page\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullPage - True if entering full-page mode, false if exiting full-page mode.\n * @property {Boolean} preventDefaultAction - Set to true to prevent full-page mode change. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'pre-full-page', fullPageEventArgs );\n if ( fullPageEventArgs.preventDefaultAction ) {\n return this;\n }\n\n if ( fullPage ) {\n\n this.elementSize = $.getElementSize( this.element );\n this.pageScroll = $.getPageScroll();\n\n this.elementMargin = this.element.style.margin;\n this.element.style.margin = \"0\";\n this.elementPadding = this.element.style.padding;\n this.element.style.padding = \"0\";\n\n this.bodyMargin = bodyStyle.margin;\n this.docMargin = docStyle.margin;\n bodyStyle.margin = \"0\";\n docStyle.margin = \"0\";\n\n this.bodyPadding = bodyStyle.padding;\n this.docPadding = docStyle.padding;\n bodyStyle.padding = \"0\";\n docStyle.padding = \"0\";\n\n this.bodyWidth = bodyStyle.width;\n this.docWidth = docStyle.width;\n bodyStyle.width = \"100%\";\n docStyle.width = \"100%\";\n\n this.bodyHeight = bodyStyle.height;\n this.docHeight = docStyle.height;\n bodyStyle.height = \"100%\";\n docStyle.height = \"100%\";\n\n //when entering full screen on the ipad it wasnt sufficient to leave\n //the body intact as only only the top half of the screen would\n //respond to touch events on the canvas, while the bottom half treated\n //them as touch events on the document body. Thus we remove and store\n //the bodies elements and replace them when we leave full screen.\n this.previousBody = [];\n THIS[ this.hash ].prevElementParent = this.element.parentNode;\n THIS[ this.hash ].prevNextSibling = this.element.nextSibling;\n THIS[ this.hash ].prevElementWidth = this.element.style.width;\n THIS[ this.hash ].prevElementHeight = this.element.style.height;\n nodes = body.childNodes.length;\n for ( i = 0; i < nodes; i++ ) {\n this.previousBody.push( body.childNodes[ 0 ] );\n body.removeChild( body.childNodes[ 0 ] );\n }\n\n //If we've got a toolbar, we need to enable the user to use css to\n //preserve it in fullpage mode\n if ( this.toolbar && this.toolbar.element ) {\n //save a reference to the parent so we can put it back\n //in the long run we need a better strategy\n this.toolbar.parentNode = this.toolbar.element.parentNode;\n this.toolbar.nextSibling = this.toolbar.element.nextSibling;\n body.appendChild( this.toolbar.element );\n\n //Make sure the user has some ability to style the toolbar based\n //on the mode\n $.addClass( this.toolbar.element, 'fullpage' );\n }\n\n $.addClass( this.element, 'fullpage' );\n body.appendChild( this.element );\n\n this.element.style.height = $.getWindowSize().y + 'px';\n this.element.style.width = $.getWindowSize().x + 'px';\n\n if ( this.toolbar && this.toolbar.element ) {\n this.element.style.height = (\n $.getElementSize( this.element ).y - $.getElementSize( this.toolbar.element ).y\n ) + 'px';\n }\n\n THIS[ this.hash ].fullPage = true;\n\n // mouse will be inside container now\n $.delegate( this, onContainerEnter )( {} );\n\n } else {\n\n this.element.style.margin = this.elementMargin;\n this.element.style.padding = this.elementPadding;\n\n bodyStyle.margin = this.bodyMargin;\n docStyle.margin = this.docMargin;\n\n bodyStyle.padding = this.bodyPadding;\n docStyle.padding = this.docPadding;\n\n bodyStyle.width = this.bodyWidth;\n docStyle.width = this.docWidth;\n\n bodyStyle.height = this.bodyHeight;\n docStyle.height = this.docHeight;\n\n body.removeChild( this.element );\n nodes = this.previousBody.length;\n for ( i = 0; i < nodes; i++ ) {\n body.appendChild( this.previousBody.shift() );\n }\n\n $.removeClass( this.element, 'fullpage' );\n THIS[ this.hash ].prevElementParent.insertBefore(\n this.element,\n THIS[ this.hash ].prevNextSibling\n );\n\n //If we've got a toolbar, we need to enable the user to use css to\n //reset it to its original state\n if ( this.toolbar && this.toolbar.element ) {\n body.removeChild( this.toolbar.element );\n\n //Make sure the user has some ability to style the toolbar based\n //on the mode\n $.removeClass( this.toolbar.element, 'fullpage' );\n\n this.toolbar.parentNode.insertBefore(\n this.toolbar.element,\n this.toolbar.nextSibling\n );\n delete this.toolbar.parentNode;\n delete this.toolbar.nextSibling;\n }\n\n this.element.style.width = THIS[ this.hash ].prevElementWidth;\n this.element.style.height = THIS[ this.hash ].prevElementHeight;\n\n // After exiting fullPage or fullScreen, it can take some time\n // before the browser can actually set the scroll.\n var restoreScrollCounter = 0;\n var restoreScroll = function() {\n $.setPageScroll( _this.pageScroll );\n var pageScroll = $.getPageScroll();\n restoreScrollCounter++;\n if (restoreScrollCounter < 10 &&\n (pageScroll.x !== _this.pageScroll.x ||\n pageScroll.y !== _this.pageScroll.y)) {\n $.requestAnimationFrame( restoreScroll );\n }\n };\n $.requestAnimationFrame( restoreScroll );\n\n THIS[ this.hash ].fullPage = false;\n\n // mouse will likely be outside now\n $.delegate( this, onContainerExit )( { } );\n\n }\n\n if ( this.navigator && this.viewport ) {\n this.navigator.update( this.viewport );\n }\n\n /**\n * Raised when the viewer has changed to/from full-page mode (see {@link OpenSeadragon.Viewer#setFullPage}).\n *\n * @event full-page\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullPage - True if changed to full-page mode, false if exited full-page mode.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'full-page', { fullPage: fullPage } );\n\n return this;\n },\n\n /**\n * Toggle full screen mode if supported. Toggle full page mode otherwise.\n * @function\n * @param {Boolean} fullScreen\n * If true, enter full screen mode. If false, exit full screen mode.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:pre-full-screen\n * @fires OpenSeadragon.Viewer.event:full-screen\n */\n setFullScreen: function( fullScreen ) {\n var _this = this;\n\n if ( !$.supportsFullScreen ) {\n return this.setFullPage( fullScreen );\n }\n\n if ( $.isFullScreen() === fullScreen ) {\n return this;\n }\n\n var fullScreeEventArgs = {\n fullScreen: fullScreen,\n preventDefaultAction: false\n };\n /**\n * Raised when the viewer is about to change to/from full-screen mode (see {@link OpenSeadragon.Viewer#setFullScreen}).\n * Note: the pre-full-screen event is not raised when the user is exiting\n * full-screen mode by pressing the Esc key. In that case, consider using\n * the full-screen, pre-full-page or full-page events.\n *\n * @event pre-full-screen\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullScreen - True if entering full-screen mode, false if exiting full-screen mode.\n * @property {Boolean} preventDefaultAction - Set to true to prevent full-screen mode change. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'pre-full-screen', fullScreeEventArgs );\n if ( fullScreeEventArgs.preventDefaultAction ) {\n return this;\n }\n\n if ( fullScreen ) {\n\n this.setFullPage( true );\n // If the full page mode is not actually entered, we need to prevent\n // the full screen mode.\n if ( !this.isFullPage() ) {\n return this;\n }\n\n this.fullPageStyleWidth = this.element.style.width;\n this.fullPageStyleHeight = this.element.style.height;\n this.element.style.width = '100%';\n this.element.style.height = '100%';\n\n var onFullScreenChange = function() {\n var isFullScreen = $.isFullScreen();\n if ( !isFullScreen ) {\n $.removeEvent( document, $.fullScreenEventName, onFullScreenChange );\n $.removeEvent( document, $.fullScreenErrorEventName, onFullScreenChange );\n\n _this.setFullPage( false );\n if ( _this.isFullPage() ) {\n _this.element.style.width = _this.fullPageStyleWidth;\n _this.element.style.height = _this.fullPageStyleHeight;\n }\n }\n if ( _this.navigator && _this.viewport ) {\n _this.navigator.update( _this.viewport );\n }\n /**\n * Raised when the viewer has changed to/from full-screen mode (see {@link OpenSeadragon.Viewer#setFullScreen}).\n *\n * @event full-screen\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullScreen - True if changed to full-screen mode, false if exited full-screen mode.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'full-screen', { fullScreen: isFullScreen } );\n };\n $.addEvent( document, $.fullScreenEventName, onFullScreenChange );\n $.addEvent( document, $.fullScreenErrorEventName, onFullScreenChange );\n\n $.requestFullScreen( document.body );\n\n } else {\n $.exitFullScreen();\n }\n return this;\n },\n\n /**\n * @function\n * @return {Boolean}\n */\n isVisible: function () {\n return this.container.style.visibility != \"hidden\";\n },\n\n\n /**\n * @function\n * @param {Boolean} visible\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:visible\n */\n setVisible: function( visible ){\n this.container.style.visibility = visible ? \"\" : \"hidden\";\n /**\n * Raised when the viewer is shown or hidden (see {@link OpenSeadragon.Viewer#setVisible}).\n *\n * @event visible\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} visible\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'visible', { visible: visible } );\n return this;\n },\n\n /**\n * Add a tiled image to the viewer.\n * options.tileSource can be anything that {@link OpenSeadragon.Viewer#open}\n * supports except arrays of images.\n * Note that you can specify options.width or options.height, but not both.\n * The other dimension will be calculated according to the item's aspect ratio.\n * If collectionMode is on (see {@link OpenSeadragon.Options}), the new image is\n * automatically arranged with the others.\n * @function\n * @param {Object} options\n * @param {String|Object|Function} options.tileSource - The TileSource specifier.\n * A String implies a url used to determine the tileSource implementation\n * based on the file extension of url. JSONP is implied by *.js,\n * otherwise the url is retrieved as text and the resulting text is\n * introspected to determine if its json, xml, or text and parsed.\n * An Object implies an inline configuration which has a single\n * property sufficient for being able to determine tileSource\n * implementation. If the object has a property which is a function\n * named 'getTileUrl', it is treated as a custom TileSource.\n * @param {Number} [options.index] The index of the item. Added on top of\n * all other items if not specified.\n * @param {Boolean} [options.replace=false] If true, the item at options.index will be\n * removed and the new item is added in its place. options.tileSource will be\n * interpreted and fetched if necessary before the old item is removed to avoid leaving\n * a gap in the world.\n * @param {Number} [options.x=0] The X position for the image in viewport coordinates.\n * @param {Number} [options.y=0] The Y position for the image in viewport coordinates.\n * @param {Number} [options.width=1] The width for the image in viewport coordinates.\n * @param {Number} [options.height] The height for the image in viewport coordinates.\n * @param {OpenSeadragon.Rect} [options.fitBounds] The bounds in viewport coordinates\n * to fit the image into. If specified, x, y, width and height get ignored.\n * @param {OpenSeadragon.Placement} [options.fitBoundsPlacement=OpenSeadragon.Placement.CENTER]\n * How to anchor the image in the bounds if options.fitBounds is set.\n * @param {OpenSeadragon.Rect} [options.clip] - An area, in image pixels, to clip to\n * (portions of the image outside of this area will not be visible). Only works on\n * browsers that support the HTML5 canvas.\n * @param {Number} [options.opacity=1] Proportional opacity of the tiled images (1=opaque, 0=hidden)\n * @param {Boolean} [options.preload=false] Default switch for loading hidden images (true loads, false blocks)\n * @param {Number} [options.degrees=0] Initial rotation of the tiled image around\n * its top left corner in degrees.\n * @param {String} [options.compositeOperation] How the image is composited onto other images.\n * @param {String} [options.crossOriginPolicy] The crossOriginPolicy for this specific image,\n * overriding viewer.crossOriginPolicy.\n * @param {Boolean} [options.ajaxWithCredentials] Whether to set withCredentials on tile AJAX\n * @param {Boolean} [options.loadTilesWithAjax]\n * Whether to load tile data using AJAX requests.\n * Defaults to the setting in {@link OpenSeadragon.Options}.\n * @param {Object} [options.ajaxHeaders]\n * A set of headers to include when making tile AJAX requests.\n * Note that these headers will be merged over any headers specified in {@link OpenSeadragon.Options}.\n * Specifying a falsy value for a header will clear its existing value set at the Viewer level (if any).\n * requests.\n * @param {Function} [options.success] A function that gets called when the image is\n * successfully added. It's passed the event object which contains a single property:\n * \"item\", which is the resulting instance of TiledImage.\n * @param {Function} [options.error] A function that gets called if the image is\n * unable to be added. It's passed the error event object, which contains \"message\"\n * and \"source\" properties.\n * @param {Boolean} [options.collectionImmediately=false] If collectionMode is on,\n * specifies whether to snap to the new arrangement immediately or to animate to it.\n * @param {String|CanvasGradient|CanvasPattern|Function} [options.placeholderFillStyle] - See {@link OpenSeadragon.Options}.\n * @fires OpenSeadragon.World.event:add-item\n * @fires OpenSeadragon.Viewer.event:add-item-failed\n */\n addTiledImage: function( options ) {\n $.console.assert(options, \"[Viewer.addTiledImage] options is required\");\n $.console.assert(options.tileSource, \"[Viewer.addTiledImage] options.tileSource is required\");\n $.console.assert(!options.replace || (options.index > -1 && options.index < this.world.getItemCount()),\n \"[Viewer.addTiledImage] if options.replace is used, options.index must be a valid index in Viewer.world\");\n\n var _this = this;\n\n if (options.replace) {\n options.replaceItem = _this.world.getItemAt(options.index);\n }\n\n this._hideMessage();\n\n if (options.placeholderFillStyle === undefined) {\n options.placeholderFillStyle = this.placeholderFillStyle;\n }\n if (options.opacity === undefined) {\n options.opacity = this.opacity;\n }\n if (options.preload === undefined) {\n options.preload = this.preload;\n }\n if (options.compositeOperation === undefined) {\n options.compositeOperation = this.compositeOperation;\n }\n if (options.crossOriginPolicy === undefined) {\n options.crossOriginPolicy = options.tileSource.crossOriginPolicy !== undefined ? options.tileSource.crossOriginPolicy : this.crossOriginPolicy;\n }\n if (options.ajaxWithCredentials === undefined) {\n options.ajaxWithCredentials = this.ajaxWithCredentials;\n }\n if (options.makeAjaxRequest === undefined) {\n options.makeAjaxRequest = options.tileSource.makeAjaxRequest;\n }\n if (options.loadTilesWithAjax === undefined) {\n options.loadTilesWithAjax = this.loadTilesWithAjax;\n }\n if (options.ajaxHeaders === undefined || options.ajaxHeaders === null) {\n options.ajaxHeaders = this.ajaxHeaders;\n } else if ($.isPlainObject(options.ajaxHeaders) && $.isPlainObject(this.ajaxHeaders)) {\n options.ajaxHeaders = $.extend({}, this.ajaxHeaders, options.ajaxHeaders);\n }\n\n var myQueueItem = {\n options: options\n };\n\n function raiseAddItemFailed( event ) {\n for (var i = 0; i < _this._loadQueue.length; i++) {\n if (_this._loadQueue[i] === myQueueItem) {\n _this._loadQueue.splice(i, 1);\n break;\n }\n }\n\n if (_this._loadQueue.length === 0) {\n refreshWorld(myQueueItem);\n }\n\n /**\n * Raised when an error occurs while adding a item.\n * @event add-item-failed\n * @memberOf OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {String} message\n * @property {String} source\n * @property {Object} options The options passed to the addTiledImage method.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'add-item-failed', event );\n\n if (options.error) {\n options.error(event);\n }\n }\n\n function refreshWorld(theItem) {\n if (_this.collectionMode) {\n _this.world.arrange({\n immediately: theItem.options.collectionImmediately,\n rows: _this.collectionRows,\n columns: _this.collectionColumns,\n layout: _this.collectionLayout,\n tileSize: _this.collectionTileSize,\n tileMargin: _this.collectionTileMargin\n });\n _this.world.setAutoRefigureSizes(true);\n }\n }\n\n if ($.isArray(options.tileSource)) {\n setTimeout(function() {\n raiseAddItemFailed({\n message: \"[Viewer.addTiledImage] Sequences can not be added; add them one at a time instead.\",\n source: options.tileSource,\n options: options\n });\n });\n return;\n }\n\n this._loadQueue.push(myQueueItem);\n\n function processReadyItems() {\n var queueItem, tiledImage, optionsClone;\n while (_this._loadQueue.length) {\n queueItem = _this._loadQueue[0];\n if (!queueItem.tileSource) {\n break;\n }\n\n _this._loadQueue.splice(0, 1);\n\n if (queueItem.options.replace) {\n var newIndex = _this.world.getIndexOfItem(queueItem.options.replaceItem);\n if (newIndex != -1) {\n queueItem.options.index = newIndex;\n }\n _this.world.removeItem(queueItem.options.replaceItem);\n }\n\n tiledImage = new $.TiledImage({\n viewer: _this,\n source: queueItem.tileSource,\n viewport: _this.viewport,\n drawer: _this.drawer,\n tileCache: _this.tileCache,\n imageLoader: _this.imageLoader,\n x: queueItem.options.x,\n y: queueItem.options.y,\n width: queueItem.options.width,\n height: queueItem.options.height,\n fitBounds: queueItem.options.fitBounds,\n fitBoundsPlacement: queueItem.options.fitBoundsPlacement,\n clip: queueItem.options.clip,\n placeholderFillStyle: queueItem.options.placeholderFillStyle,\n opacity: queueItem.options.opacity,\n preload: queueItem.options.preload,\n degrees: queueItem.options.degrees,\n compositeOperation: queueItem.options.compositeOperation,\n springStiffness: _this.springStiffness,\n animationTime: _this.animationTime,\n minZoomImageRatio: _this.minZoomImageRatio,\n wrapHorizontal: _this.wrapHorizontal,\n wrapVertical: _this.wrapVertical,\n immediateRender: _this.immediateRender,\n blendTime: _this.blendTime,\n alwaysBlend: _this.alwaysBlend,\n minPixelRatio: _this.minPixelRatio,\n smoothTileEdgesMinZoom: _this.smoothTileEdgesMinZoom,\n iOSDevice: _this.iOSDevice,\n crossOriginPolicy: queueItem.options.crossOriginPolicy,\n ajaxWithCredentials: queueItem.options.ajaxWithCredentials,\n makeAjaxRequest: queueItem.options.makeAjaxRequest,\n loadTilesWithAjax: queueItem.options.loadTilesWithAjax,\n ajaxHeaders: queueItem.options.ajaxHeaders,\n debugMode: _this.debugMode\n });\n\n if (_this.collectionMode) {\n _this.world.setAutoRefigureSizes(false);\n }\n _this.world.addItem( tiledImage, {\n index: queueItem.options.index\n });\n\n if (_this._loadQueue.length === 0) {\n //this restores the autoRefigureSizes flag to true.\n refreshWorld(queueItem);\n }\n\n if (_this.world.getItemCount() === 1 && !_this.preserveViewport) {\n _this.viewport.goHome(true);\n }\n\n if (_this.navigator) {\n optionsClone = $.extend({}, queueItem.options, {\n replace: false, // navigator already removed the layer, nothing to replace\n originalTiledImage: tiledImage,\n tileSource: queueItem.tileSource\n });\n\n _this.navigator.addTiledImage(optionsClone);\n }\n\n if (queueItem.options.success) {\n queueItem.options.success({\n item: tiledImage\n });\n }\n }\n }\n\n getTileSourceImplementation( this, options.tileSource, options, function( tileSource ) {\n\n myQueueItem.tileSource = tileSource;\n\n // add everybody at the front of the queue that's ready to go\n processReadyItems();\n }, function( event ) {\n event.options = options;\n raiseAddItemFailed(event);\n\n // add everybody at the front of the queue that's ready to go\n processReadyItems();\n } );\n },\n\n /**\n * Add a simple image to the viewer.\n * The options are the same as the ones in {@link OpenSeadragon.Viewer#addTiledImage}\n * except for options.tileSource which is replaced by options.url.\n * @function\n * @param {Object} options - See {@link OpenSeadragon.Viewer#addTiledImage}\n * for all the options\n * @param {String} options.url - The URL of the image to add.\n * @fires OpenSeadragon.World.event:add-item\n * @fires OpenSeadragon.Viewer.event:add-item-failed\n */\n addSimpleImage: function(options) {\n $.console.assert(options, \"[Viewer.addSimpleImage] options is required\");\n $.console.assert(options.url, \"[Viewer.addSimpleImage] options.url is required\");\n\n var opts = $.extend({}, options, {\n tileSource: {\n type: 'image',\n url: options.url\n }\n });\n delete opts.url;\n this.addTiledImage(opts);\n },\n\n // deprecated\n addLayer: function( options ) {\n var _this = this;\n\n $.console.error( \"[Viewer.addLayer] this function is deprecated; use Viewer.addTiledImage() instead.\" );\n\n var optionsClone = $.extend({}, options, {\n success: function(event) {\n _this.raiseEvent(\"add-layer\", {\n options: options,\n drawer: event.item\n });\n },\n error: function(event) {\n _this.raiseEvent(\"add-layer-failed\", event);\n }\n });\n\n this.addTiledImage(optionsClone);\n return this;\n },\n\n // deprecated\n getLayerAtLevel: function( level ) {\n $.console.error( \"[Viewer.getLayerAtLevel] this function is deprecated; use World.getItemAt() instead.\" );\n return this.world.getItemAt(level);\n },\n\n // deprecated\n getLevelOfLayer: function( drawer ) {\n $.console.error( \"[Viewer.getLevelOfLayer] this function is deprecated; use World.getIndexOfItem() instead.\" );\n return this.world.getIndexOfItem(drawer);\n },\n\n // deprecated\n getLayersCount: function() {\n $.console.error( \"[Viewer.getLayersCount] this function is deprecated; use World.getItemCount() instead.\" );\n return this.world.getItemCount();\n },\n\n // deprecated\n setLayerLevel: function( drawer, level ) {\n $.console.error( \"[Viewer.setLayerLevel] this function is deprecated; use World.setItemIndex() instead.\" );\n return this.world.setItemIndex(drawer, level);\n },\n\n // deprecated\n removeLayer: function( drawer ) {\n $.console.error( \"[Viewer.removeLayer] this function is deprecated; use World.removeItem() instead.\" );\n return this.world.removeItem(drawer);\n },\n\n /**\n * Force the viewer to redraw its contents.\n * @returns {OpenSeadragon.Viewer} Chainable.\n */\n forceRedraw: function() {\n THIS[ this.hash ].forceRedraw = true;\n return this;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n */\n bindSequenceControls: function(){\n\n //////////////////////////////////////////////////////////////////////////\n // Image Sequence Controls\n //////////////////////////////////////////////////////////////////////////\n var onFocusHandler = $.delegate( this, onFocus ),\n onBlurHandler = $.delegate( this, onBlur ),\n onNextHandler = $.delegate( this, onNext ),\n onPreviousHandler = $.delegate( this, onPrevious ),\n navImages = this.navImages,\n useGroup = true;\n\n if( this.showSequenceControl ){\n\n if( this.previousButton || this.nextButton ){\n //if we are binding to custom buttons then layout and\n //grouping is the responsibility of the page author\n useGroup = false;\n }\n\n this.previousButton = new $.Button({\n element: this.previousButton ? $.getElement( this.previousButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.PreviousPage\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.previous.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.previous.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.previous.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.previous.DOWN ),\n onRelease: onPreviousHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n });\n\n this.nextButton = new $.Button({\n element: this.nextButton ? $.getElement( this.nextButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.NextPage\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.next.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.next.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.next.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.next.DOWN ),\n onRelease: onNextHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n });\n\n if( !this.navPrevNextWrap ){\n this.previousButton.disable();\n }\n\n if (!this.tileSources || !this.tileSources.length) {\n this.nextButton.disable();\n }\n\n if( useGroup ){\n this.paging = new $.ButtonGroup({\n buttons: [\n this.previousButton,\n this.nextButton\n ],\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold\n });\n\n this.pagingControl = this.paging.element;\n\n if( this.toolbar ){\n this.toolbar.addControl(\n this.pagingControl,\n {anchor: $.ControlAnchor.BOTTOM_RIGHT}\n );\n }else{\n this.addControl(\n this.pagingControl,\n {anchor: this.sequenceControlAnchor || $.ControlAnchor.TOP_LEFT}\n );\n }\n }\n }\n return this;\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n */\n bindStandardControls: function(){\n //////////////////////////////////////////////////////////////////////////\n // Navigation Controls\n //////////////////////////////////////////////////////////////////////////\n var beginZoomingInHandler = $.delegate( this, beginZoomingIn ),\n endZoomingHandler = $.delegate( this, endZooming ),\n doSingleZoomInHandler = $.delegate( this, doSingleZoomIn ),\n beginZoomingOutHandler = $.delegate( this, beginZoomingOut ),\n doSingleZoomOutHandler = $.delegate( this, doSingleZoomOut ),\n onHomeHandler = $.delegate( this, onHome ),\n onFullScreenHandler = $.delegate( this, onFullScreen ),\n onRotateLeftHandler = $.delegate( this, onRotateLeft ),\n onRotateRightHandler = $.delegate( this, onRotateRight ),\n onFlipHandler = $.delegate( this, onFlip),\n onFocusHandler = $.delegate( this, onFocus ),\n onBlurHandler = $.delegate( this, onBlur ),\n navImages = this.navImages,\n buttons = [],\n useGroup = true;\n\n\n if ( this.showNavigationControl ) {\n\n if( this.zoomInButton || this.zoomOutButton ||\n this.homeButton || this.fullPageButton ||\n this.rotateLeftButton || this.rotateRightButton ||\n this.flipButton ) {\n //if we are binding to custom buttons then layout and\n //grouping is the responsibility of the page author\n useGroup = false;\n }\n\n if ( this.showZoomControl ) {\n buttons.push( this.zoomInButton = new $.Button({\n element: this.zoomInButton ? $.getElement( this.zoomInButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.ZoomIn\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.zoomIn.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.zoomIn.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.zoomIn.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.zoomIn.DOWN ),\n onPress: beginZoomingInHandler,\n onRelease: endZoomingHandler,\n onClick: doSingleZoomInHandler,\n onEnter: beginZoomingInHandler,\n onExit: endZoomingHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n\n buttons.push( this.zoomOutButton = new $.Button({\n element: this.zoomOutButton ? $.getElement( this.zoomOutButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.ZoomOut\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.zoomOut.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.zoomOut.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.zoomOut.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.zoomOut.DOWN ),\n onPress: beginZoomingOutHandler,\n onRelease: endZoomingHandler,\n onClick: doSingleZoomOutHandler,\n onEnter: beginZoomingOutHandler,\n onExit: endZoomingHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showHomeControl ) {\n buttons.push( this.homeButton = new $.Button({\n element: this.homeButton ? $.getElement( this.homeButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.Home\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.home.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.home.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.home.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.home.DOWN ),\n onRelease: onHomeHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showFullPageControl ) {\n buttons.push( this.fullPageButton = new $.Button({\n element: this.fullPageButton ? $.getElement( this.fullPageButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.FullPage\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.fullpage.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.fullpage.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.fullpage.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.fullpage.DOWN ),\n onRelease: onFullScreenHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showRotationControl ) {\n buttons.push( this.rotateLeftButton = new $.Button({\n element: this.rotateLeftButton ? $.getElement( this.rotateLeftButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.RotateLeft\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.rotateleft.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.rotateleft.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.rotateleft.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.rotateleft.DOWN ),\n onRelease: onRotateLeftHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n\n buttons.push( this.rotateRightButton = new $.Button({\n element: this.rotateRightButton ? $.getElement( this.rotateRightButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.RotateRight\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.rotateright.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.rotateright.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.rotateright.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.rotateright.DOWN ),\n onRelease: onRotateRightHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showFlipControl ) {\n buttons.push( this.flipButton = new $.Button({\n element: this.flipButton ? $.getElement( this.flipButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.Flip\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.flip.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.flip.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.flip.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.flip.DOWN ),\n onRelease: onFlipHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( useGroup ) {\n this.buttons = new $.ButtonGroup({\n buttons: buttons,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold\n });\n\n this.navControl = this.buttons.element;\n this.addHandler( 'open', $.delegate( this, lightUp ) );\n\n if( this.toolbar ){\n this.toolbar.addControl(\n this.navControl,\n {anchor: this.navigationControlAnchor || $.ControlAnchor.TOP_LEFT}\n );\n } else {\n this.addControl(\n this.navControl,\n {anchor: this.navigationControlAnchor || $.ControlAnchor.TOP_LEFT}\n );\n }\n }\n\n }\n return this;\n },\n\n /**\n * Gets the active page of a sequence\n * @function\n * @return {Number}\n */\n currentPage: function() {\n return this._sequenceIndex;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:page\n */\n goToPage: function( page ){\n if( this.tileSources && page >= 0 && page < this.tileSources.length ){\n this._sequenceIndex = page;\n\n this._updateSequenceButtons( page );\n\n this.open( this.tileSources[ page ] );\n\n if( this.referenceStrip ){\n this.referenceStrip.setFocus( page );\n }\n\n /**\n * Raised when the page is changed on a viewer configured with multiple image sources (see {@link OpenSeadragon.Viewer#goToPage}).\n *\n * @event page\n * @memberof OpenSeadragon.Viewer\n * @type {Object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Number} page - The page index.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'page', { page: page } );\n }\n\n return this;\n },\n\n /**\n * Adds an html element as an overlay to the current viewport. Useful for\n * highlighting words or areas of interest on an image or other zoomable\n * interface. The overlays added via this method are removed when the viewport\n * is closed which include when changing page.\n * @method\n * @param {Element|String|Object} element - A reference to an element or an id for\n * the element which will be overlayed. Or an Object specifying the configuration for the overlay.\n * If using an object, see {@link OpenSeadragon.Overlay} for a list of\n * all available options.\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect} location - The point or\n * rectangle which will be overlayed. This is a viewport relative location.\n * @param {OpenSeadragon.Placement} placement - The position of the\n * viewport which the location coordinates will be treated as relative\n * to.\n * @param {function} onDraw - If supplied the callback is called when the overlay\n * needs to be drawn. It it the responsibility of the callback to do any drawing/positioning.\n * It is passed position, size and element.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:add-overlay\n */\n addOverlay: function( element, location, placement, onDraw ) {\n var options;\n if( $.isPlainObject( element ) ){\n options = element;\n } else {\n options = {\n element: element,\n location: location,\n placement: placement,\n onDraw: onDraw\n };\n }\n\n element = $.getElement( options.element );\n\n if ( getOverlayIndex( this.currentOverlays, element ) >= 0 ) {\n // they're trying to add a duplicate overlay\n return this;\n }\n\n var overlay = getOverlayObject( this, options);\n this.currentOverlays.push(overlay);\n overlay.drawHTML( this.overlaysContainer, this.viewport );\n\n /**\n * Raised when an overlay is added to the viewer (see {@link OpenSeadragon.Viewer#addOverlay}).\n *\n * @event add-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Element} element - The overlay element.\n * @property {OpenSeadragon.Point|OpenSeadragon.Rect} location\n * @property {OpenSeadragon.Placement} placement\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'add-overlay', {\n element: element,\n location: options.location,\n placement: options.placement\n });\n return this;\n },\n\n /**\n * Updates the overlay represented by the reference to the element or\n * element id moving it to the new location, relative to the new placement.\n * @method\n * @param {Element|String} element - A reference to an element or an id for\n * the element which is overlayed.\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect} location - The point or\n * rectangle which will be overlayed. This is a viewport relative location.\n * @param {OpenSeadragon.Placement} placement - The position of the\n * viewport which the location coordinates will be treated as relative\n * to.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:update-overlay\n */\n updateOverlay: function( element, location, placement ) {\n var i;\n\n element = $.getElement( element );\n i = getOverlayIndex( this.currentOverlays, element );\n\n if ( i >= 0 ) {\n this.currentOverlays[ i ].update( location, placement );\n THIS[ this.hash ].forceRedraw = true;\n /**\n * Raised when an overlay's location or placement changes\n * (see {@link OpenSeadragon.Viewer#updateOverlay}).\n *\n * @event update-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the\n * Viewer which raised the event.\n * @property {Element} element\n * @property {OpenSeadragon.Point|OpenSeadragon.Rect} location\n * @property {OpenSeadragon.Placement} placement\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'update-overlay', {\n element: element,\n location: location,\n placement: placement\n });\n }\n return this;\n },\n\n /**\n * Removes an overlay identified by the reference element or element id\n * and schedules an update.\n * @method\n * @param {Element|String} element - A reference to the element or an\n * element id which represent the ovelay content to be removed.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:remove-overlay\n */\n removeOverlay: function( element ) {\n var i;\n\n element = $.getElement( element );\n i = getOverlayIndex( this.currentOverlays, element );\n\n if ( i >= 0 ) {\n this.currentOverlays[ i ].destroy();\n this.currentOverlays.splice( i, 1 );\n THIS[ this.hash ].forceRedraw = true;\n /**\n * Raised when an overlay is removed from the viewer\n * (see {@link OpenSeadragon.Viewer#removeOverlay}).\n *\n * @event remove-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the\n * Viewer which raised the event.\n * @property {Element} element - The overlay element.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'remove-overlay', {\n element: element\n });\n }\n return this;\n },\n\n /**\n * Removes all currently configured Overlays from this Viewer and schedules\n * an update.\n * @method\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:clear-overlay\n */\n clearOverlays: function() {\n while ( this.currentOverlays.length > 0 ) {\n this.currentOverlays.pop().destroy();\n }\n THIS[ this.hash ].forceRedraw = true;\n /**\n * Raised when all overlays are removed from the viewer (see {@link OpenSeadragon.Drawer#clearOverlays}).\n *\n * @event clear-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'clear-overlay', {} );\n return this;\n },\n\n /**\n * Finds an overlay identified by the reference element or element id\n * and returns it as an object, return null if not found.\n * @method\n * @param {Element|String} element - A reference to the element or an\n * element id which represents the overlay content.\n * @return {OpenSeadragon.Overlay} the matching overlay or null if none found.\n */\n getOverlayById: function( element ) {\n var i;\n\n element = $.getElement( element );\n i = getOverlayIndex( this.currentOverlays, element );\n\n if (i >= 0) {\n return this.currentOverlays[i];\n } else {\n return null;\n }\n },\n\n /**\n * Updates the sequence buttons.\n * @function OpenSeadragon.Viewer.prototype._updateSequenceButtons\n * @private\n * @param {Number} Sequence Value\n */\n _updateSequenceButtons: function( page ) {\n\n if ( this.nextButton ) {\n if(!this.tileSources || this.tileSources.length - 1 === page) {\n //Disable next button\n if ( !this.navPrevNextWrap ) {\n this.nextButton.disable();\n }\n } else {\n this.nextButton.enable();\n }\n }\n if ( this.previousButton ) {\n if ( page > 0 ) {\n //Enable previous button\n this.previousButton.enable();\n } else {\n if ( !this.navPrevNextWrap ) {\n this.previousButton.disable();\n }\n }\n }\n },\n\n /**\n * Display a message in the viewport\n * @function OpenSeadragon.Viewer.prototype._showMessage\n * @private\n * @param {String} text message\n */\n _showMessage: function ( message ) {\n this._hideMessage();\n\n var div = $.makeNeutralElement( \"div\" );\n div.appendChild( document.createTextNode( message ) );\n\n this.messageDiv = $.makeCenteredNode( div );\n\n $.addClass(this.messageDiv, \"openseadragon-message\");\n\n this.container.appendChild( this.messageDiv );\n },\n\n /**\n * Hide any currently displayed viewport message\n * @function OpenSeadragon.Viewer.prototype._hideMessage\n * @private\n */\n _hideMessage: function () {\n var div = this.messageDiv;\n if (div) {\n div.parentNode.removeChild(div);\n delete this.messageDiv;\n }\n },\n\n /**\n * Gets this viewer's gesture settings for the given pointer device type.\n * @method\n * @param {String} type - The pointer device type to get the gesture settings for (\"mouse\", \"touch\", \"pen\", etc.).\n * @return {OpenSeadragon.GestureSettings}\n */\n gestureSettingsByDeviceType: function ( type ) {\n switch ( type ) {\n case 'mouse':\n return this.gestureSettingsMouse;\n case 'touch':\n return this.gestureSettingsTouch;\n case 'pen':\n return this.gestureSettingsPen;\n default:\n return this.gestureSettingsUnknown;\n }\n },\n\n // private\n _drawOverlays: function() {\n var i,\n length = this.currentOverlays.length;\n for ( i = 0; i < length; i++ ) {\n this.currentOverlays[ i ].drawHTML( this.overlaysContainer, this.viewport );\n }\n },\n\n /**\n * Cancel the \"in flight\" images.\n */\n _cancelPendingImages: function() {\n this._loadQueue = [];\n },\n\n /**\n * Removes the reference strip and disables displaying it.\n * @function\n */\n removeReferenceStrip: function() {\n this.showReferenceStrip = false;\n\n if (this.referenceStrip) {\n this.referenceStrip.destroy();\n this.referenceStrip = null;\n }\n },\n\n /**\n * Enables and displays the reference strip based on the currently set tileSources.\n * Works only when the Viewer has sequenceMode set to true.\n * @function\n */\n addReferenceStrip: function() {\n this.showReferenceStrip = true;\n\n if (this.sequenceMode) {\n if (this.referenceStrip) {\n return;\n }\n\n if (this.tileSources.length && this.tileSources.length > 1) {\n this.referenceStrip = new $.ReferenceStrip({\n id: this.referenceStripElement,\n position: this.referenceStripPosition,\n sizeRatio: this.referenceStripSizeRatio,\n scroll: this.referenceStripScroll,\n height: this.referenceStripHeight,\n width: this.referenceStripWidth,\n tileSources: this.tileSources,\n prefixUrl: this.prefixUrl,\n viewer: this\n });\n\n this.referenceStrip.setFocus( this._sequenceIndex );\n }\n } else {\n $.console.warn('Attempting to display a reference strip while \"sequenceMode\" is off.');\n }\n }\n});\n\n\n/**\n * _getSafeElemSize is like getElementSize(), but refuses to return 0 for x or y,\n * which was causing some calling operations to return NaN.\n * @returns {Point}\n * @private\n */\nfunction _getSafeElemSize (oElement) {\n oElement = $.getElement( oElement );\n\n return new $.Point(\n (oElement.clientWidth === 0 ? 1 : oElement.clientWidth),\n (oElement.clientHeight === 0 ? 1 : oElement.clientHeight)\n );\n}\n\n\n/**\n * @function\n * @private\n */\nfunction getTileSourceImplementation( viewer, tileSource, imgOptions, successCallback,\n failCallback ) {\n var _this = viewer;\n\n //allow plain xml strings or json strings to be parsed here\n if ( $.type( tileSource ) == 'string' ) {\n //xml should start with \"<\" and end with \">\"\n if ( tileSource.match( /^\\s*<.*>\\s*$/ ) ) {\n tileSource = $.parseXml( tileSource );\n //json should start with \"{\" or \"[\" and end with \"}\" or \"]\"\n } else if ( tileSource.match(/^\\s*[\\{\\[].*[\\}\\]]\\s*$/ ) ) {\n try {\n var tileSourceJ = $.parseJSON(tileSource);\n tileSource = tileSourceJ;\n } catch (e) {\n //tileSource = tileSource;\n }\n }\n }\n\n function waitUntilReady(tileSource, originalTileSource) {\n if (tileSource.ready) {\n successCallback(tileSource);\n } else {\n tileSource.addHandler('ready', function () {\n successCallback(tileSource);\n });\n tileSource.addHandler('open-failed', function (event) {\n failCallback({\n message: event.message,\n source: originalTileSource\n });\n });\n }\n }\n\n setTimeout( function() {\n if ( $.type( tileSource ) == 'string' ) {\n //If its still a string it means it must be a url at this point\n tileSource = new $.TileSource({\n url: tileSource,\n crossOriginPolicy: imgOptions.crossOriginPolicy !== undefined ?\n imgOptions.crossOriginPolicy : viewer.crossOriginPolicy,\n ajaxWithCredentials: viewer.ajaxWithCredentials,\n ajaxHeaders: viewer.ajaxHeaders,\n useCanvas: viewer.useCanvas,\n success: function( event ) {\n successCallback( event.tileSource );\n }\n });\n tileSource.addHandler( 'open-failed', function( event ) {\n failCallback( event );\n } );\n\n } else if ($.isPlainObject(tileSource) || tileSource.nodeType) {\n if (tileSource.crossOriginPolicy === undefined &&\n (imgOptions.crossOriginPolicy !== undefined || viewer.crossOriginPolicy !== undefined)) {\n tileSource.crossOriginPolicy = imgOptions.crossOriginPolicy !== undefined ?\n imgOptions.crossOriginPolicy : viewer.crossOriginPolicy;\n }\n if (tileSource.ajaxWithCredentials === undefined) {\n tileSource.ajaxWithCredentials = viewer.ajaxWithCredentials;\n }\n if (tileSource.useCanvas === undefined) {\n tileSource.useCanvas = viewer.useCanvas;\n }\n\n if ( $.isFunction( tileSource.getTileUrl ) ) {\n //Custom tile source\n var customTileSource = new $.TileSource( tileSource );\n customTileSource.getTileUrl = tileSource.getTileUrl;\n successCallback( customTileSource );\n } else {\n //inline configuration\n var $TileSource = $.TileSource.determineType( _this, tileSource );\n if ( !$TileSource ) {\n failCallback( {\n message: \"Unable to load TileSource\",\n source: tileSource\n });\n return;\n }\n var options = $TileSource.prototype.configure.apply( _this, [ tileSource ] );\n waitUntilReady(new $TileSource(options), tileSource);\n }\n } else {\n //can assume it's already a tile source implementation\n waitUntilReady(tileSource, tileSource);\n }\n });\n}\n\nfunction getOverlayObject( viewer, overlay ) {\n if ( overlay instanceof $.Overlay ) {\n return overlay;\n }\n\n var element = null;\n if ( overlay.element ) {\n element = $.getElement( overlay.element );\n } else {\n var id = overlay.id ?\n overlay.id :\n \"openseadragon-overlay-\" + Math.floor( Math.random() * 10000000 );\n\n element = $.getElement( overlay.id );\n if ( !element ) {\n element = document.createElement( \"a\" );\n element.href = \"#/overlay/\" + id;\n }\n element.id = id;\n $.addClass( element, overlay.className ?\n overlay.className :\n \"openseadragon-overlay\"\n );\n }\n\n var location = overlay.location;\n var width = overlay.width;\n var height = overlay.height;\n if (!location) {\n var x = overlay.x;\n var y = overlay.y;\n if (overlay.px !== undefined) {\n var rect = viewer.viewport.imageToViewportRectangle(new $.Rect(\n overlay.px,\n overlay.py,\n width || 0,\n height || 0));\n x = rect.x;\n y = rect.y;\n width = width !== undefined ? rect.width : undefined;\n height = height !== undefined ? rect.height : undefined;\n }\n location = new $.Point(x, y);\n }\n\n var placement = overlay.placement;\n if (placement && $.type(placement) === \"string\") {\n placement = $.Placement[overlay.placement.toUpperCase()];\n }\n\n return new $.Overlay({\n element: element,\n location: location,\n placement: placement,\n onDraw: overlay.onDraw,\n checkResize: overlay.checkResize,\n width: width,\n height: height,\n rotationMode: overlay.rotationMode\n });\n}\n\n/**\n * @private\n * @inner\n * Determines the index of the given overlay in the given overlays array.\n */\nfunction getOverlayIndex( overlays, element ) {\n var i;\n for ( i = overlays.length - 1; i >= 0; i-- ) {\n if ( overlays[ i ].element === element ) {\n return i;\n }\n }\n\n return -1;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Schedulers provide the general engine for animation\n///////////////////////////////////////////////////////////////////////////////\nfunction scheduleUpdate( viewer, updateFunc ){\n return $.requestAnimationFrame( function(){\n updateFunc( viewer );\n } );\n}\n\n\n//provides a sequence in the fade animation\nfunction scheduleControlsFade( viewer ) {\n $.requestAnimationFrame( function(){\n updateControlsFade( viewer );\n });\n}\n\n\n//initiates an animation to hide the controls\nfunction beginControlsAutoHide( viewer ) {\n if ( !viewer.autoHideControls ) {\n return;\n }\n viewer.controlsShouldFade = true;\n viewer.controlsFadeBeginTime =\n $.now() +\n viewer.controlsFadeDelay;\n\n window.setTimeout( function(){\n scheduleControlsFade( viewer );\n }, viewer.controlsFadeDelay );\n}\n\n\n//determines if fade animation is done or continues the animation\nfunction updateControlsFade( viewer ) {\n var currentTime,\n deltaTime,\n opacity,\n i;\n if ( viewer.controlsShouldFade ) {\n currentTime = $.now();\n deltaTime = currentTime - viewer.controlsFadeBeginTime;\n opacity = 1.0 - deltaTime / viewer.controlsFadeLength;\n\n opacity = Math.min( 1.0, opacity );\n opacity = Math.max( 0.0, opacity );\n\n for ( i = viewer.controls.length - 1; i >= 0; i--) {\n if (viewer.controls[ i ].autoFade) {\n viewer.controls[ i ].setOpacity( opacity );\n }\n }\n\n if ( opacity > 0 ) {\n // fade again\n scheduleControlsFade( viewer );\n }\n }\n}\n\n\n//stop the fade animation on the controls and show them\nfunction abortControlsAutoHide( viewer ) {\n var i;\n viewer.controlsShouldFade = false;\n for ( i = viewer.controls.length - 1; i >= 0; i-- ) {\n viewer.controls[ i ].setOpacity( 1.0 );\n }\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Default view event handlers.\n///////////////////////////////////////////////////////////////////////////////\nfunction onFocus(){\n abortControlsAutoHide( this );\n}\n\nfunction onBlur(){\n beginControlsAutoHide( this );\n\n}\n\nfunction onCanvasKeyDown( event ) {\n var canvasKeyDownEventArgs = {\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction,\n preventVerticalPan: event.preventVerticalPan,\n preventHorizontalPan: event.preventHorizontalPan\n };\n\n /**\n * Raised when a keyboard key is pressed and the focus is on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-key\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default keyboard behaviour. Default: false.\n * @property {Boolean} preventVerticalPan - Set to true to prevent keyboard vertical panning. Default: false.\n * @property {Boolean} preventHorizontalPan - Set to true to prevent keyboard horizontal panning. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n\n this.raiseEvent('canvas-key', canvasKeyDownEventArgs);\n\n if ( !canvasKeyDownEventArgs.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch( event.keyCode ){\n case 38://up arrow\n if (!canvasKeyDownEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(1.1);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, -this.pixelsPerArrowPress)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 40://down arrow\n if (!canvasKeyDownEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(0.9);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, this.pixelsPerArrowPress)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 37://left arrow\n if (!canvasKeyDownEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(-this.pixelsPerArrowPress, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n case 39://right arrow\n if (!canvasKeyDownEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(this.pixelsPerArrowPress, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n default:\n //console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\nfunction onCanvasKeyPress( event ) {\n var canvasKeyPressEventArgs = {\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction,\n preventVerticalPan: event.preventVerticalPan,\n preventHorizontalPan: event.preventHorizontalPan\n };\n\n // This event is documented in onCanvasKeyDown\n this.raiseEvent('canvas-key', canvasKeyPressEventArgs);\n\n if ( !canvasKeyPressEventArgs.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch( event.keyCode ){\n case 43://=|+\n case 61://=|+\n this.viewport.zoomBy(1.1);\n this.viewport.applyConstraints();\n return false;\n case 45://-|_\n this.viewport.zoomBy(0.9);\n this.viewport.applyConstraints();\n return false;\n case 48://0|)\n this.viewport.goHome();\n this.viewport.applyConstraints();\n return false;\n case 119://w\n case 87://W\n if (!canvasKeyPressEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(1.1);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, -40)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 115://s\n case 83://S\n if (!canvasKeyPressEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(0.9);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, 40)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 97://a\n if (!canvasKeyPressEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(-40, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n case 100://d\n if (!canvasKeyPressEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(40, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n case 114: //r - 90 degrees clockwise rotation\n if(this.viewport.flipped){\n this.viewport.setRotation(this.viewport.degrees - 90);\n } else{\n this.viewport.setRotation(this.viewport.degrees + 90);\n }\n this.viewport.applyConstraints();\n return false;\n case 82: //R - 90 degrees counterclockwise rotation\n if(this.viewport.flipped){\n this.viewport.setRotation(this.viewport.degrees + 90);\n } else{\n this.viewport.setRotation(this.viewport.degrees - 90);\n }\n this.viewport.applyConstraints();\n return false;\n case 102: //f\n this.viewport.toggleFlip();\n return false;\n default:\n // console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\n\nfunction onCanvasClick( event ) {\n var gestureSettings;\n\n var haveKeyboardFocus = document.activeElement == this.canvas;\n\n // If we don't have keyboard focus, request it.\n if ( !haveKeyboardFocus ) {\n this.canvas.focus();\n }\n if(this.viewport.flipped){\n event.position.x = this.viewport.getContainerSize().x - event.position.x;\n }\n\n var canvasClickEventArgs = {\n tracker: event.eventSource,\n position: event.position,\n quick: event.quick,\n shift: event.shift,\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction\n };\n\n /**\n * Raised when a mouse press/release or touch/remove occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-click\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} quick - True only if the clickDistThreshold and clickTimeThreshold are both passed. Useful for differentiating between clicks and drags.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default click to zoom behaviour. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-click', canvasClickEventArgs);\n\n if ( !canvasClickEventArgs.preventDefaultAction && this.viewport && event.quick ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.clickToZoom ) {\n this.viewport.zoomBy(\n event.shift ? 1.0 / this.zoomPerClick : this.zoomPerClick,\n gestureSettings.zoomToRefPoint ? this.viewport.pointFromPixel( event.position, true ) : null\n );\n this.viewport.applyConstraints();\n }\n }\n}\n\nfunction onCanvasDblClick( event ) {\n var gestureSettings;\n\n var canvasDblClickEventArgs = {\n tracker: event.eventSource,\n position: event.position,\n shift: event.shift,\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction\n };\n\n /**\n * Raised when a double mouse press/release or touch/remove occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-double-click\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default double tap to zoom behaviour. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-double-click', canvasDblClickEventArgs);\n\n if ( !canvasDblClickEventArgs.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.dblClickToZoom ) {\n this.viewport.zoomBy(\n event.shift ? 1.0 / this.zoomPerClick : this.zoomPerClick,\n gestureSettings.zoomToRefPoint ? this.viewport.pointFromPixel( event.position, true ) : null\n );\n this.viewport.applyConstraints();\n }\n }\n}\n\nfunction onCanvasDrag( event ) {\n var gestureSettings;\n\n var canvasDragEventArgs = {\n tracker: event.eventSource,\n position: event.position,\n delta: event.delta,\n speed: event.speed,\n direction: event.direction,\n shift: event.shift,\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction\n };\n\n /**\n * Raised when a mouse or touch drag operation occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-drag\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {OpenSeadragon.Point} delta - The x,y components of the difference between start drag and end drag.\n * @property {Number} speed - Current computed speed, in pixels per second.\n * @property {Number} direction - Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default drag behaviour. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-drag', canvasDragEventArgs);\n\n if ( !canvasDragEventArgs.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if( !this.panHorizontal ){\n event.delta.x = 0;\n }\n if( !this.panVertical ){\n event.delta.y = 0;\n }\n if(this.viewport.flipped){\n event.delta.x = -event.delta.x;\n }\n\n if( this.constrainDuringPan ){\n var delta = this.viewport.deltaPointsFromPixels( event.delta.negate() );\n\n this.viewport.centerSpringX.target.value += delta.x;\n this.viewport.centerSpringY.target.value += delta.y;\n\n var bounds = this.viewport.getBounds();\n var constrainedBounds = this.viewport.getConstrainedBounds();\n\n this.viewport.centerSpringX.target.value -= delta.x;\n this.viewport.centerSpringY.target.value -= delta.y;\n\n if (bounds.x != constrainedBounds.x) {\n event.delta.x = 0;\n }\n\n if (bounds.y != constrainedBounds.y) {\n event.delta.y = 0;\n }\n }\n\n this.viewport.panBy( this.viewport.deltaPointsFromPixels( event.delta.negate() ), gestureSettings.flickEnabled && !this.constrainDuringPan);\n }\n}\n\nfunction onCanvasDragEnd( event ) {\n if (!event.preventDefaultAction && this.viewport) {\n var gestureSettings = this.gestureSettingsByDeviceType(event.pointerType);\n if (gestureSettings.flickEnabled &&\n event.speed >= gestureSettings.flickMinSpeed) {\n var amplitudeX = 0;\n if (this.panHorizontal) {\n amplitudeX = gestureSettings.flickMomentum * event.speed *\n Math.cos(event.direction);\n }\n var amplitudeY = 0;\n if (this.panVertical) {\n amplitudeY = gestureSettings.flickMomentum * event.speed *\n Math.sin(event.direction);\n }\n var center = this.viewport.pixelFromPoint(\n this.viewport.getCenter(true));\n var target = this.viewport.pointFromPixel(\n new $.Point(center.x - amplitudeX, center.y - amplitudeY));\n this.viewport.panTo(target, false);\n }\n this.viewport.applyConstraints();\n }\n /**\n * Raised when a mouse or touch drag operation ends on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-drag-end\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} speed - Speed at the end of a drag gesture, in pixels per second.\n * @property {Number} direction - Direction at the end of a drag gesture, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('canvas-drag-end', {\n tracker: event.eventSource,\n position: event.position,\n speed: event.speed,\n direction: event.direction,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasEnter( event ) {\n /**\n * Raised when a pointer enters the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-enter\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-enter', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasExit( event ) {\n\n if (window.location != window.parent.location){\n $.MouseTracker.resetAllMouseTrackers();\n }\n\n /**\n * Raised when a pointer leaves the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-exit\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-exit', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasPress( event ) {\n /**\n * Raised when the primary mouse button is pressed or touch starts on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-press\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} insideElementReleased - True if the cursor still inside the tracked element when the button was released.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-press', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n insideElementPressed: event.insideElementPressed,\n insideElementReleased: event.insideElementReleased,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasRelease( event ) {\n /**\n * Raised when the primary mouse button is released or touch ends on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-release\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} insideElementReleased - True if the cursor still inside the tracked element when the button was released.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-release', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n insideElementPressed: event.insideElementPressed,\n insideElementReleased: event.insideElementReleased,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasNonPrimaryPress( event ) {\n /**\n * Raised when any non-primary pointer button is pressed on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-nonprimary-press\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {Number} button - Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @property {Number} buttons - Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-nonprimary-press', {\n tracker: event.eventSource,\n position: event.position,\n pointerType: event.pointerType,\n button: event.button,\n buttons: event.buttons,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasNonPrimaryRelease( event ) {\n /**\n * Raised when any non-primary pointer button is released on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-nonprimary-release\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {Number} button - Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @property {Number} buttons - Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-nonprimary-release', {\n tracker: event.eventSource,\n position: event.position,\n pointerType: event.pointerType,\n button: event.button,\n buttons: event.buttons,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasPinch( event ) {\n var gestureSettings,\n centerPt,\n lastCenterPt,\n panByPt;\n\n if ( !event.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.pinchToZoom ) {\n centerPt = this.viewport.pointFromPixel( event.center, true );\n lastCenterPt = this.viewport.pointFromPixel( event.lastCenter, true );\n panByPt = lastCenterPt.minus( centerPt );\n if( !this.panHorizontal ) {\n panByPt.x = 0;\n }\n if( !this.panVertical ) {\n panByPt.y = 0;\n }\n this.viewport.zoomBy( event.distance / event.lastDistance, centerPt, true );\n if ( gestureSettings.zoomToRefPoint ) {\n this.viewport.panBy(panByPt, true);\n }\n this.viewport.applyConstraints();\n }\n if ( gestureSettings.pinchRotate ) {\n // Pinch rotate\n var angle1 = Math.atan2(event.gesturePoints[0].currentPos.y - event.gesturePoints[1].currentPos.y,\n event.gesturePoints[0].currentPos.x - event.gesturePoints[1].currentPos.x);\n var angle2 = Math.atan2(event.gesturePoints[0].lastPos.y - event.gesturePoints[1].lastPos.y,\n event.gesturePoints[0].lastPos.x - event.gesturePoints[1].lastPos.x);\n this.viewport.setRotation(this.viewport.getRotation() + ((angle1 - angle2) * (180 / Math.PI)));\n }\n }\n /**\n * Raised when a pinch event occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-pinch\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {Array.} gesturePoints - Gesture points associated with the gesture. Velocity data can be found here.\n * @property {OpenSeadragon.Point} lastCenter - The previous center point of the two pinch contact points relative to the tracked element.\n * @property {OpenSeadragon.Point} center - The center point of the two pinch contact points relative to the tracked element.\n * @property {Number} lastDistance - The previous distance between the two pinch contact points in CSS pixels.\n * @property {Number} distance - The distance between the two pinch contact points in CSS pixels.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('canvas-pinch', {\n tracker: event.eventSource,\n gesturePoints: event.gesturePoints,\n lastCenter: event.lastCenter,\n center: event.center,\n lastDistance: event.lastDistance,\n distance: event.distance,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n //cancels event\n return false;\n}\n\nfunction onCanvasScroll( event ) {\n var gestureSettings,\n factor,\n thisScrollTime,\n deltaScrollTime;\n\n /* Certain scroll devices fire the scroll event way too fast so we are injecting a simple adjustment to keep things\n * partially normalized. If we have already fired an event within the last 'minScrollDelta' milliseconds we skip\n * this one and wait for the next event. */\n thisScrollTime = $.now();\n deltaScrollTime = thisScrollTime - this._lastScrollTime;\n if (deltaScrollTime > this.minScrollDeltaTime) {\n this._lastScrollTime = thisScrollTime;\n\n if(this.viewport.flipped){\n event.position.x = this.viewport.getContainerSize().x - event.position.x;\n }\n\n if ( !event.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.scrollToZoom ) {\n factor = Math.pow( this.zoomPerScroll, event.scroll );\n this.viewport.zoomBy(\n factor,\n gestureSettings.zoomToRefPoint ? this.viewport.pointFromPixel( event.position, true ) : null\n );\n this.viewport.applyConstraints();\n }\n }\n /**\n * Raised when a scroll event occurs on the {@link OpenSeadragon.Viewer#canvas} element (mouse wheel).\n *\n * @event canvas-scroll\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} scroll - The scroll delta for the event.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-scroll', {\n tracker: event.eventSource,\n position: event.position,\n scroll: event.scroll,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n if (gestureSettings && gestureSettings.scrollToZoom) {\n //cancels event\n return false;\n }\n }\n else {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if (gestureSettings && gestureSettings.scrollToZoom) {\n return false; // We are swallowing this event\n }\n }\n}\n\nfunction onContainerEnter( event ) {\n THIS[ this.hash ].mouseInside = true;\n abortControlsAutoHide( this );\n /**\n * Raised when the cursor enters the {@link OpenSeadragon.Viewer#container} element.\n *\n * @event container-enter\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'container-enter', {\n tracker: event.eventSource,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onContainerExit( event ) {\n if ( event.pointers < 1 ) {\n THIS[ this.hash ].mouseInside = false;\n if ( !THIS[ this.hash ].animating ) {\n beginControlsAutoHide( this );\n }\n }\n /**\n * Raised when the cursor leaves the {@link OpenSeadragon.Viewer#container} element.\n *\n * @event container-exit\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'container-exit', {\n tracker: event.eventSource,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Page update routines ( aka Views - for future reference )\n///////////////////////////////////////////////////////////////////////////////\n\nfunction updateMulti( viewer ) {\n updateOnce( viewer );\n\n // Request the next frame, unless we've been closed\n if ( viewer.isOpen() ) {\n viewer._updateRequestId = scheduleUpdate( viewer, updateMulti );\n } else {\n viewer._updateRequestId = false;\n }\n}\n\nfunction updateOnce( viewer ) {\n\n //viewer.profiler.beginUpdate();\n\n if (viewer._opening) {\n return;\n }\n\n if (viewer.autoResize) {\n var containerSize = _getSafeElemSize(viewer.container);\n var prevContainerSize = THIS[viewer.hash].prevContainerSize;\n if (!containerSize.equals(prevContainerSize)) {\n var viewport = viewer.viewport;\n if (viewer.preserveImageSizeOnResize) {\n var resizeRatio = prevContainerSize.x / containerSize.x;\n var zoom = viewport.getZoom() * resizeRatio;\n var center = viewport.getCenter();\n viewport.resize(containerSize, false);\n viewport.zoomTo(zoom, null, true);\n viewport.panTo(center, true);\n } else {\n // maintain image position\n var oldBounds = viewport.getBounds();\n viewport.resize(containerSize, true);\n viewport.fitBoundsWithConstraints(oldBounds, true);\n }\n THIS[viewer.hash].prevContainerSize = containerSize;\n THIS[viewer.hash].forceRedraw = true;\n }\n }\n\n var viewportChange = viewer.viewport.update();\n var animated = viewer.world.update() || viewportChange;\n\n if (viewportChange) {\n /**\n * Raised when any spring animation update occurs (zoom, pan, etc.),\n * before the viewer has drawn the new location.\n *\n * @event viewport-change\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent('viewport-change');\n }\n\n if( viewer.referenceStrip ){\n animated = viewer.referenceStrip.update( viewer.viewport ) || animated;\n }\n\n if ( !THIS[ viewer.hash ].animating && animated ) {\n /**\n * Raised when any spring animation starts (zoom, pan, etc.).\n *\n * @event animation-start\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( \"animation-start\" );\n abortControlsAutoHide( viewer );\n }\n\n if ( animated || THIS[ viewer.hash ].forceRedraw || viewer.world.needsDraw() ) {\n drawWorld( viewer );\n viewer._drawOverlays();\n if( viewer.navigator ){\n viewer.navigator.update( viewer.viewport );\n }\n\n THIS[ viewer.hash ].forceRedraw = false;\n\n if (animated) {\n /**\n * Raised when any spring animation update occurs (zoom, pan, etc.),\n * after the viewer has drawn the new location.\n *\n * @event animation\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( \"animation\" );\n }\n }\n\n if ( THIS[ viewer.hash ].animating && !animated ) {\n /**\n * Raised when any spring animation ends (zoom, pan, etc.).\n *\n * @event animation-finish\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( \"animation-finish\" );\n\n if ( !THIS[ viewer.hash ].mouseInside ) {\n beginControlsAutoHide( viewer );\n }\n }\n\n THIS[ viewer.hash ].animating = animated;\n\n //viewer.profiler.endUpdate();\n}\n\nfunction drawWorld( viewer ) {\n viewer.imageLoader.clear();\n viewer.drawer.clear();\n viewer.world.draw();\n\n /**\n * - Needs documentation -\n *\n * @event update-viewport\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( 'update-viewport', {} );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Navigation Controls\n///////////////////////////////////////////////////////////////////////////////\nfunction resolveUrl( prefix, url ) {\n return prefix ? prefix + url : url;\n}\n\n\n\nfunction beginZoomingIn() {\n THIS[ this.hash ].lastZoomTime = $.now();\n THIS[ this.hash ].zoomFactor = this.zoomPerSecond;\n THIS[ this.hash ].zooming = true;\n scheduleZoom( this );\n}\n\n\nfunction beginZoomingOut() {\n THIS[ this.hash ].lastZoomTime = $.now();\n THIS[ this.hash ].zoomFactor = 1.0 / this.zoomPerSecond;\n THIS[ this.hash ].zooming = true;\n scheduleZoom( this );\n}\n\n\nfunction endZooming() {\n THIS[ this.hash ].zooming = false;\n}\n\n\nfunction scheduleZoom( viewer ) {\n $.requestAnimationFrame( $.delegate( viewer, doZoom ) );\n}\n\n\nfunction doZoom() {\n var currentTime,\n deltaTime,\n adjustedFactor;\n\n if ( THIS[ this.hash ].zooming && this.viewport) {\n currentTime = $.now();\n deltaTime = currentTime - THIS[ this.hash ].lastZoomTime;\n adjustedFactor = Math.pow( THIS[ this.hash ].zoomFactor, deltaTime / 1000 );\n\n this.viewport.zoomBy( adjustedFactor );\n this.viewport.applyConstraints();\n THIS[ this.hash ].lastZoomTime = currentTime;\n scheduleZoom( this );\n }\n}\n\n\nfunction doSingleZoomIn() {\n if ( this.viewport ) {\n THIS[ this.hash ].zooming = false;\n this.viewport.zoomBy(\n this.zoomPerClick / 1.0\n );\n this.viewport.applyConstraints();\n }\n}\n\n\nfunction doSingleZoomOut() {\n if ( this.viewport ) {\n THIS[ this.hash ].zooming = false;\n this.viewport.zoomBy(\n 1.0 / this.zoomPerClick\n );\n this.viewport.applyConstraints();\n }\n}\n\n\nfunction lightUp() {\n this.buttons.emulateEnter();\n this.buttons.emulateExit();\n}\n\n\nfunction onHome() {\n if ( this.viewport ) {\n this.viewport.goHome();\n }\n}\n\n\nfunction onFullScreen() {\n if ( this.isFullPage() && !$.isFullScreen() ) {\n // Is fullPage but not fullScreen\n this.setFullPage( false );\n } else {\n this.setFullScreen( !this.isFullPage() );\n }\n // correct for no mouseout event on change\n if ( this.buttons ) {\n this.buttons.emulateExit();\n }\n this.fullPageButton.element.focus();\n if ( this.viewport ) {\n this.viewport.applyConstraints();\n }\n}\n\n/**\n * Note: The current rotation feature is limited to 90 degree turns.\n */\nfunction onRotateLeft() {\n if ( this.viewport ) {\n var currRotation = this.viewport.getRotation();\n\n if ( this.viewport.flipped ){\n currRotation = $.positiveModulo(currRotation + 90, 360);\n } else {\n currRotation = $.positiveModulo(currRotation - 90, 360);\n }\n this.viewport.setRotation(currRotation);\n }\n}\n\n/**\n * Note: The current rotation feature is limited to 90 degree turns.\n */\nfunction onRotateRight() {\n if ( this.viewport ) {\n var currRotation = this.viewport.getRotation();\n\n if ( this.viewport.flipped ){\n currRotation = $.positiveModulo(currRotation - 90, 360);\n } else {\n currRotation = $.positiveModulo(currRotation + 90, 360);\n }\n this.viewport.setRotation(currRotation);\n }\n}\n\n/**\n * Note: When pressed flip control button\n */\nfunction onFlip() {\n this.viewport.toggleFlip();\n}\n\nfunction onPrevious(){\n var previous = this._sequenceIndex - 1;\n if(this.navPrevNextWrap && previous < 0){\n previous += this.tileSources.length;\n }\n this.goToPage( previous );\n}\n\n\nfunction onNext(){\n var next = this._sequenceIndex + 1;\n if(this.navPrevNextWrap && next >= this.tileSources.length){\n next = 0;\n }\n this.goToPage( next );\n}\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Navigator\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Navigator\n * @classdesc The Navigator provides a small view of the current image as fixed\n * while representing the viewport as a moving box serving as a frame\n * of reference in the larger viewport as to which portion of the image\n * is currently being examined. The navigator's viewport can be interacted\n * with using the keyboard or the mouse.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.Viewer\n * @extends OpenSeadragon.EventSource\n * @param {Object} options\n */\n$.Navigator = function( options ){\n\n var viewer = options.viewer,\n _this = this,\n viewerSize,\n navigatorSize;\n\n //We may need to create a new element and id if they did not\n //provide the id for the existing element\n if( !options.id ){\n options.id = 'navigator-' + $.now();\n this.element = $.makeNeutralElement( \"div\" );\n options.controlOptions = {\n anchor: $.ControlAnchor.TOP_RIGHT,\n attachToViewer: true,\n autoFade: options.autoFade\n };\n\n if( options.position ){\n if( 'BOTTOM_RIGHT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.BOTTOM_RIGHT;\n } else if( 'BOTTOM_LEFT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.BOTTOM_LEFT;\n } else if( 'TOP_RIGHT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.TOP_RIGHT;\n } else if( 'TOP_LEFT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.TOP_LEFT;\n } else if( 'ABSOLUTE' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.ABSOLUTE;\n options.controlOptions.top = options.top;\n options.controlOptions.left = options.left;\n options.controlOptions.height = options.height;\n options.controlOptions.width = options.width;\n }\n }\n\n } else {\n this.element = document.getElementById( options.id );\n options.controlOptions = {\n anchor: $.ControlAnchor.NONE,\n attachToViewer: false,\n autoFade: false\n };\n }\n this.element.id = options.id;\n this.element.className += ' navigator';\n\n options = $.extend( true, {\n sizeRatio: $.DEFAULT_SETTINGS.navigatorSizeRatio\n }, options, {\n element: this.element,\n tabIndex: -1, // No keyboard navigation, omit from tab order\n //These need to be overridden to prevent recursion since\n //the navigator is a viewer and a viewer has a navigator\n showNavigator: false,\n mouseNavEnabled: false,\n showNavigationControl: false,\n showSequenceControl: false,\n immediateRender: true,\n blendTime: 0,\n animationTime: 0,\n autoResize: options.autoResize,\n // prevent resizing the navigator from adding unwanted space around the image\n minZoomImageRatio: 1.0\n });\n\n options.minPixelRatio = this.minPixelRatio = viewer.minPixelRatio;\n\n $.setElementTouchActionNone( this.element );\n\n this.borderWidth = 2;\n //At some browser magnification levels the display regions lines up correctly, but at some there appears to\n //be a one pixel gap.\n this.fudge = new $.Point(1, 1);\n this.totalBorderWidths = new $.Point(this.borderWidth * 2, this.borderWidth * 2).minus(this.fudge);\n\n\n if ( options.controlOptions.anchor != $.ControlAnchor.NONE ) {\n (function( style, borderWidth ){\n style.margin = '0px';\n style.border = borderWidth + 'px solid #555';\n style.padding = '0px';\n style.background = '#000';\n style.opacity = 0.8;\n style.overflow = 'hidden';\n }( this.element.style, this.borderWidth));\n }\n\n this.displayRegion = $.makeNeutralElement( \"div\" );\n this.displayRegion.id = this.element.id + '-displayregion';\n this.displayRegion.className = 'displayregion';\n\n (function( style, borderWidth ){\n style.position = 'relative';\n style.top = '0px';\n style.left = '0px';\n style.fontSize = '0px';\n style.overflow = 'hidden';\n style.border = borderWidth + 'px solid #900';\n style.margin = '0px';\n style.padding = '0px';\n //TODO: IE doesnt like this property being set\n //try{ style.outline = '2px auto #909'; }catch(e){/*ignore*/}\n\n style.background = 'transparent';\n\n // We use square bracket notation on the statement below, because float is a keyword.\n // This is important for the Google Closure compiler, if nothing else.\n /*jshint sub:true */\n style['float'] = 'left'; //Webkit\n\n style.cssFloat = 'left'; //Firefox\n style.styleFloat = 'left'; //IE\n style.zIndex = 999999999;\n style.cursor = 'default';\n }( this.displayRegion.style, this.borderWidth ));\n\n this.displayRegionContainer = $.makeNeutralElement(\"div\");\n this.displayRegionContainer.id = this.element.id + '-displayregioncontainer';\n this.displayRegionContainer.className = \"displayregioncontainer\";\n this.displayRegionContainer.style.width = \"100%\";\n this.displayRegionContainer.style.height = \"100%\";\n\n viewer.addControl(\n this.element,\n options.controlOptions\n );\n\n this._resizeWithViewer = options.controlOptions.anchor != $.ControlAnchor.ABSOLUTE &&\n options.controlOptions.anchor != $.ControlAnchor.NONE;\n\n if ( this._resizeWithViewer ) {\n if ( options.width && options.height ) {\n this.element.style.height = typeof (options.height) == \"number\" ? (options.height + 'px') : options.height;\n this.element.style.width = typeof (options.width) == \"number\" ? (options.width + 'px') : options.width;\n } else {\n viewerSize = $.getElementSize( viewer.element );\n this.element.style.height = Math.round( viewerSize.y * options.sizeRatio ) + 'px';\n this.element.style.width = Math.round( viewerSize.x * options.sizeRatio ) + 'px';\n this.oldViewerSize = viewerSize;\n }\n navigatorSize = $.getElementSize( this.element );\n this.elementArea = navigatorSize.x * navigatorSize.y;\n }\n\n this.oldContainerSize = new $.Point( 0, 0 );\n\n $.Viewer.apply( this, [ options ] );\n\n this.displayRegionContainer.appendChild(this.displayRegion);\n this.element.getElementsByTagName('div')[0].appendChild(this.displayRegionContainer);\n\n function rotate(degrees) {\n _setTransformRotate(_this.displayRegionContainer, degrees);\n _setTransformRotate(_this.displayRegion, -degrees);\n _this.viewport.setRotation(degrees);\n }\n if (options.navigatorRotate) {\n var degrees = options.viewer.viewport ?\n options.viewer.viewport.getRotation() :\n options.viewer.degrees || 0;\n\n rotate(degrees);\n options.viewer.addHandler(\"rotate\", function (args) {\n rotate(args.degrees);\n });\n }\n\n\n // Remove the base class' (Viewer's) innerTracker and replace it with our own\n this.innerTracker.destroy();\n this.innerTracker = new $.MouseTracker({\n element: this.element,\n dragHandler: $.delegate( this, onCanvasDrag ),\n clickHandler: $.delegate( this, onCanvasClick ),\n releaseHandler: $.delegate( this, onCanvasRelease ),\n scrollHandler: $.delegate( this, onCanvasScroll )\n });\n\n this.addHandler(\"reset-size\", function() {\n if (_this.viewport) {\n _this.viewport.goHome(true);\n }\n });\n\n viewer.world.addHandler(\"item-index-change\", function(event) {\n window.setTimeout(function(){\n var item = _this.world.getItemAt(event.previousIndex);\n _this.world.setItemIndex(item, event.newIndex);\n }, 1);\n });\n\n viewer.world.addHandler(\"remove-item\", function(event) {\n var theirItem = event.item;\n var myItem = _this._getMatchingItem(theirItem);\n if (myItem) {\n _this.world.removeItem(myItem);\n }\n });\n\n this.update(viewer.viewport);\n};\n\n$.extend( $.Navigator.prototype, $.EventSource.prototype, $.Viewer.prototype, /** @lends OpenSeadragon.Navigator.prototype */{\n\n /**\n * Used to notify the navigator when its size has changed.\n * Especially useful when {@link OpenSeadragon.Options}.navigatorAutoResize is set to false and the navigator is resizable.\n * @function\n */\n updateSize: function () {\n if ( this.viewport ) {\n var containerSize = new $.Point(\n (this.container.clientWidth === 0 ? 1 : this.container.clientWidth),\n (this.container.clientHeight === 0 ? 1 : this.container.clientHeight)\n );\n\n if ( !containerSize.equals( this.oldContainerSize ) ) {\n this.viewport.resize( containerSize, true );\n this.viewport.goHome(true);\n this.oldContainerSize = containerSize;\n this.drawer.clear();\n this.world.draw();\n }\n }\n },\n /**\n /* Flip navigator element\n * @param {Boolean} state - Flip state to set.\n */\n setFlip: function(state) {\n this.viewport.setFlip(state);\n\n this.setDisplayTransform(this.viewer.viewport.getFlip() ? \"scale(-1,1)\" : \"scale(1,1)\");\n return this;\n },\n\n setDisplayTransform: function(rule) {\n setElementTransform(this.displayRegion, rule);\n setElementTransform(this.canvas, rule);\n setElementTransform(this.element, rule);\n },\n\n /**\n * Used to update the navigator minimap's viewport rectangle when a change in the viewer's viewport occurs.\n * @function\n * @param {OpenSeadragon.Viewport} The viewport this navigator is tracking.\n */\n update: function( viewport ) {\n\n var viewerSize,\n newWidth,\n newHeight,\n bounds,\n topleft,\n bottomright;\n\n viewerSize = $.getElementSize( this.viewer.element );\n if ( this._resizeWithViewer && viewerSize.x && viewerSize.y && !viewerSize.equals( this.oldViewerSize ) ) {\n this.oldViewerSize = viewerSize;\n\n if ( this.maintainSizeRatio || !this.elementArea) {\n newWidth = viewerSize.x * this.sizeRatio;\n newHeight = viewerSize.y * this.sizeRatio;\n } else {\n newWidth = Math.sqrt(this.elementArea * (viewerSize.x / viewerSize.y));\n newHeight = this.elementArea / newWidth;\n }\n\n this.element.style.width = Math.round( newWidth ) + 'px';\n this.element.style.height = Math.round( newHeight ) + 'px';\n\n if (!this.elementArea) {\n this.elementArea = newWidth * newHeight;\n }\n\n this.updateSize();\n }\n\n if (viewport && this.viewport) {\n bounds = viewport.getBoundsNoRotate(true);\n topleft = this.viewport.pixelFromPointNoRotate(bounds.getTopLeft(), false);\n bottomright = this.viewport.pixelFromPointNoRotate(bounds.getBottomRight(), false)\n .minus( this.totalBorderWidths );\n\n //update style for navigator-box\n var style = this.displayRegion.style;\n style.display = this.world.getItemCount() ? 'block' : 'none';\n\n style.top = Math.round( topleft.y ) + 'px';\n style.left = Math.round( topleft.x ) + 'px';\n\n var width = Math.abs( topleft.x - bottomright.x );\n var height = Math.abs( topleft.y - bottomright.y );\n // make sure width and height are non-negative so IE doesn't throw\n style.width = Math.round( Math.max( width, 0 ) ) + 'px';\n style.height = Math.round( Math.max( height, 0 ) ) + 'px';\n }\n\n },\n\n // overrides Viewer.addTiledImage\n addTiledImage: function(options) {\n var _this = this;\n\n var original = options.originalTiledImage;\n delete options.original;\n\n var optionsClone = $.extend({}, options, {\n success: function(event) {\n var myItem = event.item;\n myItem._originalForNavigator = original;\n _this._matchBounds(myItem, original, true);\n\n function matchBounds() {\n _this._matchBounds(myItem, original);\n }\n\n function matchOpacity() {\n _this._matchOpacity(myItem, original);\n }\n\n function matchCompositeOperation() {\n _this._matchCompositeOperation(myItem, original);\n }\n\n original.addHandler('bounds-change', matchBounds);\n original.addHandler('clip-change', matchBounds);\n original.addHandler('opacity-change', matchOpacity);\n original.addHandler('composite-operation-change', matchCompositeOperation);\n }\n });\n\n return $.Viewer.prototype.addTiledImage.apply(this, [optionsClone]);\n },\n\n // private\n _getMatchingItem: function(theirItem) {\n var count = this.world.getItemCount();\n var item;\n for (var i = 0; i < count; i++) {\n item = this.world.getItemAt(i);\n if (item._originalForNavigator === theirItem) {\n return item;\n }\n }\n\n return null;\n },\n\n // private\n _matchBounds: function(myItem, theirItem, immediately) {\n var bounds = theirItem.getBoundsNoRotate();\n myItem.setPosition(bounds.getTopLeft(), immediately);\n myItem.setWidth(bounds.width, immediately);\n myItem.setRotation(theirItem.getRotation(), immediately);\n myItem.setClip(theirItem.getClip());\n },\n\n // private\n _matchOpacity: function(myItem, theirItem) {\n myItem.setOpacity(theirItem.opacity);\n },\n\n // private\n _matchCompositeOperation: function(myItem, theirItem) {\n myItem.setCompositeOperation(theirItem.compositeOperation);\n }\n});\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasClick( event ) {\n if ( event.quick && this.viewer.viewport ) {\n if(this.viewer.viewport.flipped){\n event.position.x = this.viewport.getContainerSize().x - event.position.x;\n }\n this.viewer.viewport.panTo(this.viewport.pointFromPixel(event.position));\n this.viewer.viewport.applyConstraints();\n }\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasDrag( event ) {\n if ( this.viewer.viewport ) {\n if( !this.panHorizontal ){\n event.delta.x = 0;\n }\n if( !this.panVertical ){\n event.delta.y = 0;\n }\n\n if(this.viewer.viewport.flipped){\n event.delta.x = -event.delta.x;\n }\n\n this.viewer.viewport.panBy(\n this.viewport.deltaPointsFromPixels(\n event.delta\n )\n );\n if( this.viewer.constrainDuringPan ){\n this.viewer.viewport.applyConstraints();\n }\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasRelease( event ) {\n if ( event.insideElementPressed && this.viewer.viewport ) {\n this.viewer.viewport.applyConstraints();\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasScroll( event ) {\n /**\n * Raised when a scroll event occurs on the {@link OpenSeadragon.Viewer#navigator} element (mouse wheel, touch pinch, etc.).\n *\n * @event navigator-scroll\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} scroll - The scroll delta for the event.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'navigator-scroll', {\n tracker: event.eventSource,\n position: event.position,\n scroll: event.scroll,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n\n //dont scroll the page up and down if the user is scrolling\n //in the navigator\n return false;\n}\n\n/**\n * @function\n * @private\n * @param {Object} element\n * @param {Number} degrees\n */\nfunction _setTransformRotate( element, degrees ) {\n setElementTransform(element, \"rotate(\" + degrees + \"deg)\");\n}\n\nfunction setElementTransform( element, rule ) {\n element.style.webkitTransform = rule;\n element.style.mozTransform = rule;\n element.style.msTransform = rule;\n element.style.oTransform = rule;\n element.style.transform = rule;\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - getString/setString\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n//TODO: I guess this is where the i18n needs to be reimplemented. I'll look\n// into existing patterns for i18n in javascript but i think that mimicking\n// pythons gettext might be a reasonable approach.\nvar I18N = {\n Errors: {\n Dzc: \"Sorry, we don't support Deep Zoom Collections!\",\n Dzi: \"Hmm, this doesn't appear to be a valid Deep Zoom Image.\",\n Xml: \"Hmm, this doesn't appear to be a valid Deep Zoom Image.\",\n ImageFormat: \"Sorry, we don't support {0}-based Deep Zoom Images.\",\n Security: \"It looks like a security restriction stopped us from \" +\n \"loading this Deep Zoom Image.\",\n Status: \"This space unintentionally left blank ({0} {1}).\",\n OpenFailed: \"Unable to open {0}: {1}\"\n },\n\n Tooltips: {\n FullPage: \"Toggle full page\",\n Home: \"Go home\",\n ZoomIn: \"Zoom in\",\n ZoomOut: \"Zoom out\",\n NextPage: \"Next page\",\n PreviousPage: \"Previous page\",\n RotateLeft: \"Rotate left\",\n RotateRight: \"Rotate right\",\n Flip: \"Flip Horizontally\"\n }\n};\n\n$.extend( $, /** @lends OpenSeadragon */{\n\n /**\n * @function\n * @param {String} property\n */\n getString: function( prop ) {\n\n var props = prop.split('.'),\n string = null,\n args = arguments,\n container = I18N,\n i;\n\n for (i = 0; i < props.length - 1; i++) {\n // in case not a subproperty\n container = container[ props[ i ] ] || {};\n }\n string = container[ props[ i ] ];\n\n if ( typeof ( string ) != \"string\" ) {\n $.console.log( \"Untranslated source string:\", prop );\n string = \"\"; // FIXME: this breaks gettext()-style convention, which would return source\n }\n\n return string.replace(/\\{\\d+\\}/g, function(capture) {\n var i = parseInt( capture.match( /\\d+/ ), 10 ) + 1;\n return i < args.length ?\n args[ i ] :\n \"\";\n });\n },\n\n /**\n * @function\n * @param {String} property\n * @param {*} value\n */\n setString: function( prop, value ) {\n\n var props = prop.split('.'),\n container = I18N,\n i;\n\n for ( i = 0; i < props.length - 1; i++ ) {\n if ( !container[ props[ i ] ] ) {\n container[ props[ i ] ] = {};\n }\n container = container[ props[ i ] ];\n }\n\n container[ props[ i ] ] = value;\n }\n\n});\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Point\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Point\n * @classdesc A Point is really used as a 2-dimensional vector, equally useful for\n * representing a point on a plane, or the height and width of a plane\n * not requiring any other frame of reference.\n *\n * @memberof OpenSeadragon\n * @param {Number} [x] The vector component 'x'. Defaults to the origin at 0.\n * @param {Number} [y] The vector component 'y'. Defaults to the origin at 0.\n */\n$.Point = function( x, y ) {\n /**\n * The vector component 'x'.\n * @member {Number} x\n * @memberof OpenSeadragon.Point#\n */\n this.x = typeof ( x ) == \"number\" ? x : 0;\n /**\n * The vector component 'y'.\n * @member {Number} y\n * @memberof OpenSeadragon.Point#\n */\n this.y = typeof ( y ) == \"number\" ? y : 0;\n};\n\n/** @lends OpenSeadragon.Point.prototype */\n$.Point.prototype = {\n /**\n * @function\n * @returns {OpenSeadragon.Point} a duplicate of this Point\n */\n clone: function() {\n return new $.Point(this.x, this.y);\n },\n\n /**\n * Add another Point to this point and return a new Point.\n * @function\n * @param {OpenSeadragon.Point} point The point to add vector components.\n * @returns {OpenSeadragon.Point} A new point representing the sum of the\n * vector components\n */\n plus: function( point ) {\n return new $.Point(\n this.x + point.x,\n this.y + point.y\n );\n },\n\n /**\n * Substract another Point to this point and return a new Point.\n * @function\n * @param {OpenSeadragon.Point} point The point to substract vector components.\n * @returns {OpenSeadragon.Point} A new point representing the substraction of the\n * vector components\n */\n minus: function( point ) {\n return new $.Point(\n this.x - point.x,\n this.y - point.y\n );\n },\n\n /**\n * Multiply this point by a factor and return a new Point.\n * @function\n * @param {Number} factor The factor to multiply vector components.\n * @returns {OpenSeadragon.Point} A new point representing the multiplication\n * of the vector components by the factor\n */\n times: function( factor ) {\n return new $.Point(\n this.x * factor,\n this.y * factor\n );\n },\n\n /**\n * Divide this point by a factor and return a new Point.\n * @function\n * @param {Number} factor The factor to divide vector components.\n * @returns {OpenSeadragon.Point} A new point representing the division of the\n * vector components by the factor\n */\n divide: function( factor ) {\n return new $.Point(\n this.x / factor,\n this.y / factor\n );\n },\n\n /**\n * Compute the opposite of this point and return a new Point.\n * @function\n * @returns {OpenSeadragon.Point} A new point representing the opposite of the\n * vector components\n */\n negate: function() {\n return new $.Point( -this.x, -this.y );\n },\n\n /**\n * Compute the distance between this point and another point.\n * @function\n * @param {OpenSeadragon.Point} point The point to compute the distance with.\n * @returns {Number} The distance between the 2 points\n */\n distanceTo: function( point ) {\n return Math.sqrt(\n Math.pow( this.x - point.x, 2 ) +\n Math.pow( this.y - point.y, 2 )\n );\n },\n\n /**\n * Compute the squared distance between this point and another point.\n * Useful for optimizing things like comparing distances.\n * @function\n * @param {OpenSeadragon.Point} point The point to compute the squared distance with.\n * @returns {Number} The squared distance between the 2 points\n */\n squaredDistanceTo: function( point ) {\n return Math.pow( this.x - point.x, 2 ) +\n Math.pow( this.y - point.y, 2 );\n },\n\n /**\n * Apply a function to each coordinate of this point and return a new point.\n * @function\n * @param {function} func The function to apply to each coordinate.\n * @returns {OpenSeadragon.Point} A new point with the coordinates computed\n * by the specified function\n */\n apply: function( func ) {\n return new $.Point( func( this.x ), func( this.y ) );\n },\n\n /**\n * Check if this point is equal to another one.\n * @function\n * @param {OpenSeadragon.Point} point The point to compare this point with.\n * @returns {Boolean} true if they are equal, false otherwise.\n */\n equals: function( point ) {\n return (\n point instanceof $.Point\n ) && (\n this.x === point.x\n ) && (\n this.y === point.y\n );\n },\n\n /**\n * Rotates the point around the specified pivot\n * From http://stackoverflow.com/questions/4465931/rotate-rectangle-around-a-point\n * @function\n * @param {Number} degress to rotate around the pivot.\n * @param {OpenSeadragon.Point} [pivot=(0,0)] Point around which to rotate.\n * Defaults to the origin.\n * @returns {OpenSeadragon.Point}. A new point representing the point rotated around the specified pivot\n */\n rotate: function (degrees, pivot) {\n pivot = pivot || new $.Point(0, 0);\n var cos;\n var sin;\n // Avoid float computations when possible\n if (degrees % 90 === 0) {\n var d = $.positiveModulo(degrees, 360);\n switch (d) {\n case 0:\n cos = 1;\n sin = 0;\n break;\n case 90:\n cos = 0;\n sin = 1;\n break;\n case 180:\n cos = -1;\n sin = 0;\n break;\n case 270:\n cos = 0;\n sin = -1;\n break;\n }\n } else {\n var angle = degrees * Math.PI / 180.0;\n cos = Math.cos(angle);\n sin = Math.sin(angle);\n }\n var x = cos * (this.x - pivot.x) - sin * (this.y - pivot.y) + pivot.x;\n var y = sin * (this.x - pivot.x) + cos * (this.y - pivot.y) + pivot.y;\n return new $.Point(x, y);\n },\n\n /**\n * Convert this point to a string in the format (x,y) where x and y are\n * rounded to the nearest integer.\n * @function\n * @returns {String} A string representation of this point.\n */\n toString: function() {\n return \"(\" + (Math.round(this.x * 100) / 100) + \",\" + (Math.round(this.y * 100) / 100) + \")\";\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n\n/**\n * @class TileSource\n * @classdesc The TileSource contains the most basic implementation required to create a\n * smooth transition between layers in an image pyramid. It has only a single key\n * interface that must be implemented to complete its key functionality:\n * 'getTileUrl'. It also has several optional interfaces that can be\n * implemented if a new TileSource wishes to support configuration via a simple\n * object or array ('configure') and if the tile source supports or requires\n * configuration via retrieval of a document on the network ala AJAX or JSONP,\n * ('getImageInfo').\n *
\n * By default the image pyramid is split into N layers where the image's longest\n * side in M (in pixels), where N is the smallest integer which satisfies\n * 2^(N+1) >= M.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @param {Object} options\n * You can either specify a URL, or literally define the TileSource (by specifying\n * width, height, tileSize, tileOverlap, minLevel, and maxLevel). For the former,\n * the extending class is expected to implement 'getImageInfo' and 'configure'.\n * For the latter, the construction is assumed to occur through\n * the extending classes implementation of 'configure'.\n * @param {String} [options.url]\n * The URL for the data necessary for this TileSource.\n * @param {String} [options.referenceStripThumbnailUrl]\n * The URL for a thumbnail image to be used by the reference strip\n * @param {Function} [options.success]\n * A function to be called upon successful creation.\n * @param {Boolean} [options.ajaxWithCredentials]\n * If this TileSource needs to make an AJAX call, this specifies whether to set\n * the XHR's withCredentials (for accessing secure data).\n * @param {Object} [options.ajaxHeaders]\n * A set of headers to include in AJAX requests.\n * @param {Number} [options.width]\n * Width of the source image at max resolution in pixels.\n * @param {Number} [options.height]\n * Height of the source image at max resolution in pixels.\n * @param {Number} [options.tileSize]\n * The size of the tiles to assumed to make up each pyramid layer in pixels.\n * Tile size determines the point at which the image pyramid must be\n * divided into a matrix of smaller images.\n * Use options.tileWidth and options.tileHeight to support non-square tiles.\n * @param {Number} [options.tileWidth]\n * The width of the tiles to assumed to make up each pyramid layer in pixels.\n * @param {Number} [options.tileHeight]\n * The height of the tiles to assumed to make up each pyramid layer in pixels.\n * @param {Number} [options.tileOverlap]\n * The number of pixels each tile is expected to overlap touching tiles.\n * @param {Number} [options.minLevel]\n * The minimum level to attempt to load.\n * @param {Number} [options.maxLevel]\n * The maximum level to attempt to load.\n */\n$.TileSource = function( width, height, tileSize, tileOverlap, minLevel, maxLevel ) {\n var _this = this;\n\n var args = arguments,\n options,\n i;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: args[0],\n height: args[1],\n tileSize: args[2],\n tileOverlap: args[3],\n minLevel: args[4],\n maxLevel: args[5]\n };\n }\n\n //Tile sources supply some events, namely 'ready' when they must be configured\n //by asynchronously fetching their configuration data.\n $.EventSource.call( this );\n\n //we allow options to override anything we dont treat as\n //required via idiomatic options or which is functionally\n //set depending on the state of the readiness of this tile\n //source\n $.extend( true, this, options );\n\n if (!this.success) {\n //Any functions that are passed as arguments are bound to the ready callback\n for ( i = 0; i < arguments.length; i++ ) {\n if ( $.isFunction( arguments[ i ] ) ) {\n this.success = arguments[ i ];\n //only one callback per constructor\n break;\n }\n }\n }\n\n if (this.success) {\n this.addHandler( 'ready', function ( event ) {\n _this.success( event );\n } );\n }\n\n /**\n * Ratio of width to height\n * @member {Number} aspectRatio\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * Vector storing x and y dimensions ( width and height respectively ).\n * @member {OpenSeadragon.Point} dimensions\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * The overlap in pixels each tile shares with its adjacent neighbors.\n * @member {Number} tileOverlap\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * The minimum pyramid level this tile source supports or should attempt to load.\n * @member {Number} minLevel\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * The maximum pyramid level this tile source supports or should attempt to load.\n * @member {Number} maxLevel\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n *\n * @member {Boolean} ready\n * @memberof OpenSeadragon.TileSource#\n */\n\n if( 'string' == $.type( arguments[ 0 ] ) ){\n this.url = arguments[0];\n }\n\n if (this.url) {\n //in case the getImageInfo method is overriden and/or implies an\n //async mechanism set some safe defaults first\n this.aspectRatio = 1;\n this.dimensions = new $.Point( 10, 10 );\n this._tileWidth = 0;\n this._tileHeight = 0;\n this.tileOverlap = 0;\n this.minLevel = 0;\n this.maxLevel = 0;\n this.ready = false;\n //configuration via url implies the extending class\n //implements and 'configure'\n this.getImageInfo( this.url );\n\n } else {\n\n //explicit configuration via positional args in constructor\n //or the more idiomatic 'options' object\n this.ready = true;\n this.aspectRatio = (options.width && options.height) ?\n (options.width / options.height) : 1;\n this.dimensions = new $.Point( options.width, options.height );\n\n if ( this.tileSize ){\n this._tileWidth = this._tileHeight = this.tileSize;\n delete this.tileSize;\n } else {\n if( this.tileWidth ){\n // We were passed tileWidth in options, but we want to rename it\n // with a leading underscore to make clear that it is not safe to directly modify it\n this._tileWidth = this.tileWidth;\n delete this.tileWidth;\n } else {\n this._tileWidth = 0;\n }\n\n if( this.tileHeight ){\n // See note above about renaming this.tileWidth\n this._tileHeight = this.tileHeight;\n delete this.tileHeight;\n } else {\n this._tileHeight = 0;\n }\n }\n\n this.tileOverlap = options.tileOverlap ? options.tileOverlap : 0;\n this.minLevel = options.minLevel ? options.minLevel : 0;\n this.maxLevel = ( undefined !== options.maxLevel && null !== options.maxLevel ) ?\n options.maxLevel : (\n ( options.width && options.height ) ? Math.ceil(\n Math.log( Math.max( options.width, options.height ) ) /\n Math.log( 2 )\n ) : 0\n );\n if( this.success && $.isFunction( this.success ) ){\n this.success( this );\n }\n }\n\n\n};\n\n/** @lends OpenSeadragon.TileSource.prototype */\n$.TileSource.prototype = {\n\n getTileSize: function( level ) {\n $.console.error(\n \"[TileSource.getTileSize] is deprecated.\" +\n \"Use TileSource.getTileWidth() and TileSource.getTileHeight() instead\"\n );\n return this._tileWidth;\n },\n\n /**\n * Return the tileWidth for a given level.\n * Subclasses should override this if tileWidth can be different at different levels\n * such as in IIIFTileSource. Code should use this function rather than reading\n * from ._tileWidth directly.\n * @function\n * @param {Number} level\n */\n getTileWidth: function( level ) {\n if (!this._tileWidth) {\n return this.getTileSize(level);\n }\n return this._tileWidth;\n },\n\n /**\n * Return the tileHeight for a given level.\n * Subclasses should override this if tileHeight can be different at different levels\n * such as in IIIFTileSource. Code should use this function rather than reading\n * from ._tileHeight directly.\n * @function\n * @param {Number} level\n */\n getTileHeight: function( level ) {\n if (!this._tileHeight) {\n return this.getTileSize(level);\n }\n return this._tileHeight;\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function( level ) {\n\n // see https://github.com/openseadragon/openseadragon/issues/22\n // we use the tilesources implementation of getLevelScale to generate\n // a memoized re-implementation\n var levelScaleCache = {},\n i;\n for( i = 0; i <= this.maxLevel; i++ ){\n levelScaleCache[ i ] = 1 / Math.pow(2, this.maxLevel - i);\n }\n this.getLevelScale = function( _level ){\n return levelScaleCache[ _level ];\n };\n return this.getLevelScale( level );\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function( level ) {\n var scale = this.getLevelScale( level ),\n x = Math.ceil( scale * this.dimensions.x / this.getTileWidth(level) ),\n y = Math.ceil( scale * this.dimensions.y / this.getTileHeight(level) );\n\n return new $.Point( x, y );\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getPixelRatio: function( level ) {\n var imageSizeScaled = this.dimensions.times( this.getLevelScale( level ) ),\n rx = 1.0 / imageSizeScaled.x,\n ry = 1.0 / imageSizeScaled.y;\n\n return new $.Point(rx, ry);\n },\n\n\n /**\n * @function\n * @returns {Number} The highest level in this tile source that can be contained in a single tile.\n */\n getClosestLevel: function() {\n var i,\n tiles;\n\n for (i = this.minLevel + 1; i <= this.maxLevel; i++){\n tiles = this.getNumTiles(i);\n if (tiles.x > 1 || tiles.y > 1) {\n break;\n }\n }\n\n return i - 1;\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {OpenSeadragon.Point} point\n */\n getTileAtPoint: function(level, point) {\n var validPoint = point.x >= 0 && point.x <= 1 &&\n point.y >= 0 && point.y <= 1 / this.aspectRatio;\n $.console.assert(validPoint, \"[TileSource.getTileAtPoint] must be called with a valid point.\");\n\n var widthScaled = this.dimensions.x * this.getLevelScale(level);\n var pixelX = point.x * widthScaled;\n var pixelY = point.y * widthScaled;\n\n var x = Math.floor(pixelX / this.getTileWidth(level));\n var y = Math.floor(pixelY / this.getTileHeight(level));\n\n // When point.x == 1 or point.y == 1 / this.aspectRatio we want to\n // return the last tile of the row/column\n if (point.x >= 1) {\n x = this.getNumTiles(level).x - 1;\n }\n var EPSILON = 1e-15;\n if (point.y >= 1 / this.aspectRatio - EPSILON) {\n y = this.getNumTiles(level).y - 1;\n }\n\n return new $.Point(x, y);\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @param {Boolean} [isSource=false] Whether to return the source bounds of the tile.\n * @returns {OpenSeadragon.Rect} Either where this tile fits (in normalized coordinates) or the\n * portion of the tile to use as the source of the drawing operation (in pixels), depending on\n * the isSource parameter.\n */\n getTileBounds: function( level, x, y, isSource ) {\n var dimensionsScaled = this.dimensions.times( this.getLevelScale( level ) ),\n tileWidth = this.getTileWidth(level),\n tileHeight = this.getTileHeight(level),\n px = ( x === 0 ) ? 0 : tileWidth * x - this.tileOverlap,\n py = ( y === 0 ) ? 0 : tileHeight * y - this.tileOverlap,\n sx = tileWidth + ( x === 0 ? 1 : 2 ) * this.tileOverlap,\n sy = tileHeight + ( y === 0 ? 1 : 2 ) * this.tileOverlap,\n scale = 1.0 / dimensionsScaled.x;\n\n sx = Math.min( sx, dimensionsScaled.x - px );\n sy = Math.min( sy, dimensionsScaled.y - py );\n\n if (isSource) {\n return new $.Rect(0, 0, sx, sy);\n }\n\n return new $.Rect( px * scale, py * scale, sx * scale, sy * scale );\n },\n\n\n /**\n * Responsible for retrieving, and caching the\n * image metadata pertinent to this TileSources implementation.\n * @function\n * @param {String} url\n * @throws {Error}\n */\n getImageInfo: function( url ) {\n var _this = this,\n callbackName,\n callback,\n readySource,\n options,\n urlParts,\n filename,\n lastDot;\n\n\n if( url ) {\n urlParts = url.split( '/' );\n filename = urlParts[ urlParts.length - 1 ];\n lastDot = filename.lastIndexOf( '.' );\n if ( lastDot > -1 ) {\n urlParts[ urlParts.length - 1 ] = filename.slice( 0, lastDot );\n }\n }\n\n callback = function( data ){\n if( typeof (data) === \"string\" ) {\n data = $.parseXml( data );\n }\n var $TileSource = $.TileSource.determineType( _this, data, url );\n if ( !$TileSource ) {\n /**\n * Raised when an error occurs loading a TileSource.\n *\n * @event open-failed\n * @memberof OpenSeadragon.TileSource\n * @type {object}\n * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.\n * @property {String} message\n * @property {String} source\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'open-failed', { message: \"Unable to load TileSource\", source: url } );\n return;\n }\n\n options = $TileSource.prototype.configure.apply( _this, [ data, url ]);\n if (options.ajaxWithCredentials === undefined) {\n options.ajaxWithCredentials = _this.ajaxWithCredentials;\n }\n\n readySource = new $TileSource( options );\n _this.ready = true;\n /**\n * Raised when a TileSource is opened and initialized.\n *\n * @event ready\n * @memberof OpenSeadragon.TileSource\n * @type {object}\n * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.\n * @property {Object} tileSource\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'ready', { tileSource: readySource } );\n };\n\n if( url.match(/\\.js$/) ){\n //TODO: Its not very flexible to require tile sources to end jsonp\n // request for info with a url that ends with '.js' but for\n // now it's the only way I see to distinguish uniformly.\n callbackName = url.split('/').pop().replace('.js', '');\n $.jsonp({\n url: url,\n async: false,\n callbackName: callbackName,\n callback: callback\n });\n } else {\n // request info via xhr asynchronously.\n $.makeAjaxRequest( {\n url: url,\n withCredentials: this.ajaxWithCredentials,\n headers: this.ajaxHeaders,\n success: function( xhr ) {\n var data = processResponse( xhr );\n callback( data );\n },\n error: function ( xhr, exc ) {\n var msg;\n\n /*\n IE < 10 will block XHR requests to different origins. Any property access on the request\n object will raise an exception which we'll attempt to handle by formatting the original\n exception rather than the second one raised when we try to access xhr.status\n */\n try {\n msg = \"HTTP \" + xhr.status + \" attempting to load TileSource\";\n } catch ( e ) {\n var formattedExc;\n if ( typeof ( exc ) == \"undefined\" || !exc.toString ) {\n formattedExc = \"Unknown error\";\n } else {\n formattedExc = exc.toString();\n }\n\n msg = formattedExc + \" attempting to load TileSource\";\n }\n\n /***\n * Raised when an error occurs loading a TileSource.\n *\n * @event open-failed\n * @memberof OpenSeadragon.TileSource\n * @type {object}\n * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.\n * @property {String} message\n * @property {String} source\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'open-failed', {\n message: msg,\n source: url\n });\n }\n });\n }\n\n },\n\n /**\n * Responsible determining if a the particular TileSource supports the\n * data format ( and allowed to apply logic against the url the data was\n * loaded from, if any ). Overriding implementations are expected to do\n * something smart with data and / or url to determine support. Also\n * understand that iteration order of TileSources is not guarunteed so\n * please make sure your data or url is expressive enough to ensure a simple\n * and sufficient mechanisim for clear determination.\n * @function\n * @param {String|Object|Array|Document} data\n * @param {String} url - the url the data was loaded\n * from if any.\n * @return {Boolean}\n */\n supports: function( data, url ) {\n return false;\n },\n\n /**\n * Responsible for parsing and configuring the\n * image metadata pertinent to this TileSources implementation.\n * This method is not implemented by this class other than to throw an Error\n * announcing you have to implement it. Because of the variety of tile\n * server technologies, and various specifications for building image\n * pyramids, this method is here to allow easy integration.\n * @function\n * @param {String|Object|Array|Document} data\n * @param {String} url - the url the data was loaded\n * from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n * @throws {Error}\n */\n configure: function( data, url ) {\n throw new Error( \"Method not implemented.\" );\n },\n\n /**\n * Responsible for retrieving the url which will return an image for the\n * region specified by the given x, y, and level components.\n * This method is not implemented by this class other than to throw an Error\n * announcing you have to implement it. Because of the variety of tile\n * server technologies, and various specifications for building image\n * pyramids, this method is here to allow easy integration.\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @throws {Error}\n */\n getTileUrl: function( level, x, y ) {\n throw new Error( \"Method not implemented.\" );\n },\n\n /**\n * Responsible for retrieving the headers which will be attached to the image request for the\n * region specified by the given x, y, and level components.\n * This option is only relevant if {@link OpenSeadragon.Options}.loadTilesWithAjax is set to true.\n * The headers returned here will override headers specified at the Viewer or TiledImage level.\n * Specifying a falsy value for a header will clear its existing value set at the Viewer or\n * TiledImage level (if any).\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @returns {Object}\n */\n getTileAjaxHeaders: function( level, x, y ) {\n return {};\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n tileExists: function( level, x, y ) {\n var numTiles = this.getNumTiles( level );\n return level >= this.minLevel &&\n level <= this.maxLevel &&\n x >= 0 &&\n y >= 0 &&\n x < numTiles.x &&\n y < numTiles.y;\n }\n};\n\n\n$.extend( true, $.TileSource.prototype, $.EventSource.prototype );\n\n\n/**\n * Decides whether to try to process the response as xml, json, or hand back\n * the text\n * @private\n * @inner\n * @function\n * @param {XMLHttpRequest} xhr - the completed network request\n */\nfunction processResponse( xhr ){\n var responseText = xhr.responseText,\n status = xhr.status,\n statusText,\n data;\n\n if ( !xhr ) {\n throw new Error( $.getString( \"Errors.Security\" ) );\n } else if ( xhr.status !== 200 && xhr.status !== 0 ) {\n status = xhr.status;\n statusText = ( status == 404 ) ?\n \"Not Found\" :\n xhr.statusText;\n throw new Error( $.getString( \"Errors.Status\", status, statusText ) );\n }\n\n if( responseText.match(/\\s*<.*/) ){\n try{\n data = ( xhr.responseXML && xhr.responseXML.documentElement ) ?\n xhr.responseXML :\n $.parseXml( responseText );\n } catch (e){\n data = xhr.responseText;\n }\n }else if( responseText.match(/\\s*[\\{\\[].*/) ){\n try{\n data = $.parseJSON(responseText);\n } catch(e){\n data = responseText;\n }\n }else{\n data = responseText;\n }\n return data;\n}\n\n\n/**\n * Determines the TileSource Implementation by introspection of OpenSeadragon\n * namespace, calling each TileSource implementation of 'isType'\n * @private\n * @inner\n * @function\n * @param {Object|Array|Document} data - the tile source configuration object\n * @param {String} url - the url where the tile source configuration object was\n * loaded from, if any.\n */\n$.TileSource.determineType = function( tileSource, data, url ){\n var property;\n for( property in OpenSeadragon ){\n if( property.match(/.+TileSource$/) &&\n $.isFunction( OpenSeadragon[ property ] ) &&\n $.isFunction( OpenSeadragon[ property ].prototype.supports ) &&\n OpenSeadragon[ property ].prototype.supports.call( tileSource, data, url )\n ){\n return OpenSeadragon[ property ];\n }\n }\n\n $.console.error( \"No TileSource was able to open %s %s\", url, data );\n};\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - DziTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class DziTileSource\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number|Object} width - the pixel width of the image or the idiomatic\n * options object which is used instead of positional arguments.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {Number} tileOverlap\n * @param {String} tilesUrl\n * @param {String} fileFormat\n * @param {OpenSeadragon.DisplayRect[]} displayRects\n * @property {String} tilesUrl\n * @property {String} fileFormat\n * @property {OpenSeadragon.DisplayRect[]} displayRects\n */\n$.DziTileSource = function( width, height, tileSize, tileOverlap, tilesUrl, fileFormat, displayRects, minLevel, maxLevel ) {\n var i,\n rect,\n level,\n options;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: arguments[ 0 ],\n height: arguments[ 1 ],\n tileSize: arguments[ 2 ],\n tileOverlap: arguments[ 3 ],\n tilesUrl: arguments[ 4 ],\n fileFormat: arguments[ 5 ],\n displayRects: arguments[ 6 ],\n minLevel: arguments[ 7 ],\n maxLevel: arguments[ 8 ]\n };\n }\n\n this._levelRects = {};\n this.tilesUrl = options.tilesUrl;\n this.fileFormat = options.fileFormat;\n this.displayRects = options.displayRects;\n\n if ( this.displayRects ) {\n for ( i = this.displayRects.length - 1; i >= 0; i-- ) {\n rect = this.displayRects[ i ];\n for ( level = rect.minLevel; level <= rect.maxLevel; level++ ) {\n if ( !this._levelRects[ level ] ) {\n this._levelRects[ level ] = [];\n }\n this._levelRects[ level ].push( rect );\n }\n }\n }\n\n $.TileSource.apply( this, [ options ] );\n\n};\n\n$.extend( $.DziTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.DziTileSource.prototype */{\n\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n var ns;\n if ( data.Image ) {\n ns = data.Image.xmlns;\n } else if ( data.documentElement) {\n if (\"Image\" == data.documentElement.localName || \"Image\" == data.documentElement.tagName) {\n ns = data.documentElement.namespaceURI;\n }\n }\n\n ns = (ns || '').toLowerCase();\n\n return (ns.indexOf('schemas.microsoft.com/deepzoom/2008') !== -1 ||\n ns.indexOf('schemas.microsoft.com/deepzoom/2009') !== -1);\n },\n\n /**\n *\n * @function\n * @param {Object|XMLDocument} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( data, url ){\n\n var options;\n\n if( !$.isPlainObject(data) ){\n\n options = configureFromXML( this, data );\n\n }else{\n\n options = configureFromObject( this, data );\n }\n\n if (url && !options.tilesUrl) {\n options.tilesUrl = url.replace(\n /([^\\/]+?)(\\.(dzi|xml|js)?(\\?[^\\/]*)?)?\\/?$/, '$1_files/');\n\n if (url.search(/\\.(dzi|xml|js)\\?/) != -1) {\n options.queryParams = url.match(/\\?.*/);\n }else{\n options.queryParams = '';\n }\n }\n\n return options;\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function( level, x, y ) {\n return [ this.tilesUrl, level, '/', x, '_', y, '.', this.fileFormat, this.queryParams ].join( '' );\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n tileExists: function( level, x, y ) {\n var rects = this._levelRects[ level ],\n rect,\n scale,\n xMin,\n yMin,\n xMax,\n yMax,\n i;\n\n if ( !rects || !rects.length ) {\n return true;\n }\n\n for ( i = rects.length - 1; i >= 0; i-- ) {\n rect = rects[ i ];\n\n if ( level < rect.minLevel || level > rect.maxLevel ) {\n continue;\n }\n\n scale = this.getLevelScale( level );\n xMin = rect.x * scale;\n yMin = rect.y * scale;\n xMax = xMin + rect.width * scale;\n yMax = yMin + rect.height * scale;\n\n xMin = Math.floor( xMin / this._tileWidth );\n yMin = Math.floor( yMin / this._tileWidth ); // DZI tiles are square, so we just use _tileWidth\n xMax = Math.ceil( xMax / this._tileWidth );\n yMax = Math.ceil( yMax / this._tileWidth );\n\n if ( xMin <= x && x < xMax && yMin <= y && y < yMax ) {\n return true;\n }\n }\n\n return false;\n }\n});\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromXML( tileSource, xmlDoc ){\n\n if ( !xmlDoc || !xmlDoc.documentElement ) {\n throw new Error( $.getString( \"Errors.Xml\" ) );\n }\n\n var root = xmlDoc.documentElement,\n rootName = root.localName || root.tagName,\n ns = xmlDoc.documentElement.namespaceURI,\n configuration = null,\n displayRects = [],\n dispRectNodes,\n dispRectNode,\n rectNode,\n sizeNode,\n i;\n\n if ( rootName == \"Image\" ) {\n\n try {\n sizeNode = root.getElementsByTagName(\"Size\" )[ 0 ];\n if (sizeNode === undefined) {\n sizeNode = root.getElementsByTagNameNS(ns, \"Size\" )[ 0 ];\n }\n\n configuration = {\n Image: {\n xmlns: \"http://schemas.microsoft.com/deepzoom/2008\",\n Url: root.getAttribute( \"Url\" ),\n Format: root.getAttribute( \"Format\" ),\n DisplayRect: null,\n Overlap: parseInt( root.getAttribute( \"Overlap\" ), 10 ),\n TileSize: parseInt( root.getAttribute( \"TileSize\" ), 10 ),\n Size: {\n Height: parseInt( sizeNode.getAttribute( \"Height\" ), 10 ),\n Width: parseInt( sizeNode.getAttribute( \"Width\" ), 10 )\n }\n }\n };\n\n if ( !$.imageFormatSupported( configuration.Image.Format ) ) {\n throw new Error(\n $.getString( \"Errors.ImageFormat\", configuration.Image.Format.toUpperCase() )\n );\n }\n\n dispRectNodes = root.getElementsByTagName(\"DisplayRect\" );\n if (dispRectNodes === undefined) {\n dispRectNodes = root.getElementsByTagNameNS(ns, \"DisplayRect\" )[ 0 ];\n }\n\n for ( i = 0; i < dispRectNodes.length; i++ ) {\n dispRectNode = dispRectNodes[ i ];\n rectNode = dispRectNode.getElementsByTagName(\"Rect\" )[ 0 ];\n if (rectNode === undefined) {\n rectNode = dispRectNode.getElementsByTagNameNS(ns, \"Rect\" )[ 0 ];\n }\n\n displayRects.push({\n Rect: {\n X: parseInt( rectNode.getAttribute( \"X\" ), 10 ),\n Y: parseInt( rectNode.getAttribute( \"Y\" ), 10 ),\n Width: parseInt( rectNode.getAttribute( \"Width\" ), 10 ),\n Height: parseInt( rectNode.getAttribute( \"Height\" ), 10 ),\n MinLevel: parseInt( dispRectNode.getAttribute( \"MinLevel\" ), 10 ),\n MaxLevel: parseInt( dispRectNode.getAttribute( \"MaxLevel\" ), 10 )\n }\n });\n }\n\n if( displayRects.length ){\n configuration.Image.DisplayRect = displayRects;\n }\n\n return configureFromObject( tileSource, configuration );\n\n } catch ( e ) {\n throw (e instanceof Error) ?\n e :\n new Error( $.getString(\"Errors.Dzi\") );\n }\n } else if ( rootName == \"Collection\" ) {\n throw new Error( $.getString( \"Errors.Dzc\" ) );\n } else if ( rootName == \"Error\" ) {\n var messageNode = root.getElementsByTagName(\"Message\")[0];\n var message = messageNode.firstChild.nodeValue;\n throw new Error(message);\n }\n\n throw new Error( $.getString( \"Errors.Dzi\" ) );\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromObject( tileSource, configuration ){\n var imageData = configuration.Image,\n tilesUrl = imageData.Url,\n fileFormat = imageData.Format,\n sizeData = imageData.Size,\n dispRectData = imageData.DisplayRect || [],\n width = parseInt( sizeData.Width, 10 ),\n height = parseInt( sizeData.Height, 10 ),\n tileSize = parseInt( imageData.TileSize, 10 ),\n tileOverlap = parseInt( imageData.Overlap, 10 ),\n displayRects = [],\n rectData,\n i;\n\n //TODO: need to figure out out to better handle image format compatibility\n // which actually includes additional file formats like xml and pdf\n // and plain text for various tilesource implementations to avoid low\n // level errors.\n //\n // For now, just don't perform the check.\n //\n /*if ( !imageFormatSupported( fileFormat ) ) {\n throw new Error(\n $.getString( \"Errors.ImageFormat\", fileFormat.toUpperCase() )\n );\n }*/\n\n for ( i = 0; i < dispRectData.length; i++ ) {\n rectData = dispRectData[ i ].Rect;\n\n displayRects.push( new $.DisplayRect(\n parseInt( rectData.X, 10 ),\n parseInt( rectData.Y, 10 ),\n parseInt( rectData.Width, 10 ),\n parseInt( rectData.Height, 10 ),\n parseInt( rectData.MinLevel, 10 ),\n parseInt( rectData.MaxLevel, 10 )\n ));\n }\n\n return $.extend(true, {\n width: width, /* width *required */\n height: height, /* height *required */\n tileSize: tileSize, /* tileSize *required */\n tileOverlap: tileOverlap, /* tileOverlap *required */\n minLevel: null, /* minLevel */\n maxLevel: null, /* maxLevel */\n tilesUrl: tilesUrl, /* tilesUrl */\n fileFormat: fileFormat, /* fileFormat */\n displayRects: displayRects /* displayRects */\n }, configuration );\n\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - IIIFTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class IIIFTileSource\n * @classdesc A client implementation of the International Image Interoperability Framework\n * Format: Image API 1.0 - 2.1\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @see http://iiif.io/api/image/\n */\n$.IIIFTileSource = function( options ){\n\n /* eslint-disable camelcase */\n\n $.extend( true, this, options );\n\n if ( !( this.height && this.width && this['@id'] ) ) {\n throw new Error( 'IIIF required parameters not provided.' );\n }\n\n options.tileSizePerScaleFactor = {};\n\n // N.B. 2.0 renamed scale_factors to scaleFactors\n if ( this.tile_width && this.tile_height ) {\n options.tileWidth = this.tile_width;\n options.tileHeight = this.tile_height;\n } else if ( this.tile_width ) {\n options.tileSize = this.tile_width;\n } else if ( this.tile_height ) {\n options.tileSize = this.tile_height;\n } else if ( this.tiles ) {\n // Version 2.0 forwards\n if ( this.tiles.length == 1 ) {\n options.tileWidth = this.tiles[0].width;\n // Use height if provided, otherwise assume square tiles and use width.\n options.tileHeight = this.tiles[0].height || this.tiles[0].width;\n this.scale_factors = this.tiles[0].scaleFactors;\n } else {\n // Multiple tile sizes at different levels\n this.scale_factors = [];\n for (var t = 0; t < this.tiles.length; t++ ) {\n for (var sf = 0; sf < this.tiles[t].scaleFactors.length; sf++) {\n var scaleFactor = this.tiles[t].scaleFactors[sf];\n this.scale_factors.push(scaleFactor);\n options.tileSizePerScaleFactor[scaleFactor] = {\n width: this.tiles[t].width,\n height: this.tiles[t].height || this.tiles[t].width\n };\n }\n }\n }\n } else if ( canBeTiled(options.profile) ) {\n // use the largest of tileOptions that is smaller than the short dimension\n var shortDim = Math.min( this.height, this.width ),\n tileOptions = [256, 512, 1024],\n smallerTiles = [];\n\n for ( var c = 0; c < tileOptions.length; c++ ) {\n if ( tileOptions[c] <= shortDim ) {\n smallerTiles.push( tileOptions[c] );\n }\n }\n\n if ( smallerTiles.length > 0 ) {\n options.tileSize = Math.max.apply( null, smallerTiles );\n } else {\n // If we're smaller than 256, just use the short side.\n options.tileSize = shortDim;\n }\n } else if (this.sizes && this.sizes.length > 0) {\n // This info.json can't be tiled, but we can still construct a legacy pyramid from the sizes array.\n // In this mode, IIIFTileSource will call functions from the abstract baseTileSource or the\n // LegacyTileSource instead of performing IIIF tiling.\n this.emulateLegacyImagePyramid = true;\n\n options.levels = constructLevels( this );\n // use the largest available size to define tiles\n $.extend( true, options, {\n width: options.levels[ options.levels.length - 1 ].width,\n height: options.levels[ options.levels.length - 1 ].height,\n tileSize: Math.max( options.height, options.width ),\n tileOverlap: 0,\n minLevel: 0,\n maxLevel: options.levels.length - 1\n });\n this.levels = options.levels;\n } else {\n $.console.error(\"Nothing in the info.json to construct image pyramids from\");\n }\n\n if (!options.maxLevel && !this.emulateLegacyImagePyramid) {\n if (!this.scale_factors) {\n options.maxLevel = Number(Math.ceil(Math.log(Math.max(this.width, this.height), 2)));\n } else {\n var maxScaleFactor = Math.max.apply(null, this.scale_factors);\n options.maxLevel = Math.round(Math.log(maxScaleFactor) * Math.LOG2E);\n }\n }\n\n $.TileSource.apply( this, [ options ] );\n};\n\n$.extend( $.IIIFTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.IIIFTileSource.prototype */{\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n\n supports: function( data, url ) {\n // Version 2.0 and forwards\n if (data.protocol && data.protocol == 'http://iiif.io/api/image') {\n return true;\n // Version 1.1\n } else if ( data['@context'] && (\n data['@context'] == \"http://library.stanford.edu/iiif/image-api/1.1/context.json\" ||\n data['@context'] == \"http://iiif.io/api/image/1/context.json\") ) {\n // N.B. the iiif.io context is wrong, but where the representation lives so likely to be used\n return true;\n\n // Version 1.0\n } else if ( data.profile &&\n data.profile.indexOf(\"http://library.stanford.edu/iiif/image-api/compliance.html\") === 0) {\n return true;\n } else if ( data.identifier && data.width && data.height ) {\n return true;\n } else if ( data.documentElement &&\n \"info\" == data.documentElement.tagName &&\n \"http://library.stanford.edu/iiif/image-api/ns/\" ==\n data.documentElement.namespaceURI) {\n return true;\n\n // Not IIIF\n } else {\n return false;\n }\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @example IIIF 1.1 Info Looks like this\n * {\n * \"@context\" : \"http://library.stanford.edu/iiif/image-api/1.1/context.json\",\n * \"@id\" : \"http://iiif.example.com/prefix/1E34750D-38DB-4825-A38A-B60A345E591C\",\n * \"width\" : 6000,\n * \"height\" : 4000,\n * \"scale_factors\" : [ 1, 2, 4 ],\n * \"tile_width\" : 1024,\n * \"tile_height\" : 1024,\n * \"formats\" : [ \"jpg\", \"png\" ],\n * \"qualities\" : [ \"native\", \"grey\" ],\n * \"profile\" : \"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0\"\n * }\n */\n configure: function( data, url ){\n // Try to deduce our version and fake it upwards if needed\n if ( !$.isPlainObject(data) ) {\n var options = configureFromXml10( data );\n options['@context'] = \"http://iiif.io/api/image/1.0/context.json\";\n options['@id'] = url.replace('/info.xml', '');\n return options;\n } else if ( !data['@context'] ) {\n data['@context'] = 'http://iiif.io/api/image/1.0/context.json';\n data['@id'] = url.replace('/info.json', '');\n return data;\n } else {\n return data;\n }\n },\n\n /**\n * Return the tileWidth for the given level.\n * @function\n * @param {Number} level\n */\n getTileWidth: function( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n return $.TileSource.prototype.getTileWidth.call(this, level);\n }\n\n var scaleFactor = Math.pow(2, this.maxLevel - level);\n\n if (this.tileSizePerScaleFactor && this.tileSizePerScaleFactor[scaleFactor]) {\n return this.tileSizePerScaleFactor[scaleFactor].width;\n }\n return this._tileWidth;\n },\n\n /**\n * Return the tileHeight for the given level.\n * @function\n * @param {Number} level\n */\n getTileHeight: function( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n return $.TileSource.prototype.getTileHeight.call(this, level);\n }\n\n var scaleFactor = Math.pow(2, this.maxLevel - level);\n\n if (this.tileSizePerScaleFactor && this.tileSizePerScaleFactor[scaleFactor]) {\n return this.tileSizePerScaleFactor[scaleFactor].height;\n }\n return this._tileHeight;\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function ( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n var levelScale = NaN;\n if (this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel) {\n levelScale =\n this.levels[level].width /\n this.levels[this.maxLevel].width;\n }\n return levelScale;\n }\n\n return $.TileSource.prototype.getLevelScale.call(this, level);\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n var scale = this.getLevelScale(level);\n if (scale) {\n return new $.Point(1, 1);\n } else {\n return new $.Point(0, 0);\n }\n }\n\n return $.TileSource.prototype.getNumTiles.call(this, level);\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {OpenSeadragon.Point} point\n */\n getTileAtPoint: function( level, point ) {\n\n if(this.emulateLegacyImagePyramid) {\n return new $.Point(0, 0);\n }\n\n return $.TileSource.prototype.getTileAtPoint.call(this, level, point);\n },\n\n\n /**\n * Responsible for retrieving the url which will return an image for the\n * region specified by the given x, y, and level components.\n * @function\n * @param {Number} level - z index\n * @param {Number} x\n * @param {Number} y\n * @throws {Error}\n */\n getTileUrl: function( level, x, y ){\n\n if(this.emulateLegacyImagePyramid) {\n var url = null;\n if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {\n url = this.levels[ level ].url;\n }\n return url;\n }\n\n //# constants\n var IIIF_ROTATION = '0',\n //## get the scale (level as a decimal)\n scale = Math.pow( 0.5, this.maxLevel - level ),\n\n //# image dimensions at this level\n levelWidth = Math.ceil( this.width * scale ),\n levelHeight = Math.ceil( this.height * scale ),\n\n //## iiif region\n tileWidth,\n tileHeight,\n iiifTileSizeWidth,\n iiifTileSizeHeight,\n iiifRegion,\n iiifTileX,\n iiifTileY,\n iiifTileW,\n iiifTileH,\n iiifSize,\n iiifQuality,\n uri;\n\n tileWidth = this.getTileWidth(level);\n tileHeight = this.getTileHeight(level);\n iiifTileSizeWidth = Math.ceil( tileWidth / scale );\n iiifTileSizeHeight = Math.ceil( tileHeight / scale );\n\n if ( this['@context'].indexOf('/1.0/context.json') > -1 ||\n this['@context'].indexOf('/1.1/context.json') > -1 ||\n this['@context'].indexOf('/1/context.json') > -1 ) {\n iiifQuality = \"native.jpg\";\n } else {\n iiifQuality = \"default.jpg\";\n }\n\n if ( levelWidth < tileWidth && levelHeight < tileHeight ){\n iiifSize = levelWidth + \",\";\n iiifRegion = 'full';\n } else {\n iiifTileX = x * iiifTileSizeWidth;\n iiifTileY = y * iiifTileSizeHeight;\n iiifTileW = Math.min( iiifTileSizeWidth, this.width - iiifTileX );\n iiifTileH = Math.min( iiifTileSizeHeight, this.height - iiifTileY );\n iiifSize = Math.ceil( iiifTileW * scale ) + \",\";\n iiifRegion = [ iiifTileX, iiifTileY, iiifTileW, iiifTileH ].join( ',' );\n }\n uri = [ this['@id'], iiifRegion, iiifSize, IIIF_ROTATION, iiifQuality ].join( '/' );\n\n return uri;\n }\n\n });\n\n /**\n * Determine whether arbitrary tile requests can be made against a service with the given profile\n * @function\n * @param {object} profile - IIIF profile object\n * @throws {Error}\n */\n function canBeTiled (profile ) {\n var level0Profiles = [\n \"http://library.stanford.edu/iiif/image-api/compliance.html#level0\",\n \"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0\",\n \"http://iiif.io/api/image/2/level0.json\"\n ];\n var isLevel0 = (level0Profiles.indexOf(profile[0]) != -1);\n return !isLevel0 || (profile.indexOf(\"sizeByW\") != -1);\n }\n\n /**\n * Build the legacy pyramid URLs (one tile per level)\n * @function\n * @param {object} options - infoJson\n * @throws {Error}\n */\n function constructLevels(options) {\n var levels = [];\n for(var i = 0; i < options.sizes.length; i++) {\n levels.push({\n url: options['@id'] + '/full/' + options.sizes[i].width + ',/0/default.jpg',\n width: options.sizes[i].width,\n height: options.sizes[i].height\n });\n }\n return levels.sort(function(a, b) {\n return a.width - b.width;\n });\n }\n\n\n function configureFromXml10(xmlDoc) {\n //parse the xml\n if ( !xmlDoc || !xmlDoc.documentElement ) {\n throw new Error( $.getString( \"Errors.Xml\" ) );\n }\n\n var root = xmlDoc.documentElement,\n rootName = root.tagName,\n configuration = null;\n\n if ( rootName == \"info\" ) {\n try {\n configuration = {};\n parseXML10( root, configuration );\n return configuration;\n\n } catch ( e ) {\n throw (e instanceof Error) ?\n e :\n new Error( $.getString(\"Errors.IIIF\") );\n }\n }\n throw new Error( $.getString( \"Errors.IIIF\" ) );\n }\n\n function parseXML10( node, configuration, property ) {\n var i,\n value;\n if ( node.nodeType == 3 && property ) {//text node\n value = node.nodeValue.trim();\n if( value.match(/^\\d*$/)){\n value = Number( value );\n }\n if( !configuration[ property ] ){\n configuration[ property ] = value;\n }else{\n if( !$.isArray( configuration[ property ] ) ){\n configuration[ property ] = [ configuration[ property ] ];\n }\n configuration[ property ].push( value );\n }\n } else if( node.nodeType == 1 ){\n for( i = 0; i < node.childNodes.length; i++ ){\n parseXML10( node.childNodes[ i ], configuration, node.nodeName );\n }\n }\n }\n\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - OsmTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Derived from the OSM tile source in Rainer Simon's seajax-utils project\n * . Rainer Simon has contributed\n * the included code to the OpenSeadragon project under the New BSD license;\n * see .\n */\n\n\n(function( $ ){\n\n/**\n * @class OsmTileSource\n * @classdesc A tilesource implementation for OpenStreetMap.

\n *\n * Note 1. Zoomlevels. Deep Zoom and OSM define zoom levels differently. In Deep\n * Zoom, level 0 equals an image of 1x1 pixels. In OSM, level 0 equals an image of\n * 256x256 levels (see http://gasi.ch/blog/inside-deep-zoom-2). I.e. there is a\n * difference of log2(256)=8 levels.

\n *\n * Note 2. Image dimension. According to the OSM Wiki\n * (http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Zoom_levels)\n * the highest Mapnik zoom level has 256.144x256.144 tiles, with a 256x256\n * pixel size. I.e. the Deep Zoom image dimension is 65.572.864x65.572.864\n * pixels.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number|Object} width - the pixel width of the image or the idiomatic\n * options object which is used instead of positional arguments.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {Number} tileOverlap\n * @param {String} tilesUrl\n */\n$.OsmTileSource = function( width, height, tileSize, tileOverlap, tilesUrl ) {\n var options;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: arguments[0],\n height: arguments[1],\n tileSize: arguments[2],\n tileOverlap: arguments[3],\n tilesUrl: arguments[4]\n };\n }\n //apply default setting for standard public OpenStreatMaps service\n //but allow them to be specified so fliks can host there own instance\n //or apply against other services supportting the same standard\n if( !options.width || !options.height ){\n options.width = 65572864;\n options.height = 65572864;\n }\n if( !options.tileSize ){\n options.tileSize = 256;\n options.tileOverlap = 0;\n }\n if( !options.tilesUrl ){\n options.tilesUrl = \"http://tile.openstreetmap.org/\";\n }\n options.minLevel = 8;\n\n $.TileSource.apply( this, [ options ] );\n\n};\n\n$.extend( $.OsmTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.OsmTileSource.prototype */{\n\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n return (\n data.type &&\n \"openstreetmaps\" == data.type\n );\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( data, url ){\n return data;\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function( level, x, y ) {\n return this.tilesUrl + (level - 8) + \"/\" + x + \"/\" + y + \".png\";\n }\n});\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TmsTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Derived from the TMS tile source in Rainer Simon's seajax-utils project\n * . Rainer Simon has contributed\n * the included code to the OpenSeadragon project under the New BSD license;\n * see .\n */\n\n\n(function( $ ){\n\n/**\n * @class TmsTileSource\n * @classdesc A tilesource implementation for Tiled Map Services (TMS).\n * TMS tile scheme ( [ as supported by OpenLayers ] is described here\n * ( http://openlayers.org/dev/examples/tms.html ).\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number|Object} width - the pixel width of the image or the idiomatic\n * options object which is used instead of positional arguments.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {Number} tileOverlap\n * @param {String} tilesUrl\n */\n$.TmsTileSource = function( width, height, tileSize, tileOverlap, tilesUrl ) {\n var options;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: arguments[0],\n height: arguments[1],\n tileSize: arguments[2],\n tileOverlap: arguments[3],\n tilesUrl: arguments[4]\n };\n }\n // TMS has integer multiples of 256 for width/height and adds buffer\n // if necessary -> account for this!\n var bufferedWidth = Math.ceil(options.width / 256) * 256,\n bufferedHeight = Math.ceil(options.height / 256) * 256,\n max;\n\n // Compute number of zoomlevels in this tileset\n if (bufferedWidth > bufferedHeight) {\n max = bufferedWidth / 256;\n } else {\n max = bufferedHeight / 256;\n }\n options.maxLevel = Math.ceil(Math.log(max) / Math.log(2)) - 1;\n options.tileSize = 256;\n options.width = bufferedWidth;\n options.height = bufferedHeight;\n\n $.TileSource.apply( this, [ options ] );\n\n};\n\n$.extend( $.TmsTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.TmsTileSource.prototype */{\n\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n return ( data.type && \"tiledmapservice\" == data.type );\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( data, url ){\n return data;\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function( level, x, y ) {\n // Convert from Deep Zoom definition to TMS zoom definition\n var yTiles = this.getNumTiles( level ).y - 1;\n\n return this.tilesUrl + level + \"/\" + x + \"/\" + (yTiles - y) + \".png\";\n }\n});\n\n\n}( OpenSeadragon ));\n\n(function($) {\n\n /**\n * @class ZoomifyTileSource\n * @classdesc A tilesource implementation for the zoomify format.\n *\n * A description of the format can be found here:\n * https://ecommons.cornell.edu/bitstream/handle/1813/5410/Introducing_Zoomify_Image.pdf\n *\n * There are two ways of creating a zoomify tilesource for openseadragon\n *\n * 1) Supplying all necessary information in the tilesource object. A minimal example object for this method looks like this:\n *\n * {\n * type: \"zoomifytileservice\",\n * width: 1000,\n * height: 1000,\n * tilesUrl: \"/test/data/zoomify/\"\n * }\n *\n * The tileSize is currently hardcoded to 256 (the usual Zoomify default). The tileUrl must the path to the image _directory_.\n *\n * 2) Loading image metadata from xml file: (CURRENTLY NOT SUPPORTED)\n *\n * When creating zoomify formatted images one \"xml\" like file with name ImageProperties.xml\n * will be created as well. Here is an example of such a file:\n *\n * \n *\n * To use this xml file as metadata source you must supply the path to the ImageProperties.xml file and leave out all other parameters:\n * As stated above, this method of loading a zoomify tilesource is currently not supported\n *\n * {\n * type: \"zoomifytileservice\",\n * tilesUrl: \"/test/data/zoomify/ImageProperties.xml\"\n * }\n\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number} width - the pixel width of the image.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {String} tilesUrl\n */\n $.ZoomifyTileSource = function(options) {\n options.tileSize = 256;\n\n var currentImageSize = {\n x: options.width,\n y: options.height\n };\n options.imageSizes = [{\n x: options.width,\n y: options.height\n }];\n options.gridSize = [this._getGridSize(options.width, options.height, options.tileSize)];\n\n while (parseInt(currentImageSize.x, 10) > options.tileSize || parseInt(currentImageSize.y, 10) > options.tileSize) {\n currentImageSize.x = Math.floor(currentImageSize.x / 2);\n currentImageSize.y = Math.floor(currentImageSize.y / 2);\n options.imageSizes.push({\n x: currentImageSize.x,\n y: currentImageSize.y\n });\n options.gridSize.push(this._getGridSize(currentImageSize.x, currentImageSize.y, options.tileSize));\n }\n options.imageSizes.reverse();\n options.gridSize.reverse();\n options.minLevel = 0;\n options.maxLevel = options.gridSize.length - 1;\n\n OpenSeadragon.TileSource.apply(this, [options]);\n };\n\n $.extend($.ZoomifyTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.ZoomifyTileSource.prototype */ {\n\n //private\n _getGridSize: function(width, height, tileSize) {\n return {\n x: Math.ceil(width / tileSize),\n y: Math.ceil(height / tileSize)\n };\n },\n\n //private\n _calculateAbsoluteTileNumber: function(level, x, y) {\n var num = 0;\n var size = {};\n\n //Sum up all tiles below the level we want the number of tiles\n for (var z = 0; z < level; z++) {\n size = this.gridSize[z];\n num += size.x * size.y;\n }\n //Add the tiles of the level\n size = this.gridSize[level];\n num += size.x * y + x;\n return num;\n },\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function(data, url) {\n return (data.type && \"zoomifytileservice\" == data.type);\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function(data, url) {\n return data;\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function(level, x, y) {\n //console.log(level);\n var result = 0;\n var num = this._calculateAbsoluteTileNumber(level, x, y);\n result = Math.floor(num / 256);\n return this.tilesUrl + 'TileGroup' + result + '/' + level + '-' + x + '-' + y + '.jpg';\n\n }\n });\n\n}(OpenSeadragon));\n\n\n/*\n * OpenSeadragon - LegacyTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class LegacyTileSource\n * @classdesc The LegacyTileSource allows simple, traditional image pyramids to be loaded\n * into an OpenSeadragon Viewer. Basically, this translates to the historically\n * common practice of starting with a 'master' image, maybe a tiff for example,\n * and generating a set of 'service' images like one or more thumbnails, a medium\n * resolution image and a high resolution image in standard web formats like\n * png or jpg.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Array} levels An array of file descriptions, each is an object with\n * a 'url', a 'width', and a 'height'. Overriding classes can expect more\n * properties but these properties are sufficient for this implementation.\n * Additionally, the levels are required to be listed in order from\n * smallest to largest.\n * @property {Number} aspectRatio\n * @property {Number} dimensions\n * @property {Number} tileSize\n * @property {Number} tileOverlap\n * @property {Number} minLevel\n * @property {Number} maxLevel\n * @property {Array} levels\n */\n$.LegacyTileSource = function( levels ) {\n\n var options,\n width,\n height;\n\n if( $.isArray( levels ) ){\n options = {\n type: 'legacy-image-pyramid',\n levels: levels\n };\n }\n\n //clean up the levels to make sure we support all formats\n options.levels = filterFiles( options.levels );\n\n if ( options.levels.length > 0 ) {\n width = options.levels[ options.levels.length - 1 ].width;\n height = options.levels[ options.levels.length - 1 ].height;\n }\n else {\n width = 0;\n height = 0;\n $.console.error( \"No supported image formats found\" );\n }\n\n $.extend( true, options, {\n width: width,\n height: height,\n tileSize: Math.max( height, width ),\n tileOverlap: 0,\n minLevel: 0,\n maxLevel: options.levels.length > 0 ? options.levels.length - 1 : 0\n } );\n\n $.TileSource.apply( this, [ options ] );\n\n this.levels = options.levels;\n};\n\n$.extend( $.LegacyTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.LegacyTileSource.prototype */{\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n return (\n data.type &&\n \"legacy-image-pyramid\" == data.type\n ) || (\n data.documentElement &&\n \"legacy-image-pyramid\" == data.documentElement.getAttribute('type')\n );\n },\n\n\n /**\n *\n * @function\n * @param {Object|XMLDocument} configuration - the raw configuration\n * @param {String} dataUrl - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( configuration, dataUrl ){\n\n var options;\n\n if( !$.isPlainObject(configuration) ){\n\n options = configureFromXML( this, configuration );\n\n }else{\n\n options = configureFromObject( this, configuration );\n }\n\n return options;\n\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function ( level ) {\n var levelScale = NaN;\n if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {\n levelScale =\n this.levels[ level ].width /\n this.levels[ this.maxLevel ].width;\n }\n return levelScale;\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function( level ) {\n var scale = this.getLevelScale( level );\n if ( scale ){\n return new $.Point( 1, 1 );\n } else {\n return new $.Point( 0, 0 );\n }\n },\n\n /**\n * This method is not implemented by this class other than to throw an Error\n * announcing you have to implement it. Because of the variety of tile\n * server technologies, and various specifications for building image\n * pyramids, this method is here to allow easy integration.\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @throws {Error}\n */\n getTileUrl: function ( level, x, y ) {\n var url = null;\n if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {\n url = this.levels[ level ].url;\n }\n return url;\n }\n} );\n\n/**\n * This method removes any files from the Array which dont conform to our\n * basic requirements for a 'level' in the LegacyTileSource.\n * @private\n * @inner\n * @function\n */\nfunction filterFiles( files ){\n var filtered = [],\n file,\n i;\n for( i = 0; i < files.length; i++ ){\n file = files[ i ];\n if( file.height &&\n file.width &&\n file.url ){\n //This is sufficient to serve as a level\n filtered.push({\n url: file.url,\n width: Number( file.width ),\n height: Number( file.height )\n });\n }\n else {\n $.console.error( 'Unsupported image format: %s', file.url ? file.url : '' );\n }\n }\n\n return filtered.sort(function(a, b) {\n return a.height - b.height;\n });\n\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromXML( tileSource, xmlDoc ){\n\n if ( !xmlDoc || !xmlDoc.documentElement ) {\n throw new Error( $.getString( \"Errors.Xml\" ) );\n }\n\n var root = xmlDoc.documentElement,\n rootName = root.tagName,\n conf = null,\n levels = [],\n level,\n i;\n\n if ( rootName == \"image\" ) {\n\n try {\n conf = {\n type: root.getAttribute( \"type\" ),\n levels: []\n };\n\n levels = root.getElementsByTagName( \"level\" );\n for ( i = 0; i < levels.length; i++ ) {\n level = levels[ i ];\n\n conf.levels.push({\n url: level.getAttribute( \"url\" ),\n width: parseInt( level.getAttribute( \"width\" ), 10 ),\n height: parseInt( level.getAttribute( \"height\" ), 10 )\n });\n }\n\n return configureFromObject( tileSource, conf );\n\n } catch ( e ) {\n throw (e instanceof Error) ?\n e :\n new Error( 'Unknown error parsing Legacy Image Pyramid XML.' );\n }\n } else if ( rootName == \"collection\" ) {\n throw new Error( 'Legacy Image Pyramid Collections not yet supported.' );\n } else if ( rootName == \"error\" ) {\n throw new Error( 'Error: ' + xmlDoc );\n }\n\n throw new Error( 'Unknown element ' + rootName );\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromObject( tileSource, configuration ){\n\n return configuration.levels;\n\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ImageTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function ($) {\n\n /**\n * @class ImageTileSource\n * @classdesc The ImageTileSource allows a simple image to be loaded\n * into an OpenSeadragon Viewer.\n * There are 2 ways to open an ImageTileSource:\n * 1. viewer.open({type: 'image', url: fooUrl});\n * 2. viewer.open(new OpenSeadragon.ImageTileSource({url: fooUrl}));\n *\n * With the first syntax, the crossOriginPolicy, ajaxWithCredentials and\n * useCanvas options are inherited from the viewer if they are not\n * specified directly in the options object.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Object} options Options object.\n * @param {String} options.url URL of the image\n * @param {Boolean} [options.buildPyramid=true] If set to true (default), a\n * pyramid will be built internally to provide a better downsampling.\n * @param {String|Boolean} [options.crossOriginPolicy=false] Valid values are\n * 'Anonymous', 'use-credentials', and false. If false, image requests will\n * not use CORS preventing internal pyramid building for images from other\n * domains.\n * @param {String|Boolean} [options.ajaxWithCredentials=false] Whether to set\n * the withCredentials XHR flag for AJAX requests (when loading tile sources).\n * @param {Boolean} [options.useCanvas=true] Set to false to prevent any use\n * of the canvas API.\n */\n $.ImageTileSource = function (options) {\n\n options = $.extend({\n buildPyramid: true,\n crossOriginPolicy: false,\n ajaxWithCredentials: false,\n useCanvas: true\n }, options);\n $.TileSource.apply(this, [options]);\n\n };\n\n $.extend($.ImageTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.ImageTileSource.prototype */{\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function (data, url) {\n return data.type && data.type === \"image\";\n },\n /**\n *\n * @function\n * @param {Object} options - the options\n * @param {String} dataUrl - the url the image was retreived from, if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function (options, dataUrl) {\n return options;\n },\n /**\n * Responsible for retrieving, and caching the\n * image metadata pertinent to this TileSources implementation.\n * @function\n * @param {String} url\n * @throws {Error}\n */\n getImageInfo: function (url) {\n var image = this._image = new Image();\n var _this = this;\n\n if (this.crossOriginPolicy) {\n image.crossOrigin = this.crossOriginPolicy;\n }\n if (this.ajaxWithCredentials) {\n image.useCredentials = this.ajaxWithCredentials;\n }\n\n $.addEvent(image, 'load', function () {\n /* IE8 fix since it has no naturalWidth and naturalHeight */\n _this.width = Object.prototype.hasOwnProperty.call(image, 'naturalWidth') ? image.naturalWidth : image.width;\n _this.height = Object.prototype.hasOwnProperty.call(image, 'naturalHeight') ? image.naturalHeight : image.height;\n _this.aspectRatio = _this.width / _this.height;\n _this.dimensions = new $.Point(_this.width, _this.height);\n _this._tileWidth = _this.width;\n _this._tileHeight = _this.height;\n _this.tileOverlap = 0;\n _this.minLevel = 0;\n _this.levels = _this._buildLevels();\n _this.maxLevel = _this.levels.length - 1;\n\n _this.ready = true;\n\n // Note: this event is documented elsewhere, in TileSource\n _this.raiseEvent('ready', {tileSource: _this});\n });\n\n $.addEvent(image, 'error', function () {\n // Note: this event is documented elsewhere, in TileSource\n _this.raiseEvent('open-failed', {\n message: \"Error loading image at \" + url,\n source: url\n });\n });\n\n image.src = url;\n },\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function (level) {\n var levelScale = NaN;\n if (level >= this.minLevel && level <= this.maxLevel) {\n levelScale =\n this.levels[level].width /\n this.levels[this.maxLevel].width;\n }\n return levelScale;\n },\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function (level) {\n var scale = this.getLevelScale(level);\n if (scale) {\n return new $.Point(1, 1);\n } else {\n return new $.Point(0, 0);\n }\n },\n /**\n * Retrieves a tile url\n * @function\n * @param {Number} level Level of the tile\n * @param {Number} x x coordinate of the tile\n * @param {Number} y y coordinate of the tile\n */\n getTileUrl: function (level, x, y) {\n var url = null;\n if (level >= this.minLevel && level <= this.maxLevel) {\n url = this.levels[level].url;\n }\n return url;\n },\n /**\n * Retrieves a tile context 2D\n * @function\n * @param {Number} level Level of the tile\n * @param {Number} x x coordinate of the tile\n * @param {Number} y y coordinate of the tile\n */\n getContext2D: function (level, x, y) {\n var context = null;\n if (level >= this.minLevel && level <= this.maxLevel) {\n context = this.levels[level].context2D;\n }\n return context;\n },\n\n // private\n //\n // Builds the differents levels of the pyramid if possible\n // (i.e. if canvas API enabled and no canvas tainting issue).\n _buildLevels: function () {\n var levels = [{\n url: this._image.src,\n /* IE8 fix since it has no naturalWidth and naturalHeight */\n width: Object.prototype.hasOwnProperty.call(this._image, 'naturalWidth') ? this._image.naturalWidth : this._image.width,\n height: Object.prototype.hasOwnProperty.call(this._image, 'naturalHeight') ? this._image.naturalHeight : this._image.height\n }];\n\n if (!this.buildPyramid || !$.supportsCanvas || !this.useCanvas) {\n // We don't need the image anymore. Allows it to be GC.\n delete this._image;\n return levels;\n }\n\n /* IE8 fix since it has no naturalWidth and naturalHeight */\n var currentWidth = Object.prototype.hasOwnProperty.call(this._image, 'naturalWidth') ? this._image.naturalWidth : this._image.width;\n var currentHeight = Object.prototype.hasOwnProperty.call(this._image, 'naturalHeight') ? this._image.naturalHeight : this._image.height;\n\n\n var bigCanvas = document.createElement(\"canvas\");\n var bigContext = bigCanvas.getContext(\"2d\");\n\n bigCanvas.width = currentWidth;\n bigCanvas.height = currentHeight;\n bigContext.drawImage(this._image, 0, 0, currentWidth, currentHeight);\n // We cache the context of the highest level because the browser\n // is a lot faster at downsampling something it already has\n // downsampled before.\n levels[0].context2D = bigContext;\n // We don't need the image anymore. Allows it to be GC.\n delete this._image;\n\n if ($.isCanvasTainted(bigCanvas)) {\n // If the canvas is tainted, we can't compute the pyramid.\n return levels;\n }\n\n // We build smaller levels until either width or height becomes\n // 1 pixel wide.\n while (currentWidth >= 2 && currentHeight >= 2) {\n currentWidth = Math.floor(currentWidth / 2);\n currentHeight = Math.floor(currentHeight / 2);\n var smallCanvas = document.createElement(\"canvas\");\n var smallContext = smallCanvas.getContext(\"2d\");\n smallCanvas.width = currentWidth;\n smallCanvas.height = currentHeight;\n smallContext.drawImage(bigCanvas, 0, 0, currentWidth, currentHeight);\n\n levels.splice(0, 0, {\n context2D: smallContext,\n width: currentWidth,\n height: currentHeight\n });\n\n bigCanvas = smallCanvas;\n bigContext = smallContext;\n }\n return levels;\n }\n });\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - TileSourceCollection\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n// deprecated\n$.TileSourceCollection = function(tileSize, tileSources, rows, layout) {\n $.console.error('TileSourceCollection is deprecated; use World instead');\n};\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Button\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * An enumeration of button states\n * @member ButtonState\n * @memberof OpenSeadragon\n * @static\n * @type {Object}\n * @property {Number} REST\n * @property {Number} GROUP\n * @property {Number} HOVER\n * @property {Number} DOWN\n */\n$.ButtonState = {\n REST: 0,\n GROUP: 1,\n HOVER: 2,\n DOWN: 3\n};\n\n/**\n * @class Button\n * @classdesc Manages events, hover states for individual buttons, tool-tips, as well\n * as fading the buttons out when the user has not interacted with them\n * for a specified period.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @param {Object} options\n * @param {Element} [options.element=null] Element to use as the button. If not specified, an HTML <div> element is created.\n * @param {String} [options.tooltip=null] Provides context help for the button when the\n * user hovers over it.\n * @param {String} [options.srcRest=null] URL of image to use in 'rest' state.\n * @param {String} [options.srcGroup=null] URL of image to use in 'up' state.\n * @param {String} [options.srcHover=null] URL of image to use in 'hover' state.\n * @param {String} [options.srcDown=null] URL of image to use in 'down' state.\n * @param {Number} [options.fadeDelay=0] How long to wait before fading.\n * @param {Number} [options.fadeLength=2000] How long should it take to fade the button.\n * @param {OpenSeadragon.EventHandler} [options.onPress=null] Event handler callback for {@link OpenSeadragon.Button.event:press}.\n * @param {OpenSeadragon.EventHandler} [options.onRelease=null] Event handler callback for {@link OpenSeadragon.Button.event:release}.\n * @param {OpenSeadragon.EventHandler} [options.onClick=null] Event handler callback for {@link OpenSeadragon.Button.event:click}.\n * @param {OpenSeadragon.EventHandler} [options.onEnter=null] Event handler callback for {@link OpenSeadragon.Button.event:enter}.\n * @param {OpenSeadragon.EventHandler} [options.onExit=null] Event handler callback for {@link OpenSeadragon.Button.event:exit}.\n * @param {OpenSeadragon.EventHandler} [options.onFocus=null] Event handler callback for {@link OpenSeadragon.Button.event:focus}.\n * @param {OpenSeadragon.EventHandler} [options.onBlur=null] Event handler callback for {@link OpenSeadragon.Button.event:blur}.\n */\n$.Button = function( options ) {\n\n var _this = this;\n\n $.EventSource.call( this );\n\n $.extend( true, this, {\n\n tooltip: null,\n srcRest: null,\n srcGroup: null,\n srcHover: null,\n srcDown: null,\n clickTimeThreshold: $.DEFAULT_SETTINGS.clickTimeThreshold,\n clickDistThreshold: $.DEFAULT_SETTINGS.clickDistThreshold,\n /**\n * How long to wait before fading.\n * @member {Number} fadeDelay\n * @memberof OpenSeadragon.Button#\n */\n fadeDelay: 0,\n /**\n * How long should it take to fade the button.\n * @member {Number} fadeLength\n * @memberof OpenSeadragon.Button#\n */\n fadeLength: 2000,\n onPress: null,\n onRelease: null,\n onClick: null,\n onEnter: null,\n onExit: null,\n onFocus: null,\n onBlur: null\n\n }, options );\n\n /**\n * The button element.\n * @member {Element} element\n * @memberof OpenSeadragon.Button#\n */\n this.element = options.element || $.makeNeutralElement(\"div\");\n\n //if the user has specified the element to bind the control to explicitly\n //then do not add the default control images\n if ( !options.element ) {\n this.imgRest = $.makeTransparentImage( this.srcRest );\n this.imgGroup = $.makeTransparentImage( this.srcGroup );\n this.imgHover = $.makeTransparentImage( this.srcHover );\n this.imgDown = $.makeTransparentImage( this.srcDown );\n\n this.imgRest.alt =\n this.imgGroup.alt =\n this.imgHover.alt =\n this.imgDown.alt =\n this.tooltip;\n\n this.element.style.position = \"relative\";\n $.setElementTouchActionNone( this.element );\n\n this.imgGroup.style.position =\n this.imgHover.style.position =\n this.imgDown.style.position =\n \"absolute\";\n\n this.imgGroup.style.top =\n this.imgHover.style.top =\n this.imgDown.style.top =\n \"0px\";\n\n this.imgGroup.style.left =\n this.imgHover.style.left =\n this.imgDown.style.left =\n \"0px\";\n\n this.imgHover.style.visibility =\n this.imgDown.style.visibility =\n \"hidden\";\n\n if ($.Browser.vendor == $.BROWSERS.FIREFOX && $.Browser.version < 3) {\n this.imgGroup.style.top =\n this.imgHover.style.top =\n this.imgDown.style.top =\n \"\";\n }\n\n this.element.appendChild( this.imgRest );\n this.element.appendChild( this.imgGroup );\n this.element.appendChild( this.imgHover );\n this.element.appendChild( this.imgDown );\n }\n\n\n this.addHandler(\"press\", this.onPress);\n this.addHandler(\"release\", this.onRelease);\n this.addHandler(\"click\", this.onClick);\n this.addHandler(\"enter\", this.onEnter);\n this.addHandler(\"exit\", this.onExit);\n this.addHandler(\"focus\", this.onFocus);\n this.addHandler(\"blur\", this.onBlur);\n\n /**\n * The button's current state.\n * @member {OpenSeadragon.ButtonState} currentState\n * @memberof OpenSeadragon.Button#\n */\n this.currentState = $.ButtonState.GROUP;\n\n // When the button last began to fade.\n this.fadeBeginTime = null;\n // Whether this button should fade after user stops interacting with the viewport.\n this.shouldFade = false;\n\n this.element.style.display = \"inline-block\";\n this.element.style.position = \"relative\";\n this.element.title = this.tooltip;\n\n /**\n * Tracks mouse/touch/key events on the button.\n * @member {OpenSeadragon.MouseTracker} tracker\n * @memberof OpenSeadragon.Button#\n */\n this.tracker = new $.MouseTracker({\n\n element: this.element,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n\n enterHandler: function( event ) {\n if ( event.insideElementPressed ) {\n inTo( _this, $.ButtonState.DOWN );\n /**\n * Raised when the cursor enters the Button element.\n *\n * @event enter\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"enter\", { originalEvent: event.originalEvent } );\n } else if ( !event.buttonDownAny ) {\n inTo( _this, $.ButtonState.HOVER );\n }\n },\n\n focusHandler: function ( event ) {\n this.enterHandler( event );\n /**\n * Raised when the Button element receives focus.\n *\n * @event focus\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"focus\", { originalEvent: event.originalEvent } );\n },\n\n exitHandler: function( event ) {\n outTo( _this, $.ButtonState.GROUP );\n if ( event.insideElementPressed ) {\n /**\n * Raised when the cursor leaves the Button element.\n *\n * @event exit\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"exit\", { originalEvent: event.originalEvent } );\n }\n },\n\n blurHandler: function ( event ) {\n this.exitHandler( event );\n /**\n * Raised when the Button element loses focus.\n *\n * @event blur\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"blur\", { originalEvent: event.originalEvent } );\n },\n\n pressHandler: function ( event ) {\n inTo( _this, $.ButtonState.DOWN );\n /**\n * Raised when a mouse button is pressed or touch occurs in the Button element.\n *\n * @event press\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"press\", { originalEvent: event.originalEvent } );\n },\n\n releaseHandler: function( event ) {\n if ( event.insideElementPressed && event.insideElementReleased ) {\n outTo( _this, $.ButtonState.HOVER );\n /**\n * Raised when the mouse button is released or touch ends in the Button element.\n *\n * @event release\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"release\", { originalEvent: event.originalEvent } );\n } else if ( event.insideElementPressed ) {\n outTo( _this, $.ButtonState.GROUP );\n } else {\n inTo( _this, $.ButtonState.HOVER );\n }\n },\n\n clickHandler: function( event ) {\n if ( event.quick ) {\n /**\n * Raised when a mouse button is pressed and released or touch is initiated and ended in the Button element within the time and distance threshold.\n *\n * @event click\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent(\"click\", { originalEvent: event.originalEvent });\n }\n },\n\n keyHandler: function( event ){\n //console.log( \"%s : handling key %s!\", _this.tooltip, event.keyCode);\n if( 13 === event.keyCode ){\n /***\n * Raised when a mouse button is pressed and released or touch is initiated and ended in the Button element within the time and distance threshold.\n *\n * @event click\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"click\", { originalEvent: event.originalEvent } );\n /***\n * Raised when the mouse button is released or touch ends in the Button element.\n *\n * @event release\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"release\", { originalEvent: event.originalEvent } );\n return false;\n }\n return true;\n }\n\n });\n\n outTo( this, $.ButtonState.REST );\n};\n\n$.extend( $.Button.prototype, $.EventSource.prototype, /** @lends OpenSeadragon.Button.prototype */{\n\n /**\n * TODO: Determine what this function is intended to do and if it's actually\n * useful as an API point.\n * @function\n */\n notifyGroupEnter: function() {\n inTo( this, $.ButtonState.GROUP );\n },\n\n /**\n * TODO: Determine what this function is intended to do and if it's actually\n * useful as an API point.\n * @function\n */\n notifyGroupExit: function() {\n outTo( this, $.ButtonState.REST );\n },\n\n /**\n * @function\n */\n disable: function(){\n this.notifyGroupExit();\n this.element.disabled = true;\n $.setElementOpacity( this.element, 0.2, true );\n },\n\n /**\n * @function\n */\n enable: function(){\n this.element.disabled = false;\n $.setElementOpacity( this.element, 1.0, true );\n this.notifyGroupEnter();\n }\n\n});\n\n\nfunction scheduleFade( button ) {\n $.requestAnimationFrame(function(){\n updateFade( button );\n });\n}\n\nfunction updateFade( button ) {\n var currentTime,\n deltaTime,\n opacity;\n\n if ( button.shouldFade ) {\n currentTime = $.now();\n deltaTime = currentTime - button.fadeBeginTime;\n opacity = 1.0 - deltaTime / button.fadeLength;\n opacity = Math.min( 1.0, opacity );\n opacity = Math.max( 0.0, opacity );\n\n if( button.imgGroup ){\n $.setElementOpacity( button.imgGroup, opacity, true );\n }\n if ( opacity > 0 ) {\n // fade again\n scheduleFade( button );\n }\n }\n}\n\nfunction beginFading( button ) {\n button.shouldFade = true;\n button.fadeBeginTime = $.now() + button.fadeDelay;\n window.setTimeout( function(){\n scheduleFade( button );\n }, button.fadeDelay );\n}\n\nfunction stopFading( button ) {\n button.shouldFade = false;\n if( button.imgGroup ){\n $.setElementOpacity( button.imgGroup, 1.0, true );\n }\n}\n\nfunction inTo( button, newState ) {\n\n if( button.element.disabled ){\n return;\n }\n\n if ( newState >= $.ButtonState.GROUP &&\n button.currentState == $.ButtonState.REST ) {\n stopFading( button );\n button.currentState = $.ButtonState.GROUP;\n }\n\n if ( newState >= $.ButtonState.HOVER &&\n button.currentState == $.ButtonState.GROUP ) {\n if( button.imgHover ){\n button.imgHover.style.visibility = \"\";\n }\n button.currentState = $.ButtonState.HOVER;\n }\n\n if ( newState >= $.ButtonState.DOWN &&\n button.currentState == $.ButtonState.HOVER ) {\n if( button.imgDown ){\n button.imgDown.style.visibility = \"\";\n }\n button.currentState = $.ButtonState.DOWN;\n }\n}\n\n\nfunction outTo( button, newState ) {\n\n if( button.element.disabled ){\n return;\n }\n\n if ( newState <= $.ButtonState.HOVER &&\n button.currentState == $.ButtonState.DOWN ) {\n if( button.imgDown ){\n button.imgDown.style.visibility = \"hidden\";\n }\n button.currentState = $.ButtonState.HOVER;\n }\n\n if ( newState <= $.ButtonState.GROUP &&\n button.currentState == $.ButtonState.HOVER ) {\n if( button.imgHover ){\n button.imgHover.style.visibility = \"hidden\";\n }\n button.currentState = $.ButtonState.GROUP;\n }\n\n if ( newState <= $.ButtonState.REST &&\n button.currentState == $.ButtonState.GROUP ) {\n beginFading( button );\n button.currentState = $.ButtonState.REST;\n }\n}\n\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ButtonGroup\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n/**\n * @class ButtonGroup\n * @classdesc Manages events on groups of buttons.\n *\n * @memberof OpenSeadragon\n * @param {Object} options - A dictionary of settings applied against the entire group of buttons.\n * @param {Array} options.buttons Array of buttons\n * @param {Element} [options.element] Element to use as the container\n **/\n$.ButtonGroup = function( options ) {\n\n $.extend( true, this, {\n /**\n * An array containing the buttons themselves.\n * @member {Array} buttons\n * @memberof OpenSeadragon.ButtonGroup#\n */\n buttons: [],\n clickTimeThreshold: $.DEFAULT_SETTINGS.clickTimeThreshold,\n clickDistThreshold: $.DEFAULT_SETTINGS.clickDistThreshold,\n labelText: \"\"\n }, options );\n\n // copy the button elements TODO: Why?\n var buttons = this.buttons.concat([]),\n _this = this,\n i;\n\n /**\n * The shared container for the buttons.\n * @member {Element} element\n * @memberof OpenSeadragon.ButtonGroup#\n */\n this.element = options.element || $.makeNeutralElement( \"div\" );\n\n // TODO What if there IS an options.group specified?\n if( !options.group ){\n this.label = $.makeNeutralElement( \"label\" );\n //TODO: support labels for ButtonGroups\n //this.label.innerHTML = this.labelText;\n this.element.style.display = \"inline-block\";\n this.element.appendChild( this.label );\n for ( i = 0; i < buttons.length; i++ ) {\n this.element.appendChild( buttons[ i ].element );\n }\n }\n\n $.setElementTouchActionNone( this.element );\n\n /**\n * Tracks mouse/touch/key events accross the group of buttons.\n * @member {OpenSeadragon.MouseTracker} tracker\n * @memberof OpenSeadragon.ButtonGroup#\n */\n this.tracker = new $.MouseTracker({\n element: this.element,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n enterHandler: function ( event ) {\n var i;\n for ( i = 0; i < _this.buttons.length; i++ ) {\n _this.buttons[ i ].notifyGroupEnter();\n }\n },\n exitHandler: function ( event ) {\n var i;\n if ( !event.insideElementPressed ) {\n for ( i = 0; i < _this.buttons.length; i++ ) {\n _this.buttons[ i ].notifyGroupExit();\n }\n }\n },\n });\n};\n\n/** @lends OpenSeadragon.ButtonGroup.prototype */\n$.ButtonGroup.prototype = {\n\n /**\n * TODO: Figure out why this is used on the public API and if a more useful\n * api can be created.\n * @function\n * @private\n */\n emulateEnter: function() {\n this.tracker.enterHandler( { eventSource: this.tracker } );\n },\n\n /**\n * TODO: Figure out why this is used on the public API and if a more useful\n * api can be created.\n * @function\n * @private\n */\n emulateExit: function() {\n this.tracker.exitHandler( { eventSource: this.tracker } );\n }\n};\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Rect\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n/**\n * @class Rect\n * @classdesc A Rectangle is described by it top left coordinates (x, y), width,\n * height and degrees of rotation around (x, y).\n * Note that the coordinate system used is the one commonly used with images:\n * x increases when going to the right\n * y increases when going to the bottom\n * degrees increases clockwise with 0 being the horizontal\n *\n * The constructor normalizes the rectangle to always have 0 <= degrees < 90\n *\n * @memberof OpenSeadragon\n * @param {Number} [x=0] The vector component 'x'.\n * @param {Number} [y=0] The vector component 'y'.\n * @param {Number} [width=0] The vector component 'width'.\n * @param {Number} [height=0] The vector component 'height'.\n * @param {Number} [degrees=0] Rotation of the rectangle around (x,y) in degrees.\n */\n$.Rect = function(x, y, width, height, degrees) {\n /**\n * The vector component 'x'.\n * @member {Number} x\n * @memberof OpenSeadragon.Rect#\n */\n this.x = typeof (x) === \"number\" ? x : 0;\n /**\n * The vector component 'y'.\n * @member {Number} y\n * @memberof OpenSeadragon.Rect#\n */\n this.y = typeof (y) === \"number\" ? y : 0;\n /**\n * The vector component 'width'.\n * @member {Number} width\n * @memberof OpenSeadragon.Rect#\n */\n this.width = typeof (width) === \"number\" ? width : 0;\n /**\n * The vector component 'height'.\n * @member {Number} height\n * @memberof OpenSeadragon.Rect#\n */\n this.height = typeof (height) === \"number\" ? height : 0;\n\n this.degrees = typeof (degrees) === \"number\" ? degrees : 0;\n\n // Normalizes the rectangle.\n this.degrees = $.positiveModulo(this.degrees, 360);\n var newTopLeft, newWidth;\n if (this.degrees >= 270) {\n newTopLeft = this.getTopRight();\n this.x = newTopLeft.x;\n this.y = newTopLeft.y;\n newWidth = this.height;\n this.height = this.width;\n this.width = newWidth;\n this.degrees -= 270;\n } else if (this.degrees >= 180) {\n newTopLeft = this.getBottomRight();\n this.x = newTopLeft.x;\n this.y = newTopLeft.y;\n this.degrees -= 180;\n } else if (this.degrees >= 90) {\n newTopLeft = this.getBottomLeft();\n this.x = newTopLeft.x;\n this.y = newTopLeft.y;\n newWidth = this.height;\n this.height = this.width;\n this.width = newWidth;\n this.degrees -= 90;\n }\n};\n\n/**\n * Builds a rectangle having the 3 specified points as summits.\n * @static\n * @memberof OpenSeadragon.Rect\n * @param {OpenSeadragon.Point} topLeft\n * @param {OpenSeadragon.Point} topRight\n * @param {OpenSeadragon.Point} bottomLeft\n * @returns {OpenSeadragon.Rect}\n */\n$.Rect.fromSummits = function(topLeft, topRight, bottomLeft) {\n var width = topLeft.distanceTo(topRight);\n var height = topLeft.distanceTo(bottomLeft);\n var diff = topRight.minus(topLeft);\n var radians = Math.atan(diff.y / diff.x);\n if (diff.x < 0) {\n radians += Math.PI;\n } else if (diff.y < 0) {\n radians += 2 * Math.PI;\n }\n return new $.Rect(\n topLeft.x,\n topLeft.y,\n width,\n height,\n radians / Math.PI * 180);\n};\n\n/** @lends OpenSeadragon.Rect.prototype */\n$.Rect.prototype = {\n /**\n * @function\n * @returns {OpenSeadragon.Rect} a duplicate of this Rect\n */\n clone: function() {\n return new $.Rect(\n this.x,\n this.y,\n this.width,\n this.height,\n this.degrees);\n },\n\n /**\n * The aspect ratio is simply the ratio of width to height.\n * @function\n * @returns {Number} The ratio of width to height.\n */\n getAspectRatio: function() {\n return this.width / this.height;\n },\n\n /**\n * Provides the coordinates of the upper-left corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the upper-left corner of\n * the rectangle.\n */\n getTopLeft: function() {\n return new $.Point(\n this.x,\n this.y\n );\n },\n\n /**\n * Provides the coordinates of the bottom-right corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the bottom-right corner of\n * the rectangle.\n */\n getBottomRight: function() {\n return new $.Point(this.x + this.width, this.y + this.height)\n .rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Provides the coordinates of the top-right corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the top-right corner of\n * the rectangle.\n */\n getTopRight: function() {\n return new $.Point(this.x + this.width, this.y)\n .rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Provides the coordinates of the bottom-left corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the bottom-left corner of\n * the rectangle.\n */\n getBottomLeft: function() {\n return new $.Point(this.x, this.y + this.height)\n .rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Computes the center of the rectangle.\n * @function\n * @returns {OpenSeadragon.Point} The center of the rectangle as represented\n * as represented by a 2-dimensional vector (x,y)\n */\n getCenter: function() {\n return new $.Point(\n this.x + this.width / 2.0,\n this.y + this.height / 2.0\n ).rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Returns the width and height component as a vector OpenSeadragon.Point\n * @function\n * @returns {OpenSeadragon.Point} The 2 dimensional vector representing the\n * the width and height of the rectangle.\n */\n getSize: function() {\n return new $.Point(this.width, this.height);\n },\n\n /**\n * Determines if two Rectangles have equivalent components.\n * @function\n * @param {OpenSeadragon.Rect} rectangle The Rectangle to compare to.\n * @return {Boolean} 'true' if all components are equal, otherwise 'false'.\n */\n equals: function(other) {\n return (other instanceof $.Rect) &&\n this.x === other.x &&\n this.y === other.y &&\n this.width === other.width &&\n this.height === other.height &&\n this.degrees === other.degrees;\n },\n\n /**\n * Multiply all dimensions (except degrees) in this Rect by a factor and\n * return a new Rect.\n * @function\n * @param {Number} factor The factor to multiply vector components.\n * @returns {OpenSeadragon.Rect} A new rect representing the multiplication\n * of the vector components by the factor\n */\n times: function(factor) {\n return new $.Rect(\n this.x * factor,\n this.y * factor,\n this.width * factor,\n this.height * factor,\n this.degrees);\n },\n\n /**\n * Translate/move this Rect by a vector and return new Rect.\n * @function\n * @param {OpenSeadragon.Point} delta The translation vector.\n * @returns {OpenSeadragon.Rect} A new rect with altered position\n */\n translate: function(delta) {\n return new $.Rect(\n this.x + delta.x,\n this.y + delta.y,\n this.width,\n this.height,\n this.degrees);\n },\n\n /**\n * Returns the smallest rectangle that will contain this and the given\n * rectangle bounding boxes.\n * @param {OpenSeadragon.Rect} rect\n * @return {OpenSeadragon.Rect} The new rectangle.\n */\n union: function(rect) {\n var thisBoundingBox = this.getBoundingBox();\n var otherBoundingBox = rect.getBoundingBox();\n\n var left = Math.min(thisBoundingBox.x, otherBoundingBox.x);\n var top = Math.min(thisBoundingBox.y, otherBoundingBox.y);\n var right = Math.max(\n thisBoundingBox.x + thisBoundingBox.width,\n otherBoundingBox.x + otherBoundingBox.width);\n var bottom = Math.max(\n thisBoundingBox.y + thisBoundingBox.height,\n otherBoundingBox.y + otherBoundingBox.height);\n\n return new $.Rect(\n left,\n top,\n right - left,\n bottom - top);\n },\n\n /**\n * Returns the bounding box of the intersection of this rectangle with the\n * given rectangle.\n * @param {OpenSeadragon.Rect} rect\n * @return {OpenSeadragon.Rect} the bounding box of the intersection\n * or null if the rectangles don't intersect.\n */\n intersection: function(rect) {\n // Simplified version of Weiler Atherton clipping algorithm\n // https://en.wikipedia.org/wiki/Weiler%E2%80%93Atherton_clipping_algorithm\n // Because we just want the bounding box of the intersection,\n // we can just compute the bounding box of:\n // 1. all the summits of this which are inside rect\n // 2. all the summits of rect which are inside this\n // 3. all the intersections of rect and this\n var EPSILON = 0.0000000001;\n\n var intersectionPoints = [];\n\n var thisTopLeft = this.getTopLeft();\n if (rect.containsPoint(thisTopLeft, EPSILON)) {\n intersectionPoints.push(thisTopLeft);\n }\n var thisTopRight = this.getTopRight();\n if (rect.containsPoint(thisTopRight, EPSILON)) {\n intersectionPoints.push(thisTopRight);\n }\n var thisBottomLeft = this.getBottomLeft();\n if (rect.containsPoint(thisBottomLeft, EPSILON)) {\n intersectionPoints.push(thisBottomLeft);\n }\n var thisBottomRight = this.getBottomRight();\n if (rect.containsPoint(thisBottomRight, EPSILON)) {\n intersectionPoints.push(thisBottomRight);\n }\n\n var rectTopLeft = rect.getTopLeft();\n if (this.containsPoint(rectTopLeft, EPSILON)) {\n intersectionPoints.push(rectTopLeft);\n }\n var rectTopRight = rect.getTopRight();\n if (this.containsPoint(rectTopRight, EPSILON)) {\n intersectionPoints.push(rectTopRight);\n }\n var rectBottomLeft = rect.getBottomLeft();\n if (this.containsPoint(rectBottomLeft, EPSILON)) {\n intersectionPoints.push(rectBottomLeft);\n }\n var rectBottomRight = rect.getBottomRight();\n if (this.containsPoint(rectBottomRight, EPSILON)) {\n intersectionPoints.push(rectBottomRight);\n }\n\n var thisSegments = this._getSegments();\n var rectSegments = rect._getSegments();\n for (var i = 0; i < thisSegments.length; i++) {\n var thisSegment = thisSegments[i];\n for (var j = 0; j < rectSegments.length; j++) {\n var rectSegment = rectSegments[j];\n var intersect = getIntersection(thisSegment[0], thisSegment[1],\n rectSegment[0], rectSegment[1]);\n if (intersect) {\n intersectionPoints.push(intersect);\n }\n }\n }\n\n // Get intersection point of segments [a,b] and [c,d]\n function getIntersection(a, b, c, d) {\n // http://stackoverflow.com/a/1968345/1440403\n var abVector = b.minus(a);\n var cdVector = d.minus(c);\n\n var denom = -cdVector.x * abVector.y + abVector.x * cdVector.y;\n if (denom === 0) {\n return null;\n }\n\n var s = (abVector.x * (a.y - c.y) - abVector.y * (a.x - c.x)) / denom;\n var t = (cdVector.x * (a.y - c.y) - cdVector.y * (a.x - c.x)) / denom;\n\n if (-EPSILON <= s && s <= 1 - EPSILON &&\n -EPSILON <= t && t <= 1 - EPSILON) {\n return new $.Point(a.x + t * abVector.x, a.y + t * abVector.y);\n }\n return null;\n }\n\n if (intersectionPoints.length === 0) {\n return null;\n }\n\n var minX = intersectionPoints[0].x;\n var maxX = intersectionPoints[0].x;\n var minY = intersectionPoints[0].y;\n var maxY = intersectionPoints[0].y;\n for (var k = 1; k < intersectionPoints.length; k++) {\n var point = intersectionPoints[k];\n if (point.x < minX) {\n minX = point.x;\n }\n if (point.x > maxX) {\n maxX = point.x;\n }\n if (point.y < minY) {\n minY = point.y;\n }\n if (point.y > maxY) {\n maxY = point.y;\n }\n }\n return new $.Rect(minX, minY, maxX - minX, maxY - minY);\n },\n\n // private\n _getSegments: function() {\n var topLeft = this.getTopLeft();\n var topRight = this.getTopRight();\n var bottomLeft = this.getBottomLeft();\n var bottomRight = this.getBottomRight();\n return [[topLeft, topRight],\n [topRight, bottomRight],\n [bottomRight, bottomLeft],\n [bottomLeft, topLeft]];\n },\n\n /**\n * Rotates a rectangle around a point.\n * @function\n * @param {Number} degrees The angle in degrees to rotate.\n * @param {OpenSeadragon.Point} [pivot] The point about which to rotate.\n * Defaults to the center of the rectangle.\n * @return {OpenSeadragon.Rect}\n */\n rotate: function(degrees, pivot) {\n degrees = $.positiveModulo(degrees, 360);\n if (degrees === 0) {\n return this.clone();\n }\n\n pivot = pivot || this.getCenter();\n var newTopLeft = this.getTopLeft().rotate(degrees, pivot);\n var newTopRight = this.getTopRight().rotate(degrees, pivot);\n\n var diff = newTopRight.minus(newTopLeft);\n // Handle floating point error\n diff = diff.apply(function(x) {\n var EPSILON = 1e-15;\n return Math.abs(x) < EPSILON ? 0 : x;\n });\n var radians = Math.atan(diff.y / diff.x);\n if (diff.x < 0) {\n radians += Math.PI;\n } else if (diff.y < 0) {\n radians += 2 * Math.PI;\n }\n return new $.Rect(\n newTopLeft.x,\n newTopLeft.y,\n this.width,\n this.height,\n radians / Math.PI * 180);\n },\n\n /**\n * Retrieves the smallest horizontal (degrees=0) rectangle which contains\n * this rectangle.\n * @returns {OpenSeadragon.Rect}\n */\n getBoundingBox: function() {\n if (this.degrees === 0) {\n return this.clone();\n }\n var topLeft = this.getTopLeft();\n var topRight = this.getTopRight();\n var bottomLeft = this.getBottomLeft();\n var bottomRight = this.getBottomRight();\n var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);\n var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);\n var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);\n var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);\n return new $.Rect(\n minX,\n minY,\n maxX - minX,\n maxY - minY);\n },\n\n /**\n * Retrieves the smallest horizontal (degrees=0) rectangle which contains\n * this rectangle and has integers x, y, width and height\n * @returns {OpenSeadragon.Rect}\n */\n getIntegerBoundingBox: function() {\n var boundingBox = this.getBoundingBox();\n var x = Math.floor(boundingBox.x);\n var y = Math.floor(boundingBox.y);\n var width = Math.ceil(boundingBox.width + boundingBox.x - x);\n var height = Math.ceil(boundingBox.height + boundingBox.y - y);\n return new $.Rect(x, y, width, height);\n },\n\n /**\n * Determines whether a point is inside this rectangle (edge included).\n * @function\n * @param {OpenSeadragon.Point} point\n * @param {Number} [epsilon=0] the margin of error allowed\n * @returns {Boolean} true if the point is inside this rectangle, false\n * otherwise.\n */\n containsPoint: function(point, epsilon) {\n epsilon = epsilon || 0;\n\n // See http://stackoverflow.com/a/2752754/1440403 for explanation\n var topLeft = this.getTopLeft();\n var topRight = this.getTopRight();\n var bottomLeft = this.getBottomLeft();\n var topDiff = topRight.minus(topLeft);\n var leftDiff = bottomLeft.minus(topLeft);\n\n return ((point.x - topLeft.x) * topDiff.x +\n (point.y - topLeft.y) * topDiff.y >= -epsilon) &&\n\n ((point.x - topRight.x) * topDiff.x +\n (point.y - topRight.y) * topDiff.y <= epsilon) &&\n\n ((point.x - topLeft.x) * leftDiff.x +\n (point.y - topLeft.y) * leftDiff.y >= -epsilon) &&\n\n ((point.x - bottomLeft.x) * leftDiff.x +\n (point.y - bottomLeft.y) * leftDiff.y <= epsilon);\n },\n\n /**\n * Provides a string representation of the rectangle which is useful for\n * debugging.\n * @function\n * @returns {String} A string representation of the rectangle.\n */\n toString: function() {\n return \"[\" +\n (Math.round(this.x * 100) / 100) + \", \" +\n (Math.round(this.y * 100) / 100) + \", \" +\n (Math.round(this.width * 100) / 100) + \"x\" +\n (Math.round(this.height * 100) / 100) + \", \" +\n (Math.round(this.degrees * 100) / 100) + \"deg\" +\n \"]\";\n }\n};\n\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - ReferenceStrip\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function ( $ ) {\n\n// dictionary from id to private properties\nvar THIS = {};\n\n/**\n * The CollectionDrawer is a reimplementation if the Drawer API that\n * focuses on allowing a viewport to be redefined as a collection\n * of smaller viewports, defined by a clear number of rows and / or\n * columns of which each item in the matrix of viewports has its own\n * source.\n *\n * This idea is a reexpression of the idea of dzi collections\n * which allows a clearer algorithm to reuse the tile sources already\n * supported by OpenSeadragon, in heterogenious or homogenious\n * sequences just like mixed groups already supported by the viewer\n * for the purpose of image sequnces.\n *\n * TODO: The difficult part of this feature is figuring out how to express\n * this functionality as a combination of the functionality already\n * provided by Drawer, Viewport, TileSource, and Navigator. It may\n * require better abstraction at those points in order to effeciently\n * reuse those paradigms.\n */\n/**\n * @class ReferenceStrip\n * @memberof OpenSeadragon\n * @param {Object} options\n */\n$.ReferenceStrip = function ( options ) {\n\n var _this = this,\n viewer = options.viewer,\n viewerSize = $.getElementSize( viewer.element ),\n element,\n style,\n i;\n\n //We may need to create a new element and id if they did not\n //provide the id for the existing element\n if ( !options.id ) {\n options.id = 'referencestrip-' + $.now();\n this.element = $.makeNeutralElement( \"div\" );\n this.element.id = options.id;\n this.element.className = 'referencestrip';\n }\n\n options = $.extend( true, {\n sizeRatio: $.DEFAULT_SETTINGS.referenceStripSizeRatio,\n position: $.DEFAULT_SETTINGS.referenceStripPosition,\n scroll: $.DEFAULT_SETTINGS.referenceStripScroll,\n clickTimeThreshold: $.DEFAULT_SETTINGS.clickTimeThreshold\n }, options, {\n //required overrides\n element: this.element,\n //These need to be overridden to prevent recursion since\n //the navigator is a viewer and a viewer has a navigator\n showNavigator: false,\n mouseNavEnabled: false,\n showNavigationControl: false,\n showSequenceControl: false\n } );\n\n $.extend( this, options );\n //Private state properties\n THIS[this.id] = {\n \"animating\": false\n };\n\n this.minPixelRatio = this.viewer.minPixelRatio;\n\n style = this.element.style;\n style.marginTop = '0px';\n style.marginRight = '0px';\n style.marginBottom = '0px';\n style.marginLeft = '0px';\n style.left = '0px';\n style.bottom = '0px';\n style.border = '0px';\n style.background = '#000';\n style.position = 'relative';\n\n $.setElementTouchActionNone( this.element );\n\n $.setElementOpacity( this.element, 0.8 );\n\n this.viewer = viewer;\n this.innerTracker = new $.MouseTracker( {\n element: this.element,\n dragHandler: $.delegate( this, onStripDrag ),\n scrollHandler: $.delegate( this, onStripScroll ),\n enterHandler: $.delegate( this, onStripEnter ),\n exitHandler: $.delegate( this, onStripExit ),\n keyDownHandler: $.delegate( this, onKeyDown ),\n keyHandler: $.delegate( this, onKeyPress )\n } );\n\n //Controls the position and orientation of the reference strip and sets the\n //appropriate width and height\n if ( options.width && options.height ) {\n this.element.style.width = options.width + 'px';\n this.element.style.height = options.height + 'px';\n viewer.addControl(\n this.element,\n { anchor: $.ControlAnchor.BOTTOM_LEFT }\n );\n } else {\n if ( \"horizontal\" == options.scroll ) {\n this.element.style.width = (\n viewerSize.x *\n options.sizeRatio *\n viewer.tileSources.length\n ) + ( 12 * viewer.tileSources.length ) + 'px';\n\n this.element.style.height = (\n viewerSize.y *\n options.sizeRatio\n ) + 'px';\n\n viewer.addControl(\n this.element,\n { anchor: $.ControlAnchor.BOTTOM_LEFT }\n );\n } else {\n this.element.style.height = (\n viewerSize.y *\n options.sizeRatio *\n viewer.tileSources.length\n ) + ( 12 * viewer.tileSources.length ) + 'px';\n\n this.element.style.width = (\n viewerSize.x *\n options.sizeRatio\n ) + 'px';\n\n viewer.addControl(\n this.element,\n { anchor: $.ControlAnchor.TOP_LEFT }\n );\n\n }\n }\n\n this.panelWidth = ( viewerSize.x * this.sizeRatio ) + 8;\n this.panelHeight = ( viewerSize.y * this.sizeRatio ) + 8;\n this.panels = [];\n this.miniViewers = {};\n\n /*jshint loopfunc:true*/\n for ( i = 0; i < viewer.tileSources.length; i++ ) {\n\n element = $.makeNeutralElement( 'div' );\n element.id = this.element.id + \"-\" + i;\n\n element.style.width = _this.panelWidth + 'px';\n element.style.height = _this.panelHeight + 'px';\n element.style.display = 'inline';\n element.style.float = 'left'; //Webkit\n element.style.cssFloat = 'left'; //Firefox\n element.style.styleFloat = 'left'; //IE\n element.style.padding = '2px';\n $.setElementTouchActionNone( element );\n\n element.innerTracker = new $.MouseTracker( {\n element: element,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n pressHandler: function ( event ) {\n event.eventSource.dragging = $.now();\n },\n releaseHandler: function ( event ) {\n var tracker = event.eventSource,\n id = tracker.element.id,\n page = Number( id.split( '-' )[2] ),\n now = $.now();\n\n if ( event.insideElementPressed &&\n event.insideElementReleased &&\n tracker.dragging &&\n ( now - tracker.dragging ) < tracker.clickTimeThreshold ) {\n tracker.dragging = null;\n viewer.goToPage( page );\n }\n }\n } );\n\n this.element.appendChild( element );\n\n element.activePanel = false;\n\n this.panels.push( element );\n\n }\n loadPanels( this, this.scroll == 'vertical' ? viewerSize.y : viewerSize.x, 0 );\n this.setFocus( 0 );\n\n};\n\n$.extend( $.ReferenceStrip.prototype, $.EventSource.prototype, $.Viewer.prototype, /** @lends OpenSeadragon.ReferenceStrip.prototype */{\n\n /**\n * @function\n */\n setFocus: function ( page ) {\n var element = $.getElement( this.element.id + '-' + page ),\n viewerSize = $.getElementSize( this.viewer.canvas ),\n scrollWidth = Number( this.element.style.width.replace( 'px', '' ) ),\n scrollHeight = Number( this.element.style.height.replace( 'px', '' ) ),\n offsetLeft = -Number( this.element.style.marginLeft.replace( 'px', '' ) ),\n offsetTop = -Number( this.element.style.marginTop.replace( 'px', '' ) ),\n offset;\n\n if ( this.currentSelected !== element ) {\n if ( this.currentSelected ) {\n this.currentSelected.style.background = '#000';\n }\n this.currentSelected = element;\n this.currentSelected.style.background = '#999';\n\n if ( 'horizontal' == this.scroll ) {\n //right left\n offset = ( Number( page ) ) * ( this.panelWidth + 3 );\n if ( offset > offsetLeft + viewerSize.x - this.panelWidth ) {\n offset = Math.min( offset, ( scrollWidth - viewerSize.x ) );\n this.element.style.marginLeft = -offset + 'px';\n loadPanels( this, viewerSize.x, -offset );\n } else if ( offset < offsetLeft ) {\n offset = Math.max( 0, offset - viewerSize.x / 2 );\n this.element.style.marginLeft = -offset + 'px';\n loadPanels( this, viewerSize.x, -offset );\n }\n } else {\n offset = ( Number( page ) ) * ( this.panelHeight + 3 );\n if ( offset > offsetTop + viewerSize.y - this.panelHeight ) {\n offset = Math.min( offset, ( scrollHeight - viewerSize.y ) );\n this.element.style.marginTop = -offset + 'px';\n loadPanels( this, viewerSize.y, -offset );\n } else if ( offset < offsetTop ) {\n offset = Math.max( 0, offset - viewerSize.y / 2 );\n this.element.style.marginTop = -offset + 'px';\n loadPanels( this, viewerSize.y, -offset );\n }\n }\n\n this.currentPage = page;\n onStripEnter.call( this, { eventSource: this.innerTracker } );\n }\n },\n\n /**\n * @function\n */\n update: function () {\n if ( THIS[this.id].animating ) {\n $.console.log( 'image reference strip update' );\n return true;\n }\n return false;\n },\n\n // Overrides Viewer.destroy\n destroy: function() {\n if (this.miniViewers) {\n for (var key in this.miniViewers) {\n this.miniViewers[key].destroy();\n }\n }\n\n if (this.element) {\n this.element.parentNode.removeChild(this.element);\n }\n }\n\n} );\n\n\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripDrag( event ) {\n\n var offsetLeft = Number( this.element.style.marginLeft.replace( 'px', '' ) ),\n offsetTop = Number( this.element.style.marginTop.replace( 'px', '' ) ),\n scrollWidth = Number( this.element.style.width.replace( 'px', '' ) ),\n scrollHeight = Number( this.element.style.height.replace( 'px', '' ) ),\n viewerSize = $.getElementSize( this.viewer.canvas );\n this.dragging = true;\n if ( this.element ) {\n if ( 'horizontal' == this.scroll ) {\n if ( -event.delta.x > 0 ) {\n //forward\n if ( offsetLeft > -( scrollWidth - viewerSize.x ) ) {\n this.element.style.marginLeft = ( offsetLeft + ( event.delta.x * 2 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft + ( event.delta.x * 2 ) );\n }\n } else if ( -event.delta.x < 0 ) {\n //reverse\n if ( offsetLeft < 0 ) {\n this.element.style.marginLeft = ( offsetLeft + ( event.delta.x * 2 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft + ( event.delta.x * 2 ) );\n }\n }\n } else {\n if ( -event.delta.y > 0 ) {\n //forward\n if ( offsetTop > -( scrollHeight - viewerSize.y ) ) {\n this.element.style.marginTop = ( offsetTop + ( event.delta.y * 2 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.delta.y * 2 ) );\n }\n } else if ( -event.delta.y < 0 ) {\n //reverse\n if ( offsetTop < 0 ) {\n this.element.style.marginTop = ( offsetTop + ( event.delta.y * 2 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.delta.y * 2 ) );\n }\n }\n }\n }\n return false;\n\n}\n\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripScroll( event ) {\n var offsetLeft = Number( this.element.style.marginLeft.replace( 'px', '' ) ),\n offsetTop = Number( this.element.style.marginTop.replace( 'px', '' ) ),\n scrollWidth = Number( this.element.style.width.replace( 'px', '' ) ),\n scrollHeight = Number( this.element.style.height.replace( 'px', '' ) ),\n viewerSize = $.getElementSize( this.viewer.canvas );\n if ( this.element ) {\n if ( 'horizontal' == this.scroll ) {\n if ( event.scroll > 0 ) {\n //forward\n if ( offsetLeft > -( scrollWidth - viewerSize.x ) ) {\n this.element.style.marginLeft = ( offsetLeft - ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft - ( event.scroll * 60 ) );\n }\n } else if ( event.scroll < 0 ) {\n //reverse\n if ( offsetLeft < 0 ) {\n this.element.style.marginLeft = ( offsetLeft - ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft - ( event.scroll * 60 ) );\n }\n }\n } else {\n if ( event.scroll < 0 ) {\n //scroll up\n if ( offsetTop > viewerSize.y - scrollHeight ) {\n this.element.style.marginTop = ( offsetTop + ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.scroll * 60 ) );\n }\n } else if ( event.scroll > 0 ) {\n //scroll dowm\n if ( offsetTop < 0 ) {\n this.element.style.marginTop = ( offsetTop + ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.scroll * 60 ) );\n }\n }\n }\n }\n //cancels event\n return false;\n}\n\n\nfunction loadPanels( strip, viewerSize, scroll ) {\n var panelSize,\n activePanelsStart,\n activePanelsEnd,\n miniViewer,\n style,\n i,\n element;\n if ( 'horizontal' == strip.scroll ) {\n panelSize = strip.panelWidth;\n } else {\n panelSize = strip.panelHeight;\n }\n activePanelsStart = Math.ceil( viewerSize / panelSize ) + 5;\n activePanelsEnd = Math.ceil( ( Math.abs( scroll ) + viewerSize ) / panelSize ) + 1;\n activePanelsStart = activePanelsEnd - activePanelsStart;\n activePanelsStart = activePanelsStart < 0 ? 0 : activePanelsStart;\n\n for ( i = activePanelsStart; i < activePanelsEnd && i < strip.panels.length; i++ ) {\n element = strip.panels[i];\n if ( !element.activePanel ) {\n var miniTileSource;\n var originalTileSource = strip.viewer.tileSources[i];\n if (originalTileSource.referenceStripThumbnailUrl) {\n miniTileSource = {\n type: 'image',\n url: originalTileSource.referenceStripThumbnailUrl\n };\n } else {\n miniTileSource = originalTileSource;\n }\n miniViewer = new $.Viewer( {\n id: element.id,\n tileSources: [miniTileSource],\n element: element,\n navigatorSizeRatio: strip.sizeRatio,\n showNavigator: false,\n mouseNavEnabled: false,\n showNavigationControl: false,\n showSequenceControl: false,\n immediateRender: true,\n blendTime: 0,\n animationTime: 0\n } );\n\n miniViewer.displayRegion = $.makeNeutralElement( \"div\" );\n miniViewer.displayRegion.id = element.id + '-displayregion';\n miniViewer.displayRegion.className = 'displayregion';\n\n style = miniViewer.displayRegion.style;\n style.position = 'relative';\n style.top = '0px';\n style.left = '0px';\n style.fontSize = '0px';\n style.overflow = 'hidden';\n style.float = 'left'; //Webkit\n style.cssFloat = 'left'; //Firefox\n style.styleFloat = 'left'; //IE\n style.zIndex = 999999999;\n style.cursor = 'default';\n style.width = ( strip.panelWidth - 4 ) + 'px';\n style.height = ( strip.panelHeight - 4 ) + 'px';\n\n // TODO: What is this for? Future keyboard navigation support?\n miniViewer.displayRegion.innerTracker = new $.MouseTracker( {\n element: miniViewer.displayRegion,\n startDisabled: true\n } );\n\n element.getElementsByTagName( 'div' )[0].appendChild(\n miniViewer.displayRegion\n );\n\n strip.miniViewers[element.id] = miniViewer;\n\n element.activePanel = true;\n }\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripEnter( event ) {\n var element = event.eventSource.element;\n\n //$.setElementOpacity(element, 0.8);\n\n //element.style.border = '1px solid #555';\n //element.style.background = '#000';\n\n if ( 'horizontal' == this.scroll ) {\n\n //element.style.paddingTop = \"0px\";\n element.style.marginBottom = \"0px\";\n\n } else {\n\n //element.style.paddingRight = \"0px\";\n element.style.marginLeft = \"0px\";\n\n }\n return false;\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripExit( event ) {\n var element = event.eventSource.element;\n\n if ( 'horizontal' == this.scroll ) {\n\n //element.style.paddingTop = \"10px\";\n element.style.marginBottom = \"-\" + ( $.getElementSize( element ).y / 2 ) + \"px\";\n\n } else {\n\n //element.style.paddingRight = \"10px\";\n element.style.marginLeft = \"-\" + ( $.getElementSize( element ).x / 2 ) + \"px\";\n\n }\n return false;\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onKeyDown( event ) {\n //console.log( event.keyCode );\n\n if ( !event.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch ( event.keyCode ) {\n case 38: //up arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n case 40: //down arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 37: //left arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 39: //right arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n default:\n //console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onKeyPress( event ) {\n //console.log( event.keyCode );\n\n if ( !event.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch ( event.keyCode ) {\n case 61: //=|+\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n case 45: //-|_\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 48: //0|)\n case 119: //w\n case 87: //W\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n case 115: //s\n case 83: //S\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 97: //a\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 100: //d\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n default:\n //console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - DisplayRect\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class DisplayRect\n * @classdesc A display rectangle is very similar to {@link OpenSeadragon.Rect} but adds two\n * fields, 'minLevel' and 'maxLevel' which denote the supported zoom levels\n * for this rectangle.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.Rect\n * @param {Number} x The vector component 'x'.\n * @param {Number} y The vector component 'y'.\n * @param {Number} width The vector component 'height'.\n * @param {Number} height The vector component 'width'.\n * @param {Number} minLevel The lowest zoom level supported.\n * @param {Number} maxLevel The highest zoom level supported.\n */\n$.DisplayRect = function( x, y, width, height, minLevel, maxLevel ) {\n $.Rect.apply( this, [ x, y, width, height ] );\n\n /**\n * The lowest zoom level supported.\n * @member {Number} minLevel\n * @memberof OpenSeadragon.DisplayRect#\n */\n this.minLevel = minLevel;\n /**\n * The highest zoom level supported.\n * @member {Number} maxLevel\n * @memberof OpenSeadragon.DisplayRect#\n */\n this.maxLevel = maxLevel;\n};\n\n$.extend( $.DisplayRect.prototype, $.Rect.prototype );\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Spring\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Spring\n * @memberof OpenSeadragon\n * @param {Object} options - Spring configuration settings.\n * @param {Number} options.springStiffness - Spring stiffness. Must be greater than zero.\n * The closer to zero, the closer to linear animation.\n * @param {Number} options.animationTime - Animation duration per spring, in seconds.\n * Must be zero or greater.\n * @param {Number} [options.initial=0] - Initial value of spring.\n * @param {Boolean} [options.exponential=false] - Whether this spring represents\n * an exponential scale (such as zoom) and should be animated accordingly. Note that\n * exponential springs must have non-zero values.\n */\n$.Spring = function( options ) {\n var args = arguments;\n\n if( typeof ( options ) != 'object' ){\n //allows backward compatible use of ( initialValue, config ) as\n //constructor parameters\n options = {\n initial: args.length && typeof ( args[ 0 ] ) == \"number\" ?\n args[ 0 ] :\n undefined,\n /**\n * Spring stiffness.\n * @member {Number} springStiffness\n * @memberof OpenSeadragon.Spring#\n */\n springStiffness: args.length > 1 ?\n args[ 1 ].springStiffness :\n 5.0,\n /**\n * Animation duration per spring.\n * @member {Number} animationTime\n * @memberof OpenSeadragon.Spring#\n */\n animationTime: args.length > 1 ?\n args[ 1 ].animationTime :\n 1.5\n };\n }\n\n $.console.assert(typeof options.springStiffness === \"number\" && options.springStiffness !== 0,\n \"[OpenSeadragon.Spring] options.springStiffness must be a non-zero number\");\n\n $.console.assert(typeof options.animationTime === \"number\" && options.animationTime >= 0,\n \"[OpenSeadragon.Spring] options.animationTime must be a number greater than or equal to 0\");\n\n if (options.exponential) {\n this._exponential = true;\n delete options.exponential;\n }\n\n $.extend( true, this, options);\n\n /**\n * @member {Object} current\n * @memberof OpenSeadragon.Spring#\n * @property {Number} value\n * @property {Number} time\n */\n this.current = {\n value: typeof ( this.initial ) == \"number\" ?\n this.initial :\n (this._exponential ? 0 : 1),\n time: $.now() // always work in milliseconds\n };\n\n $.console.assert(!this._exponential || this.current.value !== 0,\n \"[OpenSeadragon.Spring] value must be non-zero for exponential springs\");\n\n /**\n * @member {Object} start\n * @memberof OpenSeadragon.Spring#\n * @property {Number} value\n * @property {Number} time\n */\n this.start = {\n value: this.current.value,\n time: this.current.time\n };\n\n /**\n * @member {Object} target\n * @memberof OpenSeadragon.Spring#\n * @property {Number} value\n * @property {Number} time\n */\n this.target = {\n value: this.current.value,\n time: this.current.time\n };\n\n if (this._exponential) {\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n this.current._logValue = Math.log(this.current.value);\n }\n};\n\n/** @lends OpenSeadragon.Spring.prototype */\n$.Spring.prototype = {\n\n /**\n * @function\n * @param {Number} target\n */\n resetTo: function( target ) {\n $.console.assert(!this._exponential || target !== 0,\n \"[OpenSeadragon.Spring.resetTo] target must be non-zero for exponential springs\");\n\n this.start.value = this.target.value = this.current.value = target;\n this.start.time = this.target.time = this.current.time = $.now();\n\n if (this._exponential) {\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n this.current._logValue = Math.log(this.current.value);\n }\n },\n\n /**\n * @function\n * @param {Number} target\n */\n springTo: function( target ) {\n $.console.assert(!this._exponential || target !== 0,\n \"[OpenSeadragon.Spring.springTo] target must be non-zero for exponential springs\");\n\n this.start.value = this.current.value;\n this.start.time = this.current.time;\n this.target.value = target;\n this.target.time = this.start.time + 1000 * this.animationTime;\n\n if (this._exponential) {\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n }\n },\n\n /**\n * @function\n * @param {Number} delta\n */\n shiftBy: function( delta ) {\n this.start.value += delta;\n this.target.value += delta;\n\n if (this._exponential) {\n $.console.assert(this.target.value !== 0 && this.start.value !== 0,\n \"[OpenSeadragon.Spring.shiftBy] spring value must be non-zero for exponential springs\");\n\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n }\n },\n\n setExponential: function(value) {\n this._exponential = value;\n\n if (this._exponential) {\n $.console.assert(this.current.value !== 0 && this.target.value !== 0 && this.start.value !== 0,\n \"[OpenSeadragon.Spring.setExponential] spring value must be non-zero for exponential springs\");\n\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n this.current._logValue = Math.log(this.current.value);\n }\n },\n\n /**\n * @function\n * @returns true if the value got updated, false otherwise\n */\n update: function() {\n this.current.time = $.now();\n\n var startValue, targetValue;\n if (this._exponential) {\n startValue = this.start._logValue;\n targetValue = this.target._logValue;\n } else {\n startValue = this.start.value;\n targetValue = this.target.value;\n }\n\n var currentValue = (this.current.time >= this.target.time) ?\n targetValue :\n startValue +\n ( targetValue - startValue ) *\n transform(\n this.springStiffness,\n ( this.current.time - this.start.time ) /\n ( this.target.time - this.start.time )\n );\n\n var oldValue = this.current.value;\n if (this._exponential) {\n this.current.value = Math.exp(currentValue);\n } else {\n this.current.value = currentValue;\n }\n\n return oldValue != this.current.value;\n },\n\n /**\n * Returns whether the spring is at the target value\n * @function\n * @returns {Boolean} True if at target value, false otherwise\n */\n isAtTargetValue: function() {\n return this.current.value === this.target.value;\n }\n};\n\n/**\n * @private\n */\nfunction transform( stiffness, x ) {\n return ( 1.0 - Math.exp( stiffness * -x ) ) /\n ( 1.0 - Math.exp( -stiffness ) );\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ImageLoader\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($){\n\n/**\n * @private\n * @class ImageJob\n * @classdesc Handles downloading of a single image.\n * @param {Object} options - Options for this ImageJob.\n * @param {String} [options.src] - URL of image to download.\n * @param {String} [options.loadWithAjax] - Whether to load this image with AJAX.\n * @param {String} [options.ajaxHeaders] - Headers to add to the image request if using AJAX.\n * @param {String} [options.crossOriginPolicy] - CORS policy to use for downloads\n * @param {Function} [options.callback] - Called once image has been downloaded.\n * @param {Function} [options.abort] - Called when this image job is aborted.\n * @param {Number} [options.timeout] - The max number of milliseconds that this image job may take to complete.\n */\nfunction ImageJob (options) {\n\n $.extend(true, this, {\n timeout: $.DEFAULT_SETTINGS.timeout,\n makeAjaxRequest: $.makeAjaxRequest,\n jobId: null\n }, options);\n\n /**\n * Image object which will contain downloaded image.\n * @member {Image} image\n * @memberof OpenSeadragon.ImageJob#\n */\n this.image = null;\n}\n\nImageJob.prototype = {\n errorMsg: null,\n\n /**\n * Starts the image job.\n * @method\n */\n start: function(){\n var self = this;\n var selfAbort = this.abort;\n\n this.image = new Image();\n\n this.image.onload = function(){\n self.finish(true);\n };\n this.image.onabort = this.image.onerror = function() {\n self.errorMsg = \"Image load aborted\";\n self.finish(false);\n };\n\n this.jobId = window.setTimeout(function(){\n self.errorMsg = \"Image load exceeded timeout\";\n self.finish(false);\n }, this.timeout);\n\n // Load the tile with an AJAX request if the loadWithAjax option is\n // set. Otherwise load the image by setting the source proprety of the image object.\n if (this.loadWithAjax) {\n this.request = self.makeAjaxRequest({\n url: this.src,\n withCredentials: this.ajaxWithCredentials,\n headers: this.ajaxHeaders,\n responseType: \"arraybuffer\",\n success: function(request) {\n var blb;\n // Make the raw data into a blob.\n // BlobBuilder fallback adapted from\n // http://stackoverflow.com/questions/15293694/blob-constructor-browser-compatibility\n try {\n // Store the original response\n self.image._array = request.response;\n blb = new window.Blob([request.response]);\n } catch (e) {\n var BlobBuilder = (\n window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder\n );\n if (e.name === 'TypeError' && BlobBuilder) {\n var bb = new BlobBuilder();\n bb.append(request.response);\n blb = bb.getBlob();\n }\n }\n // If the blob is empty for some reason consider the image load a failure.\n if (blb === undefined || blb.size === 0) {\n self.errorMsg = \"Empty image response.\";\n self.finish(false);\n }\n\n // Create a URL for the blob data and make it the source of the image object.\n // This will still trigger Image.onload to indicate a successful tile load.\n var url = (window.URL || window.webkitURL).createObjectURL(blb);\n self.image.src = url;\n },\n error: function(request) {\n self.errorMsg = \"Image load aborted - XHR error\";\n self.finish(false);\n }\n });\n\n // Provide a function to properly abort the request.\n this.abort = function() {\n self.request.abort();\n\n // Call the existing abort function if available\n if (typeof selfAbort === \"function\") {\n selfAbort();\n }\n };\n } else {\n if (this.crossOriginPolicy !== false) {\n this.image.crossOrigin = this.crossOriginPolicy;\n }\n\n this.image.src = this.src;\n }\n },\n\n finish: function(successful) {\n this.image.onload = this.image.onerror = this.image.onabort = null;\n if (!successful) {\n this.image = null;\n }\n\n if (this.jobId) {\n window.clearTimeout(this.jobId);\n }\n\n this.callback(this);\n }\n\n};\n\n/**\n * @class ImageLoader\n * @memberof OpenSeadragon\n * @classdesc Handles downloading of a set of images using asynchronous queue pattern.\n * You generally won't have to interact with the ImageLoader directly.\n * @param {Object} options - Options for this ImageLoader.\n * @param {Number} [options.jobLimit] - The number of concurrent image requests. See imageLoaderLimit in {@link OpenSeadragon.Options} for details.\n * @param {Number} [options.timeout] - The max number of milliseconds that an image job may take to complete.\n */\n$.ImageLoader = function(options) {\n\n $.extend(true, this, {\n jobLimit: $.DEFAULT_SETTINGS.imageLoaderLimit,\n timeout: $.DEFAULT_SETTINGS.timeout,\n jobQueue: [],\n jobsInProgress: 0\n }, options);\n\n};\n\n/** @lends OpenSeadragon.ImageLoader.prototype */\n$.ImageLoader.prototype = {\n\n /**\n * Add an unloaded image to the loader queue.\n * @method\n * @param {Object} options - Options for this job.\n * @param {String} [options.src] - URL of image to download.\n * @param {String} [options.loadWithAjax] - Whether to load this image with AJAX.\n * @param {String} [options.ajaxHeaders] - Headers to add to the image request if using AJAX.\n * @param {String|Boolean} [options.crossOriginPolicy] - CORS policy to use for downloads\n * @param {Boolean} [options.ajaxWithCredentials] - Whether to set withCredentials on AJAX\n * requests.\n * @param {Function} [options.callback] - Called once image has been downloaded.\n * @param {Function} [options.abort] - Called when this image job is aborted.\n */\n addJob: function(options) {\n var _this = this,\n complete = function(job) {\n completeJob(_this, job, options.callback);\n },\n jobOptions = {\n src: options.src,\n loadWithAjax: options.loadWithAjax,\n ajaxHeaders: options.loadWithAjax ? options.ajaxHeaders : null,\n crossOriginPolicy: options.crossOriginPolicy,\n ajaxWithCredentials: options.ajaxWithCredentials,\n makeAjaxRequest: options.makeAjaxRequest,\n callback: complete,\n abort: options.abort,\n timeout: this.timeout\n },\n newJob = new ImageJob(jobOptions);\n\n if ( !this.jobLimit || this.jobsInProgress < this.jobLimit ) {\n newJob.start();\n this.jobsInProgress++;\n }\n else {\n this.jobQueue.push( newJob );\n }\n },\n\n /**\n * Clear any unstarted image loading jobs from the queue.\n * @method\n */\n clear: function() {\n for( var i = 0; i < this.jobQueue.length; i++ ) {\n var job = this.jobQueue[i];\n if ( typeof job.abort === \"function\" ) {\n job.abort();\n }\n }\n\n this.jobQueue = [];\n }\n};\n\n/**\n * Cleans up ImageJob once completed.\n * @method\n * @private\n * @param loader - ImageLoader used to start job.\n * @param job - The ImageJob that has completed.\n * @param callback - Called once cleanup is finished.\n */\nfunction completeJob(loader, job, callback) {\n var nextJob;\n\n loader.jobsInProgress--;\n\n if ((!loader.jobLimit || loader.jobsInProgress < loader.jobLimit) && loader.jobQueue.length > 0) {\n nextJob = loader.jobQueue.shift();\n nextJob.start();\n loader.jobsInProgress++;\n }\n\n callback(job.image, job.errorMsg, job.request);\n}\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Tile\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Tile\n * @memberof OpenSeadragon\n * @param {Number} level The zoom level this tile belongs to.\n * @param {Number} x The vector component 'x'.\n * @param {Number} y The vector component 'y'.\n * @param {OpenSeadragon.Rect} bounds Where this tile fits, in normalized\n * coordinates.\n * @param {Boolean} exists Is this tile a part of a sparse image? ( Also has\n * this tile failed to load? )\n * @param {String} url The URL of this tile's image.\n * @param {CanvasRenderingContext2D} context2D The context2D of this tile if it\n * is provided directly by the tile source.\n * @param {Boolean} loadWithAjax Whether this tile image should be loaded with an AJAX request .\n * @param {Object} ajaxHeaders The headers to send with this tile's AJAX request (if applicable).\n * @param {OpenSeadragon.Rect} sourceBounds The portion of the tile to use as the source of the\n * drawing operation, in pixels. Note that this only works when drawing with canvas; when drawing\n * with HTML the entire tile is always used.\n */\n$.Tile = function(level, x, y, bounds, exists, url, context2D, loadWithAjax, ajaxHeaders, sourceBounds) {\n /**\n * The zoom level this tile belongs to.\n * @member {Number} level\n * @memberof OpenSeadragon.Tile#\n */\n this.level = level;\n /**\n * The vector component 'x'.\n * @member {Number} x\n * @memberof OpenSeadragon.Tile#\n */\n this.x = x;\n /**\n * The vector component 'y'.\n * @member {Number} y\n * @memberof OpenSeadragon.Tile#\n */\n this.y = y;\n /**\n * Where this tile fits, in normalized coordinates\n * @member {OpenSeadragon.Rect} bounds\n * @memberof OpenSeadragon.Tile#\n */\n this.bounds = bounds;\n /**\n * The portion of the tile to use as the source of the drawing operation, in pixels. Note that\n * this only works when drawing with canvas; when drawing with HTML the entire tile is always used.\n * @member {OpenSeadragon.Rect} sourceBounds\n * @memberof OpenSeadragon.Tile#\n */\n this.sourceBounds = sourceBounds;\n /**\n * Is this tile a part of a sparse image? Also has this tile failed to load?\n * @member {Boolean} exists\n * @memberof OpenSeadragon.Tile#\n */\n this.exists = exists;\n /**\n * The URL of this tile's image.\n * @member {String} url\n * @memberof OpenSeadragon.Tile#\n */\n this.url = url;\n /**\n * The context2D of this tile if it is provided directly by the tile source.\n * @member {CanvasRenderingContext2D} context2D\n * @memberOf OpenSeadragon.Tile#\n */\n this.context2D = context2D;\n /**\n * Whether to load this tile's image with an AJAX request.\n * @member {Boolean} loadWithAjax\n * @memberof OpenSeadragon.Tile#\n */\n this.loadWithAjax = loadWithAjax;\n /**\n * The headers to be used in requesting this tile's image.\n * Only used if loadWithAjax is set to true.\n * @member {Object} ajaxHeaders\n * @memberof OpenSeadragon.Tile#\n */\n this.ajaxHeaders = ajaxHeaders;\n /**\n * The unique cache key for this tile.\n * @member {String} cacheKey\n * @memberof OpenSeadragon.Tile#\n */\n if (this.ajaxHeaders) {\n this.cacheKey = this.url + \"+\" + JSON.stringify(this.ajaxHeaders);\n } else {\n this.cacheKey = this.url;\n }\n /**\n * Is this tile loaded?\n * @member {Boolean} loaded\n * @memberof OpenSeadragon.Tile#\n */\n this.loaded = false;\n /**\n * Is this tile loading?\n * @member {Boolean} loading\n * @memberof OpenSeadragon.Tile#\n */\n this.loading = false;\n\n /**\n * The HTML div element for this tile\n * @member {Element} element\n * @memberof OpenSeadragon.Tile#\n */\n this.element = null;\n /**\n * The HTML img element for this tile.\n * @member {Element} imgElement\n * @memberof OpenSeadragon.Tile#\n */\n this.imgElement = null;\n /**\n * The Image object for this tile.\n * @member {Object} image\n * @memberof OpenSeadragon.Tile#\n */\n this.image = null;\n\n /**\n * The alias of this.element.style.\n * @member {String} style\n * @memberof OpenSeadragon.Tile#\n */\n this.style = null;\n /**\n * This tile's position on screen, in pixels.\n * @member {OpenSeadragon.Point} position\n * @memberof OpenSeadragon.Tile#\n */\n this.position = null;\n /**\n * This tile's size on screen, in pixels.\n * @member {OpenSeadragon.Point} size\n * @memberof OpenSeadragon.Tile#\n */\n this.size = null;\n /**\n * The start time of this tile's blending.\n * @member {Number} blendStart\n * @memberof OpenSeadragon.Tile#\n */\n this.blendStart = null;\n /**\n * The current opacity this tile should be.\n * @member {Number} opacity\n * @memberof OpenSeadragon.Tile#\n */\n this.opacity = null;\n /**\n * The squared distance of this tile to the viewport center.\n * Use for comparing tiles.\n * @private\n * @member {Number} squaredDistance\n * @memberof OpenSeadragon.Tile#\n */\n this.squaredDistance = null;\n /**\n * The visibility score of this tile.\n * @member {Number} visibility\n * @memberof OpenSeadragon.Tile#\n */\n this.visibility = null;\n\n /**\n * Whether this tile is currently being drawn.\n * @member {Boolean} beingDrawn\n * @memberof OpenSeadragon.Tile#\n */\n this.beingDrawn = false;\n\n /**\n * Timestamp the tile was last touched.\n * @member {Number} lastTouchTime\n * @memberof OpenSeadragon.Tile#\n */\n this.lastTouchTime = 0;\n\n /**\n * Whether this tile is in the right-most column for its level.\n * @member {Boolean} isRightMost\n * @memberof OpenSeadragon.Tile#\n */\n this.isRightMost = false;\n\n /**\n * Whether this tile is in the bottom-most row for its level.\n * @member {Boolean} isBottomMost\n * @memberof OpenSeadragon.Tile#\n */\n this.isBottomMost = false;\n};\n\n/** @lends OpenSeadragon.Tile.prototype */\n$.Tile.prototype = {\n\n /**\n * Provides a string representation of this tiles level and (x,y)\n * components.\n * @function\n * @returns {String}\n */\n toString: function() {\n return this.level + \"/\" + this.x + \"_\" + this.y;\n },\n\n // private\n _hasTransparencyChannel: function() {\n return !!this.context2D || this.url.match('.png');\n },\n\n /**\n * Renders the tile in an html container.\n * @function\n * @param {Element} container\n */\n drawHTML: function( container ) {\n if (!this.cacheImageRecord) {\n $.console.warn(\n '[Tile.drawHTML] attempting to draw tile %s when it\\'s not cached',\n this.toString());\n return;\n }\n\n if ( !this.loaded ) {\n $.console.warn(\n \"Attempting to draw tile %s when it's not yet loaded.\",\n this.toString()\n );\n return;\n }\n\n //EXPERIMENTAL - trying to figure out how to scale the container\n // content during animation of the container size.\n\n if ( !this.element ) {\n this.element = $.makeNeutralElement( \"div\" );\n this.imgElement = this.cacheImageRecord.getImage().cloneNode();\n this.imgElement.style.msInterpolationMode = \"nearest-neighbor\";\n this.imgElement.style.width = \"100%\";\n this.imgElement.style.height = \"100%\";\n\n this.style = this.element.style;\n this.style.position = \"absolute\";\n }\n if ( this.element.parentNode != container ) {\n container.appendChild( this.element );\n }\n if ( this.imgElement.parentNode != this.element ) {\n this.element.appendChild( this.imgElement );\n }\n\n this.style.top = this.position.y + \"px\";\n this.style.left = this.position.x + \"px\";\n this.style.height = this.size.y + \"px\";\n this.style.width = this.size.x + \"px\";\n\n $.setElementOpacity( this.element, this.opacity );\n },\n\n /**\n * Renders the tile in a canvas-based context.\n * @function\n * @param {Canvas} context\n * @param {Function} drawingHandler - Method for firing the drawing event.\n * drawingHandler({context, tile, rendered})\n * where rendered is the context with the pre-drawn image.\n * @param {Number} [scale=1] - Apply a scale to position and size\n * @param {OpenSeadragon.Point} [translate] - A translation vector\n */\n drawCanvas: function( context, drawingHandler, scale, translate ) {\n\n var position = this.position.times($.pixelDensityRatio),\n size = this.size.times($.pixelDensityRatio),\n rendered;\n\n if (!this.context2D && !this.cacheImageRecord) {\n $.console.warn(\n '[Tile.drawCanvas] attempting to draw tile %s when it\\'s not cached',\n this.toString());\n return;\n }\n\n rendered = this.context2D || this.cacheImageRecord.getRenderedContext();\n\n if ( !this.loaded || !rendered ){\n $.console.warn(\n \"Attempting to draw tile %s when it's not yet loaded.\",\n this.toString()\n );\n\n return;\n }\n\n context.save();\n\n context.globalAlpha = this.opacity;\n\n if (typeof scale === 'number' && scale !== 1) {\n // draw tile at a different scale\n position = position.times(scale);\n size = size.times(scale);\n }\n\n if (translate instanceof $.Point) {\n // shift tile position slightly\n position = position.plus(translate);\n }\n\n //if we are supposed to be rendering fully opaque rectangle,\n //ie its done fading or fading is turned off, and if we are drawing\n //an image with an alpha channel, then the only way\n //to avoid seeing the tile underneath is to clear the rectangle\n if (context.globalAlpha === 1 && this._hasTransparencyChannel()) {\n //clearing only the inside of the rectangle occupied\n //by the png prevents edge flikering\n context.clearRect(\n position.x,\n position.y,\n size.x,\n size.y\n );\n }\n\n // This gives the application a chance to make image manipulation\n // changes as we are rendering the image\n drawingHandler({context: context, tile: this, rendered: rendered});\n\n var sourceWidth, sourceHeight;\n if (this.sourceBounds) {\n sourceWidth = Math.min(this.sourceBounds.width, rendered.canvas.width);\n sourceHeight = Math.min(this.sourceBounds.height, rendered.canvas.height);\n } else {\n sourceWidth = rendered.canvas.width;\n sourceHeight = rendered.canvas.height;\n }\n\n context.drawImage(\n rendered.canvas,\n 0,\n 0,\n sourceWidth,\n sourceHeight,\n position.x,\n position.y,\n size.x,\n size.y\n );\n\n context.restore();\n },\n\n /**\n * Get the ratio between current and original size.\n * @function\n * @return {Float}\n */\n getScaleForEdgeSmoothing: function() {\n var context;\n if (this.cacheImageRecord) {\n context = this.cacheImageRecord.getRenderedContext();\n } else if (this.context2D) {\n context = this.context2D;\n } else {\n $.console.warn(\n '[Tile.drawCanvas] attempting to get tile scale %s when tile\\'s not cached',\n this.toString());\n return 1;\n }\n return context.canvas.width / (this.size.x * $.pixelDensityRatio);\n },\n\n /**\n * Get a translation vector that when applied to the tile position produces integer coordinates.\n * Needed to avoid swimming and twitching.\n * @function\n * @param {Number} [scale=1] - Scale to be applied to position.\n * @return {OpenSeadragon.Point}\n */\n getTranslationForEdgeSmoothing: function(scale, canvasSize, sketchCanvasSize) {\n // The translation vector must have positive values, otherwise the image goes a bit off\n // the sketch canvas to the top and left and we must use negative coordinates to repaint it\n // to the main canvas. In that case, some browsers throw:\n // INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.\n var x = Math.max(1, Math.ceil((sketchCanvasSize.x - canvasSize.x) / 2));\n var y = Math.max(1, Math.ceil((sketchCanvasSize.y - canvasSize.y) / 2));\n return new $.Point(x, y).minus(\n this.position\n .times($.pixelDensityRatio)\n .times(scale || 1)\n .apply(function(x) {\n return x % 1;\n })\n );\n },\n\n /**\n * Removes tile from its container.\n * @function\n */\n unload: function() {\n if ( this.imgElement && this.imgElement.parentNode ) {\n this.imgElement.parentNode.removeChild( this.imgElement );\n }\n if ( this.element && this.element.parentNode ) {\n this.element.parentNode.removeChild( this.element );\n }\n\n this.element = null;\n this.imgElement = null;\n this.loaded = false;\n this.loading = false;\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Overlay\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n /**\n * An enumeration of positions that an overlay may be assigned relative to\n * the viewport.\n * It is identical to OpenSeadragon.Placement but is kept for backward\n * compatibility.\n * @member OverlayPlacement\n * @memberof OpenSeadragon\n * @see OpenSeadragon.Placement\n * @static\n * @readonly\n * @type {Object}\n * @property {Number} CENTER\n * @property {Number} TOP_LEFT\n * @property {Number} TOP\n * @property {Number} TOP_RIGHT\n * @property {Number} RIGHT\n * @property {Number} BOTTOM_RIGHT\n * @property {Number} BOTTOM\n * @property {Number} BOTTOM_LEFT\n * @property {Number} LEFT\n */\n $.OverlayPlacement = $.Placement;\n\n /**\n * An enumeration of possible ways to handle overlays rotation\n * @member OverlayRotationMode\n * @memberOf OpenSeadragon\n * @static\n * @readonly\n * @property {Number} NO_ROTATION The overlay ignore the viewport rotation.\n * @property {Number} EXACT The overlay use CSS 3 transforms to rotate with\n * the viewport. If the overlay contains text, it will get rotated as well.\n * @property {Number} BOUNDING_BOX The overlay adjusts for rotation by\n * taking the size of the bounding box of the rotated bounds.\n * Only valid for overlays with Rect location and scalable in both directions.\n */\n $.OverlayRotationMode = $.freezeObject({\n NO_ROTATION: 1,\n EXACT: 2,\n BOUNDING_BOX: 3\n });\n\n /**\n * @class Overlay\n * @classdesc Provides a way to float an HTML element on top of the viewer element.\n *\n * @memberof OpenSeadragon\n * @param {Object} options\n * @param {Element} options.element\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect} options.location - The\n * location of the overlay on the image. If a {@link OpenSeadragon.Point}\n * is specified, the overlay will be located at this location with respect\n * to the placement option. If a {@link OpenSeadragon.Rect} is specified,\n * the overlay will be placed at this location with the corresponding width\n * and height and placement TOP_LEFT.\n * @param {OpenSeadragon.Placement} [options.placement=OpenSeadragon.Placement.TOP_LEFT]\n * Defines what part of the overlay should be at the specified options.location\n * @param {OpenSeadragon.Overlay.OnDrawCallback} [options.onDraw]\n * @param {Boolean} [options.checkResize=true] Set to false to avoid to\n * check the size of the overlay everytime it is drawn in the directions\n * which are not scaled. It will improve performances but will cause a\n * misalignment if the overlay size changes.\n * @param {Number} [options.width] The width of the overlay in viewport\n * coordinates. If specified, the width of the overlay will be adjusted when\n * the zoom changes.\n * @param {Number} [options.height] The height of the overlay in viewport\n * coordinates. If specified, the height of the overlay will be adjusted when\n * the zoom changes.\n * @param {Boolean} [options.rotationMode=OpenSeadragon.OverlayRotationMode.EXACT]\n * How to handle the rotation of the viewport.\n */\n $.Overlay = function(element, location, placement) {\n\n /**\n * onDraw callback signature used by {@link OpenSeadragon.Overlay}.\n *\n * @callback OnDrawCallback\n * @memberof OpenSeadragon.Overlay\n * @param {OpenSeadragon.Point} position\n * @param {OpenSeadragon.Point} size\n * @param {Element} element\n */\n\n var options;\n if ($.isPlainObject(element)) {\n options = element;\n } else {\n options = {\n element: element,\n location: location,\n placement: placement\n };\n }\n\n this.element = options.element;\n this.style = options.element.style;\n this._init(options);\n };\n\n /** @lends OpenSeadragon.Overlay.prototype */\n $.Overlay.prototype = {\n\n // private\n _init: function(options) {\n this.location = options.location;\n this.placement = options.placement === undefined ?\n $.Placement.TOP_LEFT : options.placement;\n this.onDraw = options.onDraw;\n this.checkResize = options.checkResize === undefined ?\n true : options.checkResize;\n\n // When this.width is not null, the overlay get scaled horizontally\n this.width = options.width === undefined ? null : options.width;\n\n // When this.height is not null, the overlay get scaled vertically\n this.height = options.height === undefined ? null : options.height;\n\n this.rotationMode = options.rotationMode || $.OverlayRotationMode.EXACT;\n\n // Having a rect as location is a syntactic sugar\n if (this.location instanceof $.Rect) {\n this.width = this.location.width;\n this.height = this.location.height;\n this.location = this.location.getTopLeft();\n this.placement = $.Placement.TOP_LEFT;\n }\n\n // Deprecated properties kept for backward compatibility.\n this.scales = this.width !== null && this.height !== null;\n this.bounds = new $.Rect(\n this.location.x, this.location.y, this.width, this.height);\n this.position = this.location;\n },\n\n /**\n * Internal function to adjust the position of an overlay\n * depending on it size and placement.\n * @function\n * @param {OpenSeadragon.Point} position\n * @param {OpenSeadragon.Point} size\n */\n adjust: function(position, size) {\n var properties = $.Placement.properties[this.placement];\n if (!properties) {\n return;\n }\n if (properties.isHorizontallyCentered) {\n position.x -= size.x / 2;\n } else if (properties.isRight) {\n position.x -= size.x;\n }\n if (properties.isVerticallyCentered) {\n position.y -= size.y / 2;\n } else if (properties.isBottom) {\n position.y -= size.y;\n }\n },\n\n /**\n * @function\n */\n destroy: function() {\n var element = this.element;\n var style = this.style;\n\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n //this should allow us to preserve overlays when required between\n //pages\n if (element.prevElementParent) {\n style.display = 'none';\n //element.prevElementParent.insertBefore(\n // element,\n // element.prevNextSibling\n //);\n document.body.appendChild(element);\n }\n }\n\n // clear the onDraw callback\n this.onDraw = null;\n\n style.top = \"\";\n style.left = \"\";\n style.position = \"\";\n\n if (this.width !== null) {\n style.width = \"\";\n }\n if (this.height !== null) {\n style.height = \"\";\n }\n var transformOriginProp = $.getCssPropertyWithVendorPrefix(\n 'transformOrigin');\n var transformProp = $.getCssPropertyWithVendorPrefix(\n 'transform');\n if (transformOriginProp && transformProp) {\n style[transformOriginProp] = \"\";\n style[transformProp] = \"\";\n }\n },\n\n /**\n * @function\n * @param {Element} container\n */\n drawHTML: function(container, viewport) {\n var element = this.element;\n if (element.parentNode !== container) {\n //save the source parent for later if we need it\n element.prevElementParent = element.parentNode;\n element.prevNextSibling = element.nextSibling;\n container.appendChild(element);\n\n // have to set position before calculating size, fix #1116\n this.style.position = \"absolute\";\n // this.size is used by overlays which don't get scaled in at\n // least one direction when this.checkResize is set to false.\n this.size = $.getElementSize(element);\n }\n\n var positionAndSize = this._getOverlayPositionAndSize(viewport);\n\n var position = positionAndSize.position;\n var size = this.size = positionAndSize.size;\n var rotate = positionAndSize.rotate;\n\n // call the onDraw callback if it exists to allow one to overwrite\n // the drawing/positioning/sizing of the overlay\n if (this.onDraw) {\n this.onDraw(position, size, this.element);\n } else {\n var style = this.style;\n style.left = position.x + \"px\";\n style.top = position.y + \"px\";\n if (this.width !== null) {\n style.width = size.x + \"px\";\n }\n if (this.height !== null) {\n style.height = size.y + \"px\";\n }\n var transformOriginProp = $.getCssPropertyWithVendorPrefix(\n 'transformOrigin');\n var transformProp = $.getCssPropertyWithVendorPrefix(\n 'transform');\n if (transformOriginProp && transformProp) {\n if (rotate) {\n style[transformOriginProp] = this._getTransformOrigin();\n style[transformProp] = \"rotate(\" + rotate + \"deg)\";\n } else {\n style[transformOriginProp] = \"\";\n style[transformProp] = \"\";\n }\n }\n\n if (style.display !== 'none') {\n style.display = 'block';\n }\n }\n },\n\n // private\n _getOverlayPositionAndSize: function(viewport) {\n var position = viewport.pixelFromPoint(this.location, true);\n var size = this._getSizeInPixels(viewport);\n this.adjust(position, size);\n\n var rotate = 0;\n if (viewport.degrees &&\n this.rotationMode !== $.OverlayRotationMode.NO_ROTATION) {\n // BOUNDING_BOX is only valid if both directions get scaled.\n // Get replaced by EXACT otherwise.\n if (this.rotationMode === $.OverlayRotationMode.BOUNDING_BOX &&\n this.width !== null && this.height !== null) {\n var rect = new $.Rect(position.x, position.y, size.x, size.y);\n var boundingBox = this._getBoundingBox(rect, viewport.degrees);\n position = boundingBox.getTopLeft();\n size = boundingBox.getSize();\n } else {\n rotate = viewport.degrees;\n }\n }\n\n return {\n position: position,\n size: size,\n rotate: rotate\n };\n },\n\n // private\n _getSizeInPixels: function(viewport) {\n var width = this.size.x;\n var height = this.size.y;\n if (this.width !== null || this.height !== null) {\n var scaledSize = viewport.deltaPixelsFromPointsNoRotate(\n new $.Point(this.width || 0, this.height || 0), true);\n if (this.width !== null) {\n width = scaledSize.x;\n }\n if (this.height !== null) {\n height = scaledSize.y;\n }\n }\n if (this.checkResize &&\n (this.width === null || this.height === null)) {\n var eltSize = this.size = $.getElementSize(this.element);\n if (this.width === null) {\n width = eltSize.x;\n }\n if (this.height === null) {\n height = eltSize.y;\n }\n }\n return new $.Point(width, height);\n },\n\n // private\n _getBoundingBox: function(rect, degrees) {\n var refPoint = this._getPlacementPoint(rect);\n return rect.rotate(degrees, refPoint).getBoundingBox();\n },\n\n // private\n _getPlacementPoint: function(rect) {\n var result = new $.Point(rect.x, rect.y);\n var properties = $.Placement.properties[this.placement];\n if (properties) {\n if (properties.isHorizontallyCentered) {\n result.x += rect.width / 2;\n } else if (properties.isRight) {\n result.x += rect.width;\n }\n if (properties.isVerticallyCentered) {\n result.y += rect.height / 2;\n } else if (properties.isBottom) {\n result.y += rect.height;\n }\n }\n return result;\n },\n\n // private\n _getTransformOrigin: function() {\n var result = \"\";\n var properties = $.Placement.properties[this.placement];\n if (!properties) {\n return result;\n }\n if (properties.isLeft) {\n result = \"left\";\n } else if (properties.isRight) {\n result = \"right\";\n }\n if (properties.isTop) {\n result += \" top\";\n } else if (properties.isBottom) {\n result += \" bottom\";\n }\n return result;\n },\n\n /**\n * Changes the overlay settings.\n * @function\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect|Object} location\n * If an object is specified, the options are the same than the constructor\n * except for the element which can not be changed.\n * @param {OpenSeadragon.Placement} placement\n */\n update: function(location, placement) {\n var options = $.isPlainObject(location) ? location : {\n location: location,\n placement: placement\n };\n this._init({\n location: options.location || this.location,\n placement: options.placement !== undefined ?\n options.placement : this.placement,\n onDraw: options.onDraw || this.onDraw,\n checkResize: options.checkResize || this.checkResize,\n width: options.width !== undefined ? options.width : this.width,\n height: options.height !== undefined ? options.height : this.height,\n rotationMode: options.rotationMode || this.rotationMode\n });\n },\n\n /**\n * Returns the current bounds of the overlay in viewport coordinates\n * @function\n * @param {OpenSeadragon.Viewport} viewport the viewport\n * @returns {OpenSeadragon.Rect} overlay bounds\n */\n getBounds: function(viewport) {\n $.console.assert(viewport,\n 'A viewport must now be passed to Overlay.getBounds.');\n var width = this.width;\n var height = this.height;\n if (width === null || height === null) {\n var size = viewport.deltaPointsFromPixelsNoRotate(this.size, true);\n if (width === null) {\n width = size.x;\n }\n if (height === null) {\n height = size.y;\n }\n }\n var location = this.location.clone();\n this.adjust(location, new $.Point(width, height));\n return this._adjustBoundsForRotation(\n viewport, new $.Rect(location.x, location.y, width, height));\n },\n\n // private\n _adjustBoundsForRotation: function(viewport, bounds) {\n if (!viewport ||\n viewport.degrees === 0 ||\n this.rotationMode === $.OverlayRotationMode.EXACT) {\n return bounds;\n }\n if (this.rotationMode === $.OverlayRotationMode.BOUNDING_BOX) {\n // If overlay not fully scalable, BOUNDING_BOX falls back to EXACT\n if (this.width === null || this.height === null) {\n return bounds;\n }\n // It is easier to just compute the position and size and\n // convert to viewport coordinates.\n var positionAndSize = this._getOverlayPositionAndSize(viewport);\n return viewport.viewerElementToViewportRectangle(new $.Rect(\n positionAndSize.position.x,\n positionAndSize.position.y,\n positionAndSize.size.x,\n positionAndSize.size.y));\n }\n\n // NO_ROTATION case\n return bounds.rotate(-viewport.degrees,\n this._getPlacementPoint(bounds));\n }\n };\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Drawer\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Drawer\n * @memberof OpenSeadragon\n * @classdesc Handles rendering of tiles for an {@link OpenSeadragon.Viewer}.\n * @param {Object} options - Options for this Drawer.\n * @param {OpenSeadragon.Viewer} options.viewer - The Viewer that owns this Drawer.\n * @param {OpenSeadragon.Viewport} options.viewport - Reference to Viewer viewport.\n * @param {Element} options.element - Parent element.\n * @param {Number} [options.debugGridColor] - See debugGridColor in {@link OpenSeadragon.Options} for details.\n */\n$.Drawer = function( options ) {\n\n $.console.assert( options.viewer, \"[Drawer] options.viewer is required\" );\n\n //backward compatibility for positional args while prefering more\n //idiomatic javascript options object as the only argument\n var args = arguments;\n\n if( !$.isPlainObject( options ) ){\n options = {\n source: args[ 0 ], // Reference to Viewer tile source.\n viewport: args[ 1 ], // Reference to Viewer viewport.\n element: args[ 2 ] // Parent element.\n };\n }\n\n $.console.assert( options.viewport, \"[Drawer] options.viewport is required\" );\n $.console.assert( options.element, \"[Drawer] options.element is required\" );\n\n if ( options.source ) {\n $.console.error( \"[Drawer] options.source is no longer accepted; use TiledImage instead\" );\n }\n\n this.viewer = options.viewer;\n this.viewport = options.viewport;\n this.debugGridColor = typeof options.debugGridColor === 'string' ? [options.debugGridColor] : options.debugGridColor || $.DEFAULT_SETTINGS.debugGridColor;\n if (options.opacity) {\n $.console.error( \"[Drawer] options.opacity is no longer accepted; set the opacity on the TiledImage instead\" );\n }\n\n this.useCanvas = $.supportsCanvas && ( this.viewer ? this.viewer.useCanvas : true );\n /**\n * The parent element of this Drawer instance, passed in when the Drawer was created.\n * The parent of {@link OpenSeadragon.Drawer#canvas}.\n * @member {Element} container\n * @memberof OpenSeadragon.Drawer#\n */\n this.container = $.getElement( options.element );\n /**\n * A <canvas> element if the browser supports them, otherwise a <div> element.\n * Child element of {@link OpenSeadragon.Drawer#container}.\n * @member {Element} canvas\n * @memberof OpenSeadragon.Drawer#\n */\n this.canvas = $.makeNeutralElement( this.useCanvas ? \"canvas\" : \"div\" );\n /**\n * 2d drawing context for {@link OpenSeadragon.Drawer#canvas} if it's a <canvas> element, otherwise null.\n * @member {Object} context\n * @memberof OpenSeadragon.Drawer#\n */\n this.context = this.useCanvas ? this.canvas.getContext( \"2d\" ) : null;\n\n /**\n * Sketch canvas used to temporarily draw tiles which cannot be drawn directly\n * to the main canvas due to opacity. Lazily initialized.\n */\n this.sketchCanvas = null;\n this.sketchContext = null;\n\n /**\n * @member {Element} element\n * @memberof OpenSeadragon.Drawer#\n * @deprecated Alias for {@link OpenSeadragon.Drawer#container}.\n */\n this.element = this.container;\n\n // We force our container to ltr because our drawing math doesn't work in rtl.\n // This issue only affects our canvas renderer, but we do it always for consistency.\n // Note that this means overlays you want to be rtl need to be explicitly set to rtl.\n this.container.dir = 'ltr';\n\n // check canvas available width and height, set canvas width and height such that the canvas backing store is set to the proper pixel density\n if (this.useCanvas) {\n var viewportSize = this._calculateCanvasSize();\n this.canvas.width = viewportSize.x;\n this.canvas.height = viewportSize.y;\n }\n\n this.canvas.style.width = \"100%\";\n this.canvas.style.height = \"100%\";\n this.canvas.style.position = \"absolute\";\n $.setElementOpacity( this.canvas, this.opacity, true );\n\n // explicit left-align\n this.container.style.textAlign = \"left\";\n this.container.appendChild( this.canvas );\n};\n\n/** @lends OpenSeadragon.Drawer.prototype */\n$.Drawer.prototype = {\n // deprecated\n addOverlay: function( element, location, placement, onDraw ) {\n $.console.error(\"drawer.addOverlay is deprecated. Use viewer.addOverlay instead.\");\n this.viewer.addOverlay( element, location, placement, onDraw );\n return this;\n },\n\n // deprecated\n updateOverlay: function( element, location, placement ) {\n $.console.error(\"drawer.updateOverlay is deprecated. Use viewer.updateOverlay instead.\");\n this.viewer.updateOverlay( element, location, placement );\n return this;\n },\n\n // deprecated\n removeOverlay: function( element ) {\n $.console.error(\"drawer.removeOverlay is deprecated. Use viewer.removeOverlay instead.\");\n this.viewer.removeOverlay( element );\n return this;\n },\n\n // deprecated\n clearOverlays: function() {\n $.console.error(\"drawer.clearOverlays is deprecated. Use viewer.clearOverlays instead.\");\n this.viewer.clearOverlays();\n return this;\n },\n\n /**\n * Set the opacity of the drawer.\n * @param {Number} opacity\n * @return {OpenSeadragon.Drawer} Chainable.\n */\n setOpacity: function( opacity ) {\n $.console.error(\"drawer.setOpacity is deprecated. Use tiledImage.setOpacity instead.\");\n var world = this.viewer.world;\n for (var i = 0; i < world.getItemCount(); i++) {\n world.getItemAt( i ).setOpacity( opacity );\n }\n return this;\n },\n\n /**\n * Get the opacity of the drawer.\n * @returns {Number}\n */\n getOpacity: function() {\n $.console.error(\"drawer.getOpacity is deprecated. Use tiledImage.getOpacity instead.\");\n var world = this.viewer.world;\n var maxOpacity = 0;\n for (var i = 0; i < world.getItemCount(); i++) {\n var opacity = world.getItemAt( i ).getOpacity();\n if ( opacity > maxOpacity ) {\n maxOpacity = opacity;\n }\n }\n return maxOpacity;\n },\n\n // deprecated\n needsUpdate: function() {\n $.console.error( \"[Drawer.needsUpdate] this function is deprecated. Use World.needsDraw instead.\" );\n return this.viewer.world.needsDraw();\n },\n\n // deprecated\n numTilesLoaded: function() {\n $.console.error( \"[Drawer.numTilesLoaded] this function is deprecated. Use TileCache.numTilesLoaded instead.\" );\n return this.viewer.tileCache.numTilesLoaded();\n },\n\n // deprecated\n reset: function() {\n $.console.error( \"[Drawer.reset] this function is deprecated. Use World.resetItems instead.\" );\n this.viewer.world.resetItems();\n return this;\n },\n\n // deprecated\n update: function() {\n $.console.error( \"[Drawer.update] this function is deprecated. Use Drawer.clear and World.draw instead.\" );\n this.clear();\n this.viewer.world.draw();\n return this;\n },\n\n /**\n * @return {Boolean} True if rotation is supported.\n */\n canRotate: function() {\n return this.useCanvas;\n },\n\n /**\n * Destroy the drawer (unload current loaded tiles)\n */\n destroy: function() {\n //force unloading of current canvas (1x1 will be gc later, trick not necessarily needed)\n this.canvas.width = 1;\n this.canvas.height = 1;\n this.sketchCanvas = null;\n this.sketchContext = null;\n },\n\n /**\n * Clears the Drawer so it's ready to draw another frame.\n */\n clear: function() {\n this.canvas.innerHTML = \"\";\n if ( this.useCanvas ) {\n var viewportSize = this._calculateCanvasSize();\n if( this.canvas.width != viewportSize.x ||\n this.canvas.height != viewportSize.y ) {\n this.canvas.width = viewportSize.x;\n this.canvas.height = viewportSize.y;\n if ( this.sketchCanvas !== null ) {\n var sketchCanvasSize = this._calculateSketchCanvasSize();\n this.sketchCanvas.width = sketchCanvasSize.x;\n this.sketchCanvas.height = sketchCanvasSize.y;\n }\n }\n this._clear();\n }\n },\n\n _clear: function (useSketch, bounds) {\n if (!this.useCanvas) {\n return;\n }\n var context = this._getContext(useSketch);\n if (bounds) {\n context.clearRect(bounds.x, bounds.y, bounds.width, bounds.height);\n } else {\n var canvas = context.canvas;\n context.clearRect(0, 0, canvas.width, canvas.height);\n }\n },\n\n /**\n * Scale from OpenSeadragon viewer rectangle to drawer rectangle\n * (ignoring rotation)\n * @param {OpenSeadragon.Rect} rectangle - The rectangle in viewport coordinate system.\n * @return {OpenSeadragon.Rect} Rectangle in drawer coordinate system.\n */\n viewportToDrawerRectangle: function(rectangle) {\n var topLeft = this.viewport.pixelFromPointNoRotate(rectangle.getTopLeft(), true);\n var size = this.viewport.deltaPixelsFromPointsNoRotate(rectangle.getSize(), true);\n\n return new $.Rect(\n topLeft.x * $.pixelDensityRatio,\n topLeft.y * $.pixelDensityRatio,\n size.x * $.pixelDensityRatio,\n size.y * $.pixelDensityRatio\n );\n },\n\n /**\n * Draws the given tile.\n * @param {OpenSeadragon.Tile} tile - The tile to draw.\n * @param {Function} drawingHandler - Method for firing the drawing event if using canvas.\n * drawingHandler({context, tile, rendered})\n * @param {Boolean} useSketch - Whether to use the sketch canvas or not.\n * where rendered is the context with the pre-drawn image.\n * @param {Float} [scale=1] - Apply a scale to tile position and size. Defaults to 1.\n * @param {OpenSeadragon.Point} [translate] A translation vector to offset tile position\n */\n drawTile: function(tile, drawingHandler, useSketch, scale, translate) {\n $.console.assert(tile, '[Drawer.drawTile] tile is required');\n $.console.assert(drawingHandler, '[Drawer.drawTile] drawingHandler is required');\n\n if (this.useCanvas) {\n var context = this._getContext(useSketch);\n scale = scale || 1;\n tile.drawCanvas(context, drawingHandler, scale, translate);\n } else {\n tile.drawHTML( this.canvas );\n }\n },\n\n _getContext: function( useSketch ) {\n var context = this.context;\n if ( useSketch ) {\n if (this.sketchCanvas === null) {\n this.sketchCanvas = document.createElement( \"canvas\" );\n var sketchCanvasSize = this._calculateSketchCanvasSize();\n this.sketchCanvas.width = sketchCanvasSize.x;\n this.sketchCanvas.height = sketchCanvasSize.y;\n this.sketchContext = this.sketchCanvas.getContext( \"2d\" );\n\n // If the viewport is not currently rotated, the sketchCanvas\n // will have the same size as the main canvas. However, if\n // the viewport get rotated later on, we will need to resize it.\n if (this.viewport.getRotation() === 0) {\n var self = this;\n this.viewer.addHandler('rotate', function resizeSketchCanvas() {\n if (self.viewport.getRotation() === 0) {\n return;\n }\n self.viewer.removeHandler('rotate', resizeSketchCanvas);\n var sketchCanvasSize = self._calculateSketchCanvasSize();\n self.sketchCanvas.width = sketchCanvasSize.x;\n self.sketchCanvas.height = sketchCanvasSize.y;\n });\n }\n }\n context = this.sketchContext;\n }\n return context;\n },\n\n // private\n saveContext: function( useSketch ) {\n if (!this.useCanvas) {\n return;\n }\n\n this._getContext( useSketch ).save();\n },\n\n // private\n restoreContext: function( useSketch ) {\n if (!this.useCanvas) {\n return;\n }\n\n this._getContext( useSketch ).restore();\n },\n\n // private\n setClip: function(rect, useSketch) {\n if (!this.useCanvas) {\n return;\n }\n\n var context = this._getContext( useSketch );\n context.beginPath();\n context.rect(rect.x, rect.y, rect.width, rect.height);\n context.clip();\n },\n\n // private\n drawRectangle: function(rect, fillStyle, useSketch) {\n if (!this.useCanvas) {\n return;\n }\n\n var context = this._getContext( useSketch );\n context.save();\n context.fillStyle = fillStyle;\n context.fillRect(rect.x, rect.y, rect.width, rect.height);\n context.restore();\n },\n\n /**\n * Blends the sketch canvas in the main canvas.\n * @param {Object} options The options\n * @param {Float} options.opacity The opacity of the blending.\n * @param {Float} [options.scale=1] The scale at which tiles were drawn on\n * the sketch. Default is 1.\n * Use scale to draw at a lower scale and then enlarge onto the main canvas.\n * @param {OpenSeadragon.Point} [options.translate] A translation vector\n * that was used to draw the tiles\n * @param {String} [options.compositeOperation] - How the image is\n * composited onto other images; see compositeOperation in\n * {@link OpenSeadragon.Options} for possible values.\n * @param {OpenSeadragon.Rect} [options.bounds] The part of the sketch\n * canvas to blend in the main canvas. If specified, options.scale and\n * options.translate get ignored.\n */\n blendSketch: function(opacity, scale, translate, compositeOperation) {\n var options = opacity;\n if (!$.isPlainObject(options)) {\n options = {\n opacity: opacity,\n scale: scale,\n translate: translate,\n compositeOperation: compositeOperation\n };\n }\n if (!this.useCanvas || !this.sketchCanvas) {\n return;\n }\n opacity = options.opacity;\n compositeOperation = options.compositeOperation;\n var bounds = options.bounds;\n\n this.context.save();\n this.context.globalAlpha = opacity;\n if (compositeOperation) {\n this.context.globalCompositeOperation = compositeOperation;\n }\n if (bounds) {\n // Internet Explorer, Microsoft Edge, and Safari have problems\n // when you call context.drawImage with negative x or y\n // or x + width or y + height greater than the canvas width or height respectively.\n if (bounds.x < 0) {\n bounds.width += bounds.x;\n bounds.x = 0;\n }\n if (bounds.x + bounds.width > this.canvas.width) {\n bounds.width = this.canvas.width - bounds.x;\n }\n if (bounds.y < 0) {\n bounds.height += bounds.y;\n bounds.y = 0;\n }\n if (bounds.y + bounds.height > this.canvas.height) {\n bounds.height = this.canvas.height - bounds.y;\n }\n\n this.context.drawImage(\n this.sketchCanvas,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height\n );\n } else {\n scale = options.scale || 1;\n translate = options.translate;\n var position = translate instanceof $.Point ?\n translate : new $.Point(0, 0);\n\n var widthExt = 0;\n var heightExt = 0;\n if (translate) {\n var widthDiff = this.sketchCanvas.width - this.canvas.width;\n var heightDiff = this.sketchCanvas.height - this.canvas.height;\n widthExt = Math.round(widthDiff / 2);\n heightExt = Math.round(heightDiff / 2);\n }\n this.context.drawImage(\n this.sketchCanvas,\n position.x - widthExt * scale,\n position.y - heightExt * scale,\n (this.canvas.width + 2 * widthExt) * scale,\n (this.canvas.height + 2 * heightExt) * scale,\n -widthExt,\n -heightExt,\n this.canvas.width + 2 * widthExt,\n this.canvas.height + 2 * heightExt\n );\n }\n this.context.restore();\n },\n\n // private\n drawDebugInfo: function(tile, count, i, tiledImage) {\n if ( !this.useCanvas ) {\n return;\n }\n\n var colorIndex = this.viewer.world.getIndexOfItem(tiledImage) % this.debugGridColor.length;\n var context = this.context;\n context.save();\n context.lineWidth = 2 * $.pixelDensityRatio;\n context.font = 'small-caps bold ' + (13 * $.pixelDensityRatio) + 'px arial';\n context.strokeStyle = this.debugGridColor[colorIndex];\n context.fillStyle = this.debugGridColor[colorIndex];\n\n if ( this.viewport.degrees !== 0 ) {\n this._offsetForRotation({degrees: this.viewport.degrees});\n } else{\n if(this.viewer.viewport.flipped) {\n this._flip();\n }\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n this._offsetForRotation({\n degrees: tiledImage.getRotation(true),\n point: tiledImage.viewport.pixelFromPointNoRotate(\n tiledImage._getRotationPoint(true), true)\n });\n }\n\n context.strokeRect(\n tile.position.x * $.pixelDensityRatio,\n tile.position.y * $.pixelDensityRatio,\n tile.size.x * $.pixelDensityRatio,\n tile.size.y * $.pixelDensityRatio\n );\n\n var tileCenterX = (tile.position.x + (tile.size.x / 2)) * $.pixelDensityRatio;\n var tileCenterY = (tile.position.y + (tile.size.y / 2)) * $.pixelDensityRatio;\n\n // Rotate the text the right way around.\n context.translate( tileCenterX, tileCenterY );\n context.rotate( Math.PI / 180 * -this.viewport.degrees );\n context.translate( -tileCenterX, -tileCenterY );\n\n if( tile.x === 0 && tile.y === 0 ){\n context.fillText(\n \"Zoom: \" + this.viewport.getZoom(),\n tile.position.x * $.pixelDensityRatio,\n (tile.position.y - 30) * $.pixelDensityRatio\n );\n context.fillText(\n \"Pan: \" + this.viewport.getBounds().toString(),\n tile.position.x * $.pixelDensityRatio,\n (tile.position.y - 20) * $.pixelDensityRatio\n );\n }\n context.fillText(\n \"Level: \" + tile.level,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 20) * $.pixelDensityRatio\n );\n context.fillText(\n \"Column: \" + tile.x,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 30) * $.pixelDensityRatio\n );\n context.fillText(\n \"Row: \" + tile.y,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 40) * $.pixelDensityRatio\n );\n context.fillText(\n \"Order: \" + i + \" of \" + count,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 50) * $.pixelDensityRatio\n );\n context.fillText(\n \"Size: \" + tile.size.toString(),\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 60) * $.pixelDensityRatio\n );\n context.fillText(\n \"Position: \" + tile.position.toString(),\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 70) * $.pixelDensityRatio\n );\n\n if ( this.viewport.degrees !== 0 ) {\n this._restoreRotationChanges();\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n this._restoreRotationChanges();\n }\n context.restore();\n },\n\n // private\n debugRect: function(rect) {\n if ( this.useCanvas ) {\n var context = this.context;\n context.save();\n context.lineWidth = 2 * $.pixelDensityRatio;\n context.strokeStyle = this.debugGridColor[0];\n context.fillStyle = this.debugGridColor[0];\n\n context.strokeRect(\n rect.x * $.pixelDensityRatio,\n rect.y * $.pixelDensityRatio,\n rect.width * $.pixelDensityRatio,\n rect.height * $.pixelDensityRatio\n );\n\n context.restore();\n }\n },\n\n /**\n * Get the canvas size\n * @param {Boolean} sketch If set to true return the size of the sketch canvas\n * @returns {OpenSeadragon.Point} The size of the canvas\n */\n getCanvasSize: function(sketch) {\n var canvas = this._getContext(sketch).canvas;\n return new $.Point(canvas.width, canvas.height);\n },\n\n getCanvasCenter: function() {\n return new $.Point(this.canvas.width / 2, this.canvas.height / 2);\n },\n\n // private\n _offsetForRotation: function(options) {\n var point = options.point ?\n options.point.times($.pixelDensityRatio) :\n this.getCanvasCenter();\n\n var context = this._getContext(options.useSketch);\n context.save();\n\n context.translate(point.x, point.y);\n if(this.viewer.viewport.flipped){\n context.rotate(Math.PI / 180 * -options.degrees);\n context.scale(-1, 1);\n } else{\n context.rotate(Math.PI / 180 * options.degrees);\n }\n context.translate(-point.x, -point.y);\n },\n\n // private\n _flip: function(options) {\n options = options || {};\n var point = options.point ?\n options.point.times($.pixelDensityRatio) :\n this.getCanvasCenter();\n var context = this._getContext(options.useSketch);\n\n context.translate(point.x, 0);\n context.scale(-1, 1);\n context.translate(-point.x, 0);\n },\n\n // private\n _restoreRotationChanges: function(useSketch) {\n var context = this._getContext(useSketch);\n context.restore();\n },\n\n // private\n _calculateCanvasSize: function() {\n var pixelDensityRatio = $.pixelDensityRatio;\n var viewportSize = this.viewport.getContainerSize();\n return {\n x: viewportSize.x * pixelDensityRatio,\n y: viewportSize.y * pixelDensityRatio\n };\n },\n\n // private\n _calculateSketchCanvasSize: function() {\n var canvasSize = this._calculateCanvasSize();\n if (this.viewport.getRotation() === 0) {\n return canvasSize;\n }\n // If the viewport is rotated, we need a larger sketch canvas in order\n // to support edge smoothing.\n var sketchCanvasSize = Math.ceil(Math.sqrt(\n canvasSize.x * canvasSize.x +\n canvasSize.y * canvasSize.y));\n return {\n x: sketchCanvasSize,\n y: sketchCanvasSize\n };\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Viewport\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n\n/**\n * @class Viewport\n * @memberof OpenSeadragon\n * @classdesc Handles coordinate-related functionality (zoom, pan, rotation, etc.)\n * for an {@link OpenSeadragon.Viewer}.\n * @param {Object} options - Options for this Viewport.\n * @param {Object} [options.margins] - See viewportMargins in {@link OpenSeadragon.Options}.\n * @param {Number} [options.springStiffness] - See springStiffness in {@link OpenSeadragon.Options}.\n * @param {Number} [options.animationTime] - See animationTime in {@link OpenSeadragon.Options}.\n * @param {Number} [options.minZoomImageRatio] - See minZoomImageRatio in {@link OpenSeadragon.Options}.\n * @param {Number} [options.maxZoomPixelRatio] - See maxZoomPixelRatio in {@link OpenSeadragon.Options}.\n * @param {Number} [options.visibilityRatio] - See visibilityRatio in {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapHorizontal] - See wrapHorizontal in {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapVertical] - See wrapVertical in {@link OpenSeadragon.Options}.\n * @param {Number} [options.defaultZoomLevel] - See defaultZoomLevel in {@link OpenSeadragon.Options}.\n * @param {Number} [options.minZoomLevel] - See minZoomLevel in {@link OpenSeadragon.Options}.\n * @param {Number} [options.maxZoomLevel] - See maxZoomLevel in {@link OpenSeadragon.Options}.\n * @param {Number} [options.degrees] - See degrees in {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.homeFillsViewer] - See homeFillsViewer in {@link OpenSeadragon.Options}.\n */\n$.Viewport = function( options ) {\n\n //backward compatibility for positional args while prefering more\n //idiomatic javascript options object as the only argument\n var args = arguments;\n if (args.length && args[0] instanceof $.Point) {\n options = {\n containerSize: args[0],\n contentSize: args[1],\n config: args[2]\n };\n }\n\n //options.config and the general config argument are deprecated\n //in favor of the more direct specification of optional settings\n //being passed directly on the options object\n if ( options.config ){\n $.extend( true, options, options.config );\n delete options.config;\n }\n\n this._margins = $.extend({\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n }, options.margins || {});\n\n delete options.margins;\n\n $.extend( true, this, {\n\n //required settings\n containerSize: null,\n contentSize: null,\n\n //internal state properties\n zoomPoint: null,\n viewer: null,\n\n //configurable options\n springStiffness: $.DEFAULT_SETTINGS.springStiffness,\n animationTime: $.DEFAULT_SETTINGS.animationTime,\n minZoomImageRatio: $.DEFAULT_SETTINGS.minZoomImageRatio,\n maxZoomPixelRatio: $.DEFAULT_SETTINGS.maxZoomPixelRatio,\n visibilityRatio: $.DEFAULT_SETTINGS.visibilityRatio,\n wrapHorizontal: $.DEFAULT_SETTINGS.wrapHorizontal,\n wrapVertical: $.DEFAULT_SETTINGS.wrapVertical,\n defaultZoomLevel: $.DEFAULT_SETTINGS.defaultZoomLevel,\n minZoomLevel: $.DEFAULT_SETTINGS.minZoomLevel,\n maxZoomLevel: $.DEFAULT_SETTINGS.maxZoomLevel,\n degrees: $.DEFAULT_SETTINGS.degrees,\n flipped: $.DEFAULT_SETTINGS.flipped,\n homeFillsViewer: $.DEFAULT_SETTINGS.homeFillsViewer\n\n }, options );\n\n this._updateContainerInnerSize();\n\n this.centerSpringX = new $.Spring({\n initial: 0,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n this.centerSpringY = new $.Spring({\n initial: 0,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n this.zoomSpring = new $.Spring({\n exponential: true,\n initial: 1,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._oldCenterX = this.centerSpringX.current.value;\n this._oldCenterY = this.centerSpringY.current.value;\n this._oldZoom = this.zoomSpring.current.value;\n\n this._setContentBounds(new $.Rect(0, 0, 1, 1), 1);\n\n this.goHome(true);\n this.update();\n};\n\n/** @lends OpenSeadragon.Viewport.prototype */\n$.Viewport.prototype = {\n /**\n * Updates the viewport's home bounds and constraints for the given content size.\n * @function\n * @param {OpenSeadragon.Point} contentSize - size of the content in content units\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:reset-size\n */\n resetContentSize: function(contentSize) {\n $.console.assert(contentSize, \"[Viewport.resetContentSize] contentSize is required\");\n $.console.assert(contentSize instanceof $.Point, \"[Viewport.resetContentSize] contentSize must be an OpenSeadragon.Point\");\n $.console.assert(contentSize.x > 0, \"[Viewport.resetContentSize] contentSize.x must be greater than 0\");\n $.console.assert(contentSize.y > 0, \"[Viewport.resetContentSize] contentSize.y must be greater than 0\");\n\n this._setContentBounds(new $.Rect(0, 0, 1, contentSize.y / contentSize.x), contentSize.x);\n return this;\n },\n\n // deprecated\n setHomeBounds: function(bounds, contentFactor) {\n $.console.error(\"[Viewport.setHomeBounds] this function is deprecated; The content bounds should not be set manually.\");\n this._setContentBounds(bounds, contentFactor);\n },\n\n // Set the viewport's content bounds\n // @param {OpenSeadragon.Rect} bounds - the new bounds in viewport coordinates\n // without rotation\n // @param {Number} contentFactor - how many content units per viewport unit\n // @fires OpenSeadragon.Viewer.event:reset-size\n // @private\n _setContentBounds: function(bounds, contentFactor) {\n $.console.assert(bounds, \"[Viewport._setContentBounds] bounds is required\");\n $.console.assert(bounds instanceof $.Rect, \"[Viewport._setContentBounds] bounds must be an OpenSeadragon.Rect\");\n $.console.assert(bounds.width > 0, \"[Viewport._setContentBounds] bounds.width must be greater than 0\");\n $.console.assert(bounds.height > 0, \"[Viewport._setContentBounds] bounds.height must be greater than 0\");\n\n this._contentBoundsNoRotate = bounds.clone();\n this._contentSizeNoRotate = this._contentBoundsNoRotate.getSize().times(\n contentFactor);\n\n this._contentBounds = bounds.rotate(this.degrees).getBoundingBox();\n this._contentSize = this._contentBounds.getSize().times(contentFactor);\n this._contentAspectRatio = this._contentSize.x / this._contentSize.y;\n\n if (this.viewer) {\n /**\n * Raised when the viewer's content size or home bounds are reset\n * (see {@link OpenSeadragon.Viewport#resetContentSize}).\n *\n * @event reset-size\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.Point} contentSize\n * @property {OpenSeadragon.Rect} contentBounds - Content bounds.\n * @property {OpenSeadragon.Rect} homeBounds - Content bounds.\n * Deprecated use contentBounds instead.\n * @property {Number} contentFactor\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('reset-size', {\n contentSize: this._contentSizeNoRotate.clone(),\n contentFactor: contentFactor,\n homeBounds: this._contentBoundsNoRotate.clone(),\n contentBounds: this._contentBounds.clone()\n });\n }\n },\n\n /**\n * Returns the home zoom in \"viewport zoom\" value.\n * @function\n * @returns {Number} The home zoom in \"viewport zoom\".\n */\n getHomeZoom: function() {\n if (this.defaultZoomLevel) {\n return this.defaultZoomLevel;\n }\n\n var aspectFactor = this._contentAspectRatio / this.getAspectRatio();\n var output;\n if (this.homeFillsViewer) { // fill the viewer and clip the image\n output = aspectFactor >= 1 ? aspectFactor : 1;\n } else {\n output = aspectFactor >= 1 ? 1 : aspectFactor;\n }\n\n return output / this._contentBounds.width;\n },\n\n /**\n * Returns the home bounds in viewport coordinates.\n * @function\n * @returns {OpenSeadragon.Rect} The home bounds in vewport coordinates.\n */\n getHomeBounds: function() {\n return this.getHomeBoundsNoRotate().rotate(-this.getRotation());\n },\n\n /**\n * Returns the home bounds in viewport coordinates.\n * This method ignores the viewport rotation. Use\n * {@link OpenSeadragon.Viewport#getHomeBounds} to take it into account.\n * @function\n * @returns {OpenSeadragon.Rect} The home bounds in vewport coordinates.\n */\n getHomeBoundsNoRotate: function() {\n var center = this._contentBounds.getCenter();\n var width = 1.0 / this.getHomeZoom();\n var height = width / this.getAspectRatio();\n\n return new $.Rect(\n center.x - (width / 2.0),\n center.y - (height / 2.0),\n width,\n height\n );\n },\n\n /**\n * @function\n * @param {Boolean} immediately\n * @fires OpenSeadragon.Viewer.event:home\n */\n goHome: function(immediately) {\n if (this.viewer) {\n /**\n * Raised when the \"home\" operation occurs (see {@link OpenSeadragon.Viewport#goHome}).\n *\n * @event home\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Boolean} immediately\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('home', {\n immediately: immediately\n });\n }\n return this.fitBounds(this.getHomeBounds(), immediately);\n },\n\n /**\n * @function\n */\n getMinZoom: function() {\n var homeZoom = this.getHomeZoom(),\n zoom = this.minZoomLevel ?\n this.minZoomLevel :\n this.minZoomImageRatio * homeZoom;\n\n return zoom;\n },\n\n /**\n * @function\n */\n getMaxZoom: function() {\n var zoom = this.maxZoomLevel;\n if (!zoom) {\n zoom = this._contentSize.x * this.maxZoomPixelRatio / this._containerInnerSize.x;\n zoom /= this._contentBounds.width;\n }\n\n return Math.max( zoom, this.getHomeZoom() );\n },\n\n /**\n * @function\n */\n getAspectRatio: function() {\n return this._containerInnerSize.x / this._containerInnerSize.y;\n },\n\n /**\n * @function\n * @returns {OpenSeadragon.Point} The size of the container, in screen coordinates.\n */\n getContainerSize: function() {\n return new $.Point(\n this.containerSize.x,\n this.containerSize.y\n );\n },\n\n /**\n * The margins push the \"home\" region in from the sides by the specified amounts.\n * @function\n * @returns {Object} Properties (Numbers, in screen coordinates): left, top, right, bottom.\n */\n getMargins: function() {\n return $.extend({}, this._margins); // Make a copy so we are not returning our original\n },\n\n /**\n * The margins push the \"home\" region in from the sides by the specified amounts.\n * @function\n * @param {Object} margins - Properties (Numbers, in screen coordinates): left, top, right, bottom.\n */\n setMargins: function(margins) {\n $.console.assert($.type(margins) === 'object', '[Viewport.setMargins] margins must be an object');\n\n this._margins = $.extend({\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n }, margins);\n\n this._updateContainerInnerSize();\n if (this.viewer) {\n this.viewer.forceRedraw();\n }\n },\n\n /**\n * Returns the bounds of the visible area in viewport coordinates.\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to, in viewport coordinates.\n */\n getBounds: function(current) {\n return this.getBoundsNoRotate(current).rotate(-this.getRotation());\n },\n\n /**\n * Returns the bounds of the visible area in viewport coordinates.\n * This method ignores the viewport rotation. Use\n * {@link OpenSeadragon.Viewport#getBounds} to take it into account.\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to, in viewport coordinates.\n */\n getBoundsNoRotate: function(current) {\n var center = this.getCenter(current);\n var width = 1.0 / this.getZoom(current);\n var height = width / this.getAspectRatio();\n\n return new $.Rect(\n center.x - (width / 2.0),\n center.y - (height / 2.0),\n width,\n height\n );\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to,\n * including the space taken by margins, in viewport coordinates.\n */\n getBoundsWithMargins: function(current) {\n return this.getBoundsNoRotateWithMargins(current).rotate(\n -this.getRotation(), this.getCenter(current));\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to,\n * including the space taken by margins, in viewport coordinates.\n */\n getBoundsNoRotateWithMargins: function(current) {\n var bounds = this.getBoundsNoRotate(current);\n var factor = this._containerInnerSize.x * this.getZoom(current);\n bounds.x -= this._margins.left / factor;\n bounds.y -= this._margins.top / factor;\n bounds.width += (this._margins.left + this._margins.right) / factor;\n bounds.height += (this._margins.top + this._margins.bottom) / factor;\n return bounds;\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n */\n getCenter: function( current ) {\n var centerCurrent = new $.Point(\n this.centerSpringX.current.value,\n this.centerSpringY.current.value\n ),\n centerTarget = new $.Point(\n this.centerSpringX.target.value,\n this.centerSpringY.target.value\n ),\n oldZoomPixel,\n zoom,\n width,\n height,\n bounds,\n newZoomPixel,\n deltaZoomPixels,\n deltaZoomPoints;\n\n if ( current ) {\n return centerCurrent;\n } else if ( !this.zoomPoint ) {\n return centerTarget;\n }\n\n oldZoomPixel = this.pixelFromPoint(this.zoomPoint, true);\n\n zoom = this.getZoom();\n width = 1.0 / zoom;\n height = width / this.getAspectRatio();\n bounds = new $.Rect(\n centerCurrent.x - width / 2.0,\n centerCurrent.y - height / 2.0,\n width,\n height\n );\n\n newZoomPixel = this._pixelFromPoint(this.zoomPoint, bounds);\n deltaZoomPixels = newZoomPixel.minus( oldZoomPixel );\n deltaZoomPoints = deltaZoomPixels.divide( this._containerInnerSize.x * zoom );\n\n return centerTarget.plus( deltaZoomPoints );\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n */\n getZoom: function( current ) {\n if ( current ) {\n return this.zoomSpring.current.value;\n } else {\n return this.zoomSpring.target.value;\n }\n },\n\n // private\n _applyZoomConstraints: function(zoom) {\n return Math.max(\n Math.min(zoom, this.getMaxZoom()),\n this.getMinZoom());\n },\n\n /**\n * @function\n * @private\n * @param {OpenSeadragon.Rect} bounds\n * @return {OpenSeadragon.Rect} constrained bounds.\n */\n _applyBoundaryConstraints: function(bounds) {\n var newBounds = new $.Rect(\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height);\n\n if (this.wrapHorizontal) {\n //do nothing\n } else {\n var horizontalThreshold = this.visibilityRatio * newBounds.width;\n var boundsRight = newBounds.x + newBounds.width;\n var contentRight = this._contentBoundsNoRotate.x + this._contentBoundsNoRotate.width;\n var leftDx = this._contentBoundsNoRotate.x - boundsRight + horizontalThreshold;\n var rightDx = contentRight - newBounds.x - horizontalThreshold;\n\n if (horizontalThreshold > this._contentBoundsNoRotate.width) {\n newBounds.x += (leftDx + rightDx) / 2;\n } else if (rightDx < 0) {\n newBounds.x += rightDx;\n } else if (leftDx > 0) {\n newBounds.x += leftDx;\n }\n }\n\n if (this.wrapVertical) {\n //do nothing\n } else {\n var verticalThreshold = this.visibilityRatio * newBounds.height;\n var boundsBottom = newBounds.y + newBounds.height;\n var contentBottom = this._contentBoundsNoRotate.y + this._contentBoundsNoRotate.height;\n var topDy = this._contentBoundsNoRotate.y - boundsBottom + verticalThreshold;\n var bottomDy = contentBottom - newBounds.y - verticalThreshold;\n\n if (verticalThreshold > this._contentBoundsNoRotate.height) {\n newBounds.y += (topDy + bottomDy) / 2;\n } else if (bottomDy < 0) {\n newBounds.y += bottomDy;\n } else if (topDy > 0) {\n newBounds.y += topDy;\n }\n }\n\n return newBounds;\n },\n\n /**\n * @function\n * @private\n * @param {Boolean} [immediately=false] - whether the function that triggered this event was\n * called with the \"immediately\" flag\n */\n _raiseConstraintsEvent: function(immediately) {\n if (this.viewer) {\n /**\n * Raised when the viewport constraints are applied (see {@link OpenSeadragon.Viewport#applyConstraints}).\n *\n * @event constrain\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Boolean} immediately - whether the function that triggered this event was\n * called with the \"immediately\" flag\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'constrain', {\n immediately: immediately\n });\n }\n },\n\n /**\n * Enforces the minZoom, maxZoom and visibilityRatio constraints by\n * zooming and panning to the closest acceptable zoom and location.\n * @function\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:constrain\n */\n applyConstraints: function(immediately) {\n var actualZoom = this.getZoom();\n var constrainedZoom = this._applyZoomConstraints(actualZoom);\n\n if (actualZoom !== constrainedZoom) {\n this.zoomTo(constrainedZoom, this.zoomPoint, immediately);\n }\n\n var bounds = this.getBoundsNoRotate();\n var constrainedBounds = this._applyBoundaryConstraints(bounds);\n this._raiseConstraintsEvent(immediately);\n\n if (bounds.x !== constrainedBounds.x ||\n bounds.y !== constrainedBounds.y ||\n immediately) {\n this.fitBounds(\n constrainedBounds.rotate(-this.getRotation()),\n immediately);\n }\n return this;\n },\n\n /**\n * Equivalent to {@link OpenSeadragon.Viewport#applyConstraints}\n * @function\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:constrain\n */\n ensureVisible: function(immediately) {\n return this.applyConstraints(immediately);\n },\n\n /**\n * @function\n * @private\n * @param {OpenSeadragon.Rect} bounds\n * @param {Object} options (immediately=false, constraints=false)\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n _fitBounds: function(bounds, options) {\n options = options || {};\n var immediately = options.immediately || false;\n var constraints = options.constraints || false;\n\n var aspect = this.getAspectRatio();\n var center = bounds.getCenter();\n\n // Compute width and height of bounding box.\n var newBounds = new $.Rect(\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n bounds.degrees + this.getRotation())\n .getBoundingBox();\n\n if (newBounds.getAspectRatio() >= aspect) {\n newBounds.height = newBounds.width / aspect;\n } else {\n newBounds.width = newBounds.height * aspect;\n }\n\n // Compute x and y from width, height and center position\n newBounds.x = center.x - newBounds.width / 2;\n newBounds.y = center.y - newBounds.height / 2;\n var newZoom = 1.0 / newBounds.width;\n\n if (constraints) {\n var newBoundsAspectRatio = newBounds.getAspectRatio();\n var newConstrainedZoom = this._applyZoomConstraints(newZoom);\n\n if (newZoom !== newConstrainedZoom) {\n newZoom = newConstrainedZoom;\n newBounds.width = 1.0 / newZoom;\n newBounds.x = center.x - newBounds.width / 2;\n newBounds.height = newBounds.width / newBoundsAspectRatio;\n newBounds.y = center.y - newBounds.height / 2;\n }\n\n newBounds = this._applyBoundaryConstraints(newBounds);\n center = newBounds.getCenter();\n this._raiseConstraintsEvent(immediately);\n }\n\n if (immediately) {\n this.panTo(center, true);\n return this.zoomTo(newZoom, null, true);\n }\n\n this.panTo(this.getCenter(true), true);\n this.zoomTo(this.getZoom(true), null, true);\n\n var oldBounds = this.getBounds();\n var oldZoom = this.getZoom();\n\n if (oldZoom === 0 || Math.abs(newZoom / oldZoom - 1) < 0.00000001) {\n this.zoomTo(newZoom, true);\n return this.panTo(center, immediately);\n }\n\n newBounds = newBounds.rotate(-this.getRotation());\n var referencePoint = newBounds.getTopLeft().times(newZoom)\n .minus(oldBounds.getTopLeft().times(oldZoom))\n .divide(newZoom - oldZoom);\n\n return this.zoomTo(newZoom, referencePoint, immediately);\n },\n\n /**\n * Makes the viewport zoom and pan so that the specified bounds take\n * as much space as possible in the viewport.\n * Note: this method ignores the constraints (minZoom, maxZoom and\n * visibilityRatio).\n * Use {@link OpenSeadragon.Viewport#fitBoundsWithConstraints} to enforce\n * them.\n * @function\n * @param {OpenSeadragon.Rect} bounds\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitBounds: function(bounds, immediately) {\n return this._fitBounds(bounds, {\n immediately: immediately,\n constraints: false\n });\n },\n\n /**\n * Makes the viewport zoom and pan so that the specified bounds take\n * as much space as possible in the viewport while enforcing the constraints\n * (minZoom, maxZoom and visibilityRatio).\n * Note: because this method enforces the constraints, part of the\n * provided bounds may end up outside of the viewport.\n * Use {@link OpenSeadragon.Viewport#fitBounds} to ignore them.\n * @function\n * @param {OpenSeadragon.Rect} bounds\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitBoundsWithConstraints: function(bounds, immediately) {\n return this._fitBounds(bounds, {\n immediately: immediately,\n constraints: true\n });\n },\n\n /**\n * Zooms so the image just fills the viewer vertically.\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitVertically: function(immediately) {\n var box = new $.Rect(\n this._contentBounds.x + (this._contentBounds.width / 2),\n this._contentBounds.y,\n 0,\n this._contentBounds.height);\n return this.fitBounds(box, immediately);\n },\n\n /**\n * Zooms so the image just fills the viewer horizontally.\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitHorizontally: function(immediately) {\n var box = new $.Rect(\n this._contentBounds.x,\n this._contentBounds.y + (this._contentBounds.height / 2),\n this._contentBounds.width,\n 0);\n return this.fitBounds(box, immediately);\n },\n\n\n /**\n * Returns bounds taking constraints into account\n * Added to improve constrained panning\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n getConstrainedBounds: function(current) {\n var bounds,\n constrainedBounds;\n\n bounds = this.getBounds(current);\n\n constrainedBounds = this._applyBoundaryConstraints(bounds);\n\n return constrainedBounds;\n },\n\n /**\n * @function\n * @param {OpenSeadragon.Point} delta\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:pan\n */\n panBy: function( delta, immediately ) {\n var center = new $.Point(\n this.centerSpringX.target.value,\n this.centerSpringY.target.value\n );\n return this.panTo( center.plus( delta ), immediately );\n },\n\n /**\n * @function\n * @param {OpenSeadragon.Point} center\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:pan\n */\n panTo: function( center, immediately ) {\n if ( immediately ) {\n this.centerSpringX.resetTo( center.x );\n this.centerSpringY.resetTo( center.y );\n } else {\n this.centerSpringX.springTo( center.x );\n this.centerSpringY.springTo( center.y );\n }\n\n if( this.viewer ){\n /**\n * Raised when the viewport is panned (see {@link OpenSeadragon.Viewport#panBy} and {@link OpenSeadragon.Viewport#panTo}).\n *\n * @event pan\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.Point} center\n * @property {Boolean} immediately\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'pan', {\n center: center,\n immediately: immediately\n });\n }\n\n return this;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:zoom\n */\n zoomBy: function(factor, refPoint, immediately) {\n return this.zoomTo(\n this.zoomSpring.target.value * factor, refPoint, immediately);\n },\n\n /**\n * Zooms to the specified zoom level\n * @function\n * @param {Number} zoom The zoom level to zoom to.\n * @param {OpenSeadragon.Point} [refPoint] The point which will stay at\n * the same screen location. Defaults to the viewport center.\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:zoom\n */\n zoomTo: function(zoom, refPoint, immediately) {\n var _this = this;\n\n this.zoomPoint = refPoint instanceof $.Point &&\n !isNaN(refPoint.x) &&\n !isNaN(refPoint.y) ?\n refPoint :\n null;\n\n if (immediately) {\n this._adjustCenterSpringsForZoomPoint(function() {\n _this.zoomSpring.resetTo(zoom);\n });\n } else {\n this.zoomSpring.springTo(zoom);\n }\n\n if (this.viewer) {\n /**\n * Raised when the viewport zoom level changes (see {@link OpenSeadragon.Viewport#zoomBy} and {@link OpenSeadragon.Viewport#zoomTo}).\n *\n * @event zoom\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Number} zoom\n * @property {OpenSeadragon.Point} refPoint\n * @property {Boolean} immediately\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('zoom', {\n zoom: zoom,\n refPoint: refPoint,\n immediately: immediately\n });\n }\n\n return this;\n },\n\n /**\n * Rotates this viewport to the angle specified.\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n setRotation: function(degrees) {\n if (!this.viewer || !this.viewer.drawer.canRotate()) {\n return this;\n }\n this.degrees = $.positiveModulo(degrees, 360);\n this._setContentBounds(\n this.viewer.world.getHomeBounds(),\n this.viewer.world.getContentFactor());\n this.viewer.forceRedraw();\n\n /**\n * Raised when rotation has been changed.\n *\n * @event rotate\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Number} degrees - The number of degrees the rotation was set to.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('rotate', {\"degrees\": degrees});\n return this;\n },\n\n /**\n * Gets the current rotation in degrees.\n * @function\n * @return {Number} The current rotation in degrees.\n */\n getRotation: function() {\n return this.degrees;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:resize\n */\n resize: function( newContainerSize, maintain ) {\n var oldBounds = this.getBoundsNoRotate(),\n newBounds = oldBounds,\n widthDeltaFactor;\n\n this.containerSize.x = newContainerSize.x;\n this.containerSize.y = newContainerSize.y;\n\n this._updateContainerInnerSize();\n\n if ( maintain ) {\n // TODO: widthDeltaFactor will always be 1; probably not what's intended\n widthDeltaFactor = newContainerSize.x / this.containerSize.x;\n newBounds.width = oldBounds.width * widthDeltaFactor;\n newBounds.height = newBounds.width / this.getAspectRatio();\n }\n\n if( this.viewer ){\n /**\n * Raised when the viewer is resized (see {@link OpenSeadragon.Viewport#resize}).\n *\n * @event resize\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.Point} newContainerSize\n * @property {Boolean} maintain\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'resize', {\n newContainerSize: newContainerSize,\n maintain: maintain\n });\n }\n\n return this.fitBounds( newBounds, true );\n },\n\n // private\n _updateContainerInnerSize: function() {\n this._containerInnerSize = new $.Point(\n Math.max(1, this.containerSize.x - (this._margins.left + this._margins.right)),\n Math.max(1, this.containerSize.y - (this._margins.top + this._margins.bottom))\n );\n },\n\n /**\n * Update the zoom and center (X and Y) springs.\n * @function\n * @returns {Boolean} True if any change has been made, false otherwise.\n */\n update: function() {\n var _this = this;\n this._adjustCenterSpringsForZoomPoint(function() {\n _this.zoomSpring.update();\n });\n\n this.centerSpringX.update();\n this.centerSpringY.update();\n\n var changed = this.centerSpringX.current.value !== this._oldCenterX ||\n this.centerSpringY.current.value !== this._oldCenterY ||\n this.zoomSpring.current.value !== this._oldZoom;\n\n this._oldCenterX = this.centerSpringX.current.value;\n this._oldCenterY = this.centerSpringY.current.value;\n this._oldZoom = this.zoomSpring.current.value;\n\n return changed;\n },\n\n _adjustCenterSpringsForZoomPoint: function(zoomSpringHandler) {\n if (this.zoomPoint) {\n var oldZoomPixel = this.pixelFromPoint(this.zoomPoint, true);\n zoomSpringHandler();\n var newZoomPixel = this.pixelFromPoint(this.zoomPoint, true);\n\n var deltaZoomPixels = newZoomPixel.minus(oldZoomPixel);\n var deltaZoomPoints = this.deltaPointsFromPixels(\n deltaZoomPixels, true);\n\n this.centerSpringX.shiftBy(deltaZoomPoints.x);\n this.centerSpringY.shiftBy(deltaZoomPoints.y);\n\n if (this.zoomSpring.isAtTargetValue()) {\n this.zoomPoint = null;\n }\n } else {\n zoomSpringHandler();\n }\n },\n\n /**\n * Convert a delta (translation vector) from viewport coordinates to pixels\n * coordinates. This method does not take rotation into account.\n * Consider using deltaPixelsFromPoints if you need to account for rotation.\n * @param {OpenSeadragon.Point} deltaPoints - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPixelsFromPointsNoRotate: function(deltaPoints, current) {\n return deltaPoints.times(\n this._containerInnerSize.x * this.getZoom(current)\n );\n },\n\n /**\n * Convert a delta (translation vector) from viewport coordinates to pixels\n * coordinates.\n * @param {OpenSeadragon.Point} deltaPoints - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPixelsFromPoints: function(deltaPoints, current) {\n return this.deltaPixelsFromPointsNoRotate(\n deltaPoints.rotate(this.getRotation()),\n current);\n },\n\n /**\n * Convert a delta (translation vector) from pixels coordinates to viewport\n * coordinates. This method does not take rotation into account.\n * Consider using deltaPointsFromPixels if you need to account for rotation.\n * @param {OpenSeadragon.Point} deltaPixels - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPointsFromPixelsNoRotate: function(deltaPixels, current) {\n return deltaPixels.divide(\n this._containerInnerSize.x * this.getZoom(current)\n );\n },\n\n /**\n * Convert a delta (translation vector) from pixels coordinates to viewport\n * coordinates.\n * @param {OpenSeadragon.Point} deltaPixels - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPointsFromPixels: function(deltaPixels, current) {\n return this.deltaPointsFromPixelsNoRotate(deltaPixels, current)\n .rotate(-this.getRotation());\n },\n\n /**\n * Convert viewport coordinates to pixels coordinates.\n * This method does not take rotation into account.\n * Consider using pixelFromPoint if you need to account for rotation.\n * @param {OpenSeadragon.Point} point the viewport coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pixelFromPointNoRotate: function(point, current) {\n return this._pixelFromPointNoRotate(\n point, this.getBoundsNoRotate(current));\n },\n\n /**\n * Convert viewport coordinates to pixel coordinates.\n * @param {OpenSeadragon.Point} point the viewport coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pixelFromPoint: function(point, current) {\n return this._pixelFromPoint(point, this.getBoundsNoRotate(current));\n },\n\n // private\n _pixelFromPointNoRotate: function(point, bounds) {\n return point.minus(\n bounds.getTopLeft()\n ).times(\n this._containerInnerSize.x / bounds.width\n ).plus(\n new $.Point(this._margins.left, this._margins.top)\n );\n },\n\n // private\n _pixelFromPoint: function(point, bounds) {\n return this._pixelFromPointNoRotate(\n point.rotate(this.getRotation(), this.getCenter(true)),\n bounds);\n },\n\n /**\n * Convert pixel coordinates to viewport coordinates.\n * This method does not take rotation into account.\n * Consider using pointFromPixel if you need to account for rotation.\n * @param {OpenSeadragon.Point} pixel Pixel coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pointFromPixelNoRotate: function(pixel, current) {\n var bounds = this.getBoundsNoRotate(current);\n return pixel.minus(\n new $.Point(this._margins.left, this._margins.top)\n ).divide(\n this._containerInnerSize.x / bounds.width\n ).plus(\n bounds.getTopLeft()\n );\n },\n\n /**\n * Convert pixel coordinates to viewport coordinates.\n * @param {OpenSeadragon.Point} pixel Pixel coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pointFromPixel: function(pixel, current) {\n return this.pointFromPixelNoRotate(pixel, current).rotate(\n -this.getRotation(),\n this.getCenter(true)\n );\n },\n\n // private\n _viewportToImageDelta: function( viewerX, viewerY ) {\n var scale = this._contentBoundsNoRotate.width;\n return new $.Point(\n viewerX * this._contentSizeNoRotate.x / scale,\n viewerY * this._contentSizeNoRotate.x / scale);\n },\n\n /**\n * Translates from OpenSeadragon viewer coordinate system to image coordinate system.\n * This method can be called either by passing X,Y coordinates or an\n * OpenSeadragon.Point\n * Note: not accurate with multi-image; use TiledImage.viewportToImageCoordinates instead.\n * @function\n * @param {(OpenSeadragon.Point|Number)} viewerX either a point or the X\n * coordinate in viewport coordinate system.\n * @param {Number} [viewerY] Y coordinate in viewport coordinate system.\n * @return {OpenSeadragon.Point} a point representing the coordinates in the image.\n */\n viewportToImageCoordinates: function(viewerX, viewerY) {\n if (viewerX instanceof $.Point) {\n //they passed a point instead of individual components\n return this.viewportToImageCoordinates(viewerX.x, viewerX.y);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.viewportToImageCoordinates] is not accurate ' +\n 'with multi-image; use TiledImage.viewportToImageCoordinates instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageCoordinates\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.viewportToImageCoordinates(viewerX, viewerY, true);\n }\n }\n\n return this._viewportToImageDelta(\n viewerX - this._contentBoundsNoRotate.x,\n viewerY - this._contentBoundsNoRotate.y);\n },\n\n // private\n _imageToViewportDelta: function( imageX, imageY ) {\n var scale = this._contentBoundsNoRotate.width;\n return new $.Point(\n imageX / this._contentSizeNoRotate.x * scale,\n imageY / this._contentSizeNoRotate.x * scale);\n },\n\n /**\n * Translates from image coordinate system to OpenSeadragon viewer coordinate system\n * This method can be called either by passing X,Y coordinates or an\n * OpenSeadragon.Point\n * Note: not accurate with multi-image; use TiledImage.imageToViewportCoordinates instead.\n * @function\n * @param {(OpenSeadragon.Point | Number)} imageX the point or the\n * X coordinate in image coordinate system.\n * @param {Number} [imageY] Y coordinate in image coordinate system.\n * @return {OpenSeadragon.Point} a point representing the coordinates in the viewport.\n */\n imageToViewportCoordinates: function(imageX, imageY) {\n if (imageX instanceof $.Point) {\n //they passed a point instead of individual components\n return this.imageToViewportCoordinates(imageX.x, imageX.y);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.imageToViewportCoordinates] is not accurate ' +\n 'with multi-image; use TiledImage.imageToViewportCoordinates instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageCoordinates\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.imageToViewportCoordinates(imageX, imageY, true);\n }\n }\n\n var point = this._imageToViewportDelta(imageX, imageY);\n point.x += this._contentBoundsNoRotate.x;\n point.y += this._contentBoundsNoRotate.y;\n return point;\n },\n\n /**\n * Translates from a rectangle which describes a portion of the image in\n * pixel coordinates to OpenSeadragon viewport rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an\n * OpenSeadragon.Rect\n * Note: not accurate with multi-image; use TiledImage.imageToViewportRectangle instead.\n * @function\n * @param {(OpenSeadragon.Rect | Number)} imageX the rectangle or the X\n * coordinate of the top left corner of the rectangle in image coordinate system.\n * @param {Number} [imageY] the Y coordinate of the top left corner of the rectangle\n * in image coordinate system.\n * @param {Number} [pixelWidth] the width in pixel of the rectangle.\n * @param {Number} [pixelHeight] the height in pixel of the rectangle.\n * @returns {OpenSeadragon.Rect} This image's bounds in viewport coordinates\n */\n imageToViewportRectangle: function(imageX, imageY, pixelWidth, pixelHeight) {\n var rect = imageX;\n if (!(rect instanceof $.Rect)) {\n //they passed individual components instead of a rectangle\n rect = new $.Rect(imageX, imageY, pixelWidth, pixelHeight);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.imageToViewportRectangle] is not accurate ' +\n 'with multi-image; use TiledImage.imageToViewportRectangle instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.imageToViewportRectangle\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.imageToViewportRectangle(\n imageX, imageY, pixelWidth, pixelHeight, true);\n }\n }\n\n var coordA = this.imageToViewportCoordinates(rect.x, rect.y);\n var coordB = this._imageToViewportDelta(rect.width, rect.height);\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees\n );\n },\n\n /**\n * Translates from a rectangle which describes a portion of\n * the viewport in point coordinates to image rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an\n * OpenSeadragon.Rect\n * Note: not accurate with multi-image; use TiledImage.viewportToImageRectangle instead.\n * @function\n * @param {(OpenSeadragon.Rect | Number)} viewerX either a rectangle or\n * the X coordinate of the top left corner of the rectangle in viewport\n * coordinate system.\n * @param {Number} [viewerY] the Y coordinate of the top left corner of the rectangle\n * in viewport coordinate system.\n * @param {Number} [pointWidth] the width of the rectangle in viewport coordinate system.\n * @param {Number} [pointHeight] the height of the rectangle in viewport coordinate system.\n */\n viewportToImageRectangle: function(viewerX, viewerY, pointWidth, pointHeight) {\n var rect = viewerX;\n if (!(rect instanceof $.Rect)) {\n //they passed individual components instead of a rectangle\n rect = new $.Rect(viewerX, viewerY, pointWidth, pointHeight);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.viewportToImageRectangle] is not accurate ' +\n 'with multi-image; use TiledImage.viewportToImageRectangle instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageCoordinates\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.viewportToImageRectangle(\n viewerX, viewerY, pointWidth, pointHeight, true);\n }\n }\n\n var coordA = this.viewportToImageCoordinates(rect.x, rect.y);\n var coordB = this._viewportToImageDelta(rect.width, rect.height);\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees\n );\n },\n\n /**\n * Convert pixel coordinates relative to the viewer element to image\n * coordinates.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n viewerElementToImageCoordinates: function( pixel ) {\n var point = this.pointFromPixel( pixel, true );\n return this.viewportToImageCoordinates( point );\n },\n\n /**\n * Convert pixel coordinates relative to the image to\n * viewer element coordinates.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToViewerElementCoordinates: function( pixel ) {\n var point = this.imageToViewportCoordinates( pixel );\n return this.pixelFromPoint( point, true );\n },\n\n /**\n * Convert pixel coordinates relative to the window to image coordinates.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n windowToImageCoordinates: function(pixel) {\n $.console.assert(this.viewer,\n \"[Viewport.windowToImageCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = pixel.minus(\n $.getElementPosition(this.viewer.element));\n return this.viewerElementToImageCoordinates(viewerCoordinates);\n },\n\n /**\n * Convert image coordinates to pixel coordinates relative to the window.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToWindowCoordinates: function(pixel) {\n $.console.assert(this.viewer,\n \"[Viewport.imageToWindowCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = this.imageToViewerElementCoordinates(pixel);\n return viewerCoordinates.plus(\n $.getElementPosition(this.viewer.element));\n },\n\n /**\n * Convert pixel coordinates relative to the viewer element to viewport\n * coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n viewerElementToViewportCoordinates: function( pixel ) {\n return this.pointFromPixel( pixel, true );\n },\n\n /**\n * Convert viewport coordinates to pixel coordinates relative to the\n * viewer element.\n * @param {OpenSeadragon.Point} point\n * @returns {OpenSeadragon.Point}\n */\n viewportToViewerElementCoordinates: function( point ) {\n return this.pixelFromPoint( point, true );\n },\n\n /**\n * Convert a rectangle in pixel coordinates relative to the viewer element\n * to viewport coordinates.\n * @param {OpenSeadragon.Rect} rectangle the rectangle to convert\n * @returns {OpenSeadragon.Rect} the converted rectangle\n */\n viewerElementToViewportRectangle: function(rectangle) {\n return $.Rect.fromSummits(\n this.pointFromPixel(rectangle.getTopLeft(), true),\n this.pointFromPixel(rectangle.getTopRight(), true),\n this.pointFromPixel(rectangle.getBottomLeft(), true)\n );\n },\n\n /**\n * Convert a rectangle in viewport coordinates to pixel coordinates relative\n * to the viewer element.\n * @param {OpenSeadragon.Rect} rectangle the rectangle to convert\n * @returns {OpenSeadragon.Rect} the converted rectangle\n */\n viewportToViewerElementRectangle: function(rectangle) {\n return $.Rect.fromSummits(\n this.pixelFromPoint(rectangle.getTopLeft(), true),\n this.pixelFromPoint(rectangle.getTopRight(), true),\n this.pixelFromPoint(rectangle.getBottomLeft(), true)\n );\n },\n\n /**\n * Convert pixel coordinates relative to the window to viewport coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n windowToViewportCoordinates: function(pixel) {\n $.console.assert(this.viewer,\n \"[Viewport.windowToViewportCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = pixel.minus(\n $.getElementPosition(this.viewer.element));\n return this.viewerElementToViewportCoordinates(viewerCoordinates);\n },\n\n /**\n * Convert viewport coordinates to pixel coordinates relative to the window.\n * @param {OpenSeadragon.Point} point\n * @returns {OpenSeadragon.Point}\n */\n viewportToWindowCoordinates: function(point) {\n $.console.assert(this.viewer,\n \"[Viewport.viewportToWindowCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = this.viewportToViewerElementCoordinates(point);\n return viewerCoordinates.plus(\n $.getElementPosition(this.viewer.element));\n },\n\n /**\n * Convert a viewport zoom to an image zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * Note: not accurate with multi-image.\n * @function\n * @param {Number} viewportZoom The viewport zoom\n * target zoom.\n * @returns {Number} imageZoom The image zoom\n */\n viewportToImageZoom: function(viewportZoom) {\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.viewportToImageZoom] is not ' +\n 'accurate with multi-image.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageZoom\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.viewportToImageZoom(viewportZoom);\n }\n }\n\n var imageWidth = this._contentSizeNoRotate.x;\n var containerWidth = this._containerInnerSize.x;\n var scale = this._contentBoundsNoRotate.width;\n var viewportToImageZoomRatio = (containerWidth / imageWidth) * scale;\n return viewportZoom * viewportToImageZoomRatio;\n },\n\n /**\n * Convert an image zoom to a viewport zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * Note: not accurate with multi-image.\n * @function\n * @param {Number} imageZoom The image zoom\n * target zoom.\n * @returns {Number} viewportZoom The viewport zoom\n */\n imageToViewportZoom: function(imageZoom) {\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.imageToViewportZoom] is not accurate ' +\n 'with multi-image.');\n } else if (count === 1) {\n // It is better to use TiledImage.imageToViewportZoom\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.imageToViewportZoom(imageZoom);\n }\n }\n\n var imageWidth = this._contentSizeNoRotate.x;\n var containerWidth = this._containerInnerSize.x;\n var scale = this._contentBoundsNoRotate.width;\n var viewportToImageZoomRatio = (imageWidth / containerWidth) / scale;\n return imageZoom * viewportToImageZoomRatio;\n },\n\n /**\n * Toggles flip state and demands a new drawing on navigator and viewer objects.\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n toggleFlip: function() {\n this.setFlip(!this.getFlip());\n return this;\n },\n\n /**\n * Gets flip state stored on viewport.\n * @function\n * @return {Boolean} Flip state.\n */\n getFlip: function() {\n return this.flipped;\n },\n\n /**\n * Sets flip state according to the state input argument.\n * @function\n * @param {Boolean} state - Flip state to set.\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n setFlip: function( state ) {\n if ( this.flipped === state ) {\n return this;\n }\n\n this.flipped = state;\n if(this.viewer.navigator){\n this.viewer.navigator.setFlip(this.getFlip());\n }\n this.viewer.forceRedraw();\n\n /**\n * Raised when flip state has been changed.\n *\n * @event flip\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Number} flipped - The flip state after this change.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('flip', {\"flipped\": state});\n return this;\n }\n\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TiledImage\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * You shouldn't have to create a TiledImage instance directly; get it asynchronously by\n * using {@link OpenSeadragon.Viewer#open} or {@link OpenSeadragon.Viewer#addTiledImage} instead.\n * @class TiledImage\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @classdesc Handles rendering of tiles for an {@link OpenSeadragon.Viewer}.\n * A new instance is created for each TileSource opened.\n * @param {Object} options - Configuration for this TiledImage.\n * @param {OpenSeadragon.TileSource} options.source - The TileSource that defines this TiledImage.\n * @param {OpenSeadragon.Viewer} options.viewer - The Viewer that owns this TiledImage.\n * @param {OpenSeadragon.TileCache} options.tileCache - The TileCache for this TiledImage to use.\n * @param {OpenSeadragon.Drawer} options.drawer - The Drawer for this TiledImage to draw onto.\n * @param {OpenSeadragon.ImageLoader} options.imageLoader - The ImageLoader for this TiledImage to use.\n * @param {Number} [options.x=0] - Left position, in viewport coordinates.\n * @param {Number} [options.y=0] - Top position, in viewport coordinates.\n * @param {Number} [options.width=1] - Width, in viewport coordinates.\n * @param {Number} [options.height] - Height, in viewport coordinates.\n * @param {OpenSeadragon.Rect} [options.fitBounds] The bounds in viewport coordinates\n * to fit the image into. If specified, x, y, width and height get ignored.\n * @param {OpenSeadragon.Placement} [options.fitBoundsPlacement=OpenSeadragon.Placement.CENTER]\n * How to anchor the image in the bounds if options.fitBounds is set.\n * @param {OpenSeadragon.Rect} [options.clip] - An area, in image pixels, to clip to\n * (portions of the image outside of this area will not be visible). Only works on\n * browsers that support the HTML5 canvas.\n * @param {Number} [options.springStiffness] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.animationTime] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.minZoomImageRatio] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapHorizontal] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapVertical] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.immediateRender] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.blendTime] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.alwaysBlend] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.minPixelRatio] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.smoothTileEdgesMinZoom] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.iOSDevice] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.opacity=1] - Set to draw at proportional opacity. If zero, images will not draw.\n * @param {Boolean} [options.preload=false] - Set true to load even when the image is hidden by zero opacity.\n * @param {String} [options.compositeOperation] - How the image is composited onto other images; see compositeOperation in {@link OpenSeadragon.Options} for possible values.\n * @param {Boolean} [options.debugMode] - See {@link OpenSeadragon.Options}.\n * @param {String|CanvasGradient|CanvasPattern|Function} [options.placeholderFillStyle] - See {@link OpenSeadragon.Options}.\n * @param {String|Boolean} [options.crossOriginPolicy] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.ajaxWithCredentials] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.loadTilesWithAjax]\n * Whether to load tile data using AJAX requests.\n * Defaults to the setting in {@link OpenSeadragon.Options}.\n * @param {Object} [options.ajaxHeaders={}]\n * A set of headers to include when making tile AJAX requests.\n */\n$.TiledImage = function( options ) {\n var _this = this;\n\n $.console.assert( options.tileCache, \"[TiledImage] options.tileCache is required\" );\n $.console.assert( options.drawer, \"[TiledImage] options.drawer is required\" );\n $.console.assert( options.viewer, \"[TiledImage] options.viewer is required\" );\n $.console.assert( options.imageLoader, \"[TiledImage] options.imageLoader is required\" );\n $.console.assert( options.source, \"[TiledImage] options.source is required\" );\n $.console.assert(!options.clip || options.clip instanceof $.Rect,\n \"[TiledImage] options.clip must be an OpenSeadragon.Rect if present\");\n\n $.EventSource.call( this );\n\n this._tileCache = options.tileCache;\n delete options.tileCache;\n\n this._drawer = options.drawer;\n delete options.drawer;\n\n this._imageLoader = options.imageLoader;\n delete options.imageLoader;\n\n if (options.clip instanceof $.Rect) {\n this._clip = options.clip.clone();\n }\n\n delete options.clip;\n\n var x = options.x || 0;\n delete options.x;\n var y = options.y || 0;\n delete options.y;\n\n // Ratio of zoomable image height to width.\n this.normHeight = options.source.dimensions.y / options.source.dimensions.x;\n this.contentAspectX = options.source.dimensions.x / options.source.dimensions.y;\n\n var scale = 1;\n if ( options.width ) {\n scale = options.width;\n delete options.width;\n\n if ( options.height ) {\n $.console.error( \"specifying both width and height to a tiledImage is not supported\" );\n delete options.height;\n }\n } else if ( options.height ) {\n scale = options.height / this.normHeight;\n delete options.height;\n }\n\n var fitBounds = options.fitBounds;\n delete options.fitBounds;\n var fitBoundsPlacement = options.fitBoundsPlacement || OpenSeadragon.Placement.CENTER;\n delete options.fitBoundsPlacement;\n\n var degrees = options.degrees || 0;\n delete options.degrees;\n\n $.extend( true, this, {\n\n //internal state properties\n viewer: null,\n tilesMatrix: {}, // A '3d' dictionary [level][x][y] --> Tile.\n coverage: {}, // A '3d' dictionary [level][x][y] --> Boolean; shows what areas have been drawn.\n loadingCoverage: {}, // A '3d' dictionary [level][x][y] --> Boolean; shows what areas are loaded or are being loaded/blended.\n lastDrawn: [], // An unordered list of Tiles drawn last frame.\n lastResetTime: 0, // Last time for which the tiledImage was reset.\n _midDraw: false, // Is the tiledImage currently updating the viewport?\n _needsDraw: true, // Does the tiledImage need to update the viewport again?\n _hasOpaqueTile: false, // Do we have even one fully opaque tile?\n _tilesLoading: 0, // The number of pending tile requests.\n //configurable settings\n springStiffness: $.DEFAULT_SETTINGS.springStiffness,\n animationTime: $.DEFAULT_SETTINGS.animationTime,\n minZoomImageRatio: $.DEFAULT_SETTINGS.minZoomImageRatio,\n wrapHorizontal: $.DEFAULT_SETTINGS.wrapHorizontal,\n wrapVertical: $.DEFAULT_SETTINGS.wrapVertical,\n immediateRender: $.DEFAULT_SETTINGS.immediateRender,\n blendTime: $.DEFAULT_SETTINGS.blendTime,\n alwaysBlend: $.DEFAULT_SETTINGS.alwaysBlend,\n minPixelRatio: $.DEFAULT_SETTINGS.minPixelRatio,\n smoothTileEdgesMinZoom: $.DEFAULT_SETTINGS.smoothTileEdgesMinZoom,\n iOSDevice: $.DEFAULT_SETTINGS.iOSDevice,\n debugMode: $.DEFAULT_SETTINGS.debugMode,\n crossOriginPolicy: $.DEFAULT_SETTINGS.crossOriginPolicy,\n ajaxWithCredentials: $.DEFAULT_SETTINGS.ajaxWithCredentials,\n placeholderFillStyle: $.DEFAULT_SETTINGS.placeholderFillStyle,\n opacity: $.DEFAULT_SETTINGS.opacity,\n preload: $.DEFAULT_SETTINGS.preload,\n compositeOperation: $.DEFAULT_SETTINGS.compositeOperation\n }, options );\n\n this._preload = this.preload;\n delete this.preload;\n\n this._fullyLoaded = false;\n\n this._xSpring = new $.Spring({\n initial: x,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._ySpring = new $.Spring({\n initial: y,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._scaleSpring = new $.Spring({\n initial: scale,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._degreesSpring = new $.Spring({\n initial: degrees,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._updateForScale();\n\n if (fitBounds) {\n this.fitBounds(fitBounds, fitBoundsPlacement, true);\n }\n\n // We need a callback to give image manipulation a chance to happen\n this._drawingHandler = function(args) {\n /**\n * This event is fired just before the tile is drawn giving the application a chance to alter the image.\n *\n * NOTE: This event is only fired when the drawer is using a <canvas>.\n *\n * @event tile-drawing\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.Tile} tile - The Tile being drawn.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {OpenSeadragon.Tile} context - The HTML canvas context being drawn into.\n * @property {OpenSeadragon.Tile} rendered - The HTML canvas context containing the tile imagery.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.viewer.raiseEvent('tile-drawing', $.extend({\n tiledImage: _this\n }, args));\n };\n};\n\n$.extend($.TiledImage.prototype, $.EventSource.prototype, /** @lends OpenSeadragon.TiledImage.prototype */{\n /**\n * @returns {Boolean} Whether the TiledImage needs to be drawn.\n */\n needsDraw: function() {\n return this._needsDraw;\n },\n\n /**\n * @returns {Boolean} Whether all tiles necessary for this TiledImage to draw at the current view have been loaded.\n */\n getFullyLoaded: function() {\n return this._fullyLoaded;\n },\n\n // private\n _setFullyLoaded: function(flag) {\n if (flag === this._fullyLoaded) {\n return;\n }\n\n this._fullyLoaded = flag;\n\n /**\n * Fired when the TiledImage's \"fully loaded\" flag (whether all tiles necessary for this TiledImage\n * to draw at the current view have been loaded) changes.\n *\n * @event fully-loaded-change\n * @memberof OpenSeadragon.TiledImage\n * @type {object}\n * @property {Boolean} fullyLoaded - The new \"fully loaded\" value.\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('fully-loaded-change', {\n fullyLoaded: this._fullyLoaded\n });\n },\n\n /**\n * Clears all tiles and triggers an update on the next call to\n * {@link OpenSeadragon.TiledImage#update}.\n */\n reset: function() {\n this._tileCache.clearTilesFor(this);\n this.lastResetTime = $.now();\n this._needsDraw = true;\n },\n\n /**\n * Updates the TiledImage's bounds, animating if needed.\n * @returns {Boolean} Whether the TiledImage animated.\n */\n update: function() {\n var xUpdated = this._xSpring.update();\n var yUpdated = this._ySpring.update();\n var scaleUpdated = this._scaleSpring.update();\n var degreesUpdated = this._degreesSpring.update();\n\n if (xUpdated || yUpdated || scaleUpdated || degreesUpdated) {\n this._updateForScale();\n this._needsDraw = true;\n return true;\n }\n\n return false;\n },\n\n /**\n * Draws the TiledImage to its Drawer.\n */\n draw: function() {\n if (this.opacity !== 0 || this._preload) {\n this._midDraw = true;\n this._updateViewport();\n this._midDraw = false;\n }\n // Images with opacity 0 should not need to be drawn in future. this._needsDraw = false is set in this._updateViewport() for other images.\n else {\n this._needsDraw = false;\n }\n },\n\n /**\n * Destroy the TiledImage (unload current loaded tiles).\n */\n destroy: function() {\n this.reset();\n },\n\n /**\n * Get this TiledImage's bounds in viewport coordinates.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * false for target location.\n * @returns {OpenSeadragon.Rect} This TiledImage's bounds in viewport coordinates.\n */\n getBounds: function(current) {\n return this.getBoundsNoRotate(current)\n .rotate(this.getRotation(current), this._getRotationPoint(current));\n },\n\n /**\n * Get this TiledImage's bounds in viewport coordinates without taking\n * rotation into account.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * false for target location.\n * @returns {OpenSeadragon.Rect} This TiledImage's bounds in viewport coordinates.\n */\n getBoundsNoRotate: function(current) {\n return current ?\n new $.Rect(\n this._xSpring.current.value,\n this._ySpring.current.value,\n this._worldWidthCurrent,\n this._worldHeightCurrent) :\n new $.Rect(\n this._xSpring.target.value,\n this._ySpring.target.value,\n this._worldWidthTarget,\n this._worldHeightTarget);\n },\n\n // deprecated\n getWorldBounds: function() {\n $.console.error('[TiledImage.getWorldBounds] is deprecated; use TiledImage.getBounds instead');\n return this.getBounds();\n },\n\n /**\n * Get the bounds of the displayed part of the tiled image.\n * @param {Boolean} [current=false] Pass true for the current location,\n * false for the target location.\n * @returns {$.Rect} The clipped bounds in viewport coordinates.\n */\n getClippedBounds: function(current) {\n var bounds = this.getBoundsNoRotate(current);\n if (this._clip) {\n var worldWidth = current ?\n this._worldWidthCurrent : this._worldWidthTarget;\n var ratio = worldWidth / this.source.dimensions.x;\n var clip = this._clip.times(ratio);\n bounds = new $.Rect(\n bounds.x + clip.x,\n bounds.y + clip.y,\n clip.width,\n clip.height);\n }\n return bounds.rotate(this.getRotation(current), this._getRotationPoint(current));\n },\n\n /**\n * @returns {OpenSeadragon.Point} This TiledImage's content size, in original pixels.\n */\n getContentSize: function() {\n return new $.Point(this.source.dimensions.x, this.source.dimensions.y);\n },\n\n // private\n _viewportToImageDelta: function( viewerX, viewerY, current ) {\n var scale = (current ? this._scaleSpring.current.value : this._scaleSpring.target.value);\n return new $.Point(viewerX * (this.source.dimensions.x / scale),\n viewerY * ((this.source.dimensions.y * this.contentAspectX) / scale));\n },\n\n /**\n * Translates from OpenSeadragon viewer coordinate system to image coordinate system.\n * This method can be called either by passing X,Y coordinates or an {@link OpenSeadragon.Point}.\n * @param {Number|OpenSeadragon.Point} viewerX - The X coordinate or point in viewport coordinate system.\n * @param {Number} [viewerY] - The Y coordinate in viewport coordinate system.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Point} A point representing the coordinates in the image.\n */\n viewportToImageCoordinates: function(viewerX, viewerY, current) {\n var point;\n if (viewerX instanceof $.Point) {\n //they passed a point instead of individual components\n current = viewerY;\n point = viewerX;\n } else {\n point = new $.Point(viewerX, viewerY);\n }\n\n point = point.rotate(-this.getRotation(current), this._getRotationPoint(current));\n return current ?\n this._viewportToImageDelta(\n point.x - this._xSpring.current.value,\n point.y - this._ySpring.current.value) :\n this._viewportToImageDelta(\n point.x - this._xSpring.target.value,\n point.y - this._ySpring.target.value);\n },\n\n // private\n _imageToViewportDelta: function( imageX, imageY, current ) {\n var scale = (current ? this._scaleSpring.current.value : this._scaleSpring.target.value);\n return new $.Point((imageX / this.source.dimensions.x) * scale,\n (imageY / this.source.dimensions.y / this.contentAspectX) * scale);\n },\n\n /**\n * Translates from image coordinate system to OpenSeadragon viewer coordinate system\n * This method can be called either by passing X,Y coordinates or an {@link OpenSeadragon.Point}.\n * @param {Number|OpenSeadragon.Point} imageX - The X coordinate or point in image coordinate system.\n * @param {Number} [imageY] - The Y coordinate in image coordinate system.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Point} A point representing the coordinates in the viewport.\n */\n imageToViewportCoordinates: function(imageX, imageY, current) {\n if (imageX instanceof $.Point) {\n //they passed a point instead of individual components\n current = imageY;\n imageY = imageX.y;\n imageX = imageX.x;\n }\n\n var point = this._imageToViewportDelta(imageX, imageY);\n if (current) {\n point.x += this._xSpring.current.value;\n point.y += this._ySpring.current.value;\n } else {\n point.x += this._xSpring.target.value;\n point.y += this._ySpring.target.value;\n }\n\n return point.rotate(this.getRotation(current), this._getRotationPoint(current));\n },\n\n /**\n * Translates from a rectangle which describes a portion of the image in\n * pixel coordinates to OpenSeadragon viewport rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an {@link OpenSeadragon.Rect}.\n * @param {Number|OpenSeadragon.Rect} imageX - The left coordinate or rectangle in image coordinate system.\n * @param {Number} [imageY] - The top coordinate in image coordinate system.\n * @param {Number} [pixelWidth] - The width in pixel of the rectangle.\n * @param {Number} [pixelHeight] - The height in pixel of the rectangle.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Rect} A rect representing the coordinates in the viewport.\n */\n imageToViewportRectangle: function(imageX, imageY, pixelWidth, pixelHeight, current) {\n var rect = imageX;\n if (rect instanceof $.Rect) {\n //they passed a rect instead of individual components\n current = imageY;\n } else {\n rect = new $.Rect(imageX, imageY, pixelWidth, pixelHeight);\n }\n\n var coordA = this.imageToViewportCoordinates(rect.getTopLeft(), current);\n var coordB = this._imageToViewportDelta(rect.width, rect.height, current);\n\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees + this.getRotation(current)\n );\n },\n\n /**\n * Translates from a rectangle which describes a portion of\n * the viewport in point coordinates to image rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an {@link OpenSeadragon.Rect}.\n * @param {Number|OpenSeadragon.Rect} viewerX - The left coordinate or rectangle in viewport coordinate system.\n * @param {Number} [viewerY] - The top coordinate in viewport coordinate system.\n * @param {Number} [pointWidth] - The width in viewport coordinate system.\n * @param {Number} [pointHeight] - The height in viewport coordinate system.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Rect} A rect representing the coordinates in the image.\n */\n viewportToImageRectangle: function( viewerX, viewerY, pointWidth, pointHeight, current ) {\n var rect = viewerX;\n if (viewerX instanceof $.Rect) {\n //they passed a rect instead of individual components\n current = viewerY;\n } else {\n rect = new $.Rect(viewerX, viewerY, pointWidth, pointHeight);\n }\n\n var coordA = this.viewportToImageCoordinates(rect.getTopLeft(), current);\n var coordB = this._viewportToImageDelta(rect.width, rect.height, current);\n\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees - this.getRotation(current)\n );\n },\n\n /**\n * Convert pixel coordinates relative to the viewer element to image\n * coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n viewerElementToImageCoordinates: function( pixel ) {\n var point = this.viewport.pointFromPixel( pixel, true );\n return this.viewportToImageCoordinates( point );\n },\n\n /**\n * Convert pixel coordinates relative to the image to\n * viewer element coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToViewerElementCoordinates: function( pixel ) {\n var point = this.imageToViewportCoordinates( pixel );\n return this.viewport.pixelFromPoint( point, true );\n },\n\n /**\n * Convert pixel coordinates relative to the window to image coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n windowToImageCoordinates: function( pixel ) {\n var viewerCoordinates = pixel.minus(\n OpenSeadragon.getElementPosition( this.viewer.element ));\n return this.viewerElementToImageCoordinates( viewerCoordinates );\n },\n\n /**\n * Convert image coordinates to pixel coordinates relative to the window.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToWindowCoordinates: function( pixel ) {\n var viewerCoordinates = this.imageToViewerElementCoordinates( pixel );\n return viewerCoordinates.plus(\n OpenSeadragon.getElementPosition( this.viewer.element ));\n },\n\n // private\n // Convert rectangle in viewport coordinates to this tiled image point\n // coordinates (x in [0, 1] and y in [0, aspectRatio])\n _viewportToTiledImageRectangle: function(rect) {\n var scale = this._scaleSpring.current.value;\n rect = rect.rotate(-this.getRotation(true), this._getRotationPoint(true));\n return new $.Rect(\n (rect.x - this._xSpring.current.value) / scale,\n (rect.y - this._ySpring.current.value) / scale,\n rect.width / scale,\n rect.height / scale,\n rect.degrees);\n },\n\n /**\n * Convert a viewport zoom to an image zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * @function\n * @param {Number} viewportZoom The viewport zoom\n * @returns {Number} imageZoom The image zoom\n */\n viewportToImageZoom: function( viewportZoom ) {\n var ratio = this._scaleSpring.current.value *\n this.viewport._containerInnerSize.x / this.source.dimensions.x;\n return ratio * viewportZoom;\n },\n\n /**\n * Convert an image zoom to a viewport zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * Note: not accurate with multi-image.\n * @function\n * @param {Number} imageZoom The image zoom\n * @returns {Number} viewportZoom The viewport zoom\n */\n imageToViewportZoom: function( imageZoom ) {\n var ratio = this._scaleSpring.current.value *\n this.viewport._containerInnerSize.x / this.source.dimensions.x;\n return imageZoom / ratio;\n },\n\n /**\n * Sets the TiledImage's position in the world.\n * @param {OpenSeadragon.Point} position - The new position, in viewport coordinates.\n * @param {Boolean} [immediately=false] - Whether to animate to the new position or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setPosition: function(position, immediately) {\n var sameTarget = (this._xSpring.target.value === position.x &&\n this._ySpring.target.value === position.y);\n\n if (immediately) {\n if (sameTarget && this._xSpring.current.value === position.x &&\n this._ySpring.current.value === position.y) {\n return;\n }\n\n this._xSpring.resetTo(position.x);\n this._ySpring.resetTo(position.y);\n this._needsDraw = true;\n } else {\n if (sameTarget) {\n return;\n }\n\n this._xSpring.springTo(position.x);\n this._ySpring.springTo(position.y);\n this._needsDraw = true;\n }\n\n if (!sameTarget) {\n this._raiseBoundsChange();\n }\n },\n\n /**\n * Sets the TiledImage's width in the world, adjusting the height to match based on aspect ratio.\n * @param {Number} width - The new width, in viewport coordinates.\n * @param {Boolean} [immediately=false] - Whether to animate to the new size or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setWidth: function(width, immediately) {\n this._setScale(width, immediately);\n },\n\n /**\n * Sets the TiledImage's height in the world, adjusting the width to match based on aspect ratio.\n * @param {Number} height - The new height, in viewport coordinates.\n * @param {Boolean} [immediately=false] - Whether to animate to the new size or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setHeight: function(height, immediately) {\n this._setScale(height / this.normHeight, immediately);\n },\n\n /**\n * Positions and scales the TiledImage to fit in the specified bounds.\n * Note: this method fires OpenSeadragon.TiledImage.event:bounds-change\n * twice\n * @param {OpenSeadragon.Rect} bounds The bounds to fit the image into.\n * @param {OpenSeadragon.Placement} [anchor=OpenSeadragon.Placement.CENTER]\n * How to anchor the image in the bounds.\n * @param {Boolean} [immediately=false] Whether to animate to the new size\n * or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n fitBounds: function(bounds, anchor, immediately) {\n anchor = anchor || $.Placement.CENTER;\n var anchorProperties = $.Placement.properties[anchor];\n var aspectRatio = this.contentAspectX;\n var xOffset = 0;\n var yOffset = 0;\n var displayedWidthRatio = 1;\n var displayedHeightRatio = 1;\n if (this._clip) {\n aspectRatio = this._clip.getAspectRatio();\n displayedWidthRatio = this._clip.width / this.source.dimensions.x;\n displayedHeightRatio = this._clip.height / this.source.dimensions.y;\n if (bounds.getAspectRatio() > aspectRatio) {\n xOffset = this._clip.x / this._clip.height * bounds.height;\n yOffset = this._clip.y / this._clip.height * bounds.height;\n } else {\n xOffset = this._clip.x / this._clip.width * bounds.width;\n yOffset = this._clip.y / this._clip.width * bounds.width;\n }\n }\n\n if (bounds.getAspectRatio() > aspectRatio) {\n // We will have margins on the X axis\n var height = bounds.height / displayedHeightRatio;\n var marginLeft = 0;\n if (anchorProperties.isHorizontallyCentered) {\n marginLeft = (bounds.width - bounds.height * aspectRatio) / 2;\n } else if (anchorProperties.isRight) {\n marginLeft = bounds.width - bounds.height * aspectRatio;\n }\n this.setPosition(\n new $.Point(bounds.x - xOffset + marginLeft, bounds.y - yOffset),\n immediately);\n this.setHeight(height, immediately);\n } else {\n // We will have margins on the Y axis\n var width = bounds.width / displayedWidthRatio;\n var marginTop = 0;\n if (anchorProperties.isVerticallyCentered) {\n marginTop = (bounds.height - bounds.width / aspectRatio) / 2;\n } else if (anchorProperties.isBottom) {\n marginTop = bounds.height - bounds.width / aspectRatio;\n }\n this.setPosition(\n new $.Point(bounds.x - xOffset, bounds.y - yOffset + marginTop),\n immediately);\n this.setWidth(width, immediately);\n }\n },\n\n /**\n * @returns {OpenSeadragon.Rect|null} The TiledImage's current clip rectangle,\n * in image pixels, or null if none.\n */\n getClip: function() {\n if (this._clip) {\n return this._clip.clone();\n }\n\n return null;\n },\n\n /**\n * @param {OpenSeadragon.Rect|null} newClip - An area, in image pixels, to clip to\n * (portions of the image outside of this area will not be visible). Only works on\n * browsers that support the HTML5 canvas.\n * @fires OpenSeadragon.TiledImage.event:clip-change\n */\n setClip: function(newClip) {\n $.console.assert(!newClip || newClip instanceof $.Rect,\n \"[TiledImage.setClip] newClip must be an OpenSeadragon.Rect or null\");\n\n if (newClip instanceof $.Rect) {\n this._clip = newClip.clone();\n } else {\n this._clip = null;\n }\n\n this._needsDraw = true;\n /**\n * Raised when the TiledImage's clip is changed.\n * @event clip-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('clip-change');\n },\n\n /**\n * @returns {Number} The TiledImage's current opacity.\n */\n getOpacity: function() {\n return this.opacity;\n },\n\n /**\n * @param {Number} opacity Opacity the tiled image should be drawn at.\n * @fires OpenSeadragon.TiledImage.event:opacity-change\n */\n setOpacity: function(opacity) {\n if (opacity === this.opacity) {\n return;\n }\n\n this.opacity = opacity;\n this._needsDraw = true;\n /**\n * Raised when the TiledImage's opacity is changed.\n * @event opacity-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {Number} opacity - The new opacity value.\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('opacity-change', {\n opacity: this.opacity\n });\n },\n\n /**\n * @returns {Boolean} whether the tiledImage can load its tiles even when it has zero opacity.\n */\n getPreload: function() {\n return this._preload;\n },\n\n /**\n * Set true to load even when hidden. Set false to block loading when hidden.\n */\n setPreload: function(preload) {\n this._preload = !!preload;\n this._needsDraw = true;\n },\n\n /**\n * Get the rotation of this tiled image in degrees.\n * @param {Boolean} [current=false] True for current rotation, false for target.\n * @returns {Number} the rotation of this tiled image in degrees.\n */\n getRotation: function(current) {\n return current ?\n this._degreesSpring.current.value :\n this._degreesSpring.target.value;\n },\n\n /**\n * Set the current rotation of this tiled image in degrees.\n * @param {Number} degrees the rotation in degrees.\n * @param {Boolean} [immediately=false] Whether to animate to the new angle\n * or rotate immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setRotation: function(degrees, immediately) {\n if (this._degreesSpring.target.value === degrees &&\n this._degreesSpring.isAtTargetValue()) {\n return;\n }\n if (immediately) {\n this._degreesSpring.resetTo(degrees);\n } else {\n this._degreesSpring.springTo(degrees);\n }\n this._needsDraw = true;\n this._raiseBoundsChange();\n },\n\n /**\n * Get the point around which this tiled image is rotated\n * @private\n * @param {Boolean} current True for current rotation point, false for target.\n * @returns {OpenSeadragon.Point}\n */\n _getRotationPoint: function(current) {\n return this.getBoundsNoRotate(current).getCenter();\n },\n\n /**\n * @returns {String} The TiledImage's current compositeOperation.\n */\n getCompositeOperation: function() {\n return this.compositeOperation;\n },\n\n /**\n * @param {String} compositeOperation the tiled image should be drawn with this globalCompositeOperation.\n * @fires OpenSeadragon.TiledImage.event:composite-operation-change\n */\n setCompositeOperation: function(compositeOperation) {\n if (compositeOperation === this.compositeOperation) {\n return;\n }\n\n this.compositeOperation = compositeOperation;\n this._needsDraw = true;\n /**\n * Raised when the TiledImage's opacity is changed.\n * @event composite-operation-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {String} compositeOperation - The new compositeOperation value.\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('composite-operation-change', {\n compositeOperation: this.compositeOperation\n });\n },\n\n // private\n _setScale: function(scale, immediately) {\n var sameTarget = (this._scaleSpring.target.value === scale);\n if (immediately) {\n if (sameTarget && this._scaleSpring.current.value === scale) {\n return;\n }\n\n this._scaleSpring.resetTo(scale);\n this._updateForScale();\n this._needsDraw = true;\n } else {\n if (sameTarget) {\n return;\n }\n\n this._scaleSpring.springTo(scale);\n this._updateForScale();\n this._needsDraw = true;\n }\n\n if (!sameTarget) {\n this._raiseBoundsChange();\n }\n },\n\n // private\n _updateForScale: function() {\n this._worldWidthTarget = this._scaleSpring.target.value;\n this._worldHeightTarget = this.normHeight * this._scaleSpring.target.value;\n this._worldWidthCurrent = this._scaleSpring.current.value;\n this._worldHeightCurrent = this.normHeight * this._scaleSpring.current.value;\n },\n\n // private\n _raiseBoundsChange: function() {\n /**\n * Raised when the TiledImage's bounds are changed.\n * Note that this event is triggered only when the animation target is changed;\n * not for every frame of animation.\n * @event bounds-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('bounds-change');\n },\n\n // private\n _isBottomItem: function() {\n return this.viewer.world.getItemAt(0) === this;\n },\n\n // private\n _getLevelsInterval: function() {\n var lowestLevel = Math.max(\n this.source.minLevel,\n Math.floor(Math.log(this.minZoomImageRatio) / Math.log(2))\n );\n var currentZeroRatio = this.viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(0), true).x *\n this._scaleSpring.current.value;\n var highestLevel = Math.min(\n Math.abs(this.source.maxLevel),\n Math.abs(Math.floor(\n Math.log(currentZeroRatio / this.minPixelRatio) / Math.log(2)\n ))\n );\n\n // Calculations for the interval of levels to draw\n // can return invalid intervals; fix that here if necessary\n lowestLevel = Math.min(lowestLevel, highestLevel);\n return {\n lowestLevel: lowestLevel,\n highestLevel: highestLevel\n };\n },\n\n /**\n * @private\n * @inner\n * Pretty much every other line in this needs to be documented so it's clear\n * how each piece of this routine contributes to the drawing process. That's\n * why there are so many TODO's inside this function.\n */\n _updateViewport: function() {\n this._needsDraw = false;\n this._tilesLoading = 0;\n this.loadingCoverage = {};\n\n // Reset tile's internal drawn state\n while (this.lastDrawn.length > 0) {\n var tile = this.lastDrawn.pop();\n tile.beingDrawn = false;\n }\n\n var viewport = this.viewport;\n var drawArea = this._viewportToTiledImageRectangle(\n viewport.getBoundsWithMargins(true));\n\n if (!this.wrapHorizontal && !this.wrapVertical) {\n var tiledImageBounds = this._viewportToTiledImageRectangle(\n this.getClippedBounds(true));\n drawArea = drawArea.intersection(tiledImageBounds);\n if (drawArea === null) {\n return;\n }\n }\n\n var levelsInterval = this._getLevelsInterval();\n var lowestLevel = levelsInterval.lowestLevel;\n var highestLevel = levelsInterval.highestLevel;\n var bestTile = null;\n var haveDrawn = false;\n var currentTime = $.now();\n\n // Update any level that will be drawn\n for (var level = highestLevel; level >= lowestLevel; level--) {\n var drawLevel = false;\n\n //Avoid calculations for draw if we have already drawn this\n var currentRenderPixelRatio = viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(level),\n true\n ).x * this._scaleSpring.current.value;\n\n if (level === lowestLevel ||\n (!haveDrawn && currentRenderPixelRatio >= this.minPixelRatio)) {\n drawLevel = true;\n haveDrawn = true;\n } else if (!haveDrawn) {\n continue;\n }\n\n //Perform calculations for draw if we haven't drawn this\n var targetRenderPixelRatio = viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(level),\n false\n ).x * this._scaleSpring.current.value;\n\n var targetZeroRatio = viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(\n Math.max(\n this.source.getClosestLevel(),\n 0\n )\n ),\n false\n ).x * this._scaleSpring.current.value;\n\n var optimalRatio = this.immediateRender ? 1 : targetZeroRatio;\n var levelOpacity = Math.min(1, (currentRenderPixelRatio - 0.5) / 0.5);\n var levelVisibility = optimalRatio / Math.abs(\n optimalRatio - targetRenderPixelRatio\n );\n\n // Update the level and keep track of 'best' tile to load\n bestTile = updateLevel(\n this,\n haveDrawn,\n drawLevel,\n level,\n levelOpacity,\n levelVisibility,\n drawArea,\n currentTime,\n bestTile\n );\n\n // Stop the loop if lower-res tiles would all be covered by\n // already drawn tiles\n if (providesCoverage(this.coverage, level)) {\n break;\n }\n }\n\n // Perform the actual drawing\n drawTiles(this, this.lastDrawn);\n\n // Load the new 'best' tile\n if (bestTile && !bestTile.context2D) {\n loadTile(this, bestTile, currentTime);\n this._needsDraw = true;\n this._setFullyLoaded(false);\n } else {\n this._setFullyLoaded(this._tilesLoading === 0);\n }\n },\n\n // private\n _getCornerTiles: function(level, topLeftBound, bottomRightBound) {\n var leftX;\n var rightX;\n if (this.wrapHorizontal) {\n leftX = $.positiveModulo(topLeftBound.x, 1);\n rightX = $.positiveModulo(bottomRightBound.x, 1);\n } else {\n leftX = Math.max(0, topLeftBound.x);\n rightX = Math.min(1, bottomRightBound.x);\n }\n var topY;\n var bottomY;\n var aspectRatio = 1 / this.source.aspectRatio;\n if (this.wrapVertical) {\n topY = $.positiveModulo(topLeftBound.y, aspectRatio);\n bottomY = $.positiveModulo(bottomRightBound.y, aspectRatio);\n } else {\n topY = Math.max(0, topLeftBound.y);\n bottomY = Math.min(aspectRatio, bottomRightBound.y);\n }\n\n var topLeftTile = this.source.getTileAtPoint(level, new $.Point(leftX, topY));\n var bottomRightTile = this.source.getTileAtPoint(level, new $.Point(rightX, bottomY));\n var numTiles = this.source.getNumTiles(level);\n\n if (this.wrapHorizontal) {\n topLeftTile.x += numTiles.x * Math.floor(topLeftBound.x);\n bottomRightTile.x += numTiles.x * Math.floor(bottomRightBound.x);\n }\n if (this.wrapVertical) {\n topLeftTile.y += numTiles.y * Math.floor(topLeftBound.y / aspectRatio);\n bottomRightTile.y += numTiles.y * Math.floor(bottomRightBound.y / aspectRatio);\n }\n\n return {\n topLeft: topLeftTile,\n bottomRight: bottomRightTile,\n };\n }\n});\n\n/**\n * @private\n * @inner\n * Updates all tiles at a given resolution level.\n * @param {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @param {Boolean} haveDrawn\n * @param {Boolean} drawLevel\n * @param {Number} level\n * @param {Number} levelOpacity\n * @param {Number} levelVisibility\n * @param {OpenSeadragon.Point} viewportTL - The index of the most top-left visible tile.\n * @param {OpenSeadragon.Point} viewportBR - The index of the most bottom-right visible tile.\n * @param {Number} currentTime\n * @param {OpenSeadragon.Tile} best - The current \"best\" tile to draw.\n */\nfunction updateLevel(tiledImage, haveDrawn, drawLevel, level, levelOpacity,\n levelVisibility, drawArea, currentTime, best) {\n\n var topLeftBound = drawArea.getBoundingBox().getTopLeft();\n var bottomRightBound = drawArea.getBoundingBox().getBottomRight();\n\n if (tiledImage.viewer) {\n /**\n * - Needs documentation -\n *\n * @event update-level\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {Object} havedrawn\n * @property {Object} level\n * @property {Object} opacity\n * @property {Object} visibility\n * @property {OpenSeadragon.Rect} drawArea\n * @property {Object} topleft deprecated, use drawArea instead\n * @property {Object} bottomright deprecated, use drawArea instead\n * @property {Object} currenttime\n * @property {Object} best\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n tiledImage.viewer.raiseEvent('update-level', {\n tiledImage: tiledImage,\n havedrawn: haveDrawn,\n level: level,\n opacity: levelOpacity,\n visibility: levelVisibility,\n drawArea: drawArea,\n topleft: topLeftBound,\n bottomright: bottomRightBound,\n currenttime: currentTime,\n best: best\n });\n }\n\n resetCoverage(tiledImage.coverage, level);\n resetCoverage(tiledImage.loadingCoverage, level);\n\n //OK, a new drawing so do your calculations\n var cornerTiles = tiledImage._getCornerTiles(level, topLeftBound, bottomRightBound);\n var topLeftTile = cornerTiles.topLeft;\n var bottomRightTile = cornerTiles.bottomRight;\n var numberOfTiles = tiledImage.source.getNumTiles(level);\n\n var viewportCenter = tiledImage.viewport.pixelFromPoint(\n tiledImage.viewport.getCenter());\n for (var x = topLeftTile.x; x <= bottomRightTile.x; x++) {\n for (var y = topLeftTile.y; y <= bottomRightTile.y; y++) {\n\n // Optimisation disabled with wrapping because getTileBounds does not\n // work correctly with x and y outside of the number of tiles\n if (!tiledImage.wrapHorizontal && !tiledImage.wrapVertical) {\n var tileBounds = tiledImage.source.getTileBounds(level, x, y);\n if (drawArea.intersection(tileBounds) === null) {\n // This tile is outside of the viewport, no need to draw it\n continue;\n }\n }\n\n best = updateTile(\n tiledImage,\n drawLevel,\n haveDrawn,\n x, y,\n level,\n levelOpacity,\n levelVisibility,\n viewportCenter,\n numberOfTiles,\n currentTime,\n best\n );\n\n }\n }\n\n return best;\n}\n\n/**\n * @private\n * @inner\n * Update a single tile at a particular resolution level.\n * @param {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @param {Boolean} haveDrawn\n * @param {Boolean} drawLevel\n * @param {Number} x\n * @param {Number} y\n * @param {Number} level\n * @param {Number} levelOpacity\n * @param {Number} levelVisibility\n * @param {OpenSeadragon.Point} viewportCenter\n * @param {Number} numberOfTiles\n * @param {Number} currentTime\n * @param {OpenSeadragon.Tile} best - The current \"best\" tile to draw.\n */\nfunction updateTile( tiledImage, haveDrawn, drawLevel, x, y, level, levelOpacity, levelVisibility, viewportCenter, numberOfTiles, currentTime, best){\n\n var tile = getTile(\n x, y,\n level,\n tiledImage,\n tiledImage.source,\n tiledImage.tilesMatrix,\n currentTime,\n numberOfTiles,\n tiledImage._worldWidthCurrent,\n tiledImage._worldHeightCurrent\n ),\n drawTile = drawLevel;\n\n if( tiledImage.viewer ){\n /**\n * - Needs documentation -\n *\n * @event update-tile\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {OpenSeadragon.Tile} tile\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n tiledImage.viewer.raiseEvent( 'update-tile', {\n tiledImage: tiledImage,\n tile: tile\n });\n }\n\n setCoverage( tiledImage.coverage, level, x, y, false );\n\n var loadingCoverage = tile.loaded || tile.loading || isCovered(tiledImage.loadingCoverage, level, x, y);\n setCoverage(tiledImage.loadingCoverage, level, x, y, loadingCoverage);\n\n if ( !tile.exists ) {\n return best;\n }\n\n if ( haveDrawn && !drawTile ) {\n if ( isCovered( tiledImage.coverage, level, x, y ) ) {\n setCoverage( tiledImage.coverage, level, x, y, true );\n } else {\n drawTile = true;\n }\n }\n\n if ( !drawTile ) {\n return best;\n }\n\n positionTile(\n tile,\n tiledImage.source.tileOverlap,\n tiledImage.viewport,\n viewportCenter,\n levelVisibility,\n tiledImage\n );\n\n if (!tile.loaded) {\n if (tile.context2D) {\n setTileLoaded(tiledImage, tile);\n } else {\n var imageRecord = tiledImage._tileCache.getImageRecord(tile.cacheKey);\n if (imageRecord) {\n var image = imageRecord.getImage();\n setTileLoaded(tiledImage, tile, image);\n }\n }\n }\n\n if ( tile.loaded ) {\n var needsDraw = blendTile(\n tiledImage,\n tile,\n x, y,\n level,\n levelOpacity,\n currentTime\n );\n\n if ( needsDraw ) {\n tiledImage._needsDraw = true;\n }\n } else if ( tile.loading ) {\n // the tile is already in the download queue\n tiledImage._tilesLoading++;\n } else if (!loadingCoverage) {\n best = compareTiles( best, tile );\n }\n\n return best;\n}\n\n/**\n * @private\n * @inner\n * Obtains a tile at the given location.\n * @param {Number} x\n * @param {Number} y\n * @param {Number} level\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.TileSource} tileSource\n * @param {Object} tilesMatrix - A '3d' dictionary [level][x][y] --> Tile.\n * @param {Number} time\n * @param {Number} numTiles\n * @param {Number} worldWidth\n * @param {Number} worldHeight\n * @returns {OpenSeadragon.Tile}\n */\nfunction getTile(\n x, y,\n level,\n tiledImage,\n tileSource,\n tilesMatrix,\n time,\n numTiles,\n worldWidth,\n worldHeight\n) {\n var xMod,\n yMod,\n bounds,\n sourceBounds,\n exists,\n url,\n ajaxHeaders,\n context2D,\n tile;\n\n if ( !tilesMatrix[ level ] ) {\n tilesMatrix[ level ] = {};\n }\n if ( !tilesMatrix[ level ][ x ] ) {\n tilesMatrix[ level ][ x ] = {};\n }\n\n if ( !tilesMatrix[ level ][ x ][ y ] ) {\n xMod = ( numTiles.x + ( x % numTiles.x ) ) % numTiles.x;\n yMod = ( numTiles.y + ( y % numTiles.y ) ) % numTiles.y;\n bounds = tileSource.getTileBounds( level, xMod, yMod );\n sourceBounds = tileSource.getTileBounds( level, xMod, yMod, true );\n exists = tileSource.tileExists( level, xMod, yMod );\n url = tileSource.getTileUrl( level, xMod, yMod );\n\n // Headers are only applicable if loadTilesWithAjax is set\n if (tiledImage.loadTilesWithAjax) {\n ajaxHeaders = tileSource.getTileAjaxHeaders( level, xMod, yMod );\n // Combine tile AJAX headers with tiled image AJAX headers (if applicable)\n if ($.isPlainObject(tiledImage.ajaxHeaders)) {\n ajaxHeaders = $.extend({}, tiledImage.ajaxHeaders, ajaxHeaders);\n }\n } else {\n ajaxHeaders = null;\n }\n\n context2D = tileSource.getContext2D ?\n tileSource.getContext2D(level, xMod, yMod) : undefined;\n\n bounds.x += ( x - xMod ) / numTiles.x;\n bounds.y += (worldHeight / worldWidth) * (( y - yMod ) / numTiles.y);\n\n tile = new $.Tile(\n level,\n x,\n y,\n bounds,\n exists,\n url,\n context2D,\n tiledImage.loadTilesWithAjax,\n ajaxHeaders,\n sourceBounds\n );\n\n if (xMod === numTiles.x - 1) {\n tile.isRightMost = true;\n }\n\n if (yMod === numTiles.y - 1) {\n tile.isBottomMost = true;\n }\n\n tilesMatrix[ level ][ x ][ y ] = tile;\n }\n\n tile = tilesMatrix[ level ][ x ][ y ];\n tile.lastTouchTime = time;\n\n return tile;\n}\n\n/**\n * @private\n * @inner\n * Dispatch a job to the ImageLoader to load the Image for a Tile.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Number} time\n */\nfunction loadTile( tiledImage, tile, time ) {\n tile.loading = true;\n var customAjax;\n\n // Bind tiledImage if filtering Ajax\n if ($.isFunction(tiledImage.makeAjaxRequest)) {\n customAjax = tiledImage.makeAjaxRequest;\n }\n\n tiledImage._imageLoader.addJob({\n src: tile.url,\n makeAjaxRequest: customAjax,\n loadWithAjax: tile.loadWithAjax,\n ajaxHeaders: tile.ajaxHeaders,\n crossOriginPolicy: tiledImage.crossOriginPolicy,\n ajaxWithCredentials: tiledImage.ajaxWithCredentials,\n callback: function( image, errorMsg, tileRequest ){\n onTileLoad( tiledImage, tile, time, image, errorMsg, tileRequest );\n },\n abort: function() {\n tile.loading = false;\n }\n });\n}\n\n/**\n * @private\n * @inner\n * Callback fired when a Tile's Image finished downloading.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Number} time\n * @param {Image} image\n * @param {String} errorMsg\n * @param {XMLHttpRequest} tileRequest\n */\nfunction onTileLoad( tiledImage, tile, time, image, errorMsg, tileRequest ) {\n if ( !image ) {\n $.console.log( \"Tile %s failed to load: %s - error: %s\", tile, tile.url, errorMsg );\n /**\n * Triggered when a tile fails to load.\n *\n * @event tile-load-failed\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Tile} tile - The tile that failed to load.\n * @property {OpenSeadragon.TiledImage} tiledImage - The tiled image the tile belongs to.\n * @property {number} time - The time in milliseconds when the tile load began.\n * @property {string} message - The error message.\n * @property {XMLHttpRequest} tileRequest - The XMLHttpRequest used to load the tile if available.\n */\n tiledImage.viewer.raiseEvent(\"tile-load-failed\", {\n tile: tile,\n tiledImage: tiledImage,\n time: time,\n message: errorMsg,\n tileRequest: tileRequest\n });\n tile.loading = false;\n tile.exists = false;\n return;\n }\n\n if ( time < tiledImage.lastResetTime ) {\n $.console.log( \"Ignoring tile %s loaded before reset: %s\", tile, tile.url );\n tile.loading = false;\n return;\n }\n\n var finish = function() {\n var cutoff = tiledImage.source.getClosestLevel();\n setTileLoaded(tiledImage, tile, image, cutoff, tileRequest);\n };\n\n // Check if we're mid-update; this can happen on IE8 because image load events for\n // cached images happen immediately there\n if ( !tiledImage._midDraw ) {\n finish();\n } else {\n // Wait until after the update, in case caching unloads any tiles\n window.setTimeout( finish, 1);\n }\n}\n\n/**\n * @private\n * @inner\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Image} image\n * @param {Number} cutoff\n */\nfunction setTileLoaded(tiledImage, tile, image, cutoff, tileRequest) {\n var increment = 0;\n\n function getCompletionCallback() {\n increment++;\n return completionCallback;\n }\n\n function completionCallback() {\n increment--;\n if (increment === 0) {\n tile.loading = false;\n tile.loaded = true;\n if (!tile.context2D) {\n tiledImage._tileCache.cacheTile({\n image: image,\n tile: tile,\n cutoff: cutoff,\n tiledImage: tiledImage\n });\n }\n tiledImage._needsDraw = true;\n }\n }\n\n /**\n * Triggered when a tile has just been loaded in memory. That means that the\n * image has been downloaded and can be modified before being drawn to the canvas.\n *\n * @event tile-loaded\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {Image} image - The image of the tile.\n * @property {OpenSeadragon.TiledImage} tiledImage - The tiled image of the loaded tile.\n * @property {OpenSeadragon.Tile} tile - The tile which has been loaded.\n * @property {XMLHttpRequest} tiledImage - The AJAX request that loaded this tile (if applicable).\n * @property {function} getCompletionCallback - A function giving a callback to call\n * when the asynchronous processing of the image is done. The image will be\n * marked as entirely loaded when the callback has been called once for each\n * call to getCompletionCallback.\n */\n tiledImage.viewer.raiseEvent(\"tile-loaded\", {\n tile: tile,\n tiledImage: tiledImage,\n tileRequest: tileRequest,\n image: image,\n getCompletionCallback: getCompletionCallback\n });\n // In case the completion callback is never called, we at least force it once.\n getCompletionCallback()();\n}\n\n/**\n * @private\n * @inner\n * @param {OpenSeadragon.Tile} tile\n * @param {Boolean} overlap\n * @param {OpenSeadragon.Viewport} viewport\n * @param {OpenSeadragon.Point} viewportCenter\n * @param {Number} levelVisibility\n * @param {OpenSeadragon.TiledImage} tiledImage\n */\nfunction positionTile( tile, overlap, viewport, viewportCenter, levelVisibility, tiledImage ){\n var boundsTL = tile.bounds.getTopLeft();\n\n boundsTL.x *= tiledImage._scaleSpring.current.value;\n boundsTL.y *= tiledImage._scaleSpring.current.value;\n boundsTL.x += tiledImage._xSpring.current.value;\n boundsTL.y += tiledImage._ySpring.current.value;\n\n var boundsSize = tile.bounds.getSize();\n\n boundsSize.x *= tiledImage._scaleSpring.current.value;\n boundsSize.y *= tiledImage._scaleSpring.current.value;\n\n var positionC = viewport.pixelFromPointNoRotate(boundsTL, true),\n positionT = viewport.pixelFromPointNoRotate(boundsTL, false),\n sizeC = viewport.deltaPixelsFromPointsNoRotate(boundsSize, true),\n sizeT = viewport.deltaPixelsFromPointsNoRotate(boundsSize, false),\n tileCenter = positionT.plus( sizeT.divide( 2 ) ),\n tileSquaredDistance = viewportCenter.squaredDistanceTo( tileCenter );\n\n if ( !overlap ) {\n sizeC = sizeC.plus( new $.Point( 1, 1 ) );\n }\n\n if (tile.isRightMost && tiledImage.wrapHorizontal) {\n sizeC.x += 0.75; // Otherwise Firefox and Safari show seams\n }\n\n if (tile.isBottomMost && tiledImage.wrapVertical) {\n sizeC.y += 0.75; // Otherwise Firefox and Safari show seams\n }\n\n tile.position = positionC;\n tile.size = sizeC;\n tile.squaredDistance = tileSquaredDistance;\n tile.visibility = levelVisibility;\n}\n\n/**\n * @private\n * @inner\n * Updates the opacity of a tile according to the time it has been on screen\n * to perform a fade-in.\n * Updates coverage once a tile is fully opaque.\n * Returns whether the fade-in has completed.\n *\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Number} x\n * @param {Number} y\n * @param {Number} level\n * @param {Number} levelOpacity\n * @param {Number} currentTime\n * @returns {Boolean}\n */\nfunction blendTile( tiledImage, tile, x, y, level, levelOpacity, currentTime ){\n var blendTimeMillis = 1000 * tiledImage.blendTime,\n deltaTime,\n opacity;\n\n if ( !tile.blendStart ) {\n tile.blendStart = currentTime;\n }\n\n deltaTime = currentTime - tile.blendStart;\n opacity = blendTimeMillis ? Math.min( 1, deltaTime / ( blendTimeMillis ) ) : 1;\n\n if ( tiledImage.alwaysBlend ) {\n opacity *= levelOpacity;\n }\n\n tile.opacity = opacity;\n\n tiledImage.lastDrawn.push( tile );\n\n if ( opacity == 1 ) {\n setCoverage( tiledImage.coverage, level, x, y, true );\n tiledImage._hasOpaqueTile = true;\n } else if ( deltaTime < blendTimeMillis ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * @private\n * @inner\n * Returns true if the given tile provides coverage to lower-level tiles of\n * lower resolution representing the same content. If neither x nor y is\n * given, returns true if the entire visible level provides coverage.\n *\n * Note that out-of-bounds tiles provide coverage in this sense, since\n * there's no content that they would need to cover. Tiles at non-existent\n * levels that are within the image bounds, however, do not.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of the tile.\n * @param {Number} x - The X position of the tile.\n * @param {Number} y - The Y position of the tile.\n * @returns {Boolean}\n */\nfunction providesCoverage( coverage, level, x, y ) {\n var rows,\n cols,\n i, j;\n\n if ( !coverage[ level ] ) {\n return false;\n }\n\n if ( x === undefined || y === undefined ) {\n rows = coverage[ level ];\n for ( i in rows ) {\n if ( rows.hasOwnProperty( i ) ) {\n cols = rows[ i ];\n for ( j in cols ) {\n if ( cols.hasOwnProperty( j ) && !cols[ j ] ) {\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n return (\n coverage[ level ][ x] === undefined ||\n coverage[ level ][ x ][ y ] === undefined ||\n coverage[ level ][ x ][ y ] === true\n );\n}\n\n/**\n * @private\n * @inner\n * Returns true if the given tile is completely covered by higher-level\n * tiles of higher resolution representing the same content. If neither x\n * nor y is given, returns true if the entire visible level is covered.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of the tile.\n * @param {Number} x - The X position of the tile.\n * @param {Number} y - The Y position of the tile.\n * @returns {Boolean}\n */\nfunction isCovered( coverage, level, x, y ) {\n if ( x === undefined || y === undefined ) {\n return providesCoverage( coverage, level + 1 );\n } else {\n return (\n providesCoverage( coverage, level + 1, 2 * x, 2 * y ) &&\n providesCoverage( coverage, level + 1, 2 * x, 2 * y + 1 ) &&\n providesCoverage( coverage, level + 1, 2 * x + 1, 2 * y ) &&\n providesCoverage( coverage, level + 1, 2 * x + 1, 2 * y + 1 )\n );\n }\n}\n\n/**\n * @private\n * @inner\n * Sets whether the given tile provides coverage or not.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of the tile.\n * @param {Number} x - The X position of the tile.\n * @param {Number} y - The Y position of the tile.\n * @param {Boolean} covers - Whether the tile provides coverage.\n */\nfunction setCoverage( coverage, level, x, y, covers ) {\n if ( !coverage[ level ] ) {\n $.console.warn(\n \"Setting coverage for a tile before its level's coverage has been reset: %s\",\n level\n );\n return;\n }\n\n if ( !coverage[ level ][ x ] ) {\n coverage[ level ][ x ] = {};\n }\n\n coverage[ level ][ x ][ y ] = covers;\n}\n\n/**\n * @private\n * @inner\n * Resets coverage information for the given level. This should be called\n * after every draw routine. Note that at the beginning of the next draw\n * routine, coverage for every visible tile should be explicitly set.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of tiles to completely reset.\n */\nfunction resetCoverage( coverage, level ) {\n coverage[ level ] = {};\n}\n\n/**\n * @private\n * @inner\n * Determines whether the 'last best' tile for the area is better than the\n * tile in question.\n *\n * @param {OpenSeadragon.Tile} previousBest\n * @param {OpenSeadragon.Tile} tile\n * @returns {OpenSeadragon.Tile} The new best tile.\n */\nfunction compareTiles( previousBest, tile ) {\n if ( !previousBest ) {\n return tile;\n }\n\n if ( tile.visibility > previousBest.visibility ) {\n return tile;\n } else if ( tile.visibility == previousBest.visibility ) {\n if ( tile.squaredDistance < previousBest.squaredDistance ) {\n return tile;\n }\n }\n\n return previousBest;\n}\n\n/**\n * @private\n * @inner\n * Draws a TiledImage.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile[]} lastDrawn - An unordered list of Tiles drawn last frame.\n */\nfunction drawTiles( tiledImage, lastDrawn ) {\n if (tiledImage.opacity === 0 || (lastDrawn.length === 0 && !tiledImage.placeholderFillStyle)) {\n return;\n }\n\n var tile = lastDrawn[0];\n var useSketch;\n\n if (tile) {\n useSketch = tiledImage.opacity < 1 ||\n (tiledImage.compositeOperation &&\n tiledImage.compositeOperation !== 'source-over') ||\n (!tiledImage._isBottomItem() && tile._hasTransparencyChannel());\n }\n\n var sketchScale;\n var sketchTranslate;\n\n var zoom = tiledImage.viewport.getZoom(true);\n var imageZoom = tiledImage.viewportToImageZoom(zoom);\n\n if (lastDrawn.length > 1 &&\n imageZoom > tiledImage.smoothTileEdgesMinZoom &&\n !tiledImage.iOSDevice &&\n tiledImage.getRotation(true) % 360 === 0 && // TODO: support tile edge smoothing with tiled image rotation.\n $.supportsCanvas) {\n // When zoomed in a lot (>100%) the tile edges are visible.\n // So we have to composite them at ~100% and scale them up together.\n // Note: Disabled on iOS devices per default as it causes a native crash\n useSketch = true;\n sketchScale = tile.getScaleForEdgeSmoothing();\n sketchTranslate = tile.getTranslationForEdgeSmoothing(sketchScale,\n tiledImage._drawer.getCanvasSize(false),\n tiledImage._drawer.getCanvasSize(true));\n }\n\n var bounds;\n if (useSketch) {\n if (!sketchScale) {\n // Except when edge smoothing, we only clean the part of the\n // sketch canvas we are going to use for performance reasons.\n bounds = tiledImage.viewport.viewportToViewerElementRectangle(\n tiledImage.getClippedBounds(true))\n .getIntegerBoundingBox()\n .times($.pixelDensityRatio);\n }\n tiledImage._drawer._clear(true, bounds);\n }\n\n // When scaling, we must rotate only when blending the sketch canvas to\n // avoid interpolation\n if (!sketchScale) {\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.viewport.degrees,\n useSketch: useSketch\n });\n } else {\n if(tiledImage._drawer.viewer.viewport.flipped) {\n tiledImage._drawer._flip({});\n }\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.getRotation(true),\n point: tiledImage.viewport.pixelFromPointNoRotate(\n tiledImage._getRotationPoint(true), true),\n useSketch: useSketch\n });\n }\n }\n\n var usedClip = false;\n if ( tiledImage._clip ) {\n tiledImage._drawer.saveContext(useSketch);\n\n var box = tiledImage.imageToViewportRectangle(tiledImage._clip, true);\n box = box.rotate(-tiledImage.getRotation(true), tiledImage._getRotationPoint(true));\n var clipRect = tiledImage._drawer.viewportToDrawerRectangle(box);\n if (sketchScale) {\n clipRect = clipRect.times(sketchScale);\n }\n if (sketchTranslate) {\n clipRect = clipRect.translate(sketchTranslate);\n }\n tiledImage._drawer.setClip(clipRect, useSketch);\n\n usedClip = true;\n }\n\n if ( tiledImage.placeholderFillStyle && tiledImage._hasOpaqueTile === false ) {\n var placeholderRect = tiledImage._drawer.viewportToDrawerRectangle(tiledImage.getBounds(true));\n if (sketchScale) {\n placeholderRect = placeholderRect.times(sketchScale);\n }\n if (sketchTranslate) {\n placeholderRect = placeholderRect.translate(sketchTranslate);\n }\n\n var fillStyle = null;\n if ( typeof tiledImage.placeholderFillStyle === \"function\" ) {\n fillStyle = tiledImage.placeholderFillStyle(tiledImage, tiledImage._drawer.context);\n }\n else {\n fillStyle = tiledImage.placeholderFillStyle;\n }\n\n tiledImage._drawer.drawRectangle(placeholderRect, fillStyle, useSketch);\n }\n\n for (var i = lastDrawn.length - 1; i >= 0; i--) {\n tile = lastDrawn[ i ];\n tiledImage._drawer.drawTile( tile, tiledImage._drawingHandler, useSketch, sketchScale, sketchTranslate );\n tile.beingDrawn = true;\n\n if( tiledImage.viewer ){\n /**\n * - Needs documentation -\n *\n * @event tile-drawn\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {OpenSeadragon.Tile} tile\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n tiledImage.viewer.raiseEvent( 'tile-drawn', {\n tiledImage: tiledImage,\n tile: tile\n });\n }\n }\n\n if ( usedClip ) {\n tiledImage._drawer.restoreContext( useSketch );\n }\n\n if (!sketchScale) {\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._restoreRotationChanges(useSketch);\n }\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._restoreRotationChanges(useSketch);\n } else{\n if(tiledImage._drawer.viewer.viewport.flipped) {\n tiledImage._drawer._flip({});\n }\n }\n }\n\n if (useSketch) {\n if (sketchScale) {\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.viewport.degrees,\n useSketch: false\n });\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.getRotation(true),\n point: tiledImage.viewport.pixelFromPointNoRotate(\n tiledImage._getRotationPoint(true), true),\n useSketch: false\n });\n }\n }\n tiledImage._drawer.blendSketch({\n opacity: tiledImage.opacity,\n scale: sketchScale,\n translate: sketchTranslate,\n compositeOperation: tiledImage.compositeOperation,\n bounds: bounds\n });\n if (sketchScale) {\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._restoreRotationChanges(false);\n }\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._restoreRotationChanges(false);\n }\n }\n }\n drawDebugInfo( tiledImage, lastDrawn );\n}\n\n/**\n * @private\n * @inner\n * Draws special debug information for a TiledImage if in debug mode.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile[]} lastDrawn - An unordered list of Tiles drawn last frame.\n */\nfunction drawDebugInfo( tiledImage, lastDrawn ) {\n if( tiledImage.debugMode ) {\n for ( var i = lastDrawn.length - 1; i >= 0; i-- ) {\n var tile = lastDrawn[ i ];\n try {\n tiledImage._drawer.drawDebugInfo(\n tile, lastDrawn.length, i, tiledImage);\n } catch(e) {\n $.console.error(e);\n }\n }\n }\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TileCache\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n// private class\nvar TileRecord = function( options ) {\n $.console.assert( options, \"[TileCache.cacheTile] options is required\" );\n $.console.assert( options.tile, \"[TileCache.cacheTile] options.tile is required\" );\n $.console.assert( options.tiledImage, \"[TileCache.cacheTile] options.tiledImage is required\" );\n this.tile = options.tile;\n this.tiledImage = options.tiledImage;\n};\n\n// private class\nvar ImageRecord = function(options) {\n $.console.assert( options, \"[ImageRecord] options is required\" );\n $.console.assert( options.image, \"[ImageRecord] options.image is required\" );\n this._image = options.image;\n this._tiles = [];\n};\n\nImageRecord.prototype = {\n destroy: function() {\n this._image = null;\n this._renderedContext = null;\n this._tiles = null;\n },\n\n getImage: function() {\n return this._image;\n },\n\n getRenderedContext: function() {\n if (!this._renderedContext) {\n var canvas = document.createElement( 'canvas' );\n canvas.width = this._image.width;\n canvas.height = this._image.height;\n this._renderedContext = canvas.getContext('2d');\n this._renderedContext.drawImage( this._image, 0, 0 );\n //since we are caching the prerendered image on a canvas\n //allow the image to not be held in memory\n this._image = null;\n }\n return this._renderedContext;\n },\n\n setRenderedContext: function(renderedContext) {\n $.console.error(\"ImageRecord.setRenderedContext is deprecated. \" +\n \"The rendered context should be created by the ImageRecord \" +\n \"itself when calling ImageRecord.getRenderedContext.\");\n this._renderedContext = renderedContext;\n },\n\n addTile: function(tile) {\n $.console.assert(tile, '[ImageRecord.addTile] tile is required');\n this._tiles.push(tile);\n },\n\n removeTile: function(tile) {\n for (var i = 0; i < this._tiles.length; i++) {\n if (this._tiles[i] === tile) {\n this._tiles.splice(i, 1);\n return;\n }\n }\n\n $.console.warn('[ImageRecord.removeTile] trying to remove unknown tile', tile);\n },\n\n getTileCount: function() {\n return this._tiles.length;\n }\n};\n\n/**\n * @class TileCache\n * @memberof OpenSeadragon\n * @classdesc Stores all the tiles displayed in a {@link OpenSeadragon.Viewer}.\n * You generally won't have to interact with the TileCache directly.\n * @param {Object} options - Configuration for this TileCache.\n * @param {Number} [options.maxImageCacheCount] - See maxImageCacheCount in\n * {@link OpenSeadragon.Options} for details.\n */\n$.TileCache = function( options ) {\n options = options || {};\n\n this._maxImageCacheCount = options.maxImageCacheCount || $.DEFAULT_SETTINGS.maxImageCacheCount;\n this._tilesLoaded = [];\n this._imagesLoaded = [];\n this._imagesLoadedCount = 0;\n};\n\n/** @lends OpenSeadragon.TileCache.prototype */\n$.TileCache.prototype = {\n /**\n * @returns {Number} The total number of tiles that have been loaded by\n * this TileCache.\n */\n numTilesLoaded: function() {\n return this._tilesLoaded.length;\n },\n\n /**\n * Caches the specified tile, removing an old tile if necessary to stay under the\n * maxImageCacheCount specified on construction. Note that if multiple tiles reference\n * the same image, there may be more tiles than maxImageCacheCount; the goal is to keep\n * the number of images below that number. Note, as well, that even the number of images\n * may temporarily surpass that number, but should eventually come back down to the max specified.\n * @param {Object} options - Tile info.\n * @param {OpenSeadragon.Tile} options.tile - The tile to cache.\n * @param {String} options.tile.cacheKey - The unique key used to identify this tile in the cache.\n * @param {Image} options.image - The image of the tile to cache.\n * @param {OpenSeadragon.TiledImage} options.tiledImage - The TiledImage that owns that tile.\n * @param {Number} [options.cutoff=0] - If adding this tile goes over the cache max count, this\n * function will release an old tile. The cutoff option specifies a tile level at or below which\n * tiles will not be released.\n */\n cacheTile: function( options ) {\n $.console.assert( options, \"[TileCache.cacheTile] options is required\" );\n $.console.assert( options.tile, \"[TileCache.cacheTile] options.tile is required\" );\n $.console.assert( options.tile.cacheKey, \"[TileCache.cacheTile] options.tile.cacheKey is required\" );\n $.console.assert( options.tiledImage, \"[TileCache.cacheTile] options.tiledImage is required\" );\n\n var cutoff = options.cutoff || 0;\n var insertionIndex = this._tilesLoaded.length;\n\n var imageRecord = this._imagesLoaded[options.tile.cacheKey];\n if (!imageRecord) {\n $.console.assert( options.image, \"[TileCache.cacheTile] options.image is required to create an ImageRecord\" );\n imageRecord = this._imagesLoaded[options.tile.cacheKey] = new ImageRecord({\n image: options.image\n });\n\n this._imagesLoadedCount++;\n }\n\n imageRecord.addTile(options.tile);\n options.tile.cacheImageRecord = imageRecord;\n\n // Note that just because we're unloading a tile doesn't necessarily mean\n // we're unloading an image. With repeated calls it should sort itself out, though.\n if ( this._imagesLoadedCount > this._maxImageCacheCount ) {\n var worstTile = null;\n var worstTileIndex = -1;\n var worstTileRecord = null;\n var prevTile, worstTime, worstLevel, prevTime, prevLevel, prevTileRecord;\n\n for ( var i = this._tilesLoaded.length - 1; i >= 0; i-- ) {\n prevTileRecord = this._tilesLoaded[ i ];\n prevTile = prevTileRecord.tile;\n\n if ( prevTile.level <= cutoff || prevTile.beingDrawn ) {\n continue;\n } else if ( !worstTile ) {\n worstTile = prevTile;\n worstTileIndex = i;\n worstTileRecord = prevTileRecord;\n continue;\n }\n\n prevTime = prevTile.lastTouchTime;\n worstTime = worstTile.lastTouchTime;\n prevLevel = prevTile.level;\n worstLevel = worstTile.level;\n\n if ( prevTime < worstTime ||\n ( prevTime == worstTime && prevLevel > worstLevel ) ) {\n worstTile = prevTile;\n worstTileIndex = i;\n worstTileRecord = prevTileRecord;\n }\n }\n\n if ( worstTile && worstTileIndex >= 0 ) {\n this._unloadTile(worstTileRecord);\n insertionIndex = worstTileIndex;\n }\n }\n\n this._tilesLoaded[ insertionIndex ] = new TileRecord({\n tile: options.tile,\n tiledImage: options.tiledImage\n });\n },\n\n /**\n * Clears all tiles associated with the specified tiledImage.\n * @param {OpenSeadragon.TiledImage} tiledImage\n */\n clearTilesFor: function( tiledImage ) {\n $.console.assert(tiledImage, '[TileCache.clearTilesFor] tiledImage is required');\n var tileRecord;\n for ( var i = 0; i < this._tilesLoaded.length; ++i ) {\n tileRecord = this._tilesLoaded[ i ];\n if ( tileRecord.tiledImage === tiledImage ) {\n this._unloadTile(tileRecord);\n this._tilesLoaded.splice( i, 1 );\n i--;\n }\n }\n },\n\n // private\n getImageRecord: function(cacheKey) {\n $.console.assert(cacheKey, '[TileCache.getImageRecord] cacheKey is required');\n return this._imagesLoaded[cacheKey];\n },\n\n // private\n _unloadTile: function(tileRecord) {\n $.console.assert(tileRecord, '[TileCache._unloadTile] tileRecord is required');\n var tile = tileRecord.tile;\n var tiledImage = tileRecord.tiledImage;\n\n tile.unload();\n tile.cacheImageRecord = null;\n\n var imageRecord = this._imagesLoaded[tile.cacheKey];\n imageRecord.removeTile(tile);\n if (!imageRecord.getTileCount()) {\n imageRecord.destroy();\n delete this._imagesLoaded[tile.cacheKey];\n this._imagesLoadedCount--;\n }\n\n /**\n * Triggered when a tile has just been unloaded from memory.\n *\n * @event tile-unloaded\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.TiledImage} tiledImage - The tiled image of the unloaded tile.\n * @property {OpenSeadragon.Tile} tile - The tile which has been unloaded.\n */\n tiledImage.viewer.raiseEvent(\"tile-unloaded\", {\n tile: tile,\n tiledImage: tiledImage\n });\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - World\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class World\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @classdesc Keeps track of all of the tiled images in the scene.\n * @param {Object} options - World options.\n * @param {OpenSeadragon.Viewer} options.viewer - The Viewer that owns this World.\n **/\n$.World = function( options ) {\n var _this = this;\n\n $.console.assert( options.viewer, \"[World] options.viewer is required\" );\n\n $.EventSource.call( this );\n\n this.viewer = options.viewer;\n this._items = [];\n this._needsDraw = false;\n this._autoRefigureSizes = true;\n this._needsSizesFigured = false;\n this._delegatedFigureSizes = function(event) {\n if (_this._autoRefigureSizes) {\n _this._figureSizes();\n } else {\n _this._needsSizesFigured = true;\n }\n };\n\n this._figureSizes();\n};\n\n$.extend( $.World.prototype, $.EventSource.prototype, /** @lends OpenSeadragon.World.prototype */{\n /**\n * Add the specified item.\n * @param {OpenSeadragon.TiledImage} item - The item to add.\n * @param {Number} [options.index] - Index for the item. If not specified, goes at the top.\n * @fires OpenSeadragon.World.event:add-item\n * @fires OpenSeadragon.World.event:metrics-change\n */\n addItem: function( item, options ) {\n $.console.assert(item, \"[World.addItem] item is required\");\n $.console.assert(item instanceof $.TiledImage, \"[World.addItem] only TiledImages supported at this time\");\n\n options = options || {};\n if (options.index !== undefined) {\n var index = Math.max(0, Math.min(this._items.length, options.index));\n this._items.splice(index, 0, item);\n } else {\n this._items.push( item );\n }\n\n if (this._autoRefigureSizes) {\n this._figureSizes();\n } else {\n this._needsSizesFigured = true;\n }\n\n this._needsDraw = true;\n\n item.addHandler('bounds-change', this._delegatedFigureSizes);\n item.addHandler('clip-change', this._delegatedFigureSizes);\n\n /**\n * Raised when an item is added to the World.\n * @event add-item\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the World which raised the event.\n * @property {OpenSeadragon.TiledImage} item - The item that has been added.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'add-item', {\n item: item\n } );\n },\n\n /**\n * Get the item at the specified index.\n * @param {Number} index - The item's index.\n * @returns {OpenSeadragon.TiledImage} The item at the specified index.\n */\n getItemAt: function( index ) {\n $.console.assert(index !== undefined, \"[World.getItemAt] index is required\");\n return this._items[ index ];\n },\n\n /**\n * Get the index of the given item or -1 if not present.\n * @param {OpenSeadragon.TiledImage} item - The item.\n * @returns {Number} The index of the item or -1 if not present.\n */\n getIndexOfItem: function( item ) {\n $.console.assert(item, \"[World.getIndexOfItem] item is required\");\n return $.indexOf( this._items, item );\n },\n\n /**\n * @returns {Number} The number of items used.\n */\n getItemCount: function() {\n return this._items.length;\n },\n\n /**\n * Change the index of a item so that it appears over or under others.\n * @param {OpenSeadragon.TiledImage} item - The item to move.\n * @param {Number} index - The new index.\n * @fires OpenSeadragon.World.event:item-index-change\n */\n setItemIndex: function( item, index ) {\n $.console.assert(item, \"[World.setItemIndex] item is required\");\n $.console.assert(index !== undefined, \"[World.setItemIndex] index is required\");\n\n var oldIndex = this.getIndexOfItem( item );\n\n if ( index >= this._items.length ) {\n throw new Error( \"Index bigger than number of layers.\" );\n }\n\n if ( index === oldIndex || oldIndex === -1 ) {\n return;\n }\n\n this._items.splice( oldIndex, 1 );\n this._items.splice( index, 0, item );\n this._needsDraw = true;\n\n /**\n * Raised when the order of the indexes has been changed.\n * @event item-index-change\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.\n * @property {OpenSeadragon.TiledImage} item - The item whose index has\n * been changed\n * @property {Number} previousIndex - The previous index of the item\n * @property {Number} newIndex - The new index of the item\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'item-index-change', {\n item: item,\n previousIndex: oldIndex,\n newIndex: index\n } );\n },\n\n /**\n * Remove an item.\n * @param {OpenSeadragon.TiledImage} item - The item to remove.\n * @fires OpenSeadragon.World.event:remove-item\n * @fires OpenSeadragon.World.event:metrics-change\n */\n removeItem: function( item ) {\n $.console.assert(item, \"[World.removeItem] item is required\");\n\n var index = $.indexOf(this._items, item );\n if ( index === -1 ) {\n return;\n }\n\n item.removeHandler('bounds-change', this._delegatedFigureSizes);\n item.removeHandler('clip-change', this._delegatedFigureSizes);\n item.destroy();\n this._items.splice( index, 1 );\n this._figureSizes();\n this._needsDraw = true;\n this._raiseRemoveItem(item);\n },\n\n /**\n * Remove all items.\n * @fires OpenSeadragon.World.event:remove-item\n * @fires OpenSeadragon.World.event:metrics-change\n */\n removeAll: function() {\n // We need to make sure any pending images are canceled so the world items don't get messed up\n this.viewer._cancelPendingImages();\n var item;\n var i;\n for (i = 0; i < this._items.length; i++) {\n item = this._items[i];\n item.removeHandler('bounds-change', this._delegatedFigureSizes);\n item.removeHandler('clip-change', this._delegatedFigureSizes);\n item.destroy();\n }\n\n var removedItems = this._items;\n this._items = [];\n this._figureSizes();\n this._needsDraw = true;\n\n for (i = 0; i < removedItems.length; i++) {\n item = removedItems[i];\n this._raiseRemoveItem(item);\n }\n },\n\n /**\n * Clears all tiles and triggers updates for all items.\n */\n resetItems: function() {\n for ( var i = 0; i < this._items.length; i++ ) {\n this._items[i].reset();\n }\n },\n\n /**\n * Updates (i.e. animates bounds of) all items.\n */\n update: function() {\n var animated = false;\n for ( var i = 0; i < this._items.length; i++ ) {\n animated = this._items[i].update() || animated;\n }\n\n return animated;\n },\n\n /**\n * Draws all items.\n */\n draw: function() {\n for ( var i = 0; i < this._items.length; i++ ) {\n this._items[i].draw();\n }\n\n this._needsDraw = false;\n },\n\n /**\n * @returns {Boolean} true if any items need updating.\n */\n needsDraw: function() {\n for ( var i = 0; i < this._items.length; i++ ) {\n if ( this._items[i].needsDraw() ) {\n return true;\n }\n }\n return this._needsDraw;\n },\n\n /**\n * @returns {OpenSeadragon.Rect} The smallest rectangle that encloses all items, in viewport coordinates.\n */\n getHomeBounds: function() {\n return this._homeBounds.clone();\n },\n\n /**\n * To facilitate zoom constraints, we keep track of the pixel density of the\n * densest item in the World (i.e. the item whose content size to viewport size\n * ratio is the highest) and save it as this \"content factor\".\n * @returns {Number} the number of content units per viewport unit.\n */\n getContentFactor: function() {\n return this._contentFactor;\n },\n\n /**\n * As a performance optimization, setting this flag to false allows the bounds-change event handler\n * on tiledImages to skip calculations on the world bounds. If a lot of images are going to be positioned in\n * rapid succession, this is a good idea. When finished, setAutoRefigureSizes should be called with true\n * or the system may behave oddly.\n * @param {Boolean} [value] The value to which to set the flag.\n */\n setAutoRefigureSizes: function(value) {\n this._autoRefigureSizes = value;\n if (value & this._needsSizesFigured) {\n this._figureSizes();\n this._needsSizesFigured = false;\n }\n },\n\n /**\n * Arranges all of the TiledImages with the specified settings.\n * @param {Object} options - Specifies how to arrange.\n * @param {Boolean} [options.immediately=false] - Whether to animate to the new arrangement.\n * @param {String} [options.layout] - See collectionLayout in {@link OpenSeadragon.Options}.\n * @param {Number} [options.rows] - See collectionRows in {@link OpenSeadragon.Options}.\n * @param {Number} [options.columns] - See collectionColumns in {@link OpenSeadragon.Options}.\n * @param {Number} [options.tileSize] - See collectionTileSize in {@link OpenSeadragon.Options}.\n * @param {Number} [options.tileMargin] - See collectionTileMargin in {@link OpenSeadragon.Options}.\n * @fires OpenSeadragon.World.event:metrics-change\n */\n arrange: function(options) {\n options = options || {};\n var immediately = options.immediately || false;\n var layout = options.layout || $.DEFAULT_SETTINGS.collectionLayout;\n var rows = options.rows || $.DEFAULT_SETTINGS.collectionRows;\n var columns = options.columns || $.DEFAULT_SETTINGS.collectionColumns;\n var tileSize = options.tileSize || $.DEFAULT_SETTINGS.collectionTileSize;\n var tileMargin = options.tileMargin || $.DEFAULT_SETTINGS.collectionTileMargin;\n var increment = tileSize + tileMargin;\n var wrap;\n if (!options.rows && columns) {\n wrap = columns;\n } else {\n wrap = Math.ceil(this._items.length / rows);\n }\n var x = 0;\n var y = 0;\n var item, box, width, height, position;\n\n this.setAutoRefigureSizes(false);\n for (var i = 0; i < this._items.length; i++) {\n if (i && (i % wrap) === 0) {\n if (layout === 'horizontal') {\n y += increment;\n x = 0;\n } else {\n x += increment;\n y = 0;\n }\n }\n\n item = this._items[i];\n box = item.getBounds();\n if (box.width > box.height) {\n width = tileSize;\n } else {\n width = tileSize * (box.width / box.height);\n }\n\n height = width * (box.height / box.width);\n position = new $.Point(x + ((tileSize - width) / 2),\n y + ((tileSize - height) / 2));\n\n item.setPosition(position, immediately);\n item.setWidth(width, immediately);\n\n if (layout === 'horizontal') {\n x += increment;\n } else {\n y += increment;\n }\n }\n this.setAutoRefigureSizes(true);\n },\n\n // private\n _figureSizes: function() {\n var oldHomeBounds = this._homeBounds ? this._homeBounds.clone() : null;\n var oldContentSize = this._contentSize ? this._contentSize.clone() : null;\n var oldContentFactor = this._contentFactor || 0;\n\n if (!this._items.length) {\n this._homeBounds = new $.Rect(0, 0, 1, 1);\n this._contentSize = new $.Point(1, 1);\n this._contentFactor = 1;\n } else {\n var item = this._items[0];\n var bounds = item.getBounds();\n this._contentFactor = item.getContentSize().x / bounds.width;\n var clippedBounds = item.getClippedBounds().getBoundingBox();\n var left = clippedBounds.x;\n var top = clippedBounds.y;\n var right = clippedBounds.x + clippedBounds.width;\n var bottom = clippedBounds.y + clippedBounds.height;\n for (var i = 1; i < this._items.length; i++) {\n item = this._items[i];\n bounds = item.getBounds();\n this._contentFactor = Math.max(this._contentFactor,\n item.getContentSize().x / bounds.width);\n clippedBounds = item.getClippedBounds().getBoundingBox();\n left = Math.min(left, clippedBounds.x);\n top = Math.min(top, clippedBounds.y);\n right = Math.max(right, clippedBounds.x + clippedBounds.width);\n bottom = Math.max(bottom, clippedBounds.y + clippedBounds.height);\n }\n\n this._homeBounds = new $.Rect(left, top, right - left, bottom - top);\n this._contentSize = new $.Point(\n this._homeBounds.width * this._contentFactor,\n this._homeBounds.height * this._contentFactor);\n }\n\n if (this._contentFactor !== oldContentFactor ||\n !this._homeBounds.equals(oldHomeBounds) ||\n !this._contentSize.equals(oldContentSize)) {\n /**\n * Raised when the home bounds or content factor change.\n * @event metrics-change\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('metrics-change', {});\n }\n },\n\n // private\n _raiseRemoveItem: function(item) {\n /**\n * Raised when an item is removed.\n * @event remove-item\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.\n * @property {OpenSeadragon.TiledImage} item - The item's underlying item.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'remove-item', { item: item } );\n }\n});\n\n}( OpenSeadragon ));\n\n//# sourceMappingURL=openseadragon.js.map\n\n//# sourceURL=webpack:///./node_modules/openseadragon/build/openseadragon/openseadragon.js?"); +eval("var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;//! openseadragon 2.3.1\n//! Built on 2022-04-29\n//! Git commit: unknown\n//! http://openseadragon.github.io\n//! License: http://openseadragon.github.io/license/\n\n/*\n * OpenSeadragon\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Portions of this source file taken from jQuery:\n *\n * Copyright 2011 John Resig\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/*\n * Portions of this source file taken from mattsnider.com:\n *\n * Copyright (c) 2006-2013 Matt Snider\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT\n * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR\n * THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n\n/**\n * @namespace OpenSeadragon\n * @version openseadragon 2.3.1\n * @classdesc The root namespace for OpenSeadragon. All utility methods\n * and classes are defined on or below this namespace.\n *\n */\n\n\n// Typedefs\n\n /**\n * All required and optional settings for instantiating a new instance of an OpenSeadragon image viewer.\n *\n * @typedef {Object} Options\n * @memberof OpenSeadragon\n *\n * @property {String} id\n * Id of the element to append the viewer's container element to. If not provided, the 'element' property must be provided.\n * If both the element and id properties are specified, the viewer is appended to the element provided in the element property.\n *\n * @property {Element} element\n * The element to append the viewer's container element to. If not provided, the 'id' property must be provided.\n * If both the element and id properties are specified, the viewer is appended to the element provided in the element property.\n *\n * @property {Array|String|Function|Object} [tileSources=null]\n * Tile source(s) to open initially. This is a complex parameter; see\n * {@link OpenSeadragon.Viewer#open} for details.\n *\n * @property {Number} [tabIndex=0]\n * Tabbing order index to assign to the viewer element. Positive values are selected in increasing order. When tabIndex is 0\n * source order is used. A negative value omits the viewer from the tabbing order.\n *\n * @property {Array} overlays Array of objects defining permanent overlays of\n * the viewer. The overlays added via this option and later removed with\n * {@link OpenSeadragon.Viewer#removeOverlay} will be added back when a new\n * image is opened.\n * To add overlays which can be definitively removed, one must use\n * {@link OpenSeadragon.Viewer#addOverlay}\n * If displaying a sequence of images, the overlays can be associated\n * with a specific page by passing the overlays array to the page's\n * tile source configuration.\n * Expected properties:\n * * x, y, (or px, py for pixel coordinates) to define the location.\n * * width, height in point if using x,y or in pixels if using px,py. If width\n * and height are specified, the overlay size is adjusted when zooming,\n * otherwise the size stays the size of the content (or the size defined by CSS).\n * * className to associate a class to the overlay\n * * id to set the overlay element. If an element with this id already exists,\n * it is reused, otherwise it is created. If not specified, a new element is\n * created.\n * * placement a string to define the relative position to the viewport.\n * Only used if no width and height are specified. Default: 'TOP_LEFT'.\n * See {@link OpenSeadragon.Placement} for possible values.\n *\n * @property {String} [xmlPath=null]\n * DEPRECATED. A relative path to load a DZI file from the server.\n * Prefer the newer Options.tileSources.\n *\n * @property {String} [prefixUrl='/images/']\n * Prepends the prefixUrl to navImages paths, which is very useful\n * since the default paths are rarely useful for production\n * environments.\n *\n * @property {OpenSeadragon.NavImages} [navImages]\n * An object with a property for each button or other built-in navigation\n * control, eg the current 'zoomIn', 'zoomOut', 'home', and 'fullpage'.\n * Each of those in turn provides an image path for each state of the button\n * or navigation control, eg 'REST', 'GROUP', 'HOVER', 'PRESS'. Finally the\n * image paths, by default assume there is a folder on the servers root path\n * called '/images', eg '/images/zoomin_rest.png'. If you need to adjust\n * these paths, prefer setting the option.prefixUrl rather than overriding\n * every image path directly through this setting.\n *\n * @property {Boolean} [debugMode=false]\n * TODO: provide an in-screen panel providing event detail feedback.\n *\n * @property {String} [debugGridColor=['#437AB2', '#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E', '#E6AB02', '#A6761D', '#666666']]\n * The colors of grids in debug mode. Each tiled image's grid uses a consecutive color.\n * If there are more tiled images than provided colors, the color vector is recycled.\n *\n * @property {Number} [blendTime=0]\n * Specifies the duration of animation as higher or lower level tiles are\n * replacing the existing tile.\n *\n * @property {Boolean} [alwaysBlend=false]\n * Forces the tile to always blend. By default the tiles skip blending\n * when the blendTime is surpassed and the current animation frame would\n * not complete the blend.\n *\n * @property {Boolean} [autoHideControls=true]\n * If the user stops interacting with the viewport, fade the navigation\n * controls. Useful for presentation since the controls are by default\n * floated on top of the image the user is viewing.\n *\n * @property {Boolean} [immediateRender=false]\n * Render the best closest level first, ignoring the lowering levels which\n * provide the effect of very blurry to sharp. It is recommended to change\n * setting to true for mobile devices.\n *\n * @property {Number} [defaultZoomLevel=0]\n * Zoom level to use when image is first opened or the home button is clicked.\n * If 0, adjusts to fit viewer.\n *\n * @property {Number} [opacity=1]\n * Default proportional opacity of the tiled images (1=opaque, 0=hidden)\n * Hidden images do not draw and only load when preloading is allowed.\n *\n * @property {Boolean} [preload=false]\n * Default switch for loading hidden images (true loads, false blocks)\n *\n * @property {String} [compositeOperation=null]\n * Valid values are 'source-over', 'source-atop', 'source-in', 'source-out',\n * 'destination-over', 'destination-atop', 'destination-in',\n * 'destination-out', 'lighter', 'copy' or 'xor'\n *\n * @property {String|CanvasGradient|CanvasPattern|Function} [placeholderFillStyle=null]\n * Draws a colored rectangle behind the tile if it is not loaded yet.\n * You can pass a CSS color value like \"#FF8800\".\n * When passing a function the tiledImage and canvas context are available as argument which is useful when you draw a gradient or pattern.\n *\n * @property {Number} [degrees=0]\n * Initial rotation.\n *\n * @property {Boolean} [flipped=false]\n * Initial flip state.\n *\n * @property {Number} [minZoomLevel=null]\n *\n * @property {Number} [maxZoomLevel=null]\n *\n * @property {Boolean} [homeFillsViewer=false]\n * Make the 'home' button fill the viewer and clip the image, instead\n * of fitting the image to the viewer and letterboxing.\n *\n * @property {Boolean} [panHorizontal=true]\n * Allow horizontal pan.\n *\n * @property {Boolean} [panVertical=true]\n * Allow vertical pan.\n *\n * @property {Boolean} [constrainDuringPan=false]\n *\n * @property {Boolean} [wrapHorizontal=false]\n * Set to true to force the image to wrap horizontally within the viewport.\n * Useful for maps or images representing the surface of a sphere or cylinder.\n *\n * @property {Boolean} [wrapVertical=false]\n * Set to true to force the image to wrap vertically within the viewport.\n * Useful for maps or images representing the surface of a sphere or cylinder.\n *\n * @property {Number} [minZoomImageRatio=0.9]\n * The minimum percentage ( expressed as a number between 0 and 1 ) of\n * the viewport height or width at which the zoom out will be constrained.\n * Setting it to 0, for example will allow you to zoom out infinity.\n *\n * @property {Number} [maxZoomPixelRatio=1.1]\n * The maximum ratio to allow a zoom-in to affect the highest level pixel\n * ratio. This can be set to Infinity to allow 'infinite' zooming into the\n * image though it is less effective visually if the HTML5 Canvas is not\n * availble on the viewing device.\n *\n * @property {Number} [smoothTileEdgesMinZoom=1.1]\n * A zoom percentage ( where 1 is 100% ) of the highest resolution level.\n * When zoomed in beyond this value alternative compositing will be used to\n * smooth out the edges between tiles. This will have a performance impact.\n * Can be set to Infinity to turn it off.\n * Note: This setting is ignored on iOS devices due to a known bug (See {@link https://github.com/openseadragon/openseadragon/issues/952})\n *\n * @property {Boolean} [iOSDevice=?]\n * True if running on an iOS device, false otherwise.\n * Used to disable certain features that behave differently on iOS devices.\n *\n * @property {Boolean} [autoResize=true]\n * Set to false to prevent polling for viewer size changes. Useful for providing custom resize behavior.\n *\n * @property {Boolean} [preserveImageSizeOnResize=false]\n * Set to true to have the image size preserved when the viewer is resized. This requires autoResize=true (default).\n *\n * @property {Number} [minScrollDeltaTime=50]\n * Number of milliseconds between canvas-scroll events. This value helps normalize the rate of canvas-scroll\n * events between different devices, causing the faster devices to slow down enough to make the zoom control\n * more manageable.\n *\n * @property {Number} [pixelsPerWheelLine=40]\n * For pixel-resolution scrolling devices, the number of pixels equal to one scroll line.\n *\n * @property {Number} [pixelsPerArrowPress=40]\n * The number of pixels viewport moves when an arrow key is pressed.\n *\n * @property {Number} [visibilityRatio=0.5]\n * The percentage ( as a number from 0 to 1 ) of the source image which\n * must be kept within the viewport. If the image is dragged beyond that\n * limit, it will 'bounce' back until the minimum visibility ratio is\n * achieved. Setting this to 0 and wrapHorizontal ( or wrapVertical ) to\n * true will provide the effect of an infinitely scrolling viewport.\n *\n * @property {Object} [viewportMargins={}]\n * Pushes the \"home\" region in from the sides by the specified amounts.\n * Possible subproperties (Numbers, in screen coordinates): left, top, right, bottom.\n *\n * @property {Number} [imageLoaderLimit=0]\n * The maximum number of image requests to make concurrently. By default\n * it is set to 0 allowing the browser to make the maximum number of\n * image requests in parallel as allowed by the browsers policy.\n *\n * @property {Number} [clickTimeThreshold=300]\n * The number of milliseconds within which a pointer down-up event combination\n * will be treated as a click gesture.\n *\n * @property {Number} [clickDistThreshold=5]\n * The maximum distance allowed between a pointer down event and a pointer up event\n * to be treated as a click gesture.\n *\n * @property {Number} [dblClickTimeThreshold=300]\n * The number of milliseconds within which two pointer down-up event combinations\n * will be treated as a double-click gesture.\n *\n * @property {Number} [dblClickDistThreshold=20]\n * The maximum distance allowed between two pointer click events\n * to be treated as a double-click gesture.\n *\n * @property {Number} [springStiffness=6.5]\n *\n * @property {Number} [animationTime=1.2]\n * Specifies the animation duration per each {@link OpenSeadragon.Spring}\n * which occur when the image is dragged or zoomed.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsMouse]\n * Settings for gestures generated by a mouse pointer device. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsMouse.scrollToZoom=true] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsMouse.clickToZoom=true] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsMouse.dblClickToZoom=false] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsMouse.pinchToZoom=false] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsMouse.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsMouse.flickEnabled=false] - Enable flick gesture\n * @property {Number} [gestureSettingsMouse.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsMouse.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsMouse.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsTouch]\n * Settings for gestures generated by a touch pointer device. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsTouch.scrollToZoom=false] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsTouch.clickToZoom=false] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsTouch.dblClickToZoom=true] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsTouch.pinchToZoom=true] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsTouch.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsTouch.flickEnabled=true] - Enable flick gesture\n * @property {Number} [gestureSettingsTouch.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsTouch.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsTouch.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsPen]\n * Settings for gestures generated by a pen pointer device. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsPen.scrollToZoom=false] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsPen.clickToZoom=true] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsPen.dblClickToZoom=false] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsPen.pinchToZoom=false] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsPan.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsPen.flickEnabled=false] - Enable flick gesture\n * @property {Number} [gestureSettingsPen.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsPen.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsPen.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {OpenSeadragon.GestureSettings} [gestureSettingsUnknown]\n * Settings for gestures generated by unknown pointer devices. (See {@link OpenSeadragon.GestureSettings})\n * @property {Boolean} [gestureSettingsUnknown.scrollToZoom=true] - Zoom on scroll gesture\n * @property {Boolean} [gestureSettingsUnknown.clickToZoom=false] - Zoom on click gesture\n * @property {Boolean} [gestureSettingsUnknown.dblClickToZoom=true] - Zoom on double-click gesture. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n * @property {Boolean} [gestureSettingsUnknown.pinchToZoom=true] - Zoom on pinch gesture\n * @property {Boolean} [gestureSettingsUnknown.zoomToRefPoint=true] - If zoomToRefPoint is true, the zoom is centered at the pointer position. Otherwise,\n * the zoom is centered at the canvas center.\n * @property {Boolean} [gestureSettingsUnknown.flickEnabled=true] - Enable flick gesture\n * @property {Number} [gestureSettingsUnknown.flickMinSpeed=120] - If flickEnabled is true, the minimum speed to initiate a flick gesture (pixels-per-second)\n * @property {Number} [gestureSettingsUnknown.flickMomentum=0.25] - If flickEnabled is true, the momentum factor for the flick gesture\n * @property {Boolean} [gestureSettingsUnknown.pinchRotate=false] - If pinchRotate is true, the user will have the ability to rotate the image using their fingers.\n *\n * @property {Number} [zoomPerClick=2.0]\n * The \"zoom distance\" per mouse click or touch tap. Note: Setting this to 1.0 effectively disables the click-to-zoom feature (also see gestureSettings[Mouse|Touch|Pen].clickToZoom/dblClickToZoom).\n *\n * @property {Number} [zoomPerScroll=1.2]\n * The \"zoom distance\" per mouse scroll or touch pinch. Note: Setting this to 1.0 effectively disables the mouse-wheel zoom feature (also see gestureSettings[Mouse|Touch|Pen].scrollToZoom}).\n *\n * @property {Number} [zoomPerSecond=1.0]\n * The number of seconds to animate a single zoom event over.\n *\n * @property {Boolean} [showNavigator=false]\n * Set to true to make the navigator minimap appear.\n *\n * @property {String} [navigatorId=navigator-GENERATED DATE]\n * The ID of a div to hold the navigator minimap.\n * If an ID is specified, the navigatorPosition, navigatorSizeRatio, navigatorMaintainSizeRatio, navigator[Top|Left|Height|Width] and navigatorAutoFade options will be ignored.\n * If an ID is not specified, a div element will be generated and placed on top of the main image.\n *\n * @property {String} [navigatorPosition='TOP_RIGHT']\n * Valid values are 'TOP_LEFT', 'TOP_RIGHT', 'BOTTOM_LEFT', 'BOTTOM_RIGHT', or 'ABSOLUTE'.
\n * If 'ABSOLUTE' is specified, then navigator[Top|Left|Height|Width] determines the size and position of the navigator minimap in the viewer, and navigatorSizeRatio and navigatorMaintainSizeRatio are ignored.
\n * For 'TOP_LEFT', 'TOP_RIGHT', 'BOTTOM_LEFT', and 'BOTTOM_RIGHT', the navigatorSizeRatio or navigator[Height|Width] values determine the size of the navigator minimap.\n *\n * @property {Number} [navigatorSizeRatio=0.2]\n * Ratio of navigator size to viewer size. Ignored if navigator[Height|Width] are specified.\n *\n * @property {Boolean} [navigatorMaintainSizeRatio=false]\n * If true, the navigator minimap is resized (using navigatorSizeRatio) when the viewer size changes.\n *\n * @property {Number|String} [navigatorTop=null]\n * Specifies the location of the navigator minimap (see navigatorPosition).\n *\n * @property {Number|String} [navigatorLeft=null]\n * Specifies the location of the navigator minimap (see navigatorPosition).\n *\n * @property {Number|String} [navigatorHeight=null]\n * Specifies the size of the navigator minimap (see navigatorPosition).\n * If specified, navigatorSizeRatio and navigatorMaintainSizeRatio are ignored.\n *\n * @property {Number|String} [navigatorWidth=null]\n * Specifies the size of the navigator minimap (see navigatorPosition).\n * If specified, navigatorSizeRatio and navigatorMaintainSizeRatio are ignored.\n *\n * @property {Boolean} [navigatorAutoResize=true]\n * Set to false to prevent polling for navigator size changes. Useful for providing custom resize behavior.\n * Setting to false can also improve performance when the navigator is configured to a fixed size.\n *\n * @property {Boolean} [navigatorAutoFade=true]\n * If the user stops interacting with the viewport, fade the navigator minimap.\n * Setting to false will make the navigator minimap always visible.\n *\n * @property {Boolean} [navigatorRotate=true]\n * If true, the navigator will be rotated together with the viewer.\n *\n * @property {Number} [controlsFadeDelay=2000]\n * The number of milliseconds to wait once the user has stopped interacting\n * with the interface before begining to fade the controls. Assumes\n * showNavigationControl and autoHideControls are both true.\n *\n * @property {Number} [controlsFadeLength=1500]\n * The number of milliseconds to animate the controls fading out.\n *\n * @property {Number} [maxImageCacheCount=200]\n * The max number of images we should keep in memory (per drawer).\n *\n * @property {Number} [timeout=30000]\n * The max number of milliseconds that an image job may take to complete.\n *\n * @property {Boolean} [useCanvas=true]\n * Set to false to not use an HTML canvas element for image rendering even if canvas is supported.\n *\n * @property {Number} [minPixelRatio=0.5]\n * The higher the minPixelRatio, the lower the quality of the image that\n * is considered sufficient to stop rendering a given zoom level. For\n * example, if you are targeting mobile devices with less bandwith you may\n * try setting this to 1.5 or higher.\n *\n * @property {Boolean} [mouseNavEnabled=true]\n * Is the user able to interact with the image via mouse or touch. Default\n * interactions include draging the image in a plane, and zooming in toward\n * and away from the image.\n *\n * @property {Boolean} [showNavigationControl=true]\n * Set to false to prevent the appearance of the default navigation controls.
\n * Note that if set to false, the customs buttons set by the options\n * zoomInButton, zoomOutButton etc, are rendered inactive.\n *\n * @property {OpenSeadragon.ControlAnchor} [navigationControlAnchor=TOP_LEFT]\n * Placement of the default navigation controls.\n * To set the placement of the sequence controls, see the\n * sequenceControlAnchor option.\n *\n * @property {Boolean} [showZoomControl=true]\n * If true then + and - buttons to zoom in and out are displayed.
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showHomeControl=true]\n * If true then the 'Go home' button is displayed to go back to the original\n * zoom and pan.
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showFullPageControl=true]\n * If true then the 'Toggle full page' button is displayed to switch\n * between full page and normal mode.
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showRotationControl=false]\n * If true then the rotate left/right controls will be displayed as part of the\n * standard controls. This is also subject to the browser support for rotate\n * (e.g. viewer.drawer.canRotate()).
\n * Note: {@link OpenSeadragon.Options.showNavigationControl} is overriding\n * this setting when set to false.\n *\n * @property {Boolean} [showFlipControl=false]\n * If true then the flip controls will be displayed as part of the\n * standard controls.\n *\n * @property {Boolean} [showSequenceControl=true]\n * If sequenceMode is true, then provide buttons for navigating forward and\n * backward through the images.\n *\n * @property {OpenSeadragon.ControlAnchor} [sequenceControlAnchor=TOP_LEFT]\n * Placement of the default sequence controls.\n *\n * @property {Boolean} [navPrevNextWrap=false]\n * If true then the 'previous' button will wrap to the last image when\n * viewing the first image and the 'next' button will wrap to the first\n * image when viewing the last image.\n *\n * @property {String} zoomInButton\n * Set the id of the custom 'Zoom in' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} zoomOutButton\n * Set the id of the custom 'Zoom out' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} homeButton\n * Set the id of the custom 'Go home' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} fullPageButton\n * Set the id of the custom 'Toggle full page' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} rotateLeftButton\n * Set the id of the custom 'Rotate left' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} rotateRightButton\n * Set the id of the custom 'Rotate right' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} previousButton\n * Set the id of the custom 'Previous page' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {String} nextButton\n * Set the id of the custom 'Next page' button to use.\n * This is useful to have a custom button anywhere in the web page.
\n * To only change the button images, consider using\n * {@link OpenSeadragon.Options.navImages}\n *\n * @property {Boolean} [sequenceMode=false]\n * Set to true to have the viewer treat your tilesources as a sequence of images to\n * be opened one at a time rather than all at once.\n *\n * @property {Number} [initialPage=0]\n * If sequenceMode is true, display this page initially.\n *\n * @property {Boolean} [preserveViewport=false]\n * If sequenceMode is true, then normally navigating through each image resets the\n * viewport to 'home' position. If preserveViewport is set to true, then the viewport\n * position is preserved when navigating between images in the sequence.\n *\n * @property {Boolean} [preserveOverlays=false]\n * If sequenceMode is true, then normally navigating through each image\n * resets the overlays.\n * If preserveOverlays is set to true, then the overlays added with {@link OpenSeadragon.Viewer#addOverlay}\n * are preserved when navigating between images in the sequence.\n * Note: setting preserveOverlays overrides any overlays specified in the global\n * \"overlays\" option for the Viewer. It's also not compatible with specifying\n * per-tileSource overlays via the options, as those overlays will persist\n * even after the tileSource is closed.\n *\n * @property {Boolean} [showReferenceStrip=false]\n * If sequenceMode is true, then display a scrolling strip of image thumbnails for\n * navigating through the images.\n *\n * @property {String} [referenceStripScroll='horizontal']\n *\n * @property {Element} [referenceStripElement=null]\n *\n * @property {Number} [referenceStripHeight=null]\n *\n * @property {Number} [referenceStripWidth=null]\n *\n * @property {String} [referenceStripPosition='BOTTOM_LEFT']\n *\n * @property {Number} [referenceStripSizeRatio=0.2]\n *\n * @property {Boolean} [collectionMode=false]\n * Set to true to have the viewer arrange your TiledImages in a grid or line.\n *\n * @property {Number} [collectionRows=3]\n * If collectionMode is true, specifies how many rows the grid should have. Use 1 to make a line.\n * If collectionLayout is 'vertical', specifies how many columns instead.\n *\n * @property {Number} [collectionColumns=0]\n * If collectionMode is true, specifies how many columns the grid should have. Use 1 to make a line.\n * If collectionLayout is 'vertical', specifies how many rows instead. Ignored if collectionRows is not set to a falsy value.\n *\n * @property {String} [collectionLayout='horizontal']\n * If collectionMode is true, specifies whether to arrange vertically or horizontally.\n *\n * @property {Number} [collectionTileSize=800]\n * If collectionMode is true, specifies the size, in viewport coordinates, for each TiledImage to fit into.\n * The TiledImage will be centered within a square of the specified size.\n *\n * @property {Number} [collectionTileMargin=80]\n * If collectionMode is true, specifies the margin, in viewport coordinates, between each TiledImage.\n *\n * @property {String|Boolean} [crossOriginPolicy=false]\n * Valid values are 'Anonymous', 'use-credentials', and false. If false, canvas requests will\n * not use CORS, and the canvas will be tainted.\n *\n * @property {Boolean} [ajaxWithCredentials=false]\n * Whether to set the withCredentials XHR flag for AJAX requests.\n * Note that this can be overridden at the {@link OpenSeadragon.TileSource} level.\n *\n * @property {Boolean} [loadTilesWithAjax=false]\n * Whether to load tile data using AJAX requests.\n * Note that this can be overridden at the {@link OpenSeadragon.TileSource} level.\n *\n * @property {Object} [ajaxHeaders={}]\n * A set of headers to include when making AJAX requests for tile sources or tiles.\n *\n */\n\n /**\n * Settings for gestures generated by a pointer device.\n *\n * @typedef {Object} GestureSettings\n * @memberof OpenSeadragon\n *\n * @property {Boolean} scrollToZoom\n * Set to false to disable zooming on scroll gestures.\n *\n * @property {Boolean} clickToZoom\n * Set to false to disable zooming on click gestures.\n *\n * @property {Boolean} dblClickToZoom\n * Set to false to disable zooming on double-click gestures. Note: If set to true\n * then clickToZoom should be set to false to prevent multiple zooms.\n *\n * @property {Boolean} pinchToZoom\n * Set to false to disable zooming on pinch gestures.\n *\n * @property {Boolean} flickEnabled\n * Set to false to disable the kinetic panning effect (flick) at the end of a drag gesture.\n *\n * @property {Number} flickMinSpeed\n * If flickEnabled is true, the minimum speed (in pixels-per-second) required to cause the kinetic panning effect (flick) at the end of a drag gesture.\n *\n * @property {Number} flickMomentum\n * If flickEnabled is true, a constant multiplied by the velocity to determine the distance of the kinetic panning effect (flick) at the end of a drag gesture.\n * A larger value will make the flick feel \"lighter\", while a smaller value will make the flick feel \"heavier\".\n * Note: springStiffness and animationTime also affect the \"spring\" used to stop the flick animation.\n *\n */\n\n/**\n * The names for the image resources used for the image navigation buttons.\n *\n * @typedef {Object} NavImages\n * @memberof OpenSeadragon\n *\n * @property {Object} zoomIn - Images for the zoom-in button.\n * @property {String} zoomIn.REST\n * @property {String} zoomIn.GROUP\n * @property {String} zoomIn.HOVER\n * @property {String} zoomIn.DOWN\n *\n * @property {Object} zoomOut - Images for the zoom-out button.\n * @property {String} zoomOut.REST\n * @property {String} zoomOut.GROUP\n * @property {String} zoomOut.HOVER\n * @property {String} zoomOut.DOWN\n *\n * @property {Object} home - Images for the home button.\n * @property {String} home.REST\n * @property {String} home.GROUP\n * @property {String} home.HOVER\n * @property {String} home.DOWN\n *\n * @property {Object} fullpage - Images for the full-page button.\n * @property {String} fullpage.REST\n * @property {String} fullpage.GROUP\n * @property {String} fullpage.HOVER\n * @property {String} fullpage.DOWN\n *\n * @property {Object} rotateleft - Images for the rotate left button.\n * @property {String} rotateleft.REST\n * @property {String} rotateleft.GROUP\n * @property {String} rotateleft.HOVER\n * @property {String} rotateleft.DOWN\n *\n * @property {Object} rotateright - Images for the rotate right button.\n * @property {String} rotateright.REST\n * @property {String} rotateright.GROUP\n * @property {String} rotateright.HOVER\n * @property {String} rotateright.DOWN\n *\n * @property {Object} flip - Images for the flip button.\n * @property {String} flip.REST\n * @property {String} flip.GROUP\n * @property {String} flip.HOVER\n * @property {String} flip.DOWN\n *\n * @property {Object} previous - Images for the previous button.\n * @property {String} previous.REST\n * @property {String} previous.GROUP\n * @property {String} previous.HOVER\n * @property {String} previous.DOWN\n *\n * @property {Object} next - Images for the next button.\n * @property {String} next.REST\n * @property {String} next.GROUP\n * @property {String} next.HOVER\n * @property {String} next.DOWN\n *\n */\n\n\nfunction OpenSeadragon( options ){\n return new OpenSeadragon.Viewer( options );\n}\n\n(function( $ ){\n\n\n /**\n * The OpenSeadragon version.\n *\n * @member {Object} OpenSeadragon.version\n * @property {String} versionStr - The version number as a string ('major.minor.revision').\n * @property {Number} major - The major version number.\n * @property {Number} minor - The minor version number.\n * @property {Number} revision - The revision number.\n * @since 1.0.0\n */\n $.version = {\n versionStr: '2.3.1',\n major: parseInt('2', 10),\n minor: parseInt('3', 10),\n revision: parseInt('1', 10)\n };\n\n\n /**\n * Taken from jquery 1.6.1\n * [[Class]] -> type pairs\n * @private\n */\n var class2type = {\n '[object Boolean]': 'boolean',\n '[object Number]': 'number',\n '[object String]': 'string',\n '[object Function]': 'function',\n '[object Array]': 'array',\n '[object Date]': 'date',\n '[object RegExp]': 'regexp',\n '[object Object]': 'object'\n },\n // Save a reference to some core methods\n toString = Object.prototype.toString,\n hasOwn = Object.prototype.hasOwnProperty;\n\n /**\n * Taken from jQuery 1.6.1\n * @function isFunction\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isFunction = function( obj ) {\n return $.type(obj) === \"function\";\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function isArray\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isArray = Array.isArray || function( obj ) {\n return $.type(obj) === \"array\";\n };\n\n\n /**\n * A crude way of determining if an object is a window.\n * Taken from jQuery 1.6.1\n * @function isWindow\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isWindow = function( obj ) {\n return obj && typeof obj === \"object\" && \"setInterval\" in obj;\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function type\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.type = function( obj ) {\n return ( obj === null ) || ( obj === undefined ) ?\n String( obj ) :\n class2type[ toString.call(obj) ] || \"object\";\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function isPlainObject\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isPlainObject = function( obj ) {\n // Must be an Object.\n // Because of IE, we also have to check the presence of the constructor property.\n // Make sure that DOM nodes and window objects don't pass through, as well\n if ( !obj || OpenSeadragon.type(obj) !== \"object\" || obj.nodeType || $.isWindow( obj ) ) {\n return false;\n }\n\n // Not own constructor property must be Object\n if ( obj.constructor &&\n !hasOwn.call(obj, \"constructor\") &&\n !hasOwn.call(obj.constructor.prototype, \"isPrototypeOf\") ) {\n return false;\n }\n\n // Own properties are enumerated firstly, so to speed up,\n // if last one is own, then all properties are own.\n\n var lastKey;\n for (var key in obj ) {\n lastKey = key;\n }\n\n return lastKey === undefined || hasOwn.call( obj, lastKey );\n };\n\n\n /**\n * Taken from jQuery 1.6.1\n * @function isEmptyObject\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.isEmptyObject = function( obj ) {\n for ( var name in obj ) {\n return false;\n }\n return true;\n };\n\n /**\n * Shim around Object.freeze. Does nothing if Object.freeze is not supported.\n * @param {Object} obj The object to freeze.\n * @return {Object} obj The frozen object.\n */\n $.freezeObject = function(obj) {\n if (Object.freeze) {\n $.freezeObject = Object.freeze;\n } else {\n $.freezeObject = function(obj) {\n return obj;\n };\n }\n return $.freezeObject(obj);\n };\n\n /**\n * True if the browser supports the HTML5 canvas element\n * @member {Boolean} supportsCanvas\n * @memberof OpenSeadragon\n */\n $.supportsCanvas = (function () {\n var canvasElement = document.createElement( 'canvas' );\n return !!( $.isFunction( canvasElement.getContext ) &&\n canvasElement.getContext( '2d' ) );\n }());\n\n /**\n * Test whether the submitted canvas is tainted or not.\n * @argument {Canvas} canvas The canvas to test.\n * @returns {Boolean} True if the canvas is tainted.\n */\n $.isCanvasTainted = function(canvas) {\n var isTainted = false;\n try {\n // We test if the canvas is tainted by retrieving data from it.\n // An exception will be raised if the canvas is tainted.\n canvas.getContext('2d').getImageData(0, 0, 1, 1);\n } catch (e) {\n isTainted = true;\n }\n return isTainted;\n };\n\n /**\n * A ratio comparing the device screen's pixel density to the canvas's backing store pixel density,\n * clamped to a minimum of 1. Defaults to 1 if canvas isn't supported by the browser.\n * @member {Number} pixelDensityRatio\n * @memberof OpenSeadragon\n */\n $.pixelDensityRatio = (function () {\n if ( $.supportsCanvas ) {\n var context = document.createElement('canvas').getContext('2d');\n var devicePixelRatio = window.devicePixelRatio || 1;\n var backingStoreRatio = context.webkitBackingStorePixelRatio ||\n context.mozBackingStorePixelRatio ||\n context.msBackingStorePixelRatio ||\n context.oBackingStorePixelRatio ||\n context.backingStorePixelRatio || 1;\n return Math.max(devicePixelRatio, 1) / backingStoreRatio;\n } else {\n return 1;\n }\n }());\n\n}( OpenSeadragon ));\n\n/**\n * This closure defines all static methods available to the OpenSeadragon\n * namespace. Many, if not most, are taked directly from jQuery for use\n * to simplify and reduce common programming patterns. More static methods\n * from jQuery may eventually make their way into this though we are\n * attempting to avoid an explicit dependency on jQuery only because\n * OpenSeadragon is a broadly useful code base and would be made less broad\n * by requiring jQuery fully.\n *\n * Some static methods have also been refactored from the original OpenSeadragon\n * project.\n */\n(function( $ ){\n\n /**\n * Taken from jQuery 1.6.1\n * @function extend\n * @memberof OpenSeadragon\n * @see {@link http://www.jquery.com/ jQuery}\n */\n $.extend = function() {\n var options,\n name,\n src,\n copy,\n copyIsArray,\n clone,\n target = arguments[ 0 ] || {},\n length = arguments.length,\n deep = false,\n i = 1;\n\n // Handle a deep copy situation\n if ( typeof target === \"boolean\" ) {\n deep = target;\n target = arguments[ 1 ] || {};\n // skip the boolean and the target\n i = 2;\n }\n\n // Handle case when target is a string or something (possible in deep copy)\n if ( typeof target !== \"object\" && !OpenSeadragon.isFunction( target ) ) {\n target = {};\n }\n\n // extend jQuery itself if only one argument is passed\n if ( length === i ) {\n target = this;\n --i;\n }\n\n for ( ; i < length; i++ ) {\n // Only deal with non-null/undefined values\n options = arguments[ i ];\n if ( options !== null || options !== undefined ) {\n // Extend the base object\n for ( name in options ) {\n src = target[ name ];\n copy = options[ name ];\n\n // Prevent never-ending loop\n if ( target === copy ) {\n continue;\n }\n\n // Recurse if we're merging plain objects or arrays\n if ( deep && copy && ( OpenSeadragon.isPlainObject( copy ) || ( copyIsArray = OpenSeadragon.isArray( copy ) ) ) ) {\n if ( copyIsArray ) {\n copyIsArray = false;\n clone = src && OpenSeadragon.isArray( src ) ? src : [];\n\n } else {\n clone = src && OpenSeadragon.isPlainObject( src ) ? src : {};\n }\n\n // Never move original objects, clone them\n target[ name ] = OpenSeadragon.extend( deep, clone, copy );\n\n // Don't bring in undefined values\n } else if ( copy !== undefined ) {\n target[ name ] = copy;\n }\n }\n }\n }\n\n // Return the modified object\n return target;\n };\n\n var isIOSDevice = function () {\n if (typeof navigator !== 'object') {\n return false;\n }\n var userAgent = navigator.userAgent;\n if (typeof userAgent !== 'string') {\n return false;\n }\n return userAgent.indexOf('iPhone') !== -1 ||\n userAgent.indexOf('iPad') !== -1 ||\n userAgent.indexOf('iPod') !== -1;\n };\n\n $.extend( $, /** @lends OpenSeadragon */{\n /**\n * The default values for the optional settings documented at {@link OpenSeadragon.Options}.\n * @static\n * @type {Object}\n */\n DEFAULT_SETTINGS: {\n //DATA SOURCE DETAILS\n xmlPath: null,\n tileSources: null,\n tileHost: null,\n initialPage: 0,\n crossOriginPolicy: false,\n ajaxWithCredentials: false,\n loadTilesWithAjax: false,\n ajaxHeaders: {},\n\n //PAN AND ZOOM SETTINGS AND CONSTRAINTS\n panHorizontal: true,\n panVertical: true,\n constrainDuringPan: false,\n wrapHorizontal: false,\n wrapVertical: false,\n visibilityRatio: 0.5, //-> how much of the viewer can be negative space\n minPixelRatio: 0.5, //->closer to 0 draws tiles meant for a higher zoom at this zoom\n defaultZoomLevel: 0,\n minZoomLevel: null,\n maxZoomLevel: null,\n homeFillsViewer: false,\n\n //UI RESPONSIVENESS AND FEEL\n clickTimeThreshold: 300,\n clickDistThreshold: 5,\n dblClickTimeThreshold: 300,\n dblClickDistThreshold: 20,\n springStiffness: 6.5,\n animationTime: 1.2,\n gestureSettingsMouse: {\n scrollToZoom: true,\n clickToZoom: true,\n dblClickToZoom: false,\n pinchToZoom: false,\n zoomToRefPoint: true,\n flickEnabled: false,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n gestureSettingsTouch: {\n scrollToZoom: false,\n clickToZoom: false,\n dblClickToZoom: true,\n pinchToZoom: true,\n zoomToRefPoint: true,\n flickEnabled: true,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n gestureSettingsPen: {\n scrollToZoom: false,\n clickToZoom: true,\n dblClickToZoom: false,\n pinchToZoom: false,\n zoomToRefPoint: true,\n flickEnabled: false,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n gestureSettingsUnknown: {\n scrollToZoom: false,\n clickToZoom: false,\n dblClickToZoom: true,\n pinchToZoom: true,\n zoomToRefPoint: true,\n flickEnabled: true,\n flickMinSpeed: 120,\n flickMomentum: 0.25,\n pinchRotate: false\n },\n zoomPerClick: 2,\n zoomPerScroll: 1.2,\n zoomPerSecond: 1.0,\n blendTime: 0,\n alwaysBlend: false,\n autoHideControls: true,\n immediateRender: false,\n minZoomImageRatio: 0.9, //-> closer to 0 allows zoom out to infinity\n maxZoomPixelRatio: 1.1, //-> higher allows 'over zoom' into pixels\n smoothTileEdgesMinZoom: 1.1, //-> higher than maxZoomPixelRatio disables it\n iOSDevice: isIOSDevice(),\n pixelsPerWheelLine: 40,\n pixelsPerArrowPress: 40,\n autoResize: true,\n preserveImageSizeOnResize: false, // requires autoResize=true\n minScrollDeltaTime: 50,\n\n //DEFAULT CONTROL SETTINGS\n showSequenceControl: true, //SEQUENCE\n sequenceControlAnchor: null, //SEQUENCE\n preserveViewport: false, //SEQUENCE\n preserveOverlays: false, //SEQUENCE\n navPrevNextWrap: false, //SEQUENCE\n showNavigationControl: true, //ZOOM/HOME/FULL/ROTATION\n navigationControlAnchor: null, //ZOOM/HOME/FULL/ROTATION\n showZoomControl: true, //ZOOM\n showHomeControl: true, //HOME\n showFullPageControl: true, //FULL\n showRotationControl: false, //ROTATION\n showFlipControl: false, //FLIP\n controlsFadeDelay: 2000, //ZOOM/HOME/FULL/SEQUENCE\n controlsFadeLength: 1500, //ZOOM/HOME/FULL/SEQUENCE\n mouseNavEnabled: true, //GENERAL MOUSE INTERACTIVITY\n\n //VIEWPORT NAVIGATOR SETTINGS\n showNavigator: false,\n navigatorId: null,\n navigatorPosition: null,\n navigatorSizeRatio: 0.2,\n navigatorMaintainSizeRatio: false,\n navigatorTop: null,\n navigatorLeft: null,\n navigatorHeight: null,\n navigatorWidth: null,\n navigatorAutoResize: true,\n navigatorAutoFade: true,\n navigatorRotate: true,\n\n // INITIAL ROTATION\n degrees: 0,\n\n // INITIAL FLIP STATE\n flipped: false,\n\n // APPEARANCE\n opacity: 1,\n preload: false,\n compositeOperation: null,\n placeholderFillStyle: null,\n\n //REFERENCE STRIP SETTINGS\n showReferenceStrip: false,\n referenceStripScroll: 'horizontal',\n referenceStripElement: null,\n referenceStripHeight: null,\n referenceStripWidth: null,\n referenceStripPosition: 'BOTTOM_LEFT',\n referenceStripSizeRatio: 0.2,\n\n //COLLECTION VISUALIZATION SETTINGS\n collectionRows: 3, //or columns depending on layout\n collectionColumns: 0, //columns in horizontal layout, rows in vertical layout\n collectionLayout: 'horizontal', //vertical\n collectionMode: false,\n collectionTileSize: 800,\n collectionTileMargin: 80,\n\n //PERFORMANCE SETTINGS\n imageLoaderLimit: 0,\n maxImageCacheCount: 200,\n timeout: 30000,\n useCanvas: true, // Use canvas element for drawing if available\n\n //INTERFACE RESOURCE SETTINGS\n prefixUrl: \"/images/\",\n navImages: {\n zoomIn: {\n REST: 'zoomin_rest.png',\n GROUP: 'zoomin_grouphover.png',\n HOVER: 'zoomin_hover.png',\n DOWN: 'zoomin_pressed.png'\n },\n zoomOut: {\n REST: 'zoomout_rest.png',\n GROUP: 'zoomout_grouphover.png',\n HOVER: 'zoomout_hover.png',\n DOWN: 'zoomout_pressed.png'\n },\n home: {\n REST: 'home_rest.png',\n GROUP: 'home_grouphover.png',\n HOVER: 'home_hover.png',\n DOWN: 'home_pressed.png'\n },\n fullpage: {\n REST: 'fullpage_rest.png',\n GROUP: 'fullpage_grouphover.png',\n HOVER: 'fullpage_hover.png',\n DOWN: 'fullpage_pressed.png'\n },\n rotateleft: {\n REST: 'rotateleft_rest.png',\n GROUP: 'rotateleft_grouphover.png',\n HOVER: 'rotateleft_hover.png',\n DOWN: 'rotateleft_pressed.png'\n },\n rotateright: {\n REST: 'rotateright_rest.png',\n GROUP: 'rotateright_grouphover.png',\n HOVER: 'rotateright_hover.png',\n DOWN: 'rotateright_pressed.png'\n },\n flip: { // Flip icon designed by Yaroslav Samoylov from the Noun Project and modified by Nelson Campos ncampos@criteriamarathon.com, https://thenounproject.com/term/flip/136289/\n REST: 'flip_rest.png',\n GROUP: 'flip_grouphover.png',\n HOVER: 'flip_hover.png',\n DOWN: 'flip_pressed.png'\n },\n previous: {\n REST: 'previous_rest.png',\n GROUP: 'previous_grouphover.png',\n HOVER: 'previous_hover.png',\n DOWN: 'previous_pressed.png'\n },\n next: {\n REST: 'next_rest.png',\n GROUP: 'next_grouphover.png',\n HOVER: 'next_hover.png',\n DOWN: 'next_pressed.png'\n }\n },\n\n //DEVELOPER SETTINGS\n debugMode: false,\n debugGridColor: ['#437AB2', '#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E', '#E6AB02', '#A6761D', '#666666']\n },\n\n\n /**\n * TODO: get rid of this. I can't see how it's required at all. Looks\n * like an early legacy code artifact.\n * @static\n * @ignore\n */\n SIGNAL: \"----seadragon----\",\n\n\n /**\n * Returns a function which invokes the method as if it were a method belonging to the object.\n * @function\n * @param {Object} object\n * @param {Function} method\n * @returns {Function}\n */\n delegate: function( object, method ) {\n return function(){\n var args = arguments;\n if ( args === undefined ){\n args = [];\n }\n return method.apply( object, args );\n };\n },\n\n\n /**\n * An enumeration of Browser vendors.\n * @static\n * @type {Object}\n * @property {Number} UNKNOWN\n * @property {Number} IE\n * @property {Number} FIREFOX\n * @property {Number} SAFARI\n * @property {Number} CHROME\n * @property {Number} OPERA\n */\n BROWSERS: {\n UNKNOWN: 0,\n IE: 1,\n FIREFOX: 2,\n SAFARI: 3,\n CHROME: 4,\n OPERA: 5\n },\n\n\n /**\n * Returns a DOM Element for the given id or element.\n * @function\n * @param {String|Element} element Accepts an id or element.\n * @returns {Element} The element with the given id, null, or the element itself.\n */\n getElement: function( element ) {\n if ( typeof ( element ) == \"string\" ) {\n element = document.getElementById( element );\n }\n return element;\n },\n\n\n /**\n * Determines the position of the upper-left corner of the element.\n * @function\n * @param {Element|String} element - the elemenet we want the position for.\n * @returns {OpenSeadragon.Point} - the position of the upper left corner of the element.\n */\n getElementPosition: function( element ) {\n var result = new $.Point(),\n isFixed,\n offsetParent;\n\n element = $.getElement( element );\n isFixed = $.getElementStyle( element ).position == \"fixed\";\n offsetParent = getOffsetParent( element, isFixed );\n\n while ( offsetParent ) {\n\n result.x += element.offsetLeft;\n result.y += element.offsetTop;\n\n if ( isFixed ) {\n result = result.plus( $.getPageScroll() );\n }\n\n element = offsetParent;\n isFixed = $.getElementStyle( element ).position == \"fixed\";\n offsetParent = getOffsetParent( element, isFixed );\n }\n\n return result;\n },\n\n\n /**\n * Determines the position of the upper-left corner of the element adjusted for current page and/or element scroll.\n * @function\n * @param {Element|String} element - the element we want the position for.\n * @returns {OpenSeadragon.Point} - the position of the upper left corner of the element adjusted for current page and/or element scroll.\n */\n getElementOffset: function( element ) {\n element = $.getElement( element );\n\n var doc = element && element.ownerDocument,\n docElement,\n win,\n boundingRect = { top: 0, left: 0 };\n\n if ( !doc ) {\n return new $.Point();\n }\n\n docElement = doc.documentElement;\n\n if ( typeof element.getBoundingClientRect !== typeof undefined ) {\n boundingRect = element.getBoundingClientRect();\n }\n\n win = ( doc == doc.window ) ?\n doc :\n ( doc.nodeType === 9 ) ?\n doc.defaultView || doc.parentWindow :\n false;\n\n return new $.Point(\n boundingRect.left + ( win.pageXOffset || docElement.scrollLeft ) - ( docElement.clientLeft || 0 ),\n boundingRect.top + ( win.pageYOffset || docElement.scrollTop ) - ( docElement.clientTop || 0 )\n );\n },\n\n\n /**\n * Determines the height and width of the given element.\n * @function\n * @param {Element|String} element\n * @returns {OpenSeadragon.Point}\n */\n getElementSize: function( element ) {\n element = $.getElement( element );\n\n return new $.Point(\n element.clientWidth,\n element.clientHeight\n );\n },\n\n\n /**\n * Returns the CSSStyle object for the given element.\n * @function\n * @param {Element|String} element\n * @returns {CSSStyle}\n */\n getElementStyle:\n document.documentElement.currentStyle ?\n function( element ) {\n element = $.getElement( element );\n return element.currentStyle;\n } :\n function( element ) {\n element = $.getElement( element );\n return window.getComputedStyle( element, \"\" );\n },\n\n /**\n * Returns the property with the correct vendor prefix appended.\n * @param {String} property the property name\n * @returns {String} the property with the correct prefix or null if not\n * supported.\n */\n getCssPropertyWithVendorPrefix: function(property) {\n var memo = {};\n\n $.getCssPropertyWithVendorPrefix = function(property) {\n if (memo[property] !== undefined) {\n return memo[property];\n }\n var style = document.createElement('div').style;\n var result = null;\n if (style[property] !== undefined) {\n result = property;\n } else {\n var prefixes = ['Webkit', 'Moz', 'MS', 'O',\n 'webkit', 'moz', 'ms', 'o'];\n var suffix = $.capitalizeFirstLetter(property);\n for (var i = 0; i < prefixes.length; i++) {\n var prop = prefixes[i] + suffix;\n if (style[prop] !== undefined) {\n result = prop;\n break;\n }\n }\n }\n memo[property] = result;\n return result;\n };\n return $.getCssPropertyWithVendorPrefix(property);\n },\n\n /**\n * Capitalizes the first letter of a string\n * @param {String} string\n * @returns {String} The string with the first letter capitalized\n */\n capitalizeFirstLetter: function(string) {\n return string.charAt(0).toUpperCase() + string.slice(1);\n },\n\n /**\n * Compute the modulo of a number but makes sure to always return\n * a positive value.\n * @param {Number} number the number to computes the modulo of\n * @param {Number} modulo the modulo\n * @returns {Number} the result of the modulo of number\n */\n positiveModulo: function(number, modulo) {\n var result = number % modulo;\n if (result < 0) {\n result += modulo;\n }\n return result;\n },\n\n /**\n * Determines if a point is within the bounding rectangle of the given element (hit-test).\n * @function\n * @param {Element|String} element\n * @param {OpenSeadragon.Point} point\n * @returns {Boolean}\n */\n pointInElement: function( element, point ) {\n element = $.getElement( element );\n var offset = $.getElementOffset( element ),\n size = $.getElementSize( element );\n return point.x >= offset.x && point.x < offset.x + size.x && point.y < offset.y + size.y && point.y >= offset.y;\n },\n\n\n /**\n * Gets the latest event, really only useful internally since its\n * specific to IE behavior.\n * @function\n * @param {Event} [event]\n * @returns {Event}\n * @deprecated For internal use only\n * @private\n */\n getEvent: function( event ) {\n if( event ){\n $.getEvent = function( event ) {\n return event;\n };\n } else {\n $.getEvent = function() {\n return window.event;\n };\n }\n return $.getEvent( event );\n },\n\n\n /**\n * Gets the position of the mouse on the screen for a given event.\n * @function\n * @param {Event} [event]\n * @returns {OpenSeadragon.Point}\n */\n getMousePosition: function( event ) {\n\n if ( typeof ( event.pageX ) == \"number\" ) {\n $.getMousePosition = function( event ){\n var result = new $.Point();\n\n event = $.getEvent( event );\n result.x = event.pageX;\n result.y = event.pageY;\n\n return result;\n };\n } else if ( typeof ( event.clientX ) == \"number\" ) {\n $.getMousePosition = function( event ){\n var result = new $.Point();\n\n event = $.getEvent( event );\n result.x =\n event.clientX +\n document.body.scrollLeft +\n document.documentElement.scrollLeft;\n result.y =\n event.clientY +\n document.body.scrollTop +\n document.documentElement.scrollTop;\n\n return result;\n };\n } else {\n throw new Error(\n \"Unknown event mouse position, no known technique.\"\n );\n }\n\n return $.getMousePosition( event );\n },\n\n\n /**\n * Determines the page's current scroll position.\n * @function\n * @returns {OpenSeadragon.Point}\n */\n getPageScroll: function() {\n var docElement = document.documentElement || {},\n body = document.body || {};\n\n if ( typeof ( window.pageXOffset ) == \"number\" ) {\n $.getPageScroll = function(){\n return new $.Point(\n window.pageXOffset,\n window.pageYOffset\n );\n };\n } else if ( body.scrollLeft || body.scrollTop ) {\n $.getPageScroll = function(){\n return new $.Point(\n document.body.scrollLeft,\n document.body.scrollTop\n );\n };\n } else if ( docElement.scrollLeft || docElement.scrollTop ) {\n $.getPageScroll = function(){\n return new $.Point(\n document.documentElement.scrollLeft,\n document.documentElement.scrollTop\n );\n };\n } else {\n // We can't reassign the function yet, as there was no scroll.\n return new $.Point(0, 0);\n }\n\n return $.getPageScroll();\n },\n\n /**\n * Set the page scroll position.\n * @function\n * @returns {OpenSeadragon.Point}\n */\n setPageScroll: function( scroll ) {\n if ( typeof ( window.scrollTo ) !== \"undefined\" ) {\n $.setPageScroll = function( scroll ) {\n window.scrollTo( scroll.x, scroll.y );\n };\n } else {\n var originalScroll = $.getPageScroll();\n if ( originalScroll.x === scroll.x &&\n originalScroll.y === scroll.y ) {\n // We are already correctly positioned and there\n // is no way to detect the correct method.\n return;\n }\n\n document.body.scrollLeft = scroll.x;\n document.body.scrollTop = scroll.y;\n var currentScroll = $.getPageScroll();\n if ( currentScroll.x !== originalScroll.x &&\n currentScroll.y !== originalScroll.y ) {\n $.setPageScroll = function( scroll ) {\n document.body.scrollLeft = scroll.x;\n document.body.scrollTop = scroll.y;\n };\n return;\n }\n\n document.documentElement.scrollLeft = scroll.x;\n document.documentElement.scrollTop = scroll.y;\n currentScroll = $.getPageScroll();\n if ( currentScroll.x !== originalScroll.x &&\n currentScroll.y !== originalScroll.y ) {\n $.setPageScroll = function( scroll ) {\n document.documentElement.scrollLeft = scroll.x;\n document.documentElement.scrollTop = scroll.y;\n };\n return;\n }\n\n // We can't find anything working, so we do nothing.\n $.setPageScroll = function( scroll ) {\n };\n }\n\n return $.setPageScroll( scroll );\n },\n\n /**\n * Determines the size of the browsers window.\n * @function\n * @returns {OpenSeadragon.Point}\n */\n getWindowSize: function() {\n var docElement = document.documentElement || {},\n body = document.body || {};\n\n if ( typeof ( window.innerWidth ) == 'number' ) {\n $.getWindowSize = function(){\n return new $.Point(\n window.innerWidth,\n window.innerHeight\n );\n };\n } else if ( docElement.clientWidth || docElement.clientHeight ) {\n $.getWindowSize = function(){\n return new $.Point(\n document.documentElement.clientWidth,\n document.documentElement.clientHeight\n );\n };\n } else if ( body.clientWidth || body.clientHeight ) {\n $.getWindowSize = function(){\n return new $.Point(\n document.body.clientWidth,\n document.body.clientHeight\n );\n };\n } else {\n throw new Error(\"Unknown window size, no known technique.\");\n }\n\n return $.getWindowSize();\n },\n\n\n /**\n * Wraps the given element in a nest of divs so that the element can\n * be easily centered using CSS tables\n * @function\n * @param {Element|String} element\n * @returns {Element} outermost wrapper element\n */\n makeCenteredNode: function( element ) {\n // Convert a possible ID to an actual HTMLElement\n element = $.getElement( element );\n\n /*\n CSS tables require you to have a display:table/row/cell hierarchy so we need to create\n three nested wrapper divs:\n */\n\n var wrappers = [\n $.makeNeutralElement( 'div' ),\n $.makeNeutralElement( 'div' ),\n $.makeNeutralElement( 'div' )\n ];\n\n // It feels like we should be able to pass style dicts to makeNeutralElement:\n $.extend(wrappers[0].style, {\n display: \"table\",\n height: \"100%\",\n width: \"100%\"\n });\n\n $.extend(wrappers[1].style, {\n display: \"table-row\"\n });\n\n $.extend(wrappers[2].style, {\n display: \"table-cell\",\n verticalAlign: \"middle\",\n textAlign: \"center\"\n });\n\n wrappers[0].appendChild(wrappers[1]);\n wrappers[1].appendChild(wrappers[2]);\n wrappers[2].appendChild(element);\n\n return wrappers[0];\n },\n\n\n /**\n * Creates an easily positionable element of the given type that therefor\n * serves as an excellent container element.\n * @function\n * @param {String} tagName\n * @returns {Element}\n */\n makeNeutralElement: function( tagName ) {\n var element = document.createElement( tagName ),\n style = element.style;\n\n style.background = \"transparent none\";\n style.border = \"none\";\n style.margin = \"0px\";\n style.padding = \"0px\";\n style.position = \"static\";\n\n return element;\n },\n\n\n /**\n * Returns the current milliseconds, using Date.now() if available\n * @function\n */\n now: function( ) {\n if (Date.now) {\n $.now = Date.now;\n } else {\n $.now = function() {\n return new Date().getTime();\n };\n }\n\n return $.now();\n },\n\n\n /**\n * Ensures an image is loaded correctly to support alpha transparency.\n * Generally only IE has issues doing this correctly for formats like\n * png.\n * @function\n * @param {String} src\n * @returns {Element}\n */\n makeTransparentImage: function( src ) {\n\n $.makeTransparentImage = function( src ){\n var img = $.makeNeutralElement( \"img\" );\n\n img.src = src;\n\n return img;\n };\n\n if ( $.Browser.vendor == $.BROWSERS.IE && $.Browser.version < 7 ) {\n\n $.makeTransparentImage = function( src ){\n var img = $.makeNeutralElement( \"img\" ),\n element = null;\n\n element = $.makeNeutralElement(\"span\");\n element.style.display = \"inline-block\";\n\n img.onload = function() {\n element.style.width = element.style.width || img.width + \"px\";\n element.style.height = element.style.height || img.height + \"px\";\n\n img.onload = null;\n img = null; // to prevent memory leaks in IE\n };\n\n img.src = src;\n element.style.filter =\n \"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='\" +\n src +\n \"', sizingMethod='scale')\";\n\n return element;\n };\n\n }\n\n return $.makeTransparentImage( src );\n },\n\n\n /**\n * Sets the opacity of the specified element.\n * @function\n * @param {Element|String} element\n * @param {Number} opacity\n * @param {Boolean} [usesAlpha]\n */\n setElementOpacity: function( element, opacity, usesAlpha ) {\n\n var ieOpacity,\n ieFilter;\n\n element = $.getElement( element );\n\n if ( usesAlpha && !$.Browser.alpha ) {\n opacity = Math.round( opacity );\n }\n\n if ( $.Browser.opacity ) {\n element.style.opacity = opacity < 1 ? opacity : \"\";\n } else {\n if ( opacity < 1 ) {\n ieOpacity = Math.round( 100 * opacity );\n ieFilter = \"alpha(opacity=\" + ieOpacity + \")\";\n element.style.filter = ieFilter;\n } else {\n element.style.filter = \"\";\n }\n }\n },\n\n\n /**\n * Sets the specified element's touch-action style attribute to 'none'.\n * @function\n * @param {Element|String} element\n */\n setElementTouchActionNone: function( element ) {\n element = $.getElement( element );\n if ( typeof element.style.touchAction !== 'undefined' ) {\n element.style.touchAction = 'none';\n } else if ( typeof element.style.msTouchAction !== 'undefined' ) {\n element.style.msTouchAction = 'none';\n }\n },\n\n\n /**\n * Add the specified CSS class to the element if not present.\n * @function\n * @param {Element|String} element\n * @param {String} className\n */\n addClass: function( element, className ) {\n element = $.getElement( element );\n\n if (!element.className) {\n element.className = className;\n } else if ( ( ' ' + element.className + ' ' ).\n indexOf( ' ' + className + ' ' ) === -1 ) {\n element.className += ' ' + className;\n }\n },\n\n /**\n * Find the first index at which an element is found in an array or -1\n * if not present.\n *\n * Code taken and adapted from\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf#Compatibility\n *\n * @function\n * @param {Array} array The array from which to find the element\n * @param {Object} searchElement The element to find\n * @param {Number} [fromIndex=0] Index to start research.\n * @returns {Number} The index of the element in the array.\n */\n indexOf: function( array, searchElement, fromIndex ) {\n if ( Array.prototype.indexOf ) {\n this.indexOf = function( array, searchElement, fromIndex ) {\n return array.indexOf( searchElement, fromIndex );\n };\n } else {\n this.indexOf = function( array, searchElement, fromIndex ) {\n var i,\n pivot = ( fromIndex ) ? fromIndex : 0,\n length;\n if ( !array ) {\n throw new TypeError( );\n }\n\n length = array.length;\n if ( length === 0 || pivot >= length ) {\n return -1;\n }\n\n if ( pivot < 0 ) {\n pivot = length - Math.abs( pivot );\n }\n\n for ( i = pivot; i < length; i++ ) {\n if ( array[i] === searchElement ) {\n return i;\n }\n }\n return -1;\n };\n }\n return this.indexOf( array, searchElement, fromIndex );\n },\n\n /**\n * Remove the specified CSS class from the element.\n * @function\n * @param {Element|String} element\n * @param {String} className\n */\n removeClass: function( element, className ) {\n var oldClasses,\n newClasses = [],\n i;\n\n element = $.getElement( element );\n oldClasses = element.className.split( /\\s+/ );\n for ( i = 0; i < oldClasses.length; i++ ) {\n if ( oldClasses[ i ] && oldClasses[ i ] !== className ) {\n newClasses.push( oldClasses[ i ] );\n }\n }\n element.className = newClasses.join(' ');\n },\n\n\n /**\n * Adds an event listener for the given element, eventName and handler.\n * @function\n * @param {Element|String} element\n * @param {String} eventName\n * @param {Function} handler\n * @param {Boolean} [useCapture]\n */\n addEvent: (function () {\n if ( window.addEventListener ) {\n return function ( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.addEventListener( eventName, handler, useCapture );\n };\n } else if ( window.attachEvent ) {\n return function ( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.attachEvent( 'on' + eventName, handler );\n };\n } else {\n throw new Error( \"No known event model.\" );\n }\n }()),\n\n\n /**\n * Remove a given event listener for the given element, event type and\n * handler.\n * @function\n * @param {Element|String} element\n * @param {String} eventName\n * @param {Function} handler\n * @param {Boolean} [useCapture]\n */\n removeEvent: (function () {\n if ( window.removeEventListener ) {\n return function ( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.removeEventListener( eventName, handler, useCapture );\n };\n } else if ( window.detachEvent ) {\n return function( element, eventName, handler, useCapture ) {\n element = $.getElement( element );\n element.detachEvent( 'on' + eventName, handler );\n };\n } else {\n throw new Error( \"No known event model.\" );\n }\n }()),\n\n\n /**\n * Cancels the default browser behavior had the event propagated all\n * the way up the DOM to the window object.\n * @function\n * @param {Event} [event]\n */\n cancelEvent: function( event ) {\n event = $.getEvent( event );\n\n if ( event.preventDefault ) {\n $.cancelEvent = function( event ){\n // W3C for preventing default\n event.preventDefault();\n };\n } else {\n $.cancelEvent = function( event ){\n event = $.getEvent( event );\n // legacy for preventing default\n event.cancel = true;\n // IE for preventing default\n event.returnValue = false;\n };\n }\n $.cancelEvent( event );\n },\n\n\n /**\n * Stops the propagation of the event up the DOM.\n * @function\n * @param {Event} [event]\n */\n stopEvent: function( event ) {\n event = $.getEvent( event );\n\n if ( event.stopPropagation ) {\n // W3C for stopping propagation\n $.stopEvent = function( event ){\n event.stopPropagation();\n };\n } else {\n // IE for stopping propagation\n $.stopEvent = function( event ){\n event = $.getEvent( event );\n event.cancelBubble = true;\n };\n\n }\n\n $.stopEvent( event );\n },\n\n\n /**\n * Similar to OpenSeadragon.delegate, but it does not immediately call\n * the method on the object, returning a function which can be called\n * repeatedly to delegate the method. It also allows additonal arguments\n * to be passed during construction which will be added during each\n * invocation, and each invocation can add additional arguments as well.\n *\n * @function\n * @param {Object} object\n * @param {Function} method\n * @param [args] any additional arguments are passed as arguments to the\n * created callback\n * @returns {Function}\n */\n createCallback: function( object, method ) {\n //TODO: This pattern is painful to use and debug. It's much cleaner\n // to use pinning plus anonymous functions. Get rid of this\n // pattern!\n var initialArgs = [],\n i;\n for ( i = 2; i < arguments.length; i++ ) {\n initialArgs.push( arguments[ i ] );\n }\n\n return function() {\n var args = initialArgs.concat( [] ),\n i;\n for ( i = 0; i < arguments.length; i++ ) {\n args.push( arguments[ i ] );\n }\n\n return method.apply( object, args );\n };\n },\n\n\n /**\n * Retreives the value of a url parameter from the window.location string.\n * @function\n * @param {String} key\n * @returns {String} The value of the url parameter or null if no param matches.\n */\n getUrlParameter: function( key ) {\n // eslint-disable-next-line no-use-before-define\n var value = URLPARAMS[ key ];\n return value ? value : null;\n },\n\n /**\n * Retrieves the protocol used by the url. The url can either be absolute\n * or relative.\n * @function\n * @private\n * @param {String} url The url to retrieve the protocol from.\n * @return {String} The protocol (http:, https:, file:, ftp: ...)\n */\n getUrlProtocol: function( url ) {\n var match = url.match(/^([a-z]+:)\\/\\//i);\n if ( match === null ) {\n // Relative URL, retrive the protocol from window.location\n return window.location.protocol;\n }\n return match[1].toLowerCase();\n },\n\n /**\n * Create an XHR object\n * @private\n * @param {type} [local] If set to true, the XHR will be file: protocol\n * compatible if possible (but may raise a warning in the browser).\n * @returns {XMLHttpRequest}\n */\n createAjaxRequest: function( local ) {\n // IE11 does not support window.ActiveXObject so we just try to\n // create one to see if it is supported.\n // See: http://msdn.microsoft.com/en-us/library/ie/dn423948%28v=vs.85%29.aspx\n var supportActiveX;\n try {\n /* global ActiveXObject:true */\n supportActiveX = !!new ActiveXObject( \"Microsoft.XMLHTTP\" );\n } catch( e ) {\n supportActiveX = false;\n }\n\n if ( supportActiveX ) {\n if ( window.XMLHttpRequest ) {\n $.createAjaxRequest = function( local ) {\n if ( local ) {\n return new ActiveXObject( \"Microsoft.XMLHTTP\" );\n }\n return new XMLHttpRequest();\n };\n } else {\n $.createAjaxRequest = function() {\n return new ActiveXObject( \"Microsoft.XMLHTTP\" );\n };\n }\n } else if ( window.XMLHttpRequest ) {\n $.createAjaxRequest = function() {\n return new XMLHttpRequest();\n };\n } else {\n throw new Error( \"Browser doesn't support XMLHttpRequest.\" );\n }\n return $.createAjaxRequest( local );\n },\n\n /**\n * Makes an AJAX request.\n * @param {Object} options\n * @param {String} options.url - the url to request\n * @param {Function} options.success - a function to call on a successful response\n * @param {Function} options.error - a function to call on when an error occurs\n * @param {Object} options.headers - headers to add to the AJAX request\n * @param {String} options.responseType - the response type of the the AJAX request\n * @param {Boolean} [options.withCredentials=false] - whether to set the XHR's withCredentials\n * @throws {Error}\n * @returns {XMLHttpRequest}\n */\n makeAjaxRequest: function( url, onSuccess, onError ) {\n var withCredentials;\n var headers;\n var responseType;\n\n // Note that our preferred API is that you pass in a single object; the named\n // arguments are for legacy support.\n if( $.isPlainObject( url ) ){\n onSuccess = url.success;\n onError = url.error;\n withCredentials = url.withCredentials;\n headers = url.headers;\n responseType = url.responseType || null;\n url = url.url;\n }\n\n var protocol = $.getUrlProtocol( url );\n var request = $.createAjaxRequest( protocol === \"file:\" );\n\n if ( !$.isFunction( onSuccess ) ) {\n throw new Error( \"makeAjaxRequest requires a success callback\" );\n }\n\n request.onreadystatechange = function() {\n // 4 = DONE (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#Properties)\n if ( request.readyState == 4 ) {\n request.onreadystatechange = function(){};\n\n // With protocols other than http/https, a successful request status is in\n // the 200's on Firefox and 0 on other browsers\n if ( (request.status >= 200 && request.status < 300) ||\n ( request.status === 0 &&\n protocol !== \"http:\" &&\n protocol !== \"https:\" )) {\n onSuccess( request );\n } else {\n $.console.log( \"AJAX request returned %d: %s\", request.status, url );\n\n if ( $.isFunction( onError ) ) {\n onError( request );\n }\n }\n }\n };\n\n try {\n request.open( \"GET\", url, true );\n\n if (responseType) {\n request.responseType = responseType;\n }\n\n if (headers) {\n for (var headerName in headers) {\n if (headers.hasOwnProperty(headerName) && headers[headerName]) {\n request.setRequestHeader(headerName, headers[headerName]);\n }\n }\n }\n\n if (withCredentials) {\n request.withCredentials = true;\n }\n\n request.send(null);\n } catch (e) {\n var msg = e.message;\n\n /*\n IE < 10 does not support CORS and an XHR request to a different origin will fail as soon\n as send() is called. This is particularly easy to miss during development and appear in\n production if you use a CDN or domain sharding and the security policy is likely to break\n exception handlers since any attempt to access a property of the request object will\n raise an access denied TypeError inside the catch block.\n\n To be friendlier, we'll check for this specific error and add a documentation pointer\n to point developers in the right direction. We test the exception number because IE's\n error messages are localized.\n */\n var oldIE = $.Browser.vendor == $.BROWSERS.IE && $.Browser.version < 10;\n if ( oldIE && typeof ( e.number ) != \"undefined\" && e.number == -2147024891 ) {\n msg += \"\\nSee http://msdn.microsoft.com/en-us/library/ms537505(v=vs.85).aspx#xdomain\";\n }\n\n $.console.log( \"%s while making AJAX request: %s\", e.name, msg );\n\n request.onreadystatechange = function(){};\n\n if (window.XDomainRequest) { // IE9 or IE8 might as well try to use XDomainRequest\n var xdr = new XDomainRequest();\n if (xdr) {\n xdr.onload = function (e) {\n if ( $.isFunction( onSuccess ) ) {\n onSuccess({ // Faking an xhr object\n responseText: xdr.responseText,\n status: 200, // XDomainRequest doesn't support status codes, so we just fake one! :/\n statusText: 'OK'\n });\n }\n };\n xdr.onerror = function (e) {\n if ($.isFunction(onError)) {\n onError({ // Faking an xhr object\n responseText: xdr.responseText,\n status: 444, // 444 No Response\n statusText: 'An error happened. Due to an XDomainRequest deficiency we can not extract any information about this error. Upgrade your browser.'\n });\n }\n };\n try {\n xdr.open('GET', url);\n xdr.send();\n } catch (e2) {\n if ( $.isFunction( onError ) ) {\n onError( request, e );\n }\n }\n }\n } else {\n if ( $.isFunction( onError ) ) {\n onError( request, e );\n }\n }\n }\n\n return request;\n },\n\n /**\n * Taken from jQuery 1.6.1\n * @function\n * @param {Object} options\n * @param {String} options.url\n * @param {Function} options.callback\n * @param {String} [options.param='callback'] The name of the url parameter\n * to request the jsonp provider with.\n * @param {String} [options.callbackName=] The name of the callback to\n * request the jsonp provider with.\n */\n jsonp: function( options ){\n var script,\n url = options.url,\n head = document.head ||\n document.getElementsByTagName( \"head\" )[ 0 ] ||\n document.documentElement,\n jsonpCallback = options.callbackName || 'openseadragon' + $.now(),\n previous = window[ jsonpCallback ],\n replace = \"$1\" + jsonpCallback + \"$2\",\n callbackParam = options.param || 'callback',\n callback = options.callback;\n\n url = url.replace( /(\\=)\\?(&|$)|\\?\\?/i, replace );\n // Add callback manually\n url += (/\\?/.test( url ) ? \"&\" : \"?\") + callbackParam + \"=\" + jsonpCallback;\n\n // Install callback\n window[ jsonpCallback ] = function( response ) {\n if ( !previous ){\n try{\n delete window[ jsonpCallback ];\n }catch(e){\n //swallow\n }\n } else {\n window[ jsonpCallback ] = previous;\n }\n if( callback && $.isFunction( callback ) ){\n callback( response );\n }\n };\n\n script = document.createElement( \"script\" );\n\n //TODO: having an issue with async info requests\n if( undefined !== options.async || false !== options.async ){\n script.async = \"async\";\n }\n\n if ( options.scriptCharset ) {\n script.charset = options.scriptCharset;\n }\n\n script.src = url;\n\n // Attach handlers for all browsers\n script.onload = script.onreadystatechange = function( _, isAbort ) {\n\n if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {\n\n // Handle memory leak in IE\n script.onload = script.onreadystatechange = null;\n\n // Remove the script\n if ( head && script.parentNode ) {\n head.removeChild( script );\n }\n\n // Dereference the script\n script = undefined;\n }\n };\n // Use insertBefore instead of appendChild to circumvent an IE6 bug.\n // This arises when a base node is used (#2709 and #4378).\n head.insertBefore( script, head.firstChild );\n\n },\n\n\n /**\n * Fully deprecated. Will throw an error.\n * @function\n * @deprecated use {@link OpenSeadragon.Viewer#open}\n */\n createFromDZI: function() {\n throw \"OpenSeadragon.createFromDZI is deprecated, use Viewer.open.\";\n },\n\n /**\n * Parses an XML string into a DOM Document.\n * @function\n * @param {String} string\n * @returns {Document}\n */\n parseXml: function( string ) {\n if ( window.DOMParser ) {\n\n $.parseXml = function( string ) {\n var xmlDoc = null,\n parser;\n\n parser = new DOMParser();\n xmlDoc = parser.parseFromString( string, \"text/xml\" );\n return xmlDoc;\n };\n\n } else if ( window.ActiveXObject ) {\n\n $.parseXml = function( string ) {\n var xmlDoc = null;\n\n xmlDoc = new ActiveXObject( \"Microsoft.XMLDOM\" );\n xmlDoc.async = false;\n xmlDoc.loadXML( string );\n return xmlDoc;\n };\n\n } else {\n throw new Error( \"Browser doesn't support XML DOM.\" );\n }\n\n return $.parseXml( string );\n },\n\n /**\n * Parses a JSON string into a Javascript object.\n * @function\n * @param {String} string\n * @returns {Object}\n */\n parseJSON: function(string) {\n if (window.JSON && window.JSON.parse) {\n $.parseJSON = window.JSON.parse;\n } else {\n // Should only be used by IE8 in non standards mode\n $.parseJSON = function(string) {\n /*jshint evil:true*/\n //eslint-disable-next-line no-eval\n return eval('(' + string + ')');\n };\n }\n return $.parseJSON(string);\n },\n\n /**\n * Reports whether the image format is supported for tiling in this\n * version.\n * @function\n * @param {String} [extension]\n * @returns {Boolean}\n */\n imageFormatSupported: function( extension ) {\n extension = extension ? extension : \"\";\n // eslint-disable-next-line no-use-before-define\n return !!FILEFORMATS[ extension.toLowerCase() ];\n }\n\n });\n\n\n /**\n * The current browser vendor, version, and related information regarding detected features.\n * @member {Object} Browser\n * @memberof OpenSeadragon\n * @static\n * @type {Object}\n * @property {OpenSeadragon.BROWSERS} vendor - One of the {@link OpenSeadragon.BROWSERS} enumeration values.\n * @property {Number} version\n * @property {Boolean} alpha - Does the browser support image alpha transparency.\n */\n $.Browser = {\n vendor: $.BROWSERS.UNKNOWN,\n version: 0,\n alpha: true\n };\n\n\n var FILEFORMATS = {\n \"bmp\": false,\n \"jpeg\": true,\n \"jpg\": true,\n \"png\": true,\n \"tif\": false,\n \"wdp\": false\n },\n URLPARAMS = {};\n\n (function() {\n //A small auto-executing routine to determine the browser vendor,\n //version and supporting feature sets.\n var ver = navigator.appVersion,\n ua = navigator.userAgent,\n regex;\n\n //console.error( 'appName: ' + navigator.appName );\n //console.error( 'appVersion: ' + navigator.appVersion );\n //console.error( 'userAgent: ' + navigator.userAgent );\n\n switch( navigator.appName ){\n case \"Microsoft Internet Explorer\":\n if( !!window.attachEvent &&\n !!window.ActiveXObject ) {\n\n $.Browser.vendor = $.BROWSERS.IE;\n $.Browser.version = parseFloat(\n ua.substring(\n ua.indexOf( \"MSIE\" ) + 5,\n ua.indexOf( \";\", ua.indexOf( \"MSIE\" ) ) )\n );\n }\n break;\n case \"Netscape\":\n if (window.addEventListener) {\n if ( ua.indexOf( \"Firefox\" ) >= 0 ) {\n $.Browser.vendor = $.BROWSERS.FIREFOX;\n $.Browser.version = parseFloat(\n ua.substring( ua.indexOf( \"Firefox\" ) + 8 )\n );\n } else if ( ua.indexOf( \"Safari\" ) >= 0 ) {\n $.Browser.vendor = ua.indexOf( \"Chrome\" ) >= 0 ?\n $.BROWSERS.CHROME :\n $.BROWSERS.SAFARI;\n $.Browser.version = parseFloat(\n ua.substring(\n ua.substring( 0, ua.indexOf( \"Safari\" ) ).lastIndexOf( \"/\" ) + 1,\n ua.indexOf( \"Safari\" )\n )\n );\n } else {\n regex = new RegExp( \"Trident/.*rv:([0-9]{1,}[.0-9]{0,})\");\n if ( regex.exec( ua ) !== null ) {\n $.Browser.vendor = $.BROWSERS.IE;\n $.Browser.version = parseFloat( RegExp.$1 );\n }\n }\n }\n break;\n case \"Opera\":\n $.Browser.vendor = $.BROWSERS.OPERA;\n $.Browser.version = parseFloat( ver );\n break;\n }\n\n // ignore '?' portion of query string\n var query = window.location.search.substring( 1 ),\n parts = query.split('&'),\n part,\n sep,\n i;\n\n for ( i = 0; i < parts.length; i++ ) {\n part = parts[ i ];\n sep = part.indexOf( '=' );\n\n if ( sep > 0 ) {\n URLPARAMS[ part.substring( 0, sep ) ] =\n decodeURIComponent( part.substring( sep + 1 ) );\n }\n }\n\n //determine if this browser supports image alpha transparency\n $.Browser.alpha = !(\n (\n $.Browser.vendor == $.BROWSERS.IE &&\n $.Browser.version < 9\n ) || (\n $.Browser.vendor == $.BROWSERS.CHROME &&\n $.Browser.version < 2\n )\n );\n\n //determine if this browser supports element.style.opacity\n $.Browser.opacity = !(\n $.Browser.vendor == $.BROWSERS.IE &&\n $.Browser.version < 9\n );\n\n })();\n\n\n //TODO: $.console is often used inside a try/catch block which generally\n // prevents allowings errors to occur with detection until a debugger\n // is attached. Although I've been guilty of the same anti-pattern\n // I eventually was convinced that errors should naturally propogate in\n // all but the most special cases.\n /**\n * A convenient alias for console when available, and a simple null\n * function when console is unavailable.\n * @static\n * @private\n */\n var nullfunction = function( msg ){\n //document.location.hash = msg;\n };\n\n $.console = window.console || {\n log: nullfunction,\n debug: nullfunction,\n info: nullfunction,\n warn: nullfunction,\n error: nullfunction,\n assert: nullfunction\n };\n\n\n // Adding support for HTML5's requestAnimationFrame as suggested by acdha.\n // Implementation taken from matt synder's post here:\n // http://mattsnider.com/cross-browser-and-legacy-supported-requestframeanimation/\n (function( w ) {\n\n // most browsers have an implementation\n var requestAnimationFrame = w.requestAnimationFrame ||\n w.mozRequestAnimationFrame ||\n w.webkitRequestAnimationFrame ||\n w.msRequestAnimationFrame;\n\n var cancelAnimationFrame = w.cancelAnimationFrame ||\n w.mozCancelAnimationFrame ||\n w.webkitCancelAnimationFrame ||\n w.msCancelAnimationFrame;\n\n // polyfill, when necessary\n if ( requestAnimationFrame && cancelAnimationFrame ) {\n // We can't assign these window methods directly to $ because they\n // expect their \"this\" to be \"window\", so we call them in wrappers.\n $.requestAnimationFrame = function(){\n return requestAnimationFrame.apply( w, arguments );\n };\n $.cancelAnimationFrame = function(){\n return cancelAnimationFrame.apply( w, arguments );\n };\n } else {\n var aAnimQueue = [],\n processing = [],\n iRequestId = 0,\n iIntervalId;\n\n // create a mock requestAnimationFrame function\n $.requestAnimationFrame = function( callback ) {\n aAnimQueue.push( [ ++iRequestId, callback ] );\n\n if ( !iIntervalId ) {\n iIntervalId = setInterval( function() {\n if ( aAnimQueue.length ) {\n var time = $.now();\n // Process all of the currently outstanding frame\n // requests, but none that get added during the\n // processing.\n // Swap the arrays so we don't have to create a new\n // array every frame.\n var temp = processing;\n processing = aAnimQueue;\n aAnimQueue = temp;\n while ( processing.length ) {\n processing.shift()[ 1 ]( time );\n }\n } else {\n // don't continue the interval, if unnecessary\n clearInterval( iIntervalId );\n iIntervalId = undefined;\n }\n }, 1000 / 50); // estimating support for 50 frames per second\n }\n\n return iRequestId;\n };\n\n // create a mock cancelAnimationFrame function\n $.cancelAnimationFrame = function( requestId ) {\n // find the request ID and remove it\n var i, j;\n for ( i = 0, j = aAnimQueue.length; i < j; i += 1 ) {\n if ( aAnimQueue[ i ][ 0 ] === requestId ) {\n aAnimQueue.splice( i, 1 );\n return;\n }\n }\n\n // If it's not in the queue, it may be in the set we're currently\n // processing (if cancelAnimationFrame is called from within a\n // requestAnimationFrame callback).\n for ( i = 0, j = processing.length; i < j; i += 1 ) {\n if ( processing[ i ][ 0 ] === requestId ) {\n processing.splice( i, 1 );\n return;\n }\n }\n };\n }\n })( window );\n\n /**\n * @private\n * @inner\n * @function\n * @param {Element} element\n * @param {Boolean} [isFixed]\n * @returns {Element}\n */\n function getOffsetParent( element, isFixed ) {\n if ( isFixed && element != document.body ) {\n return document.body;\n } else {\n return element.offsetParent;\n }\n }\n\n}(OpenSeadragon));\n\n\n// Universal Module Definition, supports CommonJS, AMD and simple script tag\n(function (root, factory) {\n if (true) {\n // expose as amd module\n !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?\n\t\t\t\t(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),\n\t\t\t\t__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));\n } else {}\n}(this, function () {\n return OpenSeadragon;\n}));\n\n/*\n * OpenSeadragon - full-screen support functions\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ) {\n /**\n * Determine native full screen support we can get from the browser.\n * @member fullScreenApi\n * @memberof OpenSeadragon\n * @type {object}\n * @property {Boolean} supportsFullScreen Return true if full screen API is supported.\n * @property {Function} isFullScreen Return true if currently in full screen mode.\n * @property {Function} getFullScreenElement Return the element currently in full screen mode.\n * @property {Function} requestFullScreen Make a request to go in full screen mode.\n * @property {Function} exitFullScreen Make a request to exit full screen mode.\n * @property {Function} cancelFullScreen Deprecated, use exitFullScreen instead.\n * @property {String} fullScreenEventName Event fired when the full screen mode change.\n * @property {String} fullScreenErrorEventName Event fired when a request to go\n * in full screen mode failed.\n */\n var fullScreenApi = {\n supportsFullScreen: false,\n isFullScreen: function() { return false; },\n getFullScreenElement: function() { return null; },\n requestFullScreen: function() {},\n exitFullScreen: function() {},\n cancelFullScreen: function() {},\n fullScreenEventName: '',\n fullScreenErrorEventName: ''\n };\n\n // check for native support\n if ( document.exitFullscreen ) {\n // W3C standard\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.fullscreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.requestFullscreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.exitFullscreen();\n };\n fullScreenApi.fullScreenEventName = \"fullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"fullscreenerror\";\n } else if ( document.msExitFullscreen ) {\n // IE 11\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.msFullscreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.msRequestFullscreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.msExitFullscreen();\n };\n fullScreenApi.fullScreenEventName = \"MSFullscreenChange\";\n fullScreenApi.fullScreenErrorEventName = \"MSFullscreenError\";\n } else if ( document.webkitExitFullscreen ) {\n // Recent webkit\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.webkitFullscreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.webkitRequestFullscreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.webkitExitFullscreen();\n };\n fullScreenApi.fullScreenEventName = \"webkitfullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"webkitfullscreenerror\";\n } else if ( document.webkitCancelFullScreen ) {\n // Old webkit\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.webkitCurrentFullScreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.webkitRequestFullScreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.webkitCancelFullScreen();\n };\n fullScreenApi.fullScreenEventName = \"webkitfullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"webkitfullscreenerror\";\n } else if ( document.mozCancelFullScreen ) {\n // Firefox\n fullScreenApi.supportsFullScreen = true;\n fullScreenApi.getFullScreenElement = function() {\n return document.mozFullScreenElement;\n };\n fullScreenApi.requestFullScreen = function( element ) {\n return element.mozRequestFullScreen();\n };\n fullScreenApi.exitFullScreen = function() {\n document.mozCancelFullScreen();\n };\n fullScreenApi.fullScreenEventName = \"mozfullscreenchange\";\n fullScreenApi.fullScreenErrorEventName = \"mozfullscreenerror\";\n }\n fullScreenApi.isFullScreen = function() {\n return fullScreenApi.getFullScreenElement() !== null;\n };\n fullScreenApi.cancelFullScreen = function() {\n $.console.error(\"cancelFullScreen is deprecated. Use exitFullScreen instead.\");\n fullScreenApi.exitFullScreen();\n };\n\n // export api\n $.extend( $, fullScreenApi );\n\n})( OpenSeadragon );\n\n/*\n * OpenSeadragon - EventSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($){\n\n/**\n * Event handler method signature used by all OpenSeadragon events.\n *\n * @callback EventHandler\n * @memberof OpenSeadragon\n * @param {Object} event - See individual events for event-specific properties.\n */\n\n\n/**\n * @class EventSource\n * @classdesc For use by classes which want to support custom, non-browser events.\n *\n * @memberof OpenSeadragon\n */\n$.EventSource = function() {\n this.events = {};\n};\n\n/** @lends OpenSeadragon.EventSource.prototype */\n$.EventSource.prototype = {\n\n /**\n * Add an event handler to be triggered only once (or a given number of times)\n * for a given event.\n * @function\n * @param {String} eventName - Name of event to register.\n * @param {OpenSeadragon.EventHandler} handler - Function to call when event\n * is triggered.\n * @param {Object} [userData=null] - Arbitrary object to be passed unchanged\n * to the handler.\n * @param {Number} [times=1] - The number of times to handle the event\n * before removing it.\n */\n addOnceHandler: function(eventName, handler, userData, times) {\n var self = this;\n times = times || 1;\n var count = 0;\n var onceHandler = function(event) {\n count++;\n if (count === times) {\n self.removeHandler(eventName, onceHandler);\n }\n handler(event);\n };\n this.addHandler(eventName, onceHandler, userData);\n },\n\n /**\n * Add an event handler for a given event.\n * @function\n * @param {String} eventName - Name of event to register.\n * @param {OpenSeadragon.EventHandler} handler - Function to call when event is triggered.\n * @param {Object} [userData=null] - Arbitrary object to be passed unchanged to the handler.\n */\n addHandler: function ( eventName, handler, userData ) {\n var events = this.events[ eventName ];\n if ( !events ) {\n this.events[ eventName ] = events = [];\n }\n if ( handler && $.isFunction( handler ) ) {\n events[ events.length ] = { handler: handler, userData: userData || null };\n }\n },\n\n /**\n * Remove a specific event handler for a given event.\n * @function\n * @param {String} eventName - Name of event for which the handler is to be removed.\n * @param {OpenSeadragon.EventHandler} handler - Function to be removed.\n */\n removeHandler: function ( eventName, handler ) {\n var events = this.events[ eventName ],\n handlers = [],\n i;\n if ( !events ) {\n return;\n }\n if ( $.isArray( events ) ) {\n for ( i = 0; i < events.length; i++ ) {\n if ( events[i].handler !== handler ) {\n handlers.push( events[ i ] );\n }\n }\n this.events[ eventName ] = handlers;\n }\n },\n\n\n /**\n * Remove all event handlers for a given event type. If no type is given all\n * event handlers for every event type are removed.\n * @function\n * @param {String} eventName - Name of event for which all handlers are to be removed.\n */\n removeAllHandlers: function( eventName ) {\n if ( eventName ){\n this.events[ eventName ] = [];\n } else{\n for ( var eventType in this.events ) {\n this.events[ eventType ] = [];\n }\n }\n },\n\n /**\n * Get a function which iterates the list of all handlers registered for a given event, calling the handler for each.\n * @function\n * @param {String} eventName - Name of event to get handlers for.\n */\n getHandler: function ( eventName ) {\n var events = this.events[ eventName ];\n if ( !events || !events.length ) {\n return null;\n }\n events = events.length === 1 ?\n [ events[ 0 ] ] :\n Array.apply( null, events );\n return function ( source, args ) {\n var i,\n length = events.length;\n for ( i = 0; i < length; i++ ) {\n if ( events[ i ] ) {\n args.eventSource = source;\n args.userData = events[ i ].userData;\n events[ i ].handler( args );\n }\n }\n };\n },\n\n /**\n * Trigger an event, optionally passing additional information.\n * @function\n * @param {String} eventName - Name of event to register.\n * @param {Object} eventArgs - Event-specific data.\n */\n raiseEvent: function( eventName, eventArgs ) {\n //uncomment if you want to get a log of all events\n //$.console.log( eventName );\n var handler = this.getHandler( eventName );\n\n if ( handler ) {\n if ( !eventArgs ) {\n eventArgs = {};\n }\n\n handler( this, eventArgs );\n }\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - MouseTracker\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function ( $ ) {\n\n // All MouseTracker instances\n var MOUSETRACKERS = [];\n\n // dictionary from hash to private properties\n var THIS = {};\n\n\n /**\n * @class MouseTracker\n * @classdesc Provides simplified handling of common pointer device (mouse, touch, pen, etc.) gestures\n * and keyboard events on a specified element.\n * @memberof OpenSeadragon\n * @param {Object} options\n * Allows configurable properties to be entirely specified by passing\n * an options object to the constructor. The constructor also supports\n * the original positional arguments 'element', 'clickTimeThreshold',\n * and 'clickDistThreshold' in that order.\n * @param {Element|String} options.element\n * A reference to an element or an element id for which the pointer/key\n * events will be monitored.\n * @param {Boolean} [options.startDisabled=false]\n * If true, event tracking on the element will not start until\n * {@link OpenSeadragon.MouseTracker.setTracking|setTracking} is called.\n * @param {Number} options.clickTimeThreshold\n * The number of milliseconds within which a pointer down-up event combination\n * will be treated as a click gesture.\n * @param {Number} options.clickDistThreshold\n * The maximum distance allowed between a pointer down event and a pointer up event\n * to be treated as a click gesture.\n * @param {Number} options.dblClickTimeThreshold\n * The number of milliseconds within which two pointer down-up event combinations\n * will be treated as a double-click gesture.\n * @param {Number} options.dblClickDistThreshold\n * The maximum distance allowed between two pointer click events\n * to be treated as a click gesture.\n * @param {Number} [options.stopDelay=50]\n * The number of milliseconds without pointer move before the stop\n * event is fired.\n * @param {OpenSeadragon.EventHandler} [options.enterHandler=null]\n * An optional handler for pointer enter.\n * @param {OpenSeadragon.EventHandler} [options.exitHandler=null]\n * An optional handler for pointer exit.\n * @param {OpenSeadragon.EventHandler} [options.pressHandler=null]\n * An optional handler for pointer press.\n * @param {OpenSeadragon.EventHandler} [options.nonPrimaryPressHandler=null]\n * An optional handler for pointer non-primary button press.\n * @param {OpenSeadragon.EventHandler} [options.releaseHandler=null]\n * An optional handler for pointer release.\n * @param {OpenSeadragon.EventHandler} [options.nonPrimaryReleaseHandler=null]\n * An optional handler for pointer non-primary button release.\n * @param {OpenSeadragon.EventHandler} [options.moveHandler=null]\n * An optional handler for pointer move.\n * @param {OpenSeadragon.EventHandler} [options.scrollHandler=null]\n * An optional handler for mouse wheel scroll.\n * @param {OpenSeadragon.EventHandler} [options.clickHandler=null]\n * An optional handler for pointer click.\n * @param {OpenSeadragon.EventHandler} [options.dblClickHandler=null]\n * An optional handler for pointer double-click.\n * @param {OpenSeadragon.EventHandler} [options.dragHandler=null]\n * An optional handler for the drag gesture.\n * @param {OpenSeadragon.EventHandler} [options.dragEndHandler=null]\n * An optional handler for after a drag gesture.\n * @param {OpenSeadragon.EventHandler} [options.pinchHandler=null]\n * An optional handler for the pinch gesture.\n * @param {OpenSeadragon.EventHandler} [options.keyDownHandler=null]\n * An optional handler for keydown.\n * @param {OpenSeadragon.EventHandler} [options.keyUpHandler=null]\n * An optional handler for keyup.\n * @param {OpenSeadragon.EventHandler} [options.keyHandler=null]\n * An optional handler for keypress.\n * @param {OpenSeadragon.EventHandler} [options.focusHandler=null]\n * An optional handler for focus.\n * @param {OpenSeadragon.EventHandler} [options.blurHandler=null]\n * An optional handler for blur.\n * @param {Object} [options.userData=null]\n * Arbitrary object to be passed unchanged to any attached handler methods.\n */\n $.MouseTracker = function ( options ) {\n\n MOUSETRACKERS.push( this );\n\n var args = arguments;\n\n if ( !$.isPlainObject( options ) ) {\n options = {\n element: args[ 0 ],\n clickTimeThreshold: args[ 1 ],\n clickDistThreshold: args[ 2 ]\n };\n }\n\n this.hash = Math.random(); // An unique hash for this tracker.\n /**\n * The element for which pointer events are being monitored.\n * @member {Element} element\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.element = $.getElement( options.element );\n /**\n * The number of milliseconds within which a pointer down-up event combination\n * will be treated as a click gesture.\n * @member {Number} clickTimeThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.clickTimeThreshold = options.clickTimeThreshold || $.DEFAULT_SETTINGS.clickTimeThreshold;\n /**\n * The maximum distance allowed between a pointer down event and a pointer up event\n * to be treated as a click gesture.\n * @member {Number} clickDistThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.clickDistThreshold = options.clickDistThreshold || $.DEFAULT_SETTINGS.clickDistThreshold;\n /**\n * The number of milliseconds within which two pointer down-up event combinations\n * will be treated as a double-click gesture.\n * @member {Number} dblClickTimeThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.dblClickTimeThreshold = options.dblClickTimeThreshold || $.DEFAULT_SETTINGS.dblClickTimeThreshold;\n /**\n * The maximum distance allowed between two pointer click events\n * to be treated as a click gesture.\n * @member {Number} clickDistThreshold\n * @memberof OpenSeadragon.MouseTracker#\n */\n this.dblClickDistThreshold = options.dblClickDistThreshold || $.DEFAULT_SETTINGS.dblClickDistThreshold;\n /*eslint-disable no-multi-spaces*/\n this.userData = options.userData || null;\n this.stopDelay = options.stopDelay || 50;\n\n this.enterHandler = options.enterHandler || null;\n this.exitHandler = options.exitHandler || null;\n this.pressHandler = options.pressHandler || null;\n this.nonPrimaryPressHandler = options.nonPrimaryPressHandler || null;\n this.releaseHandler = options.releaseHandler || null;\n this.nonPrimaryReleaseHandler = options.nonPrimaryReleaseHandler || null;\n this.moveHandler = options.moveHandler || null;\n this.scrollHandler = options.scrollHandler || null;\n this.clickHandler = options.clickHandler || null;\n this.dblClickHandler = options.dblClickHandler || null;\n this.dragHandler = options.dragHandler || null;\n this.dragEndHandler = options.dragEndHandler || null;\n this.pinchHandler = options.pinchHandler || null;\n this.stopHandler = options.stopHandler || null;\n this.keyDownHandler = options.keyDownHandler || null;\n this.keyUpHandler = options.keyUpHandler || null;\n this.keyHandler = options.keyHandler || null;\n this.focusHandler = options.focusHandler || null;\n this.blurHandler = options.blurHandler || null;\n /*eslint-enable no-multi-spaces*/\n\n //Store private properties in a scope sealed hash map\n var _this = this;\n\n /**\n * @private\n * @property {Boolean} tracking\n * Are we currently tracking pointer events for this element.\n */\n THIS[ this.hash ] = {\n click: function ( event ) { onClick( _this, event ); },\n dblclick: function ( event ) { onDblClick( _this, event ); },\n keydown: function ( event ) { onKeyDown( _this, event ); },\n keyup: function ( event ) { onKeyUp( _this, event ); },\n keypress: function ( event ) { onKeyPress( _this, event ); },\n focus: function ( event ) { onFocus( _this, event ); },\n blur: function ( event ) { onBlur( _this, event ); },\n\n wheel: function ( event ) { onWheel( _this, event ); },\n mousewheel: function ( event ) { onMouseWheel( _this, event ); },\n DOMMouseScroll: function ( event ) { onMouseWheel( _this, event ); },\n MozMousePixelScroll: function ( event ) { onMouseWheel( _this, event ); },\n\n mouseenter: function ( event ) { onMouseEnter( _this, event ); }, // Used on IE8 only\n mouseleave: function ( event ) { onMouseLeave( _this, event ); }, // Used on IE8 only\n mouseover: function ( event ) { onMouseOver( _this, event ); },\n mouseout: function ( event ) { onMouseOut( _this, event ); },\n mousedown: function ( event ) { onMouseDown( _this, event ); },\n mouseup: function ( event ) { onMouseUp( _this, event ); },\n mouseupcaptured: function ( event ) { onMouseUpCaptured( _this, event ); },\n mousemove: function ( event ) { onMouseMove( _this, event ); },\n mousemovecaptured: function ( event ) { onMouseMoveCaptured( _this, event ); },\n\n touchstart: function ( event ) { onTouchStart( _this, event ); },\n touchend: function ( event ) { onTouchEnd( _this, event ); },\n touchendcaptured: function ( event ) { onTouchEndCaptured( _this, event ); },\n touchmove: function ( event ) { onTouchMove( _this, event ); },\n touchmovecaptured: function ( event ) { onTouchMoveCaptured( _this, event ); },\n touchcancel: function ( event ) { onTouchCancel( _this, event ); },\n\n gesturestart: function ( event ) { onGestureStart( _this, event ); },\n gesturechange: function ( event ) { onGestureChange( _this, event ); },\n\n pointerover: function ( event ) { onPointerOver( _this, event ); },\n MSPointerOver: function ( event ) { onPointerOver( _this, event ); },\n pointerout: function ( event ) { onPointerOut( _this, event ); },\n MSPointerOut: function ( event ) { onPointerOut( _this, event ); },\n pointerdown: function ( event ) { onPointerDown( _this, event ); },\n MSPointerDown: function ( event ) { onPointerDown( _this, event ); },\n pointerup: function ( event ) { onPointerUp( _this, event ); },\n MSPointerUp: function ( event ) { onPointerUp( _this, event ); },\n pointermove: function ( event ) { onPointerMove( _this, event ); },\n MSPointerMove: function ( event ) { onPointerMove( _this, event ); },\n pointercancel: function ( event ) { onPointerCancel( _this, event ); },\n MSPointerCancel: function ( event ) { onPointerCancel( _this, event ); },\n pointerupcaptured: function ( event ) { onPointerUpCaptured( _this, event ); },\n pointermovecaptured: function ( event ) { onPointerMoveCaptured( _this, event ); },\n\n tracking: false,\n\n // Active pointers lists. Array of GesturePointList objects, one for each pointer device type.\n // GesturePointList objects are added each time a pointer is tracked by a new pointer device type (see getActivePointersListByType()).\n // Active pointers are any pointer being tracked for this element which are in the hit-test area\n // of the element (for hover-capable devices) and/or have contact or a button press initiated in the element.\n activePointersLists: [],\n\n // Tracking for double-click gesture\n lastClickPos: null,\n dblClickTimeOut: null,\n\n // Tracking for pinch gesture\n pinchGPoints: [],\n lastPinchDist: 0,\n currentPinchDist: 0,\n lastPinchCenter: null,\n currentPinchCenter: null\n };\n\n if ( !options.startDisabled ) {\n this.setTracking( true );\n }\n };\n\n /** @lends OpenSeadragon.MouseTracker.prototype */\n $.MouseTracker.prototype = {\n\n /**\n * Clean up any events or objects created by the tracker.\n * @function\n */\n destroy: function () {\n var i;\n\n stopTracking( this );\n this.element = null;\n\n for ( i = 0; i < MOUSETRACKERS.length; i++ ) {\n if ( MOUSETRACKERS[ i ] === this ) {\n MOUSETRACKERS.splice( i, 1 );\n break;\n }\n }\n\n THIS[ this.hash ] = null;\n delete THIS[ this.hash ];\n },\n\n /**\n * Are we currently tracking events on this element.\n * @deprecated Just use this.tracking\n * @function\n * @returns {Boolean} Are we currently tracking events on this element.\n */\n isTracking: function () {\n return THIS[ this.hash ].tracking;\n },\n\n /**\n * Enable or disable whether or not we are tracking events on this element.\n * @function\n * @param {Boolean} track True to start tracking, false to stop tracking.\n * @returns {OpenSeadragon.MouseTracker} Chainable.\n */\n setTracking: function ( track ) {\n if ( track ) {\n startTracking( this );\n } else {\n stopTracking( this );\n }\n //chain\n return this;\n },\n\n /**\n * Returns the {@link OpenSeadragon.MouseTracker.GesturePointList|GesturePointList} for all but the given pointer device type.\n * @function\n * @param {String} type - The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @returns {Array.}\n */\n getActivePointersListsExceptType: function ( type ) {\n var delegate = THIS[ this.hash ];\n var listArray = [];\n\n for (var i = 0; i < delegate.activePointersLists.length; ++i) {\n if (delegate.activePointersLists[i].type !== type) {\n listArray.push(delegate.activePointersLists[i]);\n }\n }\n\n return listArray;\n },\n\n /**\n * Returns the {@link OpenSeadragon.MouseTracker.GesturePointList|GesturePointList} for the given pointer device type,\n * creating and caching a new {@link OpenSeadragon.MouseTracker.GesturePointList|GesturePointList} if one doesn't already exist for the type.\n * @function\n * @param {String} type - The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @returns {OpenSeadragon.MouseTracker.GesturePointList}\n */\n getActivePointersListByType: function ( type ) {\n var delegate = THIS[ this.hash ],\n i,\n len = delegate.activePointersLists.length,\n list;\n\n for ( i = 0; i < len; i++ ) {\n if ( delegate.activePointersLists[ i ].type === type ) {\n return delegate.activePointersLists[ i ];\n }\n }\n\n list = new $.MouseTracker.GesturePointList( type );\n delegate.activePointersLists.push( list );\n return list;\n },\n\n /**\n * Returns the total number of pointers currently active on the tracked element.\n * @function\n * @returns {Number}\n */\n getActivePointerCount: function () {\n var delegate = THIS[ this.hash ],\n i,\n len = delegate.activePointersLists.length,\n count = 0;\n\n for ( i = 0; i < len; i++ ) {\n count += delegate.activePointersLists[ i ].getLength();\n }\n\n return count;\n },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Number} event.pointers\n * Number of pointers (all types) active in the tracked element.\n * @param {Boolean} event.insideElementPressed\n * True if the left mouse button is currently being pressed and was\n * initiated inside the tracked element, otherwise false.\n * @param {Boolean} event.buttonDownAny\n * Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n enterHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Number} event.pointers\n * Number of pointers (all types) active in the tracked element.\n * @param {Boolean} event.insideElementPressed\n * True if the left mouse button is currently being pressed and was\n * initiated inside the tracked element, otherwise false.\n * @param {Boolean} event.buttonDownAny\n * Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n exitHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n pressHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.button\n * Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n nonPrimaryPressHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.insideElementPressed\n * True if the left mouse button is currently being pressed and was\n * initiated inside the tracked element, otherwise false.\n * @param {Boolean} event.insideElementReleased\n * True if the cursor inside the tracked element when the button was released.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n releaseHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.button\n * Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n nonPrimaryReleaseHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n moveHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.scroll\n * The scroll delta for the event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead. Touch devices no longer generate scroll event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n scrollHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Boolean} event.quick\n * True only if the clickDistThreshold and clickTimeThreshold are both passed. Useful for ignoring drag events.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n clickHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n dblClickHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {OpenSeadragon.Point} event.delta\n * The x,y components of the difference between the current position and the last drag event position. Useful for ignoring or weighting the events.\n * @param {Number} event.speed\n * Current computed speed, in pixels per second.\n * @param {Number} event.direction\n * Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n dragHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.speed\n * Speed at the end of a drag gesture, in pixels per second.\n * @param {Number} event.direction\n * Direction at the end of a drag gesture, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n dragEndHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {Array.} event.gesturePoints\n * Gesture points associated with the gesture. Velocity data can be found here.\n * @param {OpenSeadragon.Point} event.lastCenter\n * The previous center point of the two pinch contact points relative to the tracked element.\n * @param {OpenSeadragon.Point} event.center\n * The center point of the two pinch contact points relative to the tracked element.\n * @param {Number} event.lastDistance\n * The previous distance between the two pinch contact points in CSS pixels.\n * @param {Number} event.distance\n * The distance between the two pinch contact points in CSS pixels.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n pinchHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {String} event.pointerType\n * \"mouse\", \"touch\", \"pen\", etc.\n * @param {OpenSeadragon.Point} event.position\n * The position of the event relative to the tracked element.\n * @param {Number} event.buttons\n * Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @param {Boolean} event.isTouchEvent\n * True if the original event is a touch event, otherwise false. Deprecated. Use pointerType and/or originalEvent instead.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n stopHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Number} event.keyCode\n * The key code that was pressed.\n * @param {Boolean} event.ctrl\n * True if the ctrl key was pressed during this event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.alt\n * True if the alt key was pressed during this event.\n * @param {Boolean} event.meta\n * True if the meta key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n keyDownHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Number} event.keyCode\n * The key code that was pressed.\n * @param {Boolean} event.ctrl\n * True if the ctrl key was pressed during this event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.alt\n * True if the alt key was pressed during this event.\n * @param {Boolean} event.meta\n * True if the meta key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n keyUpHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Number} event.keyCode\n * The key code that was pressed.\n * @param {Boolean} event.ctrl\n * True if the ctrl key was pressed during this event.\n * @param {Boolean} event.shift\n * True if the shift key was pressed during this event.\n * @param {Boolean} event.alt\n * True if the alt key was pressed during this event.\n * @param {Boolean} event.meta\n * True if the meta key was pressed during this event.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n keyHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n focusHandler: function () { },\n\n /**\n * Implement or assign implementation to these handlers during or after\n * calling the constructor.\n * @function\n * @param {Object} event\n * @param {OpenSeadragon.MouseTracker} event.eventSource\n * A reference to the tracker instance.\n * @param {Object} event.originalEvent\n * The original event object.\n * @param {Boolean} event.preventDefaultAction\n * Set to true to prevent the tracker subscriber from performing its default action (subscriber implementation dependent). Default: false.\n * @param {Object} event.userData\n * Arbitrary user-defined object.\n */\n blurHandler: function () { }\n };\n\n /**\n * Resets all active mousetrakers. (Added to patch issue #697 \"Mouse up outside map will cause \"canvas-drag\" event to stick\")\n *\n * @private\n * @member resetAllMouseTrackers\n * @memberof OpenSeadragon.MouseTracker\n */\n $.MouseTracker.resetAllMouseTrackers = function(){\n for(var i = 0; i < MOUSETRACKERS.length; i++){\n if (MOUSETRACKERS[i].isTracking()){\n MOUSETRACKERS[i].setTracking(false);\n MOUSETRACKERS[i].setTracking(true);\n }\n }\n };\n\n /**\n * Provides continuous computation of velocity (speed and direction) of active pointers.\n * This is a singleton, used by all MouseTracker instances, as it is unlikely there will ever be more than\n * two active gesture pointers at a time.\n *\n * @private\n * @member gesturePointVelocityTracker\n * @memberof OpenSeadragon.MouseTracker\n */\n $.MouseTracker.gesturePointVelocityTracker = (function () {\n var trackerPoints = [],\n intervalId = 0,\n lastTime = 0;\n\n // Generates a unique identifier for a tracked gesture point\n var _generateGuid = function ( tracker, gPoint ) {\n return tracker.hash.toString() + gPoint.type + gPoint.id.toString();\n };\n\n // Interval timer callback. Computes velocity for all tracked gesture points.\n var _doTracking = function () {\n var i,\n len = trackerPoints.length,\n trackPoint,\n gPoint,\n now = $.now(),\n elapsedTime,\n distance,\n speed;\n\n elapsedTime = now - lastTime;\n lastTime = now;\n\n for ( i = 0; i < len; i++ ) {\n trackPoint = trackerPoints[ i ];\n gPoint = trackPoint.gPoint;\n // Math.atan2 gives us just what we need for a velocity vector, as we can simply\n // use cos()/sin() to extract the x/y velocity components.\n gPoint.direction = Math.atan2( gPoint.currentPos.y - trackPoint.lastPos.y, gPoint.currentPos.x - trackPoint.lastPos.x );\n // speed = distance / elapsed time\n distance = trackPoint.lastPos.distanceTo( gPoint.currentPos );\n trackPoint.lastPos = gPoint.currentPos;\n speed = 1000 * distance / ( elapsedTime + 1 );\n // Simple biased average, favors the most recent speed computation. Smooths out erratic gestures a bit.\n gPoint.speed = 0.75 * speed + 0.25 * gPoint.speed;\n }\n };\n\n // Public. Add a gesture point to be tracked\n var addPoint = function ( tracker, gPoint ) {\n var guid = _generateGuid( tracker, gPoint );\n\n trackerPoints.push(\n {\n guid: guid,\n gPoint: gPoint,\n lastPos: gPoint.currentPos\n } );\n\n // Only fire up the interval timer when there's gesture pointers to track\n if ( trackerPoints.length === 1 ) {\n lastTime = $.now();\n intervalId = window.setInterval( _doTracking, 50 );\n }\n };\n\n // Public. Stop tracking a gesture point\n var removePoint = function ( tracker, gPoint ) {\n var guid = _generateGuid( tracker, gPoint ),\n i,\n len = trackerPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( trackerPoints[ i ].guid === guid ) {\n trackerPoints.splice( i, 1 );\n // Only run the interval timer if theres gesture pointers to track\n len--;\n if ( len === 0 ) {\n window.clearInterval( intervalId );\n }\n break;\n }\n }\n };\n\n return {\n addPoint: addPoint,\n removePoint: removePoint\n };\n } )();\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Pointer event model and feature detection\n///////////////////////////////////////////////////////////////////////////////\n\n $.MouseTracker.captureElement = document;\n\n /**\n * Detect available mouse wheel event name.\n */\n $.MouseTracker.wheelEventName = ( $.Browser.vendor == $.BROWSERS.IE && $.Browser.version > 8 ) ||\n ( 'onwheel' in document.createElement( 'div' ) ) ? 'wheel' : // Modern browsers support 'wheel'\n document.onmousewheel !== undefined ? 'mousewheel' : // Webkit and IE support at least 'mousewheel'\n 'DOMMouseScroll'; // Assume old Firefox\n\n /**\n * Detect legacy mouse capture support.\n */\n $.MouseTracker.supportsMouseCapture = (function () {\n var divElement = document.createElement( 'div' );\n return $.isFunction( divElement.setCapture ) && $.isFunction( divElement.releaseCapture );\n }());\n\n /**\n * Detect browser pointer device event model(s) and build appropriate list of events to subscribe to.\n */\n $.MouseTracker.subscribeEvents = [ \"click\", \"dblclick\", \"keydown\", \"keyup\", \"keypress\", \"focus\", \"blur\", $.MouseTracker.wheelEventName ];\n\n if( $.MouseTracker.wheelEventName == \"DOMMouseScroll\" ) {\n // Older Firefox\n $.MouseTracker.subscribeEvents.push( \"MozMousePixelScroll\" );\n }\n\n // Note: window.navigator.pointerEnable is deprecated on IE 11 and not part of W3C spec.\n if ( window.PointerEvent && ( window.navigator.pointerEnabled || $.Browser.vendor !== $.BROWSERS.IE ) ) {\n // IE11 and other W3C Pointer Event implementations (see http://www.w3.org/TR/pointerevents)\n $.MouseTracker.havePointerEvents = true;\n $.MouseTracker.subscribeEvents.push( \"pointerover\", \"pointerout\", \"pointerdown\", \"pointerup\", \"pointermove\", \"pointercancel\" );\n $.MouseTracker.unprefixedPointerEvents = true;\n if( navigator.maxTouchPoints ) {\n $.MouseTracker.maxTouchPoints = navigator.maxTouchPoints;\n } else {\n $.MouseTracker.maxTouchPoints = 0;\n }\n $.MouseTracker.haveMouseEnter = false;\n } else if ( window.MSPointerEvent && window.navigator.msPointerEnabled ) {\n // IE10\n $.MouseTracker.havePointerEvents = true;\n $.MouseTracker.subscribeEvents.push( \"MSPointerOver\", \"MSPointerOut\", \"MSPointerDown\", \"MSPointerUp\", \"MSPointerMove\", \"MSPointerCancel\" );\n $.MouseTracker.unprefixedPointerEvents = false;\n if( navigator.msMaxTouchPoints ) {\n $.MouseTracker.maxTouchPoints = navigator.msMaxTouchPoints;\n } else {\n $.MouseTracker.maxTouchPoints = 0;\n }\n $.MouseTracker.haveMouseEnter = false;\n } else {\n // Legacy W3C mouse events\n $.MouseTracker.havePointerEvents = false;\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n $.MouseTracker.subscribeEvents.push( \"mouseenter\", \"mouseleave\" );\n $.MouseTracker.haveMouseEnter = true;\n } else {\n $.MouseTracker.subscribeEvents.push( \"mouseover\", \"mouseout\" );\n $.MouseTracker.haveMouseEnter = false;\n }\n $.MouseTracker.subscribeEvents.push( \"mousedown\", \"mouseup\", \"mousemove\" );\n if ( 'ontouchstart' in window ) {\n // iOS, Android, and other W3c Touch Event implementations\n // (see http://www.w3.org/TR/touch-events/)\n // (see https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)\n // (see https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)\n $.MouseTracker.subscribeEvents.push( \"touchstart\", \"touchend\", \"touchmove\", \"touchcancel\" );\n }\n if ( 'ongesturestart' in window ) {\n // iOS (see https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html)\n // Subscribe to these to prevent default gesture handling\n $.MouseTracker.subscribeEvents.push( \"gesturestart\", \"gesturechange\" );\n }\n $.MouseTracker.mousePointerId = \"legacy-mouse\";\n $.MouseTracker.maxTouchPoints = 10;\n }\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Classes and typedefs\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * Represents a point of contact on the screen made by a mouse cursor, pen, touch, or other pointer device.\n *\n * @typedef {Object} GesturePoint\n * @memberof OpenSeadragon.MouseTracker\n *\n * @property {Number} id\n * Identifier unique from all other active GesturePoints for a given pointer device.\n * @property {String} type\n * The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @property {Boolean} captured\n * True if events for the gesture point are captured to the tracked element.\n * @property {Boolean} isPrimary\n * True if the gesture point is a master pointer amongst the set of active pointers for each pointer type. True for mouse and primary (first) touch/pen pointers.\n * @property {Boolean} insideElementPressed\n * True if button pressed or contact point initiated inside the screen area of the tracked element.\n * @property {Boolean} insideElement\n * True if pointer or contact point is currently inside the bounds of the tracked element.\n * @property {Number} speed\n * Current computed speed, in pixels per second.\n * @property {Number} direction\n * Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @property {OpenSeadragon.Point} contactPos\n * The initial pointer contact position, relative to the page including any scrolling. Only valid if the pointer has contact (pressed, touch contact, pen contact).\n * @property {Number} contactTime\n * The initial pointer contact time, in milliseconds. Only valid if the pointer has contact (pressed, touch contact, pen contact).\n * @property {OpenSeadragon.Point} lastPos\n * The last pointer position, relative to the page including any scrolling.\n * @property {Number} lastTime\n * The last pointer contact time, in milliseconds.\n * @property {OpenSeadragon.Point} currentPos\n * The current pointer position, relative to the page including any scrolling.\n * @property {Number} currentTime\n * The current pointer contact time, in milliseconds.\n */\n\n\n /**\n * @class GesturePointList\n * @classdesc Provides an abstraction for a set of active {@link OpenSeadragon.MouseTracker.GesturePoint|GesturePoint} objects for a given pointer device type.\n * Active pointers are any pointer being tracked for this element which are in the hit-test area\n * of the element (for hover-capable devices) and/or have contact or a button press initiated in the element.\n * @memberof OpenSeadragon.MouseTracker\n * @param {String} type - The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n */\n $.MouseTracker.GesturePointList = function ( type ) {\n this._gPoints = [];\n /**\n * The pointer device type: \"mouse\", \"touch\", \"pen\", etc.\n * @member {String} type\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.type = type;\n /**\n * Current buttons pressed for the device.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @member {Number} buttons\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.buttons = 0;\n /**\n * Current number of contact points (touch points, mouse down, etc.) for the device.\n * @member {Number} contacts\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.contacts = 0;\n /**\n * Current number of clicks for the device. Used for multiple click gesture tracking.\n * @member {Number} clicks\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.clicks = 0;\n /**\n * Current number of captured pointers for the device.\n * @member {Number} captureCount\n * @memberof OpenSeadragon.MouseTracker.GesturePointList#\n */\n this.captureCount = 0;\n };\n\n /** @lends OpenSeadragon.MouseTracker.GesturePointList.prototype */\n $.MouseTracker.GesturePointList.prototype = {\n /**\n * @function\n * @returns {Number} Number of gesture points in the list.\n */\n getLength: function () {\n return this._gPoints.length;\n },\n /**\n * @function\n * @returns {Array.} The list of gesture points in the list as an array (read-only).\n */\n asArray: function () {\n return this._gPoints;\n },\n /**\n * @function\n * @param {OpenSeadragon.MouseTracker.GesturePoint} gesturePoint - A gesture point to add to the list.\n * @returns {Number} Number of gesture points in the list.\n */\n add: function ( gp ) {\n return this._gPoints.push( gp );\n },\n /**\n * @function\n * @param {Number} id - The id of the gesture point to remove from the list.\n * @returns {Number} Number of gesture points in the list.\n */\n removeById: function ( id ) {\n var i,\n len = this._gPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( this._gPoints[ i ].id === id ) {\n this._gPoints.splice( i, 1 );\n break;\n }\n }\n return this._gPoints.length;\n },\n /**\n * @function\n * @param {Number} index - The index of the gesture point to retrieve from the list.\n * @returns {OpenSeadragon.MouseTracker.GesturePoint|null} The gesture point at the given index, or null if not found.\n */\n getByIndex: function ( index ) {\n if ( index < this._gPoints.length) {\n return this._gPoints[ index ];\n }\n\n return null;\n },\n /**\n * @function\n * @param {Number} id - The id of the gesture point to retrieve from the list.\n * @returns {OpenSeadragon.MouseTracker.GesturePoint|null} The gesture point with the given id, or null if not found.\n */\n getById: function ( id ) {\n var i,\n len = this._gPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( this._gPoints[ i ].id === id ) {\n return this._gPoints[ i ];\n }\n }\n return null;\n },\n /**\n * @function\n * @returns {OpenSeadragon.MouseTracker.GesturePoint|null} The primary gesture point in the list, or null if not found.\n */\n getPrimary: function ( id ) {\n var i,\n len = this._gPoints.length;\n for ( i = 0; i < len; i++ ) {\n if ( this._gPoints[ i ].isPrimary ) {\n return this._gPoints[ i ];\n }\n }\n return null;\n },\n\n /**\n * Increment this pointer's contact count.\n * It will evaluate whether this pointer type is allowed to have multiple contacts.\n * @function\n */\n addContact: function() {\n ++this.contacts;\n\n if (this.contacts > 1 && (this.type === \"mouse\" || this.type === \"pen\")) {\n this.contacts = 1;\n }\n },\n\n /**\n * Decrement this pointer's contact count.\n * It will make sure the count does not go below 0.\n * @function\n */\n removeContact: function() {\n --this.contacts;\n\n if (this.contacts < 0) {\n this.contacts = 0;\n }\n }\n };\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Utility functions\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * Removes all tracked pointers.\n * @private\n * @inner\n */\n function clearTrackedPointers( tracker ) {\n var delegate = THIS[ tracker.hash ],\n i,\n pointerListCount = delegate.activePointersLists.length;\n\n for ( i = 0; i < pointerListCount; i++ ) {\n if ( delegate.activePointersLists[ i ].captureCount > 0 ) {\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'mousemove',\n delegate.mousemovecaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'mouseup',\n delegate.mouseupcaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n $.MouseTracker.unprefixedPointerEvents ? 'pointermove' : 'MSPointerMove',\n delegate.pointermovecaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n $.MouseTracker.unprefixedPointerEvents ? 'pointerup' : 'MSPointerUp',\n delegate.pointerupcaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'touchmove',\n delegate.touchmovecaptured,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n 'touchend',\n delegate.touchendcaptured,\n true\n );\n\n delegate.activePointersLists[ i ].captureCount = 0;\n }\n }\n\n for ( i = 0; i < pointerListCount; i++ ) {\n delegate.activePointersLists.pop();\n }\n }\n\n /**\n * Starts tracking pointer events on the tracked element.\n * @private\n * @inner\n */\n function startTracking( tracker ) {\n var delegate = THIS[ tracker.hash ],\n event,\n i;\n\n if ( !delegate.tracking ) {\n for ( i = 0; i < $.MouseTracker.subscribeEvents.length; i++ ) {\n event = $.MouseTracker.subscribeEvents[ i ];\n $.addEvent(\n tracker.element,\n event,\n delegate[ event ],\n false\n );\n }\n\n clearTrackedPointers( tracker );\n\n delegate.tracking = true;\n }\n }\n\n /**\n * Stops tracking pointer events on the tracked element.\n * @private\n * @inner\n */\n function stopTracking( tracker ) {\n var delegate = THIS[ tracker.hash ],\n event,\n i;\n\n if ( delegate.tracking ) {\n for ( i = 0; i < $.MouseTracker.subscribeEvents.length; i++ ) {\n event = $.MouseTracker.subscribeEvents[ i ];\n $.removeEvent(\n tracker.element,\n event,\n delegate[ event ],\n false\n );\n }\n\n clearTrackedPointers( tracker );\n\n delegate.tracking = false;\n }\n }\n\n /**\n * @private\n * @inner\n */\n function getCaptureEventParams( tracker, pointerType ) {\n var delegate = THIS[ tracker.hash ];\n\n if ( pointerType === 'pointerevent' ) {\n return {\n upName: $.MouseTracker.unprefixedPointerEvents ? 'pointerup' : 'MSPointerUp',\n upHandler: delegate.pointerupcaptured,\n moveName: $.MouseTracker.unprefixedPointerEvents ? 'pointermove' : 'MSPointerMove',\n moveHandler: delegate.pointermovecaptured\n };\n } else if ( pointerType === 'mouse' ) {\n return {\n upName: 'mouseup',\n upHandler: delegate.mouseupcaptured,\n moveName: 'mousemove',\n moveHandler: delegate.mousemovecaptured\n };\n } else if ( pointerType === 'touch' ) {\n return {\n upName: 'touchend',\n upHandler: delegate.touchendcaptured,\n moveName: 'touchmove',\n moveHandler: delegate.touchmovecaptured\n };\n } else {\n throw new Error( \"MouseTracker.getCaptureEventParams: Unknown pointer type.\" );\n }\n }\n\n /**\n * Begin capturing pointer events to the tracked element.\n * @private\n * @inner\n */\n function capturePointer( tracker, pointerType, pointerCount ) {\n var pointsList = tracker.getActivePointersListByType( pointerType ),\n eventParams;\n\n pointsList.captureCount += (pointerCount || 1);\n\n if ( pointsList.captureCount === 1 ) {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n tracker.element.setCapture( true );\n } else {\n eventParams = getCaptureEventParams( tracker, $.MouseTracker.havePointerEvents ? 'pointerevent' : pointerType );\n // We emulate mouse capture by hanging listeners on the document object.\n // (Note we listen on the capture phase so the captured handlers will get called first)\n // eslint-disable-next-line no-use-before-define\n if (isInIframe && canAccessEvents(window.top)) {\n $.addEvent(\n window.top,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n }\n $.addEvent(\n $.MouseTracker.captureElement,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n $.addEvent(\n $.MouseTracker.captureElement,\n eventParams.moveName,\n eventParams.moveHandler,\n true\n );\n }\n }\n }\n\n\n /**\n * Stop capturing pointer events to the tracked element.\n * @private\n * @inner\n */\n function releasePointer( tracker, pointerType, pointerCount ) {\n var pointsList = tracker.getActivePointersListByType( pointerType ),\n eventParams;\n\n pointsList.captureCount -= (pointerCount || 1);\n\n if ( pointsList.captureCount === 0 ) {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n tracker.element.releaseCapture();\n } else {\n eventParams = getCaptureEventParams( tracker, $.MouseTracker.havePointerEvents ? 'pointerevent' : pointerType );\n // We emulate mouse capture by hanging listeners on the document object.\n // (Note we listen on the capture phase so the captured handlers will get called first)\n // eslint-disable-next-line no-use-before-define\n if (isInIframe && canAccessEvents(window.top)) {\n $.removeEvent(\n window.top,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n }\n $.removeEvent(\n $.MouseTracker.captureElement,\n eventParams.moveName,\n eventParams.moveHandler,\n true\n );\n $.removeEvent(\n $.MouseTracker.captureElement,\n eventParams.upName,\n eventParams.upHandler,\n true\n );\n }\n }\n }\n\n\n /**\n * Gets a W3C Pointer Events model compatible pointer type string from a DOM pointer event.\n * IE10 used a long integer value, but the W3C specification (and IE11+) use a string \"mouse\", \"touch\", \"pen\", etc.\n * @private\n * @inner\n */\n function getPointerType( event ) {\n var pointerTypeStr;\n if ( $.MouseTracker.unprefixedPointerEvents ) {\n pointerTypeStr = event.pointerType;\n } else {\n // IE10\n // MSPOINTER_TYPE_TOUCH: 0x00000002\n // MSPOINTER_TYPE_PEN: 0x00000003\n // MSPOINTER_TYPE_MOUSE: 0x00000004\n switch( event.pointerType )\n {\n case 0x00000002:\n pointerTypeStr = 'touch';\n break;\n case 0x00000003:\n pointerTypeStr = 'pen';\n break;\n case 0x00000004:\n pointerTypeStr = 'mouse';\n break;\n default:\n pointerTypeStr = '';\n }\n }\n return pointerTypeStr;\n }\n\n\n /**\n * @private\n * @inner\n */\n function getMouseAbsolute( event ) {\n return $.getMousePosition( event );\n }\n\n /**\n * @private\n * @inner\n */\n function getMouseRelative( event, element ) {\n return getPointRelativeToAbsolute( getMouseAbsolute( event ), element );\n }\n\n /**\n * @private\n * @inner\n */\n function getPointRelativeToAbsolute( point, element ) {\n var offset = $.getElementOffset( element );\n return point.minus( offset );\n }\n\n /**\n * @private\n * @inner\n */\n function getCenterPoint( point1, point2 ) {\n return new $.Point( ( point1.x + point2.x ) / 2, ( point1.y + point2.y ) / 2 );\n }\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Device-specific DOM event handlers\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * @private\n * @inner\n */\n function onClick( tracker, event ) {\n if ( tracker.clickHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onDblClick( tracker, event ) {\n if ( tracker.dblClickHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onKeyDown( tracker, event ) {\n //$.console.log( \"keydown %s %s %s %s %s\", event.keyCode, event.charCode, event.ctrlKey, event.shiftKey, event.altKey );\n var propagate;\n if ( tracker.keyDownHandler ) {\n event = $.getEvent( event );\n propagate = tracker.keyDownHandler(\n {\n eventSource: tracker,\n keyCode: event.keyCode ? event.keyCode : event.charCode,\n ctrl: event.ctrlKey,\n shift: event.shiftKey,\n alt: event.altKey,\n meta: event.metaKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( !propagate ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onKeyUp( tracker, event ) {\n //$.console.log( \"keyup %s %s %s %s %s\", event.keyCode, event.charCode, event.ctrlKey, event.shiftKey, event.altKey );\n var propagate;\n if ( tracker.keyUpHandler ) {\n event = $.getEvent( event );\n propagate = tracker.keyUpHandler(\n {\n eventSource: tracker,\n keyCode: event.keyCode ? event.keyCode : event.charCode,\n ctrl: event.ctrlKey,\n shift: event.shiftKey,\n alt: event.altKey,\n meta: event.metaKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( !propagate ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onKeyPress( tracker, event ) {\n //$.console.log( \"keypress %s %s %s %s %s\", event.keyCode, event.charCode, event.ctrlKey, event.shiftKey, event.altKey );\n var propagate;\n if ( tracker.keyHandler ) {\n event = $.getEvent( event );\n propagate = tracker.keyHandler(\n {\n eventSource: tracker,\n keyCode: event.keyCode ? event.keyCode : event.charCode,\n ctrl: event.ctrlKey,\n shift: event.shiftKey,\n alt: event.altKey,\n meta: event.metaKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( !propagate ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onFocus( tracker, event ) {\n //console.log( \"focus %s\", event );\n var propagate;\n if ( tracker.focusHandler ) {\n event = $.getEvent( event );\n propagate = tracker.focusHandler(\n {\n eventSource: tracker,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onBlur( tracker, event ) {\n //console.log( \"blur %s\", event );\n var propagate;\n if ( tracker.blurHandler ) {\n event = $.getEvent( event );\n propagate = tracker.blurHandler(\n {\n eventSource: tracker,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n\n\n /**\n * Handler for 'wheel' events\n *\n * @private\n * @inner\n */\n function onWheel( tracker, event ) {\n handleWheelEvent( tracker, event, event );\n }\n\n\n /**\n * Handler for 'mousewheel', 'DOMMouseScroll', and 'MozMousePixelScroll' events\n *\n * @private\n * @inner\n */\n function onMouseWheel( tracker, event ) {\n event = $.getEvent( event );\n\n // Simulate a 'wheel' event\n var simulatedEvent = {\n target: event.target || event.srcElement,\n type: \"wheel\",\n shiftKey: event.shiftKey || false,\n clientX: event.clientX,\n clientY: event.clientY,\n pageX: event.pageX ? event.pageX : event.clientX,\n pageY: event.pageY ? event.pageY : event.clientY,\n deltaMode: event.type == \"MozMousePixelScroll\" ? 0 : 1, // 0=pixel, 1=line, 2=page\n deltaX: 0,\n deltaZ: 0\n };\n\n // Calculate deltaY\n if ( $.MouseTracker.wheelEventName == \"mousewheel\" ) {\n simulatedEvent.deltaY = -event.wheelDelta / $.DEFAULT_SETTINGS.pixelsPerWheelLine;\n } else {\n simulatedEvent.deltaY = event.detail;\n }\n\n handleWheelEvent( tracker, simulatedEvent, event );\n }\n\n\n /**\n * Handles 'wheel' events.\n * The event may be simulated by the legacy mouse wheel event handler (onMouseWheel()).\n *\n * @private\n * @inner\n */\n function handleWheelEvent( tracker, event, originalEvent ) {\n var nDelta = 0,\n propagate;\n\n // The nDelta variable is gated to provide smooth z-index scrolling\n // since the mouse wheel allows for substantial deltas meant for rapid\n // y-index scrolling.\n // event.deltaMode: 0=pixel, 1=line, 2=page\n // TODO: Deltas in pixel mode should be accumulated then a scroll value computed after $.DEFAULT_SETTINGS.pixelsPerWheelLine threshold reached\n nDelta = event.deltaY < 0 ? 1 : -1;\n\n if ( tracker.scrollHandler ) {\n propagate = tracker.scrollHandler(\n {\n eventSource: tracker,\n pointerType: 'mouse',\n position: getMouseRelative( event, tracker.element ),\n scroll: nDelta,\n shift: event.shiftKey,\n isTouchEvent: false,\n originalEvent: originalEvent,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( originalEvent );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function isParentChild( parent, child )\n {\n if ( parent === child ) {\n return false;\n }\n while ( child && child !== parent ) {\n child = child.parentNode;\n }\n return child === parent;\n }\n\n\n /**\n * Only used on IE 8\n *\n * @private\n * @inner\n */\n function onMouseEnter( tracker, event ) {\n event = $.getEvent( event );\n\n handleMouseEnter( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseOver( tracker, event ) {\n event = $.getEvent( event );\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n handleMouseEnter( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseEnter( tracker, event ) {\n var gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersEnter( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * Only used on IE 8\n *\n * @private\n * @inner\n */\n function onMouseLeave( tracker, event ) {\n event = $.getEvent( event );\n\n handleMouseExit( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseOut( tracker, event ) {\n event = $.getEvent( event );\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n handleMouseExit( tracker, event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseExit( tracker, event ) {\n var gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersExit( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * Returns a W3C DOM level 3 standard button value given an event.button property:\n * -1 == none, 0 == primary/left, 1 == middle, 2 == secondary/right, 3 == X1/back, 4 == X2/forward, 5 == eraser (pen)\n * @private\n * @inner\n */\n function getStandardizedButton( button ) {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n // On IE 8, 0 == none, 1 == left, 2 == right, 3 == left and right, 4 == middle, 5 == left and middle, 6 == right and middle, 7 == all three\n // TODO: Support chorded (multiple) button presses on IE 8?\n if ( button === 1 ) {\n return 0;\n } else if ( button === 2 ) {\n return 2;\n } else if ( button === 4 ) {\n return 1;\n } else {\n return -1;\n }\n } else {\n return button;\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseDown( tracker, event ) {\n var gPoint;\n\n event = $.getEvent( event );\n\n gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersDown( tracker, event, [ gPoint ], getStandardizedButton( event.button ) ) ) {\n $.stopEvent( event );\n capturePointer( tracker, 'mouse' );\n }\n\n if ( tracker.clickHandler || tracker.dblClickHandler || tracker.pressHandler || tracker.dragHandler || tracker.dragEndHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseUp( tracker, event ) {\n handleMouseUp( tracker, event );\n }\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onMouseUp is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onMouseUpCaptured( tracker, event ) {\n handleMouseUp( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseUp( tracker, event ) {\n var gPoint;\n\n event = $.getEvent( event );\n\n gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersUp( tracker, event, [ gPoint ], getStandardizedButton( event.button ) ) ) {\n releasePointer( tracker, 'mouse' );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onMouseMove( tracker, event ) {\n handleMouseMove( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onMouseMove is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onMouseMoveCaptured( tracker, event ) {\n handleMouseMove( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleMouseMove( tracker, event ) {\n var gPoint;\n\n event = $.getEvent( event );\n\n gPoint = {\n id: $.MouseTracker.mousePointerId,\n type: 'mouse',\n isPrimary: true,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersMove( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function abortContacts( tracker, event, pointsList ) {\n var i,\n gPointCount = pointsList.getLength(),\n abortGPoints = [];\n\n // Check contact count for hoverable pointer types before aborting\n if (pointsList.type === 'touch' || pointsList.contacts > 0) {\n for ( i = 0; i < gPointCount; i++ ) {\n abortGPoints.push( pointsList.getByIndex( i ) );\n }\n\n if ( abortGPoints.length > 0 ) {\n // simulate touchend/mouseup\n updatePointersUp( tracker, event, abortGPoints, 0 ); // 0 means primary button press/release or touch contact\n // release pointer capture\n pointsList.captureCount = 1;\n releasePointer( tracker, pointsList.type );\n // simulate touchleave/mouseout\n updatePointersExit( tracker, event, abortGPoints );\n }\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchStart( tracker, event ) {\n var time,\n i,\n j,\n touchCount = event.changedTouches.length,\n gPoints = [],\n parentGPoints,\n pointsList = tracker.getActivePointersListByType( 'touch' );\n\n time = $.now();\n\n if ( pointsList.getLength() > event.touches.length - touchCount ) {\n $.console.warn('Tracked touch contact count doesn\\'t match event.touches.length. Removing all tracked touch pointers.');\n abortContacts( tracker, event, pointsList );\n }\n\n for ( i = 0; i < touchCount; i++ ) {\n gPoints.push( {\n id: event.changedTouches[ i ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ i ] ),\n currentTime: time\n } );\n }\n\n // simulate touchenter on our tracked element\n updatePointersEnter( tracker, event, gPoints );\n\n // simulate touchenter on our tracked element's tracked ancestor elements\n for ( i = 0; i < MOUSETRACKERS.length; i++ ) {\n if ( MOUSETRACKERS[ i ] !== tracker && MOUSETRACKERS[ i ].isTracking() && isParentChild( MOUSETRACKERS[ i ].element, tracker.element ) ) {\n parentGPoints = [];\n for ( j = 0; j < touchCount; j++ ) {\n parentGPoints.push( {\n id: event.changedTouches[ j ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ j ] ),\n currentTime: time\n } );\n }\n updatePointersEnter( MOUSETRACKERS[ i ], event, parentGPoints );\n }\n }\n\n if ( updatePointersDown( tracker, event, gPoints, 0 ) ) { // 0 means primary button press/release or touch contact\n $.stopEvent( event );\n capturePointer( tracker, 'touch', touchCount );\n }\n\n $.cancelEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchEnd( tracker, event ) {\n handleTouchEnd( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate pointer capture.\n * onTouchEnd is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onTouchEndCaptured( tracker, event ) {\n handleTouchEnd( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleTouchEnd( tracker, event ) {\n var time,\n i,\n j,\n touchCount = event.changedTouches.length,\n gPoints = [],\n parentGPoints;\n\n time = $.now();\n\n for ( i = 0; i < touchCount; i++ ) {\n gPoints.push( {\n id: event.changedTouches[ i ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ i ] ),\n currentTime: time\n } );\n }\n\n if ( updatePointersUp( tracker, event, gPoints, 0 ) ) {\n releasePointer( tracker, 'touch', touchCount );\n }\n\n // simulate touchleave on our tracked element\n updatePointersExit( tracker, event, gPoints );\n\n // simulate touchleave on our tracked element's tracked ancestor elements\n for ( i = 0; i < MOUSETRACKERS.length; i++ ) {\n if ( MOUSETRACKERS[ i ] !== tracker && MOUSETRACKERS[ i ].isTracking() && isParentChild( MOUSETRACKERS[ i ].element, tracker.element ) ) {\n parentGPoints = [];\n for ( j = 0; j < touchCount; j++ ) {\n parentGPoints.push( {\n id: event.changedTouches[ j ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ j ] ),\n currentTime: time\n } );\n }\n updatePointersExit( MOUSETRACKERS[ i ], event, parentGPoints );\n }\n }\n\n $.cancelEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchMove( tracker, event ) {\n handleTouchMove( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate pointer capture.\n * onTouchMove is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onTouchMoveCaptured( tracker, event ) {\n handleTouchMove( tracker, event );\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handleTouchMove( tracker, event ) {\n var i,\n touchCount = event.changedTouches.length,\n gPoints = [];\n\n for ( i = 0; i < touchCount; i++ ) {\n gPoints.push( {\n id: event.changedTouches[ i ].identifier,\n type: 'touch',\n // isPrimary not set - let the updatePointers functions determine it\n currentPos: getMouseAbsolute( event.changedTouches[ i ] ),\n currentTime: $.now()\n } );\n }\n\n updatePointersMove( tracker, event, gPoints );\n\n $.cancelEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onTouchCancel( tracker, event ) {\n var pointsList = tracker.getActivePointersListByType('touch');\n\n abortContacts( tracker, event, pointsList );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onGestureStart( tracker, event ) {\n event.stopPropagation();\n event.preventDefault();\n return false;\n }\n\n\n /**\n * @private\n * @inner\n */\n function onGestureChange( tracker, event ) {\n event.stopPropagation();\n event.preventDefault();\n return false;\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerOver( tracker, event ) {\n var gPoint;\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersEnter( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerOut( tracker, event ) {\n var gPoint;\n\n if ( event.currentTarget === event.relatedTarget || isParentChild( event.currentTarget, event.relatedTarget ) ) {\n return;\n }\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersExit( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerDown( tracker, event ) {\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersDown( tracker, event, [ gPoint ], event.button ) ) {\n $.stopEvent( event );\n capturePointer( tracker, gPoint.type );\n }\n\n if ( tracker.clickHandler || tracker.dblClickHandler || tracker.pressHandler || tracker.dragHandler || tracker.dragEndHandler || tracker.pinchHandler ) {\n $.cancelEvent( event );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerUp( tracker, event ) {\n handlePointerUp( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onPointerUp is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onPointerUpCaptured( tracker, event ) {\n var pointsList = tracker.getActivePointersListByType( getPointerType( event ) );\n if ( pointsList.getById( event.pointerId ) ) {\n handlePointerUp( tracker, event );\n }\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handlePointerUp( tracker, event ) {\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n if ( updatePointersUp( tracker, event, [ gPoint ], event.button ) ) {\n releasePointer( tracker, gPoint.type );\n }\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerMove( tracker, event ) {\n handlePointerMove( tracker, event );\n }\n\n\n /**\n * This handler is attached to the window object (on the capture phase) to emulate mouse capture.\n * onPointerMove is still attached to the tracked element, so stop propagation to avoid processing twice.\n *\n * @private\n * @inner\n */\n function onPointerMoveCaptured( tracker, event ) {\n var pointsList = tracker.getActivePointersListByType( getPointerType( event ) );\n if ( pointsList.getById( event.pointerId ) ) {\n handlePointerMove( tracker, event );\n }\n $.stopEvent( event );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handlePointerMove( tracker, event ) {\n // Pointer changed coordinates, button state, pressure, tilt, or contact geometry (e.g. width and height)\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event ),\n isPrimary: event.isPrimary,\n currentPos: getMouseAbsolute( event ),\n currentTime: $.now()\n };\n\n updatePointersMove( tracker, event, [ gPoint ] );\n }\n\n\n /**\n * @private\n * @inner\n */\n function onPointerCancel( tracker, event ) {\n var gPoint;\n\n gPoint = {\n id: event.pointerId,\n type: getPointerType( event )\n };\n\n updatePointersCancel( tracker, event, [ gPoint ] );\n }\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Device-agnostic DOM event handlers\n///////////////////////////////////////////////////////////////////////////////\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker.GesturePointList} pointsList\n * The GesturePointList to track the pointer in.\n * @param {OpenSeadragon.MouseTracker.GesturePoint} gPoint\n * Gesture point to track.\n * @returns {Number} Number of gesture points in pointsList.\n */\n function startTrackingPointer( pointsList, gPoint ) {\n\n // If isPrimary is not known for the pointer then set it according to our rules:\n // true if the first pointer in the gesture, otherwise false\n if ( !gPoint.hasOwnProperty( 'isPrimary' ) ) {\n if ( pointsList.getLength() === 0 ) {\n gPoint.isPrimary = true;\n } else {\n gPoint.isPrimary = false;\n }\n }\n gPoint.speed = 0;\n gPoint.direction = 0;\n gPoint.contactPos = gPoint.currentPos;\n gPoint.contactTime = gPoint.currentTime;\n gPoint.lastPos = gPoint.currentPos;\n gPoint.lastTime = gPoint.currentTime;\n\n return pointsList.add( gPoint );\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker.GesturePointList} pointsList\n * The GesturePointList to stop tracking the pointer on.\n * @param {OpenSeadragon.MouseTracker.GesturePoint} gPoint\n * Gesture point to stop tracking.\n * @returns {Number} Number of gesture points in pointsList.\n */\n function stopTrackingPointer( pointsList, gPoint ) {\n var listLength,\n primaryPoint;\n\n if ( pointsList.getById( gPoint.id ) ) {\n listLength = pointsList.removeById( gPoint.id );\n\n // If isPrimary is not known for the pointer and we just removed the primary pointer from the list then we need to set another pointer as primary\n if ( !gPoint.hasOwnProperty( 'isPrimary' ) ) {\n primaryPoint = pointsList.getPrimary();\n if ( !primaryPoint ) {\n primaryPoint = pointsList.getByIndex( 0 );\n if ( primaryPoint ) {\n primaryPoint.isPrimary = true;\n }\n }\n }\n } else {\n listLength = pointsList.getLength();\n }\n\n return listLength;\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersEnter( tracker, event, gPoints ) {\n var pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n propagate;\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer...update it\n updateGPoint.insideElement = true;\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n\n curGPoint = updateGPoint;\n } else {\n // Initialize for tracking and add to the tracking list\n curGPoint.captured = false;\n curGPoint.insideElementPressed = false;\n curGPoint.insideElement = true;\n startTrackingPointer( pointsList, curGPoint );\n }\n\n // Enter\n if ( tracker.enterHandler ) {\n propagate = tracker.enterHandler(\n {\n eventSource: tracker,\n pointerType: curGPoint.type,\n position: getPointRelativeToAbsolute( curGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n pointers: tracker.getActivePointerCount(),\n insideElementPressed: curGPoint.insideElementPressed,\n buttonDownAny: pointsList.buttons !== 0,\n isTouchEvent: curGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersExit( tracker, event, gPoints ) {\n var pointsList = tracker.getActivePointersListByType(gPoints[0].type),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n propagate;\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer. If captured then update it, else stop tracking it\n if ( updateGPoint.captured ) {\n updateGPoint.insideElement = false;\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n } else {\n stopTrackingPointer( pointsList, updateGPoint );\n }\n\n curGPoint = updateGPoint;\n }\n\n // Exit\n if ( tracker.exitHandler ) {\n propagate = tracker.exitHandler(\n {\n eventSource: tracker,\n pointerType: curGPoint.type,\n position: getPointRelativeToAbsolute( curGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n pointers: tracker.getActivePointerCount(),\n insideElementPressed: updateGPoint ? updateGPoint.insideElementPressed : false,\n buttonDownAny: pointsList.buttons !== 0,\n isTouchEvent: curGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n * @param {Number} buttonChanged\n * The button involved in the event: -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * Note on chorded button presses (a button pressed when another button is already pressed): In the W3C Pointer Events model,\n * only one pointerdown/pointerup event combo is fired. Chorded button state changes instead fire pointermove events.\n *\n * @returns {Boolean} True if pointers should be captured to the tracked element, otherwise false.\n */\n function updatePointersDown( tracker, event, gPoints, buttonChanged ) {\n var delegate = THIS[ tracker.hash ],\n propagate,\n pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint;\n\n if ( typeof event.buttons !== 'undefined' ) {\n pointsList.buttons = event.buttons;\n } else {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons += 1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons += 4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons += 2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons += 8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons += 16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons += 32;\n }\n } else {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons |= 1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons |= 4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons |= 2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons |= 8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons |= 16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons |= 32;\n }\n }\n }\n\n // Some pointers may steal control from another pointer without firing the appropriate release events\n // e.g. Touching a screen while click-dragging with certain mice.\n var otherPointsLists = tracker.getActivePointersListsExceptType(gPoints[ 0 ].type);\n for (i = 0; i < otherPointsLists.length; i++) {\n //If another pointer has contact, simulate the release\n abortContacts(tracker, event, otherPointsLists[i]); // No-op if no active pointer\n }\n\n // Only capture and track primary button, pen, and touch contacts\n if ( buttonChanged !== 0 ) {\n // Aux Press\n if ( tracker.nonPrimaryPressHandler ) {\n propagate = tracker.nonPrimaryPressHandler(\n {\n eventSource: tracker,\n pointerType: gPoints[ 0 ].type,\n position: getPointRelativeToAbsolute( gPoints[ 0 ].currentPos, tracker.element ),\n button: buttonChanged,\n buttons: pointsList.buttons,\n isTouchEvent: gPoints[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n return false;\n }\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer...update it\n updateGPoint.captured = true;\n updateGPoint.insideElementPressed = true;\n updateGPoint.insideElement = true;\n updateGPoint.contactPos = curGPoint.currentPos;\n updateGPoint.contactTime = curGPoint.currentTime;\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n\n curGPoint = updateGPoint;\n } else {\n // Initialize for tracking and add to the tracking list (no pointerover or pointermove event occurred before this)\n curGPoint.captured = true;\n curGPoint.insideElementPressed = true;\n curGPoint.insideElement = true;\n startTrackingPointer( pointsList, curGPoint );\n }\n\n pointsList.addContact();\n //$.console.log('contacts++ ', pointsList.contacts);\n\n if ( tracker.dragHandler || tracker.dragEndHandler || tracker.pinchHandler ) {\n $.MouseTracker.gesturePointVelocityTracker.addPoint( tracker, curGPoint );\n }\n\n if ( pointsList.contacts === 1 ) {\n // Press\n if ( tracker.pressHandler ) {\n propagate = tracker.pressHandler(\n {\n eventSource: tracker,\n pointerType: curGPoint.type,\n position: getPointRelativeToAbsolute( curGPoint.contactPos, tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: curGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n } else if ( pointsList.contacts === 2 ) {\n if ( tracker.pinchHandler && curGPoint.type === 'touch' ) {\n // Initialize for pinch\n delegate.pinchGPoints = pointsList.asArray();\n delegate.lastPinchDist = delegate.currentPinchDist = delegate.pinchGPoints[ 0 ].currentPos.distanceTo( delegate.pinchGPoints[ 1 ].currentPos );\n delegate.lastPinchCenter = delegate.currentPinchCenter = getCenterPoint( delegate.pinchGPoints[ 0 ].currentPos, delegate.pinchGPoints[ 1 ].currentPos );\n }\n }\n }\n\n return true;\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n * @param {Number} buttonChanged\n * The button involved in the event: -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * Note on chorded button presses (a button pressed when another button is already pressed): In the W3C Pointer Events model,\n * only one pointerdown/pointerup event combo is fired. Chorded button state changes instead fire pointermove events.\n *\n * @returns {Boolean} True if pointer capture should be released from the tracked element, otherwise false.\n */\n function updatePointersUp( tracker, event, gPoints, buttonChanged ) {\n var delegate = THIS[ tracker.hash ],\n pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n propagate,\n releasePoint,\n releaseTime,\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n releaseCapture = false,\n wasCaptured = false,\n quick;\n\n if ( typeof event.buttons !== 'undefined' ) {\n pointsList.buttons = event.buttons;\n } else {\n if ( $.Browser.vendor === $.BROWSERS.IE && $.Browser.version < 9 ) {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons -= 1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons -= 4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons -= 2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons -= 8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons -= 16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons -= 32;\n }\n } else {\n if ( buttonChanged === 0 ) {\n // Primary\n pointsList.buttons ^= ~1;\n } else if ( buttonChanged === 1 ) {\n // Aux\n pointsList.buttons ^= ~4;\n } else if ( buttonChanged === 2 ) {\n // Secondary\n pointsList.buttons ^= ~2;\n } else if ( buttonChanged === 3 ) {\n // X1 (Back)\n pointsList.buttons ^= ~8;\n } else if ( buttonChanged === 4 ) {\n // X2 (Forward)\n pointsList.buttons ^= ~16;\n } else if ( buttonChanged === 5 ) {\n // Pen Eraser\n pointsList.buttons ^= ~32;\n }\n }\n }\n\n // Only capture and track primary button, pen, and touch contacts\n if ( buttonChanged !== 0 ) {\n // Aux Release\n if ( tracker.nonPrimaryReleaseHandler ) {\n propagate = tracker.nonPrimaryReleaseHandler(\n {\n eventSource: tracker,\n pointerType: gPoints[ 0 ].type,\n position: getPointRelativeToAbsolute(gPoints[0].currentPos, tracker.element),\n button: buttonChanged,\n buttons: pointsList.buttons,\n isTouchEvent: gPoints[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // A primary mouse button may have been released while the non-primary button was down\n var otherPointsList = tracker.getActivePointersListByType(\"mouse\");\n // Stop tracking the mouse; see https://github.com/openseadragon/openseadragon/pull/1223\n abortContacts(tracker, event, otherPointsList); // No-op if no active pointer\n\n return false;\n }\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Update the pointer, stop tracking it if not still in this element\n if ( updateGPoint.captured ) {\n updateGPoint.captured = false;\n releaseCapture = true;\n wasCaptured = true;\n }\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n if ( !updateGPoint.insideElement ) {\n stopTrackingPointer( pointsList, updateGPoint );\n }\n\n releasePoint = updateGPoint.currentPos;\n releaseTime = updateGPoint.currentTime;\n\n if ( wasCaptured ) {\n // Pointer was activated in our element but could have been removed in any element since events are captured to our element\n\n pointsList.removeContact();\n //$.console.log('contacts-- ', pointsList.contacts);\n\n if ( tracker.dragHandler || tracker.dragEndHandler || tracker.pinchHandler ) {\n $.MouseTracker.gesturePointVelocityTracker.removePoint( tracker, updateGPoint );\n }\n\n if ( pointsList.contacts === 0 ) {\n\n // Release (pressed in our element)\n if ( tracker.releaseHandler ) {\n propagate = tracker.releaseHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( releasePoint, tracker.element ),\n buttons: pointsList.buttons,\n insideElementPressed: updateGPoint.insideElementPressed,\n insideElementReleased: updateGPoint.insideElement,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Drag End\n if ( tracker.dragEndHandler && !updateGPoint.currentPos.equals( updateGPoint.contactPos ) ) {\n propagate = tracker.dragEndHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n speed: updateGPoint.speed,\n direction: updateGPoint.direction,\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Click / Double-Click\n if ( ( tracker.clickHandler || tracker.dblClickHandler ) && updateGPoint.insideElement ) {\n quick = releaseTime - updateGPoint.contactTime <= tracker.clickTimeThreshold &&\n updateGPoint.contactPos.distanceTo( releasePoint ) <= tracker.clickDistThreshold;\n\n // Click\n if ( tracker.clickHandler ) {\n propagate = tracker.clickHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n quick: quick,\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Double-Click\n if ( tracker.dblClickHandler && quick ) {\n pointsList.clicks++;\n if ( pointsList.clicks === 1 ) {\n delegate.lastClickPos = releasePoint;\n /*jshint loopfunc:true*/\n delegate.dblClickTimeOut = setTimeout( function() {\n pointsList.clicks = 0;\n }, tracker.dblClickTimeThreshold );\n /*jshint loopfunc:false*/\n } else if ( pointsList.clicks === 2 ) {\n clearTimeout( delegate.dblClickTimeOut );\n pointsList.clicks = 0;\n if ( delegate.lastClickPos.distanceTo( releasePoint ) <= tracker.dblClickDistThreshold ) {\n propagate = tracker.dblClickHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n delegate.lastClickPos = null;\n }\n }\n }\n } else if ( pointsList.contacts === 2 ) {\n if ( tracker.pinchHandler && updateGPoint.type === 'touch' ) {\n // Reset for pinch\n delegate.pinchGPoints = pointsList.asArray();\n delegate.lastPinchDist = delegate.currentPinchDist = delegate.pinchGPoints[ 0 ].currentPos.distanceTo( delegate.pinchGPoints[ 1 ].currentPos );\n delegate.lastPinchCenter = delegate.currentPinchCenter = getCenterPoint( delegate.pinchGPoints[ 0 ].currentPos, delegate.pinchGPoints[ 1 ].currentPos );\n }\n }\n } else {\n // Pointer was activated in another element but removed in our element\n\n // Release (pressed in another element)\n if ( tracker.releaseHandler ) {\n propagate = tracker.releaseHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( releasePoint, tracker.element ),\n buttons: pointsList.buttons,\n insideElementPressed: updateGPoint.insideElementPressed,\n insideElementReleased: updateGPoint.insideElement,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n }\n\n return releaseCapture;\n }\n\n\n /**\n * Call when pointer(s) change coordinates, button state, pressure, tilt, or contact geometry (e.g. width and height)\n *\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersMove( tracker, event, gPoints ) {\n var delegate = THIS[ tracker.hash ],\n pointsList = tracker.getActivePointersListByType( gPoints[ 0 ].type ),\n i,\n gPointCount = gPoints.length,\n curGPoint,\n updateGPoint,\n gPointArray,\n delta,\n propagate;\n\n if ( typeof event.buttons !== 'undefined' ) {\n pointsList.buttons = event.buttons;\n }\n\n for ( i = 0; i < gPointCount; i++ ) {\n curGPoint = gPoints[ i ];\n updateGPoint = pointsList.getById( curGPoint.id );\n\n if ( updateGPoint ) {\n // Already tracking the pointer...update it\n if ( curGPoint.hasOwnProperty( 'isPrimary' ) ) {\n updateGPoint.isPrimary = curGPoint.isPrimary;\n }\n updateGPoint.lastPos = updateGPoint.currentPos;\n updateGPoint.lastTime = updateGPoint.currentTime;\n updateGPoint.currentPos = curGPoint.currentPos;\n updateGPoint.currentTime = curGPoint.currentTime;\n } else {\n // Initialize for tracking and add to the tracking list (no pointerover or pointerdown event occurred before this)\n curGPoint.captured = false;\n curGPoint.insideElementPressed = false;\n curGPoint.insideElement = true;\n startTrackingPointer( pointsList, curGPoint );\n }\n }\n\n // Stop (mouse only)\n if ( tracker.stopHandler && gPoints[ 0 ].type === 'mouse' ) {\n clearTimeout( tracker.stopTimeOut );\n tracker.stopTimeOut = setTimeout( function() {\n handlePointerStop( tracker, event, gPoints[ 0 ].type );\n }, tracker.stopDelay );\n }\n\n if ( pointsList.contacts === 0 ) {\n // Move (no contacts: hovering mouse or other hover-capable device)\n if ( tracker.moveHandler ) {\n propagate = tracker.moveHandler(\n {\n eventSource: tracker,\n pointerType: gPoints[ 0 ].type,\n position: getPointRelativeToAbsolute( gPoints[ 0 ].currentPos, tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: gPoints[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n } else if ( pointsList.contacts === 1 ) {\n // Move (1 contact)\n if ( tracker.moveHandler ) {\n updateGPoint = pointsList.asArray()[ 0 ];\n propagate = tracker.moveHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Drag\n if ( tracker.dragHandler ) {\n updateGPoint = pointsList.asArray()[ 0 ];\n delta = updateGPoint.currentPos.minus( updateGPoint.lastPos );\n propagate = tracker.dragHandler(\n {\n eventSource: tracker,\n pointerType: updateGPoint.type,\n position: getPointRelativeToAbsolute( updateGPoint.currentPos, tracker.element ),\n buttons: pointsList.buttons,\n delta: delta,\n speed: updateGPoint.speed,\n direction: updateGPoint.direction,\n shift: event.shiftKey,\n isTouchEvent: updateGPoint.type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n } else if ( pointsList.contacts === 2 ) {\n // Move (2 contacts, use center)\n if ( tracker.moveHandler ) {\n gPointArray = pointsList.asArray();\n propagate = tracker.moveHandler(\n {\n eventSource: tracker,\n pointerType: gPointArray[ 0 ].type,\n position: getPointRelativeToAbsolute( getCenterPoint( gPointArray[ 0 ].currentPos, gPointArray[ 1 ].currentPos ), tracker.element ),\n buttons: pointsList.buttons,\n isTouchEvent: gPointArray[ 0 ].type === 'touch',\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n\n // Pinch\n if ( tracker.pinchHandler && gPoints[ 0 ].type === 'touch' ) {\n delta = delegate.pinchGPoints[ 0 ].currentPos.distanceTo( delegate.pinchGPoints[ 1 ].currentPos );\n if ( delta != delegate.currentPinchDist ) {\n delegate.lastPinchDist = delegate.currentPinchDist;\n delegate.currentPinchDist = delta;\n delegate.lastPinchCenter = delegate.currentPinchCenter;\n delegate.currentPinchCenter = getCenterPoint( delegate.pinchGPoints[ 0 ].currentPos, delegate.pinchGPoints[ 1 ].currentPos );\n propagate = tracker.pinchHandler(\n {\n eventSource: tracker,\n pointerType: 'touch',\n gesturePoints: delegate.pinchGPoints,\n lastCenter: getPointRelativeToAbsolute( delegate.lastPinchCenter, tracker.element ),\n center: getPointRelativeToAbsolute( delegate.currentPinchCenter, tracker.element ),\n lastDistance: delegate.lastPinchDist,\n distance: delegate.currentPinchDist,\n shift: event.shiftKey,\n originalEvent: event,\n preventDefaultAction: false,\n userData: tracker.userData\n }\n );\n if ( propagate === false ) {\n $.cancelEvent( event );\n }\n }\n }\n }\n }\n\n\n /**\n * @function\n * @private\n * @inner\n * @param {OpenSeadragon.MouseTracker} tracker\n * A reference to the MouseTracker instance.\n * @param {Object} event\n * A reference to the originating DOM event.\n * @param {Array.} gPoints\n * Gesture points associated with the event.\n */\n function updatePointersCancel( tracker, event, gPoints ) {\n updatePointersUp( tracker, event, gPoints, 0 );\n updatePointersExit( tracker, event, gPoints );\n }\n\n\n /**\n * @private\n * @inner\n */\n function handlePointerStop( tracker, originalMoveEvent, pointerType ) {\n if ( tracker.stopHandler ) {\n tracker.stopHandler( {\n eventSource: tracker,\n pointerType: pointerType,\n position: getMouseRelative( originalMoveEvent, tracker.element ),\n buttons: tracker.getActivePointersListByType( pointerType ).buttons,\n isTouchEvent: pointerType === 'touch',\n originalEvent: originalMoveEvent,\n preventDefaultAction: false,\n userData: tracker.userData\n } );\n }\n }\n\n /**\n * True if inside an iframe, otherwise false.\n * @member {Boolean} isInIframe\n * @private\n * @inner\n */\n var isInIframe = (function() {\n try {\n return window.self !== window.top;\n } catch (e) {\n return true;\n }\n })();\n\n /**\n * @function\n * @private\n * @inner\n * @returns {Boolean} True if the target has access rights to events, otherwise false.\n */\n function canAccessEvents (target) {\n try {\n return target.addEventListener && target.removeEventListener;\n } catch (e) {\n return false;\n }\n }\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Control\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * An enumeration of supported locations where controls can be anchored.\n * The anchoring is always relative to the container.\n * @member ControlAnchor\n * @memberof OpenSeadragon\n * @static\n * @type {Object}\n * @property {Number} NONE\n * @property {Number} TOP_LEFT\n * @property {Number} TOP_RIGHT\n * @property {Number} BOTTOM_LEFT\n * @property {Number} BOTTOM_RIGHT\n * @property {Number} ABSOLUTE\n */\n$.ControlAnchor = {\n NONE: 0,\n TOP_LEFT: 1,\n TOP_RIGHT: 2,\n BOTTOM_RIGHT: 3,\n BOTTOM_LEFT: 4,\n ABSOLUTE: 5\n};\n\n/**\n * @class Control\n * @classdesc A Control represents any interface element which is meant to allow the user\n * to interact with the zoomable interface. Any control can be anchored to any\n * element.\n *\n * @memberof OpenSeadragon\n * @param {Element} element - the control element to be anchored in the container.\n * @param {Object } options - All required and optional settings for configuring a control element.\n * @param {OpenSeadragon.ControlAnchor} [options.anchor=OpenSeadragon.ControlAnchor.NONE] - the position of the control\n * relative to the container.\n * @param {Boolean} [options.attachToViewer=true] - Whether the control should be added directly to the viewer, or\n * directly to the container\n * @param {Boolean} [options.autoFade=true] - Whether the control should have the autofade behavior\n * @param {Element} container - the element to control will be anchored too.\n */\n$.Control = function ( element, options, container ) {\n var parent = element.parentNode;\n if (typeof options === 'number')\n {\n $.console.error(\"Passing an anchor directly into the OpenSeadragon.Control constructor is deprecated; \" +\n \"please use an options object instead. \" +\n \"Support for this deprecated variant is scheduled for removal in December 2013\");\n options = {anchor: options};\n }\n options.attachToViewer = (typeof options.attachToViewer === 'undefined') ? true : options.attachToViewer;\n /**\n * True if the control should have autofade behavior.\n * @member {Boolean} autoFade\n * @memberof OpenSeadragon.Control#\n */\n this.autoFade = (typeof options.autoFade === 'undefined') ? true : options.autoFade;\n /**\n * The element providing the user interface with some type of control (e.g. a zoom-in button).\n * @member {Element} element\n * @memberof OpenSeadragon.Control#\n */\n this.element = element;\n /**\n * The position of the Control relative to its container.\n * @member {OpenSeadragon.ControlAnchor} anchor\n * @memberof OpenSeadragon.Control#\n */\n this.anchor = options.anchor;\n /**\n * The Control's containing element.\n * @member {Element} container\n * @memberof OpenSeadragon.Control#\n */\n this.container = container;\n /**\n * A neutral element surrounding the control element.\n * @member {Element} wrapper\n * @memberof OpenSeadragon.Control#\n */\n if ( this.anchor == $.ControlAnchor.ABSOLUTE ) {\n this.wrapper = $.makeNeutralElement( \"div\" );\n this.wrapper.style.position = \"absolute\";\n this.wrapper.style.top = typeof (options.top) == \"number\" ? (options.top + 'px') : options.top;\n this.wrapper.style.left = typeof (options.left) == \"number\" ? (options.left + 'px') : options.left;\n this.wrapper.style.height = typeof (options.height) == \"number\" ? (options.height + 'px') : options.height;\n this.wrapper.style.width = typeof (options.width) == \"number\" ? (options.width + 'px') : options.width;\n this.wrapper.style.margin = \"0px\";\n this.wrapper.style.padding = \"0px\";\n\n this.element.style.position = \"relative\";\n this.element.style.top = \"0px\";\n this.element.style.left = \"0px\";\n this.element.style.height = \"100%\";\n this.element.style.width = \"100%\";\n } else {\n this.wrapper = $.makeNeutralElement( \"div\" );\n this.wrapper.style.display = \"inline-block\";\n if ( this.anchor == $.ControlAnchor.NONE ) {\n // IE6 fix\n this.wrapper.style.width = this.wrapper.style.height = \"100%\";\n }\n }\n this.wrapper.appendChild( this.element );\n\n if (options.attachToViewer ) {\n if ( this.anchor == $.ControlAnchor.TOP_RIGHT ||\n this.anchor == $.ControlAnchor.BOTTOM_RIGHT ) {\n this.container.insertBefore(\n this.wrapper,\n this.container.firstChild\n );\n } else {\n this.container.appendChild( this.wrapper );\n }\n } else {\n parent.appendChild( this.wrapper );\n }\n};\n\n/** @lends OpenSeadragon.Control.prototype */\n$.Control.prototype = {\n\n /**\n * Removes the control from the container.\n * @function\n */\n destroy: function() {\n this.wrapper.removeChild( this.element );\n this.container.removeChild( this.wrapper );\n },\n\n /**\n * Determines if the control is currently visible.\n * @function\n * @return {Boolean} true if currenly visible, false otherwise.\n */\n isVisible: function() {\n return this.wrapper.style.display != \"none\";\n },\n\n /**\n * Toggles the visibility of the control.\n * @function\n * @param {Boolean} visible - true to make visible, false to hide.\n */\n setVisible: function( visible ) {\n this.wrapper.style.display = visible ?\n ( this.anchor == $.ControlAnchor.ABSOLUTE ? 'block' : 'inline-block' ) :\n \"none\";\n },\n\n /**\n * Sets the opacity level for the control.\n * @function\n * @param {Number} opactiy - a value between 1 and 0 inclusively.\n */\n setOpacity: function( opacity ) {\n if ( this.element[ $.SIGNAL ] && $.Browser.vendor == $.BROWSERS.IE ) {\n $.setElementOpacity( this.element, opacity, true );\n } else {\n $.setElementOpacity( this.wrapper, opacity, true );\n }\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ControlDock\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n /**\n * @class ControlDock\n * @classdesc Provides a container element (a <form> element) with support for the layout of control elements.\n *\n * @memberof OpenSeadragon\n */\n $.ControlDock = function( options ){\n var layouts = [ 'topleft', 'topright', 'bottomright', 'bottomleft'],\n layout,\n i;\n\n $.extend( true, this, {\n id: 'controldock-' + $.now() + '-' + Math.floor(Math.random() * 1000000),\n container: $.makeNeutralElement( 'div' ),\n controls: []\n }, options );\n\n // Disable the form's submit; otherwise button clicks and return keys\n // can trigger it.\n this.container.onsubmit = function() {\n return false;\n };\n\n if( this.element ){\n this.element = $.getElement( this.element );\n this.element.appendChild( this.container );\n this.element.style.position = 'relative';\n this.container.style.width = '100%';\n this.container.style.height = '100%';\n }\n\n for( i = 0; i < layouts.length; i++ ){\n layout = layouts[ i ];\n this.controls[ layout ] = $.makeNeutralElement( \"div\" );\n this.controls[ layout ].style.position = 'absolute';\n if ( layout.match( 'left' ) ){\n this.controls[ layout ].style.left = '0px';\n }\n if ( layout.match( 'right' ) ){\n this.controls[ layout ].style.right = '0px';\n }\n if ( layout.match( 'top' ) ){\n this.controls[ layout ].style.top = '0px';\n }\n if ( layout.match( 'bottom' ) ){\n this.controls[ layout ].style.bottom = '0px';\n }\n }\n\n this.container.appendChild( this.controls.topleft );\n this.container.appendChild( this.controls.topright );\n this.container.appendChild( this.controls.bottomright );\n this.container.appendChild( this.controls.bottomleft );\n };\n\n /** @lends OpenSeadragon.ControlDock.prototype */\n $.ControlDock.prototype = {\n\n /**\n * @function\n */\n addControl: function ( element, controlOptions ) {\n element = $.getElement( element );\n var div = null;\n\n if ( getControlIndex( this, element ) >= 0 ) {\n return; // they're trying to add a duplicate control\n }\n\n switch ( controlOptions.anchor ) {\n case $.ControlAnchor.TOP_RIGHT:\n div = this.controls.topright;\n element.style.position = \"relative\";\n element.style.paddingRight = \"0px\";\n element.style.paddingTop = \"0px\";\n break;\n case $.ControlAnchor.BOTTOM_RIGHT:\n div = this.controls.bottomright;\n element.style.position = \"relative\";\n element.style.paddingRight = \"0px\";\n element.style.paddingBottom = \"0px\";\n break;\n case $.ControlAnchor.BOTTOM_LEFT:\n div = this.controls.bottomleft;\n element.style.position = \"relative\";\n element.style.paddingLeft = \"0px\";\n element.style.paddingBottom = \"0px\";\n break;\n case $.ControlAnchor.TOP_LEFT:\n div = this.controls.topleft;\n element.style.position = \"relative\";\n element.style.paddingLeft = \"0px\";\n element.style.paddingTop = \"0px\";\n break;\n case $.ControlAnchor.ABSOLUTE:\n div = this.container;\n element.style.margin = \"0px\";\n element.style.padding = \"0px\";\n break;\n default:\n case $.ControlAnchor.NONE:\n div = this.container;\n element.style.margin = \"0px\";\n element.style.padding = \"0px\";\n break;\n }\n\n this.controls.push(\n new $.Control( element, controlOptions, div )\n );\n element.style.display = \"inline-block\";\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.ControlDock} Chainable.\n */\n removeControl: function ( element ) {\n element = $.getElement( element );\n var i = getControlIndex( this, element );\n\n if ( i >= 0 ) {\n this.controls[ i ].destroy();\n this.controls.splice( i, 1 );\n }\n\n return this;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.ControlDock} Chainable.\n */\n clearControls: function () {\n while ( this.controls.length > 0 ) {\n this.controls.pop().destroy();\n }\n\n return this;\n },\n\n\n /**\n * @function\n * @return {Boolean}\n */\n areControlsEnabled: function () {\n var i;\n\n for ( i = this.controls.length - 1; i >= 0; i-- ) {\n if ( this.controls[ i ].isVisible() ) {\n return true;\n }\n }\n\n return false;\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.ControlDock} Chainable.\n */\n setControlsEnabled: function( enabled ) {\n var i;\n\n for ( i = this.controls.length - 1; i >= 0; i-- ) {\n this.controls[ i ].setVisible( enabled );\n }\n\n return this;\n }\n\n };\n\n\n ///////////////////////////////////////////////////////////////////////////////\n // Utility methods\n ///////////////////////////////////////////////////////////////////////////////\n function getControlIndex( dock, element ) {\n var controls = dock.controls,\n i;\n\n for ( i = controls.length - 1; i >= 0; i-- ) {\n if ( controls[ i ].element == element ) {\n return i;\n }\n }\n\n return -1;\n }\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Placement\n *\n * Copyright (C) 2010-2016 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n /**\n * An enumeration of positions to anchor an element.\n * @member Placement\n * @memberOf OpenSeadragon\n * @static\n * @readonly\n * @property {OpenSeadragon.Placement} CENTER\n * @property {OpenSeadragon.Placement} TOP_LEFT\n * @property {OpenSeadragon.Placement} TOP\n * @property {OpenSeadragon.Placement} TOP_RIGHT\n * @property {OpenSeadragon.Placement} RIGHT\n * @property {OpenSeadragon.Placement} BOTTOM_RIGHT\n * @property {OpenSeadragon.Placement} BOTTOM\n * @property {OpenSeadragon.Placement} BOTTOM_LEFT\n * @property {OpenSeadragon.Placement} LEFT\n */\n $.Placement = $.freezeObject({\n CENTER: 0,\n TOP_LEFT: 1,\n TOP: 2,\n TOP_RIGHT: 3,\n RIGHT: 4,\n BOTTOM_RIGHT: 5,\n BOTTOM: 6,\n BOTTOM_LEFT: 7,\n LEFT: 8,\n properties: {\n 0: {\n isLeft: false,\n isHorizontallyCentered: true,\n isRight: false,\n isTop: false,\n isVerticallyCentered: true,\n isBottom: false\n },\n 1: {\n isLeft: true,\n isHorizontallyCentered: false,\n isRight: false,\n isTop: true,\n isVerticallyCentered: false,\n isBottom: false\n },\n 2: {\n isLeft: false,\n isHorizontallyCentered: true,\n isRight: false,\n isTop: true,\n isVerticallyCentered: false,\n isBottom: false\n },\n 3: {\n isLeft: false,\n isHorizontallyCentered: false,\n isRight: true,\n isTop: true,\n isVerticallyCentered: false,\n isBottom: false\n },\n 4: {\n isLeft: false,\n isHorizontallyCentered: false,\n isRight: true,\n isTop: false,\n isVerticallyCentered: true,\n isBottom: false\n },\n 5: {\n isLeft: false,\n isHorizontallyCentered: false,\n isRight: true,\n isTop: false,\n isVerticallyCentered: false,\n isBottom: true\n },\n 6: {\n isLeft: false,\n isHorizontallyCentered: true,\n isRight: false,\n isTop: false,\n isVerticallyCentered: false,\n isBottom: true\n },\n 7: {\n isLeft: true,\n isHorizontallyCentered: false,\n isRight: false,\n isTop: false,\n isVerticallyCentered: false,\n isBottom: true\n },\n 8: {\n isLeft: true,\n isHorizontallyCentered: false,\n isRight: false,\n isTop: false,\n isVerticallyCentered: true,\n isBottom: false\n }\n }\n });\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Viewer\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n// dictionary from hash to private properties\nvar THIS = {};\nvar nextHash = 1;\n\n/**\n *\n * The main point of entry into creating a zoomable image on the page.
\n *
\n * We have provided an idiomatic javascript constructor which takes\n * a single object, but still support the legacy positional arguments.
\n *
\n * The options below are given in order that they appeared in the constructor\n * as arguments and we translate a positional call into an idiomatic call.
\n *
\n * To create a viewer, you can use either of this methods:
\n *
    \n *
  • var viewer = new OpenSeadragon.Viewer(options);
  • \n *
  • var viewer = OpenSeadragon(options);
  • \n *
\n * @class Viewer\n * @classdesc The main OpenSeadragon viewer class.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @extends OpenSeadragon.ControlDock\n * @param {OpenSeadragon.Options} options - Viewer options.\n *\n **/\n$.Viewer = function( options ) {\n\n var args = arguments,\n _this = this,\n i;\n\n\n //backward compatibility for positional args while prefering more\n //idiomatic javascript options object as the only argument\n if( !$.isPlainObject( options ) ){\n options = {\n id: args[ 0 ],\n xmlPath: args.length > 1 ? args[ 1 ] : undefined,\n prefixUrl: args.length > 2 ? args[ 2 ] : undefined,\n controls: args.length > 3 ? args[ 3 ] : undefined,\n overlays: args.length > 4 ? args[ 4 ] : undefined\n };\n }\n\n //options.config and the general config argument are deprecated\n //in favor of the more direct specification of optional settings\n //being pass directly on the options object\n if ( options.config ){\n $.extend( true, options, options.config );\n delete options.config;\n }\n\n //Public properties\n //Allow the options object to override global defaults\n $.extend( true, this, {\n\n //internal state and dom identifiers\n id: options.id,\n hash: options.hash || nextHash++,\n /**\n * Index for page to be shown first next time open() is called (only used in sequenceMode).\n * @member {Number} initialPage\n * @memberof OpenSeadragon.Viewer#\n */\n initialPage: 0,\n\n //dom nodes\n /**\n * The parent element of this Viewer instance, passed in when the Viewer was created.\n * @member {Element} element\n * @memberof OpenSeadragon.Viewer#\n */\n element: null,\n /**\n * A <div> element (provided by {@link OpenSeadragon.ControlDock}), the base element of this Viewer instance.

\n * Child element of {@link OpenSeadragon.Viewer#element}.\n * @member {Element} container\n * @memberof OpenSeadragon.Viewer#\n */\n container: null,\n /**\n * A <div> element, the element where user-input events are handled for panning and zooming.

\n * Child element of {@link OpenSeadragon.Viewer#container},\n * positioned on top of {@link OpenSeadragon.Viewer#keyboardCommandArea}.

\n * The parent of {@link OpenSeadragon.Drawer#canvas} instances.\n * @member {Element} canvas\n * @memberof OpenSeadragon.Viewer#\n */\n canvas: null,\n\n // Overlays list. An overlay allows to add html on top of the viewer.\n overlays: [],\n // Container inside the canvas where overlays are drawn.\n overlaysContainer: null,\n\n //private state properties\n previousBody: [],\n\n //This was originally initialized in the constructor and so could never\n //have anything in it. now it can because we allow it to be specified\n //in the options and is only empty by default if not specified. Also\n //this array was returned from get_controls which I find confusing\n //since this object has a controls property which is treated in other\n //functions like clearControls. I'm removing the accessors.\n customControls: [],\n\n //These are originally not part options but declared as members\n //in initialize. It's still considered idiomatic to put them here\n source: null,\n /**\n * Handles rendering of tiles in the viewer. Created for each TileSource opened.\n * @member {OpenSeadragon.Drawer} drawer\n * @memberof OpenSeadragon.Viewer#\n */\n drawer: null,\n world: null,\n /**\n * Handles coordinate-related functionality - zoom, pan, rotation, etc. Created for each TileSource opened.\n * @member {OpenSeadragon.Viewport} viewport\n * @memberof OpenSeadragon.Viewer#\n */\n viewport: null,\n /**\n * @member {OpenSeadragon.Navigator} navigator\n * @memberof OpenSeadragon.Viewer#\n */\n navigator: null,\n\n //A collection viewport is a separate viewport used to provide\n //simultaneous rendering of sets of tiles\n collectionViewport: null,\n collectionDrawer: null,\n\n //UI image resources\n //TODO: rename navImages to uiImages\n navImages: null,\n\n //interface button controls\n buttons: null,\n\n //TODO: this is defunct so safely remove it\n profiler: null\n\n }, $.DEFAULT_SETTINGS, options );\n\n if ( typeof ( this.hash) === \"undefined\" ) {\n throw new Error(\"A hash must be defined, either by specifying options.id or options.hash.\");\n }\n if ( typeof ( THIS[ this.hash ] ) !== \"undefined\" ) {\n // We don't want to throw an error here, as the user might have discarded\n // the previous viewer with the same hash and now want to recreate it.\n $.console.warn(\"Hash \" + this.hash + \" has already been used.\");\n }\n\n //Private state properties\n THIS[ this.hash ] = {\n \"fsBoundsDelta\": new $.Point( 1, 1 ),\n \"prevContainerSize\": null,\n \"animating\": false,\n \"forceRedraw\": false,\n \"mouseInside\": false,\n \"group\": null,\n // whether we should be continuously zooming\n \"zooming\": false,\n // how much we should be continuously zooming by\n \"zoomFactor\": null,\n \"lastZoomTime\": null,\n \"fullPage\": false,\n \"onfullscreenchange\": null\n };\n\n this._sequenceIndex = 0;\n this._firstOpen = true;\n this._updateRequestId = null;\n this._loadQueue = [];\n this.currentOverlays = [];\n\n this._lastScrollTime = $.now(); // variable used to help normalize the scroll event speed of different devices\n\n //Inherit some behaviors and properties\n $.EventSource.call( this );\n\n this.addHandler( 'open-failed', function ( event ) {\n var msg = $.getString( \"Errors.OpenFailed\", event.eventSource, event.message);\n _this._showMessage( msg );\n });\n\n $.ControlDock.call( this, options );\n\n //Deal with tile sources\n if (this.xmlPath) {\n //Deprecated option. Now it is preferred to use the tileSources option\n this.tileSources = [ this.xmlPath ];\n }\n\n this.element = this.element || document.getElementById( this.id );\n this.canvas = $.makeNeutralElement( \"div\" );\n\n this.canvas.className = \"openseadragon-canvas\";\n (function( style ){\n style.width = \"100%\";\n style.height = \"100%\";\n style.overflow = \"hidden\";\n style.position = \"absolute\";\n style.top = \"0px\";\n style.left = \"0px\";\n }(this.canvas.style));\n $.setElementTouchActionNone( this.canvas );\n if (options.tabIndex !== \"\") {\n this.canvas.tabIndex = (options.tabIndex === undefined ? 0 : options.tabIndex);\n }\n\n //the container is created through applying the ControlDock constructor above\n this.container.className = \"openseadragon-container\";\n (function( style ){\n style.width = \"100%\";\n style.height = \"100%\";\n style.position = \"relative\";\n style.overflow = \"hidden\";\n style.left = \"0px\";\n style.top = \"0px\";\n style.textAlign = \"left\"; // needed to protect against\n }( this.container.style ));\n\n this.container.insertBefore( this.canvas, this.container.firstChild );\n this.element.appendChild( this.container );\n\n //Used for toggling between fullscreen and default container size\n //TODO: these can be closure private and shared across Viewer\n // instances.\n this.bodyWidth = document.body.style.width;\n this.bodyHeight = document.body.style.height;\n this.bodyOverflow = document.body.style.overflow;\n this.docOverflow = document.documentElement.style.overflow;\n\n this.innerTracker = new $.MouseTracker({\n element: this.canvas,\n startDisabled: !this.mouseNavEnabled,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n dblClickTimeThreshold: this.dblClickTimeThreshold,\n dblClickDistThreshold: this.dblClickDistThreshold,\n keyDownHandler: $.delegate( this, onCanvasKeyDown ),\n keyHandler: $.delegate( this, onCanvasKeyPress ),\n clickHandler: $.delegate( this, onCanvasClick ),\n dblClickHandler: $.delegate( this, onCanvasDblClick ),\n dragHandler: $.delegate( this, onCanvasDrag ),\n dragEndHandler: $.delegate( this, onCanvasDragEnd ),\n enterHandler: $.delegate( this, onCanvasEnter ),\n exitHandler: $.delegate( this, onCanvasExit ),\n pressHandler: $.delegate( this, onCanvasPress ),\n releaseHandler: $.delegate( this, onCanvasRelease ),\n nonPrimaryPressHandler: $.delegate( this, onCanvasNonPrimaryPress ),\n nonPrimaryReleaseHandler: $.delegate( this, onCanvasNonPrimaryRelease ),\n scrollHandler: $.delegate( this, onCanvasScroll ),\n pinchHandler: $.delegate( this, onCanvasPinch )\n });\n\n this.outerTracker = new $.MouseTracker({\n element: this.container,\n startDisabled: !this.mouseNavEnabled,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n dblClickTimeThreshold: this.dblClickTimeThreshold,\n dblClickDistThreshold: this.dblClickDistThreshold,\n enterHandler: $.delegate( this, onContainerEnter ),\n exitHandler: $.delegate( this, onContainerExit )\n });\n\n if( this.toolbar ){\n this.toolbar = new $.ControlDock({ element: this.toolbar });\n }\n\n this.bindStandardControls();\n\n THIS[ this.hash ].prevContainerSize = _getSafeElemSize( this.container );\n\n // Create the world\n this.world = new $.World({\n viewer: this\n });\n\n this.world.addHandler('add-item', function(event) {\n // For backwards compatibility, we maintain the source property\n _this.source = _this.world.getItemAt(0).source;\n\n THIS[ _this.hash ].forceRedraw = true;\n\n if (!_this._updateRequestId) {\n _this._updateRequestId = scheduleUpdate( _this, updateMulti );\n }\n });\n\n this.world.addHandler('remove-item', function(event) {\n // For backwards compatibility, we maintain the source property\n if (_this.world.getItemCount()) {\n _this.source = _this.world.getItemAt(0).source;\n } else {\n _this.source = null;\n }\n\n THIS[ _this.hash ].forceRedraw = true;\n });\n\n this.world.addHandler('metrics-change', function(event) {\n if (_this.viewport) {\n _this.viewport._setContentBounds(_this.world.getHomeBounds(), _this.world.getContentFactor());\n }\n });\n\n this.world.addHandler('item-index-change', function(event) {\n // For backwards compatibility, we maintain the source property\n _this.source = _this.world.getItemAt(0).source;\n });\n\n // Create the viewport\n this.viewport = new $.Viewport({\n containerSize: THIS[ this.hash ].prevContainerSize,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime,\n minZoomImageRatio: this.minZoomImageRatio,\n maxZoomPixelRatio: this.maxZoomPixelRatio,\n visibilityRatio: this.visibilityRatio,\n wrapHorizontal: this.wrapHorizontal,\n wrapVertical: this.wrapVertical,\n defaultZoomLevel: this.defaultZoomLevel,\n minZoomLevel: this.minZoomLevel,\n maxZoomLevel: this.maxZoomLevel,\n viewer: this,\n degrees: this.degrees,\n flipped: this.flipped,\n navigatorRotate: this.navigatorRotate,\n homeFillsViewer: this.homeFillsViewer,\n margins: this.viewportMargins\n });\n\n this.viewport._setContentBounds(this.world.getHomeBounds(), this.world.getContentFactor());\n\n // Create the image loader\n this.imageLoader = new $.ImageLoader({\n jobLimit: this.imageLoaderLimit,\n timeout: options.timeout\n });\n\n // Create the tile cache\n this.tileCache = new $.TileCache({\n maxImageCacheCount: this.maxImageCacheCount\n });\n\n // Create the drawer\n this.drawer = new $.Drawer({\n viewer: this,\n viewport: this.viewport,\n element: this.canvas,\n debugGridColor: this.debugGridColor\n });\n\n // Overlay container\n this.overlaysContainer = $.makeNeutralElement( \"div\" );\n this.canvas.appendChild( this.overlaysContainer );\n\n // Now that we have a drawer, see if it supports rotate. If not we need to remove the rotate buttons\n if (!this.drawer.canRotate()) {\n // Disable/remove the rotate left/right buttons since they aren't supported\n if (this.rotateLeft) {\n i = this.buttons.buttons.indexOf(this.rotateLeft);\n this.buttons.buttons.splice(i, 1);\n this.buttons.element.removeChild(this.rotateLeft.element);\n }\n if (this.rotateRight) {\n i = this.buttons.buttons.indexOf(this.rotateRight);\n this.buttons.buttons.splice(i, 1);\n this.buttons.element.removeChild(this.rotateRight.element);\n }\n }\n\n //Instantiate a navigator if configured\n if ( this.showNavigator){\n this.navigator = new $.Navigator({\n id: this.navigatorId,\n position: this.navigatorPosition,\n sizeRatio: this.navigatorSizeRatio,\n maintainSizeRatio: this.navigatorMaintainSizeRatio,\n top: this.navigatorTop,\n left: this.navigatorLeft,\n width: this.navigatorWidth,\n height: this.navigatorHeight,\n autoResize: this.navigatorAutoResize,\n autoFade: this.navigatorAutoFade,\n prefixUrl: this.prefixUrl,\n viewer: this,\n navigatorRotate: this.navigatorRotate,\n crossOriginPolicy: this.crossOriginPolicy\n });\n }\n\n // Sequence mode\n if (this.sequenceMode) {\n this.bindSequenceControls();\n }\n\n // Open initial tilesources\n if (this.tileSources) {\n this.open( this.tileSources );\n }\n\n // Add custom controls\n for ( i = 0; i < this.customControls.length; i++ ) {\n this.addControl(\n this.customControls[ i ].id,\n {anchor: this.customControls[ i ].anchor}\n );\n }\n\n // Initial fade out\n $.requestAnimationFrame( function(){\n beginControlsAutoHide( _this );\n } );\n};\n\n$.extend( $.Viewer.prototype, $.EventSource.prototype, $.ControlDock.prototype, /** @lends OpenSeadragon.Viewer.prototype */{\n\n\n /**\n * @function\n * @return {Boolean}\n */\n isOpen: function () {\n return !!this.world.getItemCount();\n },\n\n // deprecated\n openDzi: function ( dzi ) {\n $.console.error( \"[Viewer.openDzi] this function is deprecated; use Viewer.open() instead.\" );\n return this.open( dzi );\n },\n\n // deprecated\n openTileSource: function ( tileSource ) {\n $.console.error( \"[Viewer.openTileSource] this function is deprecated; use Viewer.open() instead.\" );\n return this.open( tileSource );\n },\n\n /**\n * Open tiled images into the viewer, closing any others.\n * To get the TiledImage instance created by open, add an event listener for\n * {@link OpenSeadragon.Viewer.html#.event:open}, which when fired can be used to get access\n * to the instance, i.e., viewer.world.getItemAt(0).\n * @function\n * @param {Array|String|Object|Function} tileSources - This can be a TiledImage\n * specifier, a TileSource specifier, or an array of either. A TiledImage specifier\n * is the same as the options parameter for {@link OpenSeadragon.Viewer#addTiledImage},\n * except for the index property; images are added in sequence.\n * A TileSource specifier is anything you could pass as the tileSource property\n * of the options parameter for {@link OpenSeadragon.Viewer#addTiledImage}.\n * @param {Number} initialPage - If sequenceMode is true, display this page initially\n * for the given tileSources. If specified, will overwrite the Viewer's existing initialPage property.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:open\n * @fires OpenSeadragon.Viewer.event:open-failed\n */\n open: function (tileSources, initialPage) {\n var _this = this;\n\n this.close();\n\n if (!tileSources) {\n return;\n }\n\n if (this.sequenceMode && $.isArray(tileSources)) {\n if (this.referenceStrip) {\n this.referenceStrip.destroy();\n this.referenceStrip = null;\n }\n\n if (typeof initialPage != 'undefined' && !isNaN(initialPage)) {\n this.initialPage = initialPage;\n }\n\n this.tileSources = tileSources;\n this._sequenceIndex = Math.max(0, Math.min(this.tileSources.length - 1, this.initialPage));\n if (this.tileSources.length) {\n this.open(this.tileSources[this._sequenceIndex]);\n\n if ( this.showReferenceStrip ){\n this.addReferenceStrip();\n }\n }\n\n this._updateSequenceButtons( this._sequenceIndex );\n return;\n }\n\n if (!$.isArray(tileSources)) {\n tileSources = [tileSources];\n }\n\n if (!tileSources.length) {\n return;\n }\n\n this._opening = true;\n\n var expected = tileSources.length;\n var successes = 0;\n var failures = 0;\n var failEvent;\n\n var checkCompletion = function() {\n if (successes + failures === expected) {\n if (successes) {\n if (_this._firstOpen || !_this.preserveViewport) {\n _this.viewport.goHome( true );\n _this.viewport.update();\n }\n\n _this._firstOpen = false;\n\n var source = tileSources[0];\n if (source.tileSource) {\n source = source.tileSource;\n }\n\n // Global overlays\n if( _this.overlays && !_this.preserveOverlays ){\n for ( var i = 0; i < _this.overlays.length; i++ ) {\n _this.currentOverlays[ i ] = getOverlayObject( _this, _this.overlays[ i ] );\n }\n }\n\n _this._drawOverlays();\n _this._opening = false;\n\n /**\n * Raised when the viewer has opened and loaded one or more TileSources.\n *\n * @event open\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TileSource} source - The tile source that was opened.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n // TODO: what if there are multiple sources?\n _this.raiseEvent( 'open', { source: source } );\n } else {\n _this._opening = false;\n\n /**\n * Raised when an error occurs loading a TileSource.\n *\n * @event open-failed\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {String} message - Information about what failed.\n * @property {String} source - The tile source that failed.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'open-failed', failEvent );\n }\n }\n };\n\n var doOne = function(options) {\n if (!$.isPlainObject(options) || !options.tileSource) {\n options = {\n tileSource: options\n };\n }\n\n if (options.index !== undefined) {\n $.console.error('[Viewer.open] setting indexes here is not supported; use addTiledImage instead');\n delete options.index;\n }\n\n if (options.collectionImmediately === undefined) {\n options.collectionImmediately = true;\n }\n\n var originalSuccess = options.success;\n options.success = function(event) {\n successes++;\n\n // TODO: now that options has other things besides tileSource, the overlays\n // should probably be at the options level, not the tileSource level.\n if (options.tileSource.overlays) {\n for (var i = 0; i < options.tileSource.overlays.length; i++) {\n _this.addOverlay(options.tileSource.overlays[i]);\n }\n }\n\n if (originalSuccess) {\n originalSuccess(event);\n }\n\n checkCompletion();\n };\n\n var originalError = options.error;\n options.error = function(event) {\n failures++;\n\n if (!failEvent) {\n failEvent = event;\n }\n\n if (originalError) {\n originalError(event);\n }\n\n checkCompletion();\n };\n\n _this.addTiledImage(options);\n };\n\n // TileSources\n for (var i = 0; i < tileSources.length; i++) {\n doOne(tileSources[i]);\n }\n\n return this;\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:close\n */\n close: function ( ) {\n if ( !THIS[ this.hash ] ) {\n //this viewer has already been destroyed: returning immediately\n return this;\n }\n\n this._opening = false;\n\n if ( this.navigator ) {\n this.navigator.close();\n }\n\n if (!this.preserveOverlays) {\n this.clearOverlays();\n this.overlaysContainer.innerHTML = \"\";\n }\n\n THIS[ this.hash ].animating = false;\n this.world.removeAll();\n this.imageLoader.clear();\n\n /**\n * Raised when the viewer is closed (see {@link OpenSeadragon.Viewer#close}).\n *\n * @event close\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'close' );\n\n return this;\n },\n\n\n /**\n * Function to destroy the viewer and clean up everything created by OpenSeadragon.\n *\n * Example:\n * var viewer = OpenSeadragon({\n * [...]\n * });\n *\n * //when you are done with the viewer:\n * viewer.destroy();\n * viewer = null; //important\n *\n * @function\n */\n destroy: function( ) {\n if ( !THIS[ this.hash ] ) {\n //this viewer has already been destroyed: returning immediately\n return;\n }\n\n this.close();\n\n this.clearOverlays();\n this.overlaysContainer.innerHTML = \"\";\n\n //TODO: implement this...\n //this.unbindSequenceControls()\n //this.unbindStandardControls()\n\n if (this.referenceStrip) {\n this.referenceStrip.destroy();\n this.referenceStrip = null;\n }\n\n if ( this._updateRequestId !== null ) {\n $.cancelAnimationFrame( this._updateRequestId );\n this._updateRequestId = null;\n }\n\n if ( this.drawer ) {\n this.drawer.destroy();\n }\n\n this.removeAllHandlers();\n\n // Go through top element (passed to us) and remove all children\n // Use removeChild to make sure it handles SVG or any non-html\n // also it performs better - http://jsperf.com/innerhtml-vs-removechild/15\n if (this.element){\n while (this.element.firstChild) {\n this.element.removeChild(this.element.firstChild);\n }\n }\n\n // destroy the mouse trackers\n if (this.innerTracker){\n this.innerTracker.destroy();\n }\n if (this.outerTracker){\n this.outerTracker.destroy();\n }\n\n THIS[ this.hash ] = null;\n delete THIS[ this.hash ];\n\n // clear all our references to dom objects\n this.canvas = null;\n this.container = null;\n\n // clear our reference to the main element - they will need to pass it in again, creating a new viewer\n this.element = null;\n },\n\n /**\n * @function\n * @return {Boolean}\n */\n isMouseNavEnabled: function () {\n return this.innerTracker.isTracking();\n },\n\n /**\n * @function\n * @param {Boolean} enabled - true to enable, false to disable\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:mouse-enabled\n */\n setMouseNavEnabled: function( enabled ){\n this.innerTracker.setTracking( enabled );\n this.outerTracker.setTracking( enabled );\n /**\n * Raised when mouse/touch navigation is enabled or disabled (see {@link OpenSeadragon.Viewer#setMouseNavEnabled}).\n *\n * @event mouse-enabled\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} enabled\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'mouse-enabled', { enabled: enabled } );\n return this;\n },\n\n\n /**\n * @function\n * @return {Boolean}\n */\n areControlsEnabled: function () {\n var enabled = this.controls.length,\n i;\n for( i = 0; i < this.controls.length; i++ ){\n enabled = enabled && this.controls[ i ].isVisibile();\n }\n return enabled;\n },\n\n\n /**\n * Shows or hides the controls (e.g. the default navigation buttons).\n *\n * @function\n * @param {Boolean} true to show, false to hide.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:controls-enabled\n */\n setControlsEnabled: function( enabled ) {\n if( enabled ){\n abortControlsAutoHide( this );\n } else {\n beginControlsAutoHide( this );\n }\n /**\n * Raised when the navigation controls are shown or hidden (see {@link OpenSeadragon.Viewer#setControlsEnabled}).\n *\n * @event controls-enabled\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} enabled\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'controls-enabled', { enabled: enabled } );\n return this;\n },\n\n /**\n * Turns debugging mode on or off for this viewer.\n *\n * @function\n * @param {Boolean} true to turn debug on, false to turn debug off.\n */\n setDebugMode: function(debugMode){\n\n for (var i = 0; i < this.world.getItemCount(); i++) {\n this.world.getItemAt(i).debugMode = debugMode;\n }\n\n this.debugMode = debugMode;\n this.forceRedraw();\n },\n\n /**\n * @function\n * @return {Boolean}\n */\n isFullPage: function () {\n return THIS[ this.hash ].fullPage;\n },\n\n\n /**\n * Toggle full page mode.\n * @function\n * @param {Boolean} fullPage\n * If true, enter full page mode. If false, exit full page mode.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:pre-full-page\n * @fires OpenSeadragon.Viewer.event:full-page\n */\n setFullPage: function( fullPage ) {\n\n var body = document.body,\n bodyStyle = body.style,\n docStyle = document.documentElement.style,\n _this = this,\n nodes,\n i;\n\n //dont bother modifying the DOM if we are already in full page mode.\n if ( fullPage == this.isFullPage() ) {\n return this;\n }\n\n var fullPageEventArgs = {\n fullPage: fullPage,\n preventDefaultAction: false\n };\n /**\n * Raised when the viewer is about to change to/from full-page mode (see {@link OpenSeadragon.Viewer#setFullPage}).\n *\n * @event pre-full-page\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullPage - True if entering full-page mode, false if exiting full-page mode.\n * @property {Boolean} preventDefaultAction - Set to true to prevent full-page mode change. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'pre-full-page', fullPageEventArgs );\n if ( fullPageEventArgs.preventDefaultAction ) {\n return this;\n }\n\n if ( fullPage ) {\n\n this.elementSize = $.getElementSize( this.element );\n this.pageScroll = $.getPageScroll();\n\n this.elementMargin = this.element.style.margin;\n this.element.style.margin = \"0\";\n this.elementPadding = this.element.style.padding;\n this.element.style.padding = \"0\";\n\n this.bodyMargin = bodyStyle.margin;\n this.docMargin = docStyle.margin;\n bodyStyle.margin = \"0\";\n docStyle.margin = \"0\";\n\n this.bodyPadding = bodyStyle.padding;\n this.docPadding = docStyle.padding;\n bodyStyle.padding = \"0\";\n docStyle.padding = \"0\";\n\n this.bodyWidth = bodyStyle.width;\n this.docWidth = docStyle.width;\n bodyStyle.width = \"100%\";\n docStyle.width = \"100%\";\n\n this.bodyHeight = bodyStyle.height;\n this.docHeight = docStyle.height;\n bodyStyle.height = \"100%\";\n docStyle.height = \"100%\";\n\n //when entering full screen on the ipad it wasnt sufficient to leave\n //the body intact as only only the top half of the screen would\n //respond to touch events on the canvas, while the bottom half treated\n //them as touch events on the document body. Thus we remove and store\n //the bodies elements and replace them when we leave full screen.\n this.previousBody = [];\n THIS[ this.hash ].prevElementParent = this.element.parentNode;\n THIS[ this.hash ].prevNextSibling = this.element.nextSibling;\n THIS[ this.hash ].prevElementWidth = this.element.style.width;\n THIS[ this.hash ].prevElementHeight = this.element.style.height;\n nodes = body.childNodes.length;\n for ( i = 0; i < nodes; i++ ) {\n this.previousBody.push( body.childNodes[ 0 ] );\n body.removeChild( body.childNodes[ 0 ] );\n }\n\n //If we've got a toolbar, we need to enable the user to use css to\n //preserve it in fullpage mode\n if ( this.toolbar && this.toolbar.element ) {\n //save a reference to the parent so we can put it back\n //in the long run we need a better strategy\n this.toolbar.parentNode = this.toolbar.element.parentNode;\n this.toolbar.nextSibling = this.toolbar.element.nextSibling;\n body.appendChild( this.toolbar.element );\n\n //Make sure the user has some ability to style the toolbar based\n //on the mode\n $.addClass( this.toolbar.element, 'fullpage' );\n }\n\n $.addClass( this.element, 'fullpage' );\n body.appendChild( this.element );\n\n this.element.style.height = $.getWindowSize().y + 'px';\n this.element.style.width = $.getWindowSize().x + 'px';\n\n if ( this.toolbar && this.toolbar.element ) {\n this.element.style.height = (\n $.getElementSize( this.element ).y - $.getElementSize( this.toolbar.element ).y\n ) + 'px';\n }\n\n THIS[ this.hash ].fullPage = true;\n\n // mouse will be inside container now\n $.delegate( this, onContainerEnter )( {} );\n\n } else {\n\n this.element.style.margin = this.elementMargin;\n this.element.style.padding = this.elementPadding;\n\n bodyStyle.margin = this.bodyMargin;\n docStyle.margin = this.docMargin;\n\n bodyStyle.padding = this.bodyPadding;\n docStyle.padding = this.docPadding;\n\n bodyStyle.width = this.bodyWidth;\n docStyle.width = this.docWidth;\n\n bodyStyle.height = this.bodyHeight;\n docStyle.height = this.docHeight;\n\n body.removeChild( this.element );\n nodes = this.previousBody.length;\n for ( i = 0; i < nodes; i++ ) {\n body.appendChild( this.previousBody.shift() );\n }\n\n $.removeClass( this.element, 'fullpage' );\n THIS[ this.hash ].prevElementParent.insertBefore(\n this.element,\n THIS[ this.hash ].prevNextSibling\n );\n\n //If we've got a toolbar, we need to enable the user to use css to\n //reset it to its original state\n if ( this.toolbar && this.toolbar.element ) {\n body.removeChild( this.toolbar.element );\n\n //Make sure the user has some ability to style the toolbar based\n //on the mode\n $.removeClass( this.toolbar.element, 'fullpage' );\n\n this.toolbar.parentNode.insertBefore(\n this.toolbar.element,\n this.toolbar.nextSibling\n );\n delete this.toolbar.parentNode;\n delete this.toolbar.nextSibling;\n }\n\n this.element.style.width = THIS[ this.hash ].prevElementWidth;\n this.element.style.height = THIS[ this.hash ].prevElementHeight;\n\n // After exiting fullPage or fullScreen, it can take some time\n // before the browser can actually set the scroll.\n var restoreScrollCounter = 0;\n var restoreScroll = function() {\n $.setPageScroll( _this.pageScroll );\n var pageScroll = $.getPageScroll();\n restoreScrollCounter++;\n if (restoreScrollCounter < 10 &&\n (pageScroll.x !== _this.pageScroll.x ||\n pageScroll.y !== _this.pageScroll.y)) {\n $.requestAnimationFrame( restoreScroll );\n }\n };\n $.requestAnimationFrame( restoreScroll );\n\n THIS[ this.hash ].fullPage = false;\n\n // mouse will likely be outside now\n $.delegate( this, onContainerExit )( { } );\n\n }\n\n if ( this.navigator && this.viewport ) {\n this.navigator.update( this.viewport );\n }\n\n /**\n * Raised when the viewer has changed to/from full-page mode (see {@link OpenSeadragon.Viewer#setFullPage}).\n *\n * @event full-page\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullPage - True if changed to full-page mode, false if exited full-page mode.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'full-page', { fullPage: fullPage } );\n\n return this;\n },\n\n /**\n * Toggle full screen mode if supported. Toggle full page mode otherwise.\n * @function\n * @param {Boolean} fullScreen\n * If true, enter full screen mode. If false, exit full screen mode.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:pre-full-screen\n * @fires OpenSeadragon.Viewer.event:full-screen\n */\n setFullScreen: function( fullScreen ) {\n var _this = this;\n\n if ( !$.supportsFullScreen ) {\n return this.setFullPage( fullScreen );\n }\n\n if ( $.isFullScreen() === fullScreen ) {\n return this;\n }\n\n var fullScreeEventArgs = {\n fullScreen: fullScreen,\n preventDefaultAction: false\n };\n /**\n * Raised when the viewer is about to change to/from full-screen mode (see {@link OpenSeadragon.Viewer#setFullScreen}).\n * Note: the pre-full-screen event is not raised when the user is exiting\n * full-screen mode by pressing the Esc key. In that case, consider using\n * the full-screen, pre-full-page or full-page events.\n *\n * @event pre-full-screen\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullScreen - True if entering full-screen mode, false if exiting full-screen mode.\n * @property {Boolean} preventDefaultAction - Set to true to prevent full-screen mode change. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'pre-full-screen', fullScreeEventArgs );\n if ( fullScreeEventArgs.preventDefaultAction ) {\n return this;\n }\n\n if ( fullScreen ) {\n\n this.setFullPage( true );\n // If the full page mode is not actually entered, we need to prevent\n // the full screen mode.\n if ( !this.isFullPage() ) {\n return this;\n }\n\n this.fullPageStyleWidth = this.element.style.width;\n this.fullPageStyleHeight = this.element.style.height;\n this.element.style.width = '100%';\n this.element.style.height = '100%';\n\n var onFullScreenChange = function() {\n var isFullScreen = $.isFullScreen();\n if ( !isFullScreen ) {\n $.removeEvent( document, $.fullScreenEventName, onFullScreenChange );\n $.removeEvent( document, $.fullScreenErrorEventName, onFullScreenChange );\n\n _this.setFullPage( false );\n if ( _this.isFullPage() ) {\n _this.element.style.width = _this.fullPageStyleWidth;\n _this.element.style.height = _this.fullPageStyleHeight;\n }\n }\n if ( _this.navigator && _this.viewport ) {\n _this.navigator.update( _this.viewport );\n }\n /**\n * Raised when the viewer has changed to/from full-screen mode (see {@link OpenSeadragon.Viewer#setFullScreen}).\n *\n * @event full-screen\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} fullScreen - True if changed to full-screen mode, false if exited full-screen mode.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'full-screen', { fullScreen: isFullScreen } );\n };\n $.addEvent( document, $.fullScreenEventName, onFullScreenChange );\n $.addEvent( document, $.fullScreenErrorEventName, onFullScreenChange );\n\n $.requestFullScreen( document.body );\n\n } else {\n $.exitFullScreen();\n }\n return this;\n },\n\n /**\n * @function\n * @return {Boolean}\n */\n isVisible: function () {\n return this.container.style.visibility != \"hidden\";\n },\n\n\n /**\n * @function\n * @param {Boolean} visible\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:visible\n */\n setVisible: function( visible ){\n this.container.style.visibility = visible ? \"\" : \"hidden\";\n /**\n * Raised when the viewer is shown or hidden (see {@link OpenSeadragon.Viewer#setVisible}).\n *\n * @event visible\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Boolean} visible\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'visible', { visible: visible } );\n return this;\n },\n\n /**\n * Add a tiled image to the viewer.\n * options.tileSource can be anything that {@link OpenSeadragon.Viewer#open}\n * supports except arrays of images.\n * Note that you can specify options.width or options.height, but not both.\n * The other dimension will be calculated according to the item's aspect ratio.\n * If collectionMode is on (see {@link OpenSeadragon.Options}), the new image is\n * automatically arranged with the others.\n * @function\n * @param {Object} options\n * @param {String|Object|Function} options.tileSource - The TileSource specifier.\n * A String implies a url used to determine the tileSource implementation\n * based on the file extension of url. JSONP is implied by *.js,\n * otherwise the url is retrieved as text and the resulting text is\n * introspected to determine if its json, xml, or text and parsed.\n * An Object implies an inline configuration which has a single\n * property sufficient for being able to determine tileSource\n * implementation. If the object has a property which is a function\n * named 'getTileUrl', it is treated as a custom TileSource.\n * @param {Number} [options.index] The index of the item. Added on top of\n * all other items if not specified.\n * @param {Boolean} [options.replace=false] If true, the item at options.index will be\n * removed and the new item is added in its place. options.tileSource will be\n * interpreted and fetched if necessary before the old item is removed to avoid leaving\n * a gap in the world.\n * @param {Number} [options.x=0] The X position for the image in viewport coordinates.\n * @param {Number} [options.y=0] The Y position for the image in viewport coordinates.\n * @param {Number} [options.width=1] The width for the image in viewport coordinates.\n * @param {Number} [options.height] The height for the image in viewport coordinates.\n * @param {OpenSeadragon.Rect} [options.fitBounds] The bounds in viewport coordinates\n * to fit the image into. If specified, x, y, width and height get ignored.\n * @param {OpenSeadragon.Placement} [options.fitBoundsPlacement=OpenSeadragon.Placement.CENTER]\n * How to anchor the image in the bounds if options.fitBounds is set.\n * @param {OpenSeadragon.Rect} [options.clip] - An area, in image pixels, to clip to\n * (portions of the image outside of this area will not be visible). Only works on\n * browsers that support the HTML5 canvas.\n * @param {Number} [options.opacity=1] Proportional opacity of the tiled images (1=opaque, 0=hidden)\n * @param {Boolean} [options.preload=false] Default switch for loading hidden images (true loads, false blocks)\n * @param {Number} [options.degrees=0] Initial rotation of the tiled image around\n * its top left corner in degrees.\n * @param {String} [options.compositeOperation] How the image is composited onto other images.\n * @param {String} [options.crossOriginPolicy] The crossOriginPolicy for this specific image,\n * overriding viewer.crossOriginPolicy.\n * @param {Boolean} [options.ajaxWithCredentials] Whether to set withCredentials on tile AJAX\n * @param {Boolean} [options.loadTilesWithAjax]\n * Whether to load tile data using AJAX requests.\n * Defaults to the setting in {@link OpenSeadragon.Options}.\n * @param {Object} [options.ajaxHeaders]\n * A set of headers to include when making tile AJAX requests.\n * Note that these headers will be merged over any headers specified in {@link OpenSeadragon.Options}.\n * Specifying a falsy value for a header will clear its existing value set at the Viewer level (if any).\n * requests.\n * @param {Function} [options.success] A function that gets called when the image is\n * successfully added. It's passed the event object which contains a single property:\n * \"item\", which is the resulting instance of TiledImage.\n * @param {Function} [options.error] A function that gets called if the image is\n * unable to be added. It's passed the error event object, which contains \"message\"\n * and \"source\" properties.\n * @param {Boolean} [options.collectionImmediately=false] If collectionMode is on,\n * specifies whether to snap to the new arrangement immediately or to animate to it.\n * @param {String|CanvasGradient|CanvasPattern|Function} [options.placeholderFillStyle] - See {@link OpenSeadragon.Options}.\n * @fires OpenSeadragon.World.event:add-item\n * @fires OpenSeadragon.Viewer.event:add-item-failed\n */\n addTiledImage: function( options ) {\n $.console.assert(options, \"[Viewer.addTiledImage] options is required\");\n $.console.assert(options.tileSource, \"[Viewer.addTiledImage] options.tileSource is required\");\n $.console.assert(!options.replace || (options.index > -1 && options.index < this.world.getItemCount()),\n \"[Viewer.addTiledImage] if options.replace is used, options.index must be a valid index in Viewer.world\");\n\n var _this = this;\n\n if (options.replace) {\n options.replaceItem = _this.world.getItemAt(options.index);\n }\n\n this._hideMessage();\n\n if (options.placeholderFillStyle === undefined) {\n options.placeholderFillStyle = this.placeholderFillStyle;\n }\n if (options.opacity === undefined) {\n options.opacity = this.opacity;\n }\n if (options.preload === undefined) {\n options.preload = this.preload;\n }\n if (options.compositeOperation === undefined) {\n options.compositeOperation = this.compositeOperation;\n }\n if (options.crossOriginPolicy === undefined) {\n options.crossOriginPolicy = options.tileSource.crossOriginPolicy !== undefined ? options.tileSource.crossOriginPolicy : this.crossOriginPolicy;\n }\n if (options.ajaxWithCredentials === undefined) {\n options.ajaxWithCredentials = this.ajaxWithCredentials;\n }\n if (options.makeAjaxRequest === undefined) {\n options.makeAjaxRequest = options.tileSource.makeAjaxRequest;\n }\n if (options.loadTilesWithAjax === undefined) {\n options.loadTilesWithAjax = this.loadTilesWithAjax;\n }\n if (options.ajaxHeaders === undefined || options.ajaxHeaders === null) {\n options.ajaxHeaders = this.ajaxHeaders;\n } else if ($.isPlainObject(options.ajaxHeaders) && $.isPlainObject(this.ajaxHeaders)) {\n options.ajaxHeaders = $.extend({}, this.ajaxHeaders, options.ajaxHeaders);\n }\n\n var myQueueItem = {\n options: options\n };\n\n function raiseAddItemFailed( event ) {\n for (var i = 0; i < _this._loadQueue.length; i++) {\n if (_this._loadQueue[i] === myQueueItem) {\n _this._loadQueue.splice(i, 1);\n break;\n }\n }\n\n if (_this._loadQueue.length === 0) {\n refreshWorld(myQueueItem);\n }\n\n /**\n * Raised when an error occurs while adding a item.\n * @event add-item-failed\n * @memberOf OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {String} message\n * @property {String} source\n * @property {Object} options The options passed to the addTiledImage method.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'add-item-failed', event );\n\n if (options.error) {\n options.error(event);\n }\n }\n\n function refreshWorld(theItem) {\n if (_this.collectionMode) {\n _this.world.arrange({\n immediately: theItem.options.collectionImmediately,\n rows: _this.collectionRows,\n columns: _this.collectionColumns,\n layout: _this.collectionLayout,\n tileSize: _this.collectionTileSize,\n tileMargin: _this.collectionTileMargin\n });\n _this.world.setAutoRefigureSizes(true);\n }\n }\n\n if ($.isArray(options.tileSource)) {\n setTimeout(function() {\n raiseAddItemFailed({\n message: \"[Viewer.addTiledImage] Sequences can not be added; add them one at a time instead.\",\n source: options.tileSource,\n options: options\n });\n });\n return;\n }\n\n this._loadQueue.push(myQueueItem);\n\n function processReadyItems() {\n var queueItem, tiledImage, optionsClone;\n while (_this._loadQueue.length) {\n queueItem = _this._loadQueue[0];\n if (!queueItem.tileSource) {\n break;\n }\n\n _this._loadQueue.splice(0, 1);\n\n if (queueItem.options.replace) {\n var newIndex = _this.world.getIndexOfItem(queueItem.options.replaceItem);\n if (newIndex != -1) {\n queueItem.options.index = newIndex;\n }\n _this.world.removeItem(queueItem.options.replaceItem);\n }\n\n tiledImage = new $.TiledImage({\n viewer: _this,\n source: queueItem.tileSource,\n viewport: _this.viewport,\n drawer: _this.drawer,\n tileCache: _this.tileCache,\n imageLoader: _this.imageLoader,\n x: queueItem.options.x,\n y: queueItem.options.y,\n width: queueItem.options.width,\n height: queueItem.options.height,\n fitBounds: queueItem.options.fitBounds,\n fitBoundsPlacement: queueItem.options.fitBoundsPlacement,\n clip: queueItem.options.clip,\n placeholderFillStyle: queueItem.options.placeholderFillStyle,\n opacity: queueItem.options.opacity,\n preload: queueItem.options.preload,\n degrees: queueItem.options.degrees,\n compositeOperation: queueItem.options.compositeOperation,\n springStiffness: _this.springStiffness,\n animationTime: _this.animationTime,\n minZoomImageRatio: _this.minZoomImageRatio,\n wrapHorizontal: _this.wrapHorizontal,\n wrapVertical: _this.wrapVertical,\n immediateRender: _this.immediateRender,\n blendTime: _this.blendTime,\n alwaysBlend: _this.alwaysBlend,\n minPixelRatio: _this.minPixelRatio,\n smoothTileEdgesMinZoom: _this.smoothTileEdgesMinZoom,\n iOSDevice: _this.iOSDevice,\n crossOriginPolicy: queueItem.options.crossOriginPolicy,\n ajaxWithCredentials: queueItem.options.ajaxWithCredentials,\n makeAjaxRequest: queueItem.options.makeAjaxRequest,\n loadTilesWithAjax: queueItem.options.loadTilesWithAjax,\n ajaxHeaders: queueItem.options.ajaxHeaders,\n debugMode: _this.debugMode\n });\n\n if (_this.collectionMode) {\n _this.world.setAutoRefigureSizes(false);\n }\n _this.world.addItem( tiledImage, {\n index: queueItem.options.index\n });\n\n if (_this._loadQueue.length === 0) {\n //this restores the autoRefigureSizes flag to true.\n refreshWorld(queueItem);\n }\n\n if (_this.world.getItemCount() === 1 && !_this.preserveViewport) {\n _this.viewport.goHome(true);\n }\n\n if (_this.navigator) {\n optionsClone = $.extend({}, queueItem.options, {\n replace: false, // navigator already removed the layer, nothing to replace\n originalTiledImage: tiledImage,\n tileSource: queueItem.tileSource\n });\n\n _this.navigator.addTiledImage(optionsClone);\n }\n\n if (queueItem.options.success) {\n queueItem.options.success({\n item: tiledImage\n });\n }\n }\n }\n\n getTileSourceImplementation( this, options.tileSource, options, function( tileSource ) {\n\n myQueueItem.tileSource = tileSource;\n\n // add everybody at the front of the queue that's ready to go\n processReadyItems();\n }, function( event ) {\n event.options = options;\n raiseAddItemFailed(event);\n\n // add everybody at the front of the queue that's ready to go\n processReadyItems();\n } );\n },\n\n /**\n * Add a simple image to the viewer.\n * The options are the same as the ones in {@link OpenSeadragon.Viewer#addTiledImage}\n * except for options.tileSource which is replaced by options.url.\n * @function\n * @param {Object} options - See {@link OpenSeadragon.Viewer#addTiledImage}\n * for all the options\n * @param {String} options.url - The URL of the image to add.\n * @fires OpenSeadragon.World.event:add-item\n * @fires OpenSeadragon.Viewer.event:add-item-failed\n */\n addSimpleImage: function(options) {\n $.console.assert(options, \"[Viewer.addSimpleImage] options is required\");\n $.console.assert(options.url, \"[Viewer.addSimpleImage] options.url is required\");\n\n var opts = $.extend({}, options, {\n tileSource: {\n type: 'image',\n url: options.url\n }\n });\n delete opts.url;\n this.addTiledImage(opts);\n },\n\n // deprecated\n addLayer: function( options ) {\n var _this = this;\n\n $.console.error( \"[Viewer.addLayer] this function is deprecated; use Viewer.addTiledImage() instead.\" );\n\n var optionsClone = $.extend({}, options, {\n success: function(event) {\n _this.raiseEvent(\"add-layer\", {\n options: options,\n drawer: event.item\n });\n },\n error: function(event) {\n _this.raiseEvent(\"add-layer-failed\", event);\n }\n });\n\n this.addTiledImage(optionsClone);\n return this;\n },\n\n // deprecated\n getLayerAtLevel: function( level ) {\n $.console.error( \"[Viewer.getLayerAtLevel] this function is deprecated; use World.getItemAt() instead.\" );\n return this.world.getItemAt(level);\n },\n\n // deprecated\n getLevelOfLayer: function( drawer ) {\n $.console.error( \"[Viewer.getLevelOfLayer] this function is deprecated; use World.getIndexOfItem() instead.\" );\n return this.world.getIndexOfItem(drawer);\n },\n\n // deprecated\n getLayersCount: function() {\n $.console.error( \"[Viewer.getLayersCount] this function is deprecated; use World.getItemCount() instead.\" );\n return this.world.getItemCount();\n },\n\n // deprecated\n setLayerLevel: function( drawer, level ) {\n $.console.error( \"[Viewer.setLayerLevel] this function is deprecated; use World.setItemIndex() instead.\" );\n return this.world.setItemIndex(drawer, level);\n },\n\n // deprecated\n removeLayer: function( drawer ) {\n $.console.error( \"[Viewer.removeLayer] this function is deprecated; use World.removeItem() instead.\" );\n return this.world.removeItem(drawer);\n },\n\n /**\n * Force the viewer to redraw its contents.\n * @returns {OpenSeadragon.Viewer} Chainable.\n */\n forceRedraw: function() {\n THIS[ this.hash ].forceRedraw = true;\n return this;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n */\n bindSequenceControls: function(){\n\n //////////////////////////////////////////////////////////////////////////\n // Image Sequence Controls\n //////////////////////////////////////////////////////////////////////////\n var onFocusHandler = $.delegate( this, onFocus ),\n onBlurHandler = $.delegate( this, onBlur ),\n onNextHandler = $.delegate( this, onNext ),\n onPreviousHandler = $.delegate( this, onPrevious ),\n navImages = this.navImages,\n useGroup = true;\n\n if( this.showSequenceControl ){\n\n if( this.previousButton || this.nextButton ){\n //if we are binding to custom buttons then layout and\n //grouping is the responsibility of the page author\n useGroup = false;\n }\n\n this.previousButton = new $.Button({\n element: this.previousButton ? $.getElement( this.previousButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.PreviousPage\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.previous.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.previous.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.previous.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.previous.DOWN ),\n onRelease: onPreviousHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n });\n\n this.nextButton = new $.Button({\n element: this.nextButton ? $.getElement( this.nextButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.NextPage\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.next.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.next.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.next.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.next.DOWN ),\n onRelease: onNextHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n });\n\n if( !this.navPrevNextWrap ){\n this.previousButton.disable();\n }\n\n if (!this.tileSources || !this.tileSources.length) {\n this.nextButton.disable();\n }\n\n if( useGroup ){\n this.paging = new $.ButtonGroup({\n buttons: [\n this.previousButton,\n this.nextButton\n ],\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold\n });\n\n this.pagingControl = this.paging.element;\n\n if( this.toolbar ){\n this.toolbar.addControl(\n this.pagingControl,\n {anchor: $.ControlAnchor.BOTTOM_RIGHT}\n );\n }else{\n this.addControl(\n this.pagingControl,\n {anchor: this.sequenceControlAnchor || $.ControlAnchor.TOP_LEFT}\n );\n }\n }\n }\n return this;\n },\n\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n */\n bindStandardControls: function(){\n //////////////////////////////////////////////////////////////////////////\n // Navigation Controls\n //////////////////////////////////////////////////////////////////////////\n var beginZoomingInHandler = $.delegate( this, beginZoomingIn ),\n endZoomingHandler = $.delegate( this, endZooming ),\n doSingleZoomInHandler = $.delegate( this, doSingleZoomIn ),\n beginZoomingOutHandler = $.delegate( this, beginZoomingOut ),\n doSingleZoomOutHandler = $.delegate( this, doSingleZoomOut ),\n onHomeHandler = $.delegate( this, onHome ),\n onFullScreenHandler = $.delegate( this, onFullScreen ),\n onRotateLeftHandler = $.delegate( this, onRotateLeft ),\n onRotateRightHandler = $.delegate( this, onRotateRight ),\n onFlipHandler = $.delegate( this, onFlip),\n onFocusHandler = $.delegate( this, onFocus ),\n onBlurHandler = $.delegate( this, onBlur ),\n navImages = this.navImages,\n buttons = [],\n useGroup = true;\n\n\n if ( this.showNavigationControl ) {\n\n if( this.zoomInButton || this.zoomOutButton ||\n this.homeButton || this.fullPageButton ||\n this.rotateLeftButton || this.rotateRightButton ||\n this.flipButton ) {\n //if we are binding to custom buttons then layout and\n //grouping is the responsibility of the page author\n useGroup = false;\n }\n\n if ( this.showZoomControl ) {\n buttons.push( this.zoomInButton = new $.Button({\n element: this.zoomInButton ? $.getElement( this.zoomInButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.ZoomIn\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.zoomIn.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.zoomIn.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.zoomIn.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.zoomIn.DOWN ),\n onPress: beginZoomingInHandler,\n onRelease: endZoomingHandler,\n onClick: doSingleZoomInHandler,\n onEnter: beginZoomingInHandler,\n onExit: endZoomingHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n\n buttons.push( this.zoomOutButton = new $.Button({\n element: this.zoomOutButton ? $.getElement( this.zoomOutButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.ZoomOut\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.zoomOut.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.zoomOut.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.zoomOut.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.zoomOut.DOWN ),\n onPress: beginZoomingOutHandler,\n onRelease: endZoomingHandler,\n onClick: doSingleZoomOutHandler,\n onEnter: beginZoomingOutHandler,\n onExit: endZoomingHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showHomeControl ) {\n buttons.push( this.homeButton = new $.Button({\n element: this.homeButton ? $.getElement( this.homeButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.Home\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.home.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.home.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.home.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.home.DOWN ),\n onRelease: onHomeHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showFullPageControl ) {\n buttons.push( this.fullPageButton = new $.Button({\n element: this.fullPageButton ? $.getElement( this.fullPageButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.FullPage\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.fullpage.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.fullpage.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.fullpage.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.fullpage.DOWN ),\n onRelease: onFullScreenHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showRotationControl ) {\n buttons.push( this.rotateLeftButton = new $.Button({\n element: this.rotateLeftButton ? $.getElement( this.rotateLeftButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.RotateLeft\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.rotateleft.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.rotateleft.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.rotateleft.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.rotateleft.DOWN ),\n onRelease: onRotateLeftHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n\n buttons.push( this.rotateRightButton = new $.Button({\n element: this.rotateRightButton ? $.getElement( this.rotateRightButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.RotateRight\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.rotateright.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.rotateright.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.rotateright.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.rotateright.DOWN ),\n onRelease: onRotateRightHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( this.showFlipControl ) {\n buttons.push( this.flipButton = new $.Button({\n element: this.flipButton ? $.getElement( this.flipButton ) : null,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n tooltip: $.getString( \"Tooltips.Flip\" ),\n srcRest: resolveUrl( this.prefixUrl, navImages.flip.REST ),\n srcGroup: resolveUrl( this.prefixUrl, navImages.flip.GROUP ),\n srcHover: resolveUrl( this.prefixUrl, navImages.flip.HOVER ),\n srcDown: resolveUrl( this.prefixUrl, navImages.flip.DOWN ),\n onRelease: onFlipHandler,\n onFocus: onFocusHandler,\n onBlur: onBlurHandler\n }));\n }\n\n if ( useGroup ) {\n this.buttons = new $.ButtonGroup({\n buttons: buttons,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold\n });\n\n this.navControl = this.buttons.element;\n this.addHandler( 'open', $.delegate( this, lightUp ) );\n\n if( this.toolbar ){\n this.toolbar.addControl(\n this.navControl,\n {anchor: this.navigationControlAnchor || $.ControlAnchor.TOP_LEFT}\n );\n } else {\n this.addControl(\n this.navControl,\n {anchor: this.navigationControlAnchor || $.ControlAnchor.TOP_LEFT}\n );\n }\n }\n\n }\n return this;\n },\n\n /**\n * Gets the active page of a sequence\n * @function\n * @return {Number}\n */\n currentPage: function() {\n return this._sequenceIndex;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:page\n */\n goToPage: function( page ){\n if( this.tileSources && page >= 0 && page < this.tileSources.length ){\n this._sequenceIndex = page;\n\n this._updateSequenceButtons( page );\n\n this.open( this.tileSources[ page ] );\n\n if( this.referenceStrip ){\n this.referenceStrip.setFocus( page );\n }\n\n /**\n * Raised when the page is changed on a viewer configured with multiple image sources (see {@link OpenSeadragon.Viewer#goToPage}).\n *\n * @event page\n * @memberof OpenSeadragon.Viewer\n * @type {Object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Number} page - The page index.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'page', { page: page } );\n }\n\n return this;\n },\n\n /**\n * Adds an html element as an overlay to the current viewport. Useful for\n * highlighting words or areas of interest on an image or other zoomable\n * interface. The overlays added via this method are removed when the viewport\n * is closed which include when changing page.\n * @method\n * @param {Element|String|Object} element - A reference to an element or an id for\n * the element which will be overlayed. Or an Object specifying the configuration for the overlay.\n * If using an object, see {@link OpenSeadragon.Overlay} for a list of\n * all available options.\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect} location - The point or\n * rectangle which will be overlayed. This is a viewport relative location.\n * @param {OpenSeadragon.Placement} placement - The position of the\n * viewport which the location coordinates will be treated as relative\n * to.\n * @param {function} onDraw - If supplied the callback is called when the overlay\n * needs to be drawn. It it the responsibility of the callback to do any drawing/positioning.\n * It is passed position, size and element.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:add-overlay\n */\n addOverlay: function( element, location, placement, onDraw ) {\n var options;\n if( $.isPlainObject( element ) ){\n options = element;\n } else {\n options = {\n element: element,\n location: location,\n placement: placement,\n onDraw: onDraw\n };\n }\n\n element = $.getElement( options.element );\n\n if ( getOverlayIndex( this.currentOverlays, element ) >= 0 ) {\n // they're trying to add a duplicate overlay\n return this;\n }\n\n var overlay = getOverlayObject( this, options);\n this.currentOverlays.push(overlay);\n overlay.drawHTML( this.overlaysContainer, this.viewport );\n\n /**\n * Raised when an overlay is added to the viewer (see {@link OpenSeadragon.Viewer#addOverlay}).\n *\n * @event add-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Element} element - The overlay element.\n * @property {OpenSeadragon.Point|OpenSeadragon.Rect} location\n * @property {OpenSeadragon.Placement} placement\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'add-overlay', {\n element: element,\n location: options.location,\n placement: options.placement\n });\n return this;\n },\n\n /**\n * Updates the overlay represented by the reference to the element or\n * element id moving it to the new location, relative to the new placement.\n * @method\n * @param {Element|String} element - A reference to an element or an id for\n * the element which is overlayed.\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect} location - The point or\n * rectangle which will be overlayed. This is a viewport relative location.\n * @param {OpenSeadragon.Placement} placement - The position of the\n * viewport which the location coordinates will be treated as relative\n * to.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:update-overlay\n */\n updateOverlay: function( element, location, placement ) {\n var i;\n\n element = $.getElement( element );\n i = getOverlayIndex( this.currentOverlays, element );\n\n if ( i >= 0 ) {\n this.currentOverlays[ i ].update( location, placement );\n THIS[ this.hash ].forceRedraw = true;\n /**\n * Raised when an overlay's location or placement changes\n * (see {@link OpenSeadragon.Viewer#updateOverlay}).\n *\n * @event update-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the\n * Viewer which raised the event.\n * @property {Element} element\n * @property {OpenSeadragon.Point|OpenSeadragon.Rect} location\n * @property {OpenSeadragon.Placement} placement\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'update-overlay', {\n element: element,\n location: location,\n placement: placement\n });\n }\n return this;\n },\n\n /**\n * Removes an overlay identified by the reference element or element id\n * and schedules an update.\n * @method\n * @param {Element|String} element - A reference to the element or an\n * element id which represent the ovelay content to be removed.\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:remove-overlay\n */\n removeOverlay: function( element ) {\n var i;\n\n element = $.getElement( element );\n i = getOverlayIndex( this.currentOverlays, element );\n\n if ( i >= 0 ) {\n this.currentOverlays[ i ].destroy();\n this.currentOverlays.splice( i, 1 );\n THIS[ this.hash ].forceRedraw = true;\n /**\n * Raised when an overlay is removed from the viewer\n * (see {@link OpenSeadragon.Viewer#removeOverlay}).\n *\n * @event remove-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the\n * Viewer which raised the event.\n * @property {Element} element - The overlay element.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'remove-overlay', {\n element: element\n });\n }\n return this;\n },\n\n /**\n * Removes all currently configured Overlays from this Viewer and schedules\n * an update.\n * @method\n * @return {OpenSeadragon.Viewer} Chainable.\n * @fires OpenSeadragon.Viewer.event:clear-overlay\n */\n clearOverlays: function() {\n while ( this.currentOverlays.length > 0 ) {\n this.currentOverlays.pop().destroy();\n }\n THIS[ this.hash ].forceRedraw = true;\n /**\n * Raised when all overlays are removed from the viewer (see {@link OpenSeadragon.Drawer#clearOverlays}).\n *\n * @event clear-overlay\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'clear-overlay', {} );\n return this;\n },\n\n /**\n * Finds an overlay identified by the reference element or element id\n * and returns it as an object, return null if not found.\n * @method\n * @param {Element|String} element - A reference to the element or an\n * element id which represents the overlay content.\n * @return {OpenSeadragon.Overlay} the matching overlay or null if none found.\n */\n getOverlayById: function( element ) {\n var i;\n\n element = $.getElement( element );\n i = getOverlayIndex( this.currentOverlays, element );\n\n if (i >= 0) {\n return this.currentOverlays[i];\n } else {\n return null;\n }\n },\n\n /**\n * Updates the sequence buttons.\n * @function OpenSeadragon.Viewer.prototype._updateSequenceButtons\n * @private\n * @param {Number} Sequence Value\n */\n _updateSequenceButtons: function( page ) {\n\n if ( this.nextButton ) {\n if(!this.tileSources || this.tileSources.length - 1 === page) {\n //Disable next button\n if ( !this.navPrevNextWrap ) {\n this.nextButton.disable();\n }\n } else {\n this.nextButton.enable();\n }\n }\n if ( this.previousButton ) {\n if ( page > 0 ) {\n //Enable previous button\n this.previousButton.enable();\n } else {\n if ( !this.navPrevNextWrap ) {\n this.previousButton.disable();\n }\n }\n }\n },\n\n /**\n * Display a message in the viewport\n * @function OpenSeadragon.Viewer.prototype._showMessage\n * @private\n * @param {String} text message\n */\n _showMessage: function ( message ) {\n this._hideMessage();\n\n var div = $.makeNeutralElement( \"div\" );\n div.appendChild( document.createTextNode( message ) );\n\n this.messageDiv = $.makeCenteredNode( div );\n\n $.addClass(this.messageDiv, \"openseadragon-message\");\n\n this.container.appendChild( this.messageDiv );\n },\n\n /**\n * Hide any currently displayed viewport message\n * @function OpenSeadragon.Viewer.prototype._hideMessage\n * @private\n */\n _hideMessage: function () {\n var div = this.messageDiv;\n if (div) {\n div.parentNode.removeChild(div);\n delete this.messageDiv;\n }\n },\n\n /**\n * Gets this viewer's gesture settings for the given pointer device type.\n * @method\n * @param {String} type - The pointer device type to get the gesture settings for (\"mouse\", \"touch\", \"pen\", etc.).\n * @return {OpenSeadragon.GestureSettings}\n */\n gestureSettingsByDeviceType: function ( type ) {\n switch ( type ) {\n case 'mouse':\n return this.gestureSettingsMouse;\n case 'touch':\n return this.gestureSettingsTouch;\n case 'pen':\n return this.gestureSettingsPen;\n default:\n return this.gestureSettingsUnknown;\n }\n },\n\n // private\n _drawOverlays: function() {\n var i,\n length = this.currentOverlays.length;\n for ( i = 0; i < length; i++ ) {\n this.currentOverlays[ i ].drawHTML( this.overlaysContainer, this.viewport );\n }\n },\n\n /**\n * Cancel the \"in flight\" images.\n */\n _cancelPendingImages: function() {\n this._loadQueue = [];\n },\n\n /**\n * Removes the reference strip and disables displaying it.\n * @function\n */\n removeReferenceStrip: function() {\n this.showReferenceStrip = false;\n\n if (this.referenceStrip) {\n this.referenceStrip.destroy();\n this.referenceStrip = null;\n }\n },\n\n /**\n * Enables and displays the reference strip based on the currently set tileSources.\n * Works only when the Viewer has sequenceMode set to true.\n * @function\n */\n addReferenceStrip: function() {\n this.showReferenceStrip = true;\n\n if (this.sequenceMode) {\n if (this.referenceStrip) {\n return;\n }\n\n if (this.tileSources.length && this.tileSources.length > 1) {\n this.referenceStrip = new $.ReferenceStrip({\n id: this.referenceStripElement,\n position: this.referenceStripPosition,\n sizeRatio: this.referenceStripSizeRatio,\n scroll: this.referenceStripScroll,\n height: this.referenceStripHeight,\n width: this.referenceStripWidth,\n tileSources: this.tileSources,\n prefixUrl: this.prefixUrl,\n viewer: this\n });\n\n this.referenceStrip.setFocus( this._sequenceIndex );\n }\n } else {\n $.console.warn('Attempting to display a reference strip while \"sequenceMode\" is off.');\n }\n }\n});\n\n\n/**\n * _getSafeElemSize is like getElementSize(), but refuses to return 0 for x or y,\n * which was causing some calling operations to return NaN.\n * @returns {Point}\n * @private\n */\nfunction _getSafeElemSize (oElement) {\n oElement = $.getElement( oElement );\n\n return new $.Point(\n (oElement.clientWidth === 0 ? 1 : oElement.clientWidth),\n (oElement.clientHeight === 0 ? 1 : oElement.clientHeight)\n );\n}\n\n\n/**\n * @function\n * @private\n */\nfunction getTileSourceImplementation( viewer, tileSource, imgOptions, successCallback,\n failCallback ) {\n var _this = viewer;\n\n //allow plain xml strings or json strings to be parsed here\n if ( $.type( tileSource ) == 'string' ) {\n //xml should start with \"<\" and end with \">\"\n if ( tileSource.match( /^\\s*<.*>\\s*$/ ) ) {\n tileSource = $.parseXml( tileSource );\n //json should start with \"{\" or \"[\" and end with \"}\" or \"]\"\n } else if ( tileSource.match(/^\\s*[\\{\\[].*[\\}\\]]\\s*$/ ) ) {\n try {\n var tileSourceJ = $.parseJSON(tileSource);\n tileSource = tileSourceJ;\n } catch (e) {\n //tileSource = tileSource;\n }\n }\n }\n\n function waitUntilReady(tileSource, originalTileSource) {\n if (tileSource.ready) {\n successCallback(tileSource);\n } else {\n tileSource.addHandler('ready', function () {\n successCallback(tileSource);\n });\n tileSource.addHandler('open-failed', function (event) {\n failCallback({\n message: event.message,\n source: originalTileSource\n });\n });\n }\n }\n\n setTimeout( function() {\n if ( $.type( tileSource ) == 'string' ) {\n //If its still a string it means it must be a url at this point\n tileSource = new $.TileSource({\n url: tileSource,\n crossOriginPolicy: imgOptions.crossOriginPolicy !== undefined ?\n imgOptions.crossOriginPolicy : viewer.crossOriginPolicy,\n ajaxWithCredentials: viewer.ajaxWithCredentials,\n ajaxHeaders: viewer.ajaxHeaders,\n useCanvas: viewer.useCanvas,\n success: function( event ) {\n successCallback( event.tileSource );\n }\n });\n tileSource.addHandler( 'open-failed', function( event ) {\n failCallback( event );\n } );\n\n } else if ($.isPlainObject(tileSource) || tileSource.nodeType) {\n if (tileSource.crossOriginPolicy === undefined &&\n (imgOptions.crossOriginPolicy !== undefined || viewer.crossOriginPolicy !== undefined)) {\n tileSource.crossOriginPolicy = imgOptions.crossOriginPolicy !== undefined ?\n imgOptions.crossOriginPolicy : viewer.crossOriginPolicy;\n }\n if (tileSource.ajaxWithCredentials === undefined) {\n tileSource.ajaxWithCredentials = viewer.ajaxWithCredentials;\n }\n if (tileSource.useCanvas === undefined) {\n tileSource.useCanvas = viewer.useCanvas;\n }\n\n if ( $.isFunction( tileSource.getTileUrl ) ) {\n //Custom tile source\n var customTileSource = new $.TileSource( tileSource );\n customTileSource.getTileUrl = tileSource.getTileUrl;\n successCallback( customTileSource );\n } else {\n //inline configuration\n var $TileSource = $.TileSource.determineType( _this, tileSource );\n if ( !$TileSource ) {\n failCallback( {\n message: \"Unable to load TileSource\",\n source: tileSource\n });\n return;\n }\n var options = $TileSource.prototype.configure.apply( _this, [ tileSource ] );\n waitUntilReady(new $TileSource(options), tileSource);\n }\n } else {\n //can assume it's already a tile source implementation\n waitUntilReady(tileSource, tileSource);\n }\n });\n}\n\nfunction getOverlayObject( viewer, overlay ) {\n if ( overlay instanceof $.Overlay ) {\n return overlay;\n }\n\n var element = null;\n if ( overlay.element ) {\n element = $.getElement( overlay.element );\n } else {\n var id = overlay.id ?\n overlay.id :\n \"openseadragon-overlay-\" + Math.floor( Math.random() * 10000000 );\n\n element = $.getElement( overlay.id );\n if ( !element ) {\n element = document.createElement( \"a\" );\n element.href = \"#/overlay/\" + id;\n }\n element.id = id;\n $.addClass( element, overlay.className ?\n overlay.className :\n \"openseadragon-overlay\"\n );\n }\n\n var location = overlay.location;\n var width = overlay.width;\n var height = overlay.height;\n if (!location) {\n var x = overlay.x;\n var y = overlay.y;\n if (overlay.px !== undefined) {\n var rect = viewer.viewport.imageToViewportRectangle(new $.Rect(\n overlay.px,\n overlay.py,\n width || 0,\n height || 0));\n x = rect.x;\n y = rect.y;\n width = width !== undefined ? rect.width : undefined;\n height = height !== undefined ? rect.height : undefined;\n }\n location = new $.Point(x, y);\n }\n\n var placement = overlay.placement;\n if (placement && $.type(placement) === \"string\") {\n placement = $.Placement[overlay.placement.toUpperCase()];\n }\n\n return new $.Overlay({\n element: element,\n location: location,\n placement: placement,\n onDraw: overlay.onDraw,\n checkResize: overlay.checkResize,\n width: width,\n height: height,\n rotationMode: overlay.rotationMode\n });\n}\n\n/**\n * @private\n * @inner\n * Determines the index of the given overlay in the given overlays array.\n */\nfunction getOverlayIndex( overlays, element ) {\n var i;\n for ( i = overlays.length - 1; i >= 0; i-- ) {\n if ( overlays[ i ].element === element ) {\n return i;\n }\n }\n\n return -1;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Schedulers provide the general engine for animation\n///////////////////////////////////////////////////////////////////////////////\nfunction scheduleUpdate( viewer, updateFunc ){\n return $.requestAnimationFrame( function(){\n updateFunc( viewer );\n } );\n}\n\n\n//provides a sequence in the fade animation\nfunction scheduleControlsFade( viewer ) {\n $.requestAnimationFrame( function(){\n updateControlsFade( viewer );\n });\n}\n\n\n//initiates an animation to hide the controls\nfunction beginControlsAutoHide( viewer ) {\n if ( !viewer.autoHideControls ) {\n return;\n }\n viewer.controlsShouldFade = true;\n viewer.controlsFadeBeginTime =\n $.now() +\n viewer.controlsFadeDelay;\n\n window.setTimeout( function(){\n scheduleControlsFade( viewer );\n }, viewer.controlsFadeDelay );\n}\n\n\n//determines if fade animation is done or continues the animation\nfunction updateControlsFade( viewer ) {\n var currentTime,\n deltaTime,\n opacity,\n i;\n if ( viewer.controlsShouldFade ) {\n currentTime = $.now();\n deltaTime = currentTime - viewer.controlsFadeBeginTime;\n opacity = 1.0 - deltaTime / viewer.controlsFadeLength;\n\n opacity = Math.min( 1.0, opacity );\n opacity = Math.max( 0.0, opacity );\n\n for ( i = viewer.controls.length - 1; i >= 0; i--) {\n if (viewer.controls[ i ].autoFade) {\n viewer.controls[ i ].setOpacity( opacity );\n }\n }\n\n if ( opacity > 0 ) {\n // fade again\n scheduleControlsFade( viewer );\n }\n }\n}\n\n\n//stop the fade animation on the controls and show them\nfunction abortControlsAutoHide( viewer ) {\n var i;\n viewer.controlsShouldFade = false;\n for ( i = viewer.controls.length - 1; i >= 0; i-- ) {\n viewer.controls[ i ].setOpacity( 1.0 );\n }\n}\n\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Default view event handlers.\n///////////////////////////////////////////////////////////////////////////////\nfunction onFocus(){\n abortControlsAutoHide( this );\n}\n\nfunction onBlur(){\n beginControlsAutoHide( this );\n\n}\n\nfunction onCanvasKeyDown( event ) {\n var canvasKeyDownEventArgs = {\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction,\n preventVerticalPan: event.preventVerticalPan,\n preventHorizontalPan: event.preventHorizontalPan\n };\n\n /**\n * Raised when a keyboard key is pressed and the focus is on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-key\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default keyboard behaviour. Default: false.\n * @property {Boolean} preventVerticalPan - Set to true to prevent keyboard vertical panning. Default: false.\n * @property {Boolean} preventHorizontalPan - Set to true to prevent keyboard horizontal panning. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n\n this.raiseEvent('canvas-key', canvasKeyDownEventArgs);\n\n if ( !canvasKeyDownEventArgs.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch( event.keyCode ){\n case 38://up arrow\n if (!canvasKeyDownEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(1.1);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, -this.pixelsPerArrowPress)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 40://down arrow\n if (!canvasKeyDownEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(0.9);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, this.pixelsPerArrowPress)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 37://left arrow\n if (!canvasKeyDownEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(-this.pixelsPerArrowPress, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n case 39://right arrow\n if (!canvasKeyDownEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(this.pixelsPerArrowPress, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n default:\n //console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\nfunction onCanvasKeyPress( event ) {\n var canvasKeyPressEventArgs = {\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction,\n preventVerticalPan: event.preventVerticalPan,\n preventHorizontalPan: event.preventHorizontalPan\n };\n\n // This event is documented in onCanvasKeyDown\n this.raiseEvent('canvas-key', canvasKeyPressEventArgs);\n\n if ( !canvasKeyPressEventArgs.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch( event.keyCode ){\n case 43://=|+\n case 61://=|+\n this.viewport.zoomBy(1.1);\n this.viewport.applyConstraints();\n return false;\n case 45://-|_\n this.viewport.zoomBy(0.9);\n this.viewport.applyConstraints();\n return false;\n case 48://0|)\n this.viewport.goHome();\n this.viewport.applyConstraints();\n return false;\n case 119://w\n case 87://W\n if (!canvasKeyPressEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(1.1);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, -40)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 115://s\n case 83://S\n if (!canvasKeyPressEventArgs.preventVerticalPan) {\n if ( event.shift ) {\n this.viewport.zoomBy(0.9);\n } else {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(0, 40)));\n }\n this.viewport.applyConstraints();\n }\n return false;\n case 97://a\n if (!canvasKeyPressEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(-40, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n case 100://d\n if (!canvasKeyPressEventArgs.preventHorizontalPan) {\n this.viewport.panBy(this.viewport.deltaPointsFromPixels(new $.Point(40, 0)));\n this.viewport.applyConstraints();\n }\n return false;\n case 114: //r - 90 degrees clockwise rotation\n if(this.viewport.flipped){\n this.viewport.setRotation(this.viewport.degrees - 90);\n } else{\n this.viewport.setRotation(this.viewport.degrees + 90);\n }\n this.viewport.applyConstraints();\n return false;\n case 82: //R - 90 degrees counterclockwise rotation\n if(this.viewport.flipped){\n this.viewport.setRotation(this.viewport.degrees + 90);\n } else{\n this.viewport.setRotation(this.viewport.degrees - 90);\n }\n this.viewport.applyConstraints();\n return false;\n case 102: //f\n this.viewport.toggleFlip();\n return false;\n default:\n // console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\n\nfunction onCanvasClick( event ) {\n var gestureSettings;\n\n var haveKeyboardFocus = document.activeElement == this.canvas;\n\n // If we don't have keyboard focus, request it.\n if ( !haveKeyboardFocus ) {\n this.canvas.focus();\n }\n if(this.viewport.flipped){\n event.position.x = this.viewport.getContainerSize().x - event.position.x;\n }\n\n var canvasClickEventArgs = {\n tracker: event.eventSource,\n position: event.position,\n quick: event.quick,\n shift: event.shift,\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction\n };\n\n /**\n * Raised when a mouse press/release or touch/remove occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-click\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} quick - True only if the clickDistThreshold and clickTimeThreshold are both passed. Useful for differentiating between clicks and drags.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default click to zoom behaviour. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-click', canvasClickEventArgs);\n\n if ( !canvasClickEventArgs.preventDefaultAction && this.viewport && event.quick ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.clickToZoom ) {\n this.viewport.zoomBy(\n event.shift ? 1.0 / this.zoomPerClick : this.zoomPerClick,\n gestureSettings.zoomToRefPoint ? this.viewport.pointFromPixel( event.position, true ) : null\n );\n this.viewport.applyConstraints();\n }\n }\n}\n\nfunction onCanvasDblClick( event ) {\n var gestureSettings;\n\n var canvasDblClickEventArgs = {\n tracker: event.eventSource,\n position: event.position,\n shift: event.shift,\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction\n };\n\n /**\n * Raised when a double mouse press/release or touch/remove occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-double-click\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default double tap to zoom behaviour. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-double-click', canvasDblClickEventArgs);\n\n if ( !canvasDblClickEventArgs.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.dblClickToZoom ) {\n this.viewport.zoomBy(\n event.shift ? 1.0 / this.zoomPerClick : this.zoomPerClick,\n gestureSettings.zoomToRefPoint ? this.viewport.pointFromPixel( event.position, true ) : null\n );\n this.viewport.applyConstraints();\n }\n }\n}\n\nfunction onCanvasDrag( event ) {\n var gestureSettings;\n\n var canvasDragEventArgs = {\n tracker: event.eventSource,\n position: event.position,\n delta: event.delta,\n speed: event.speed,\n direction: event.direction,\n shift: event.shift,\n originalEvent: event.originalEvent,\n preventDefaultAction: event.preventDefaultAction\n };\n\n /**\n * Raised when a mouse or touch drag operation occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-drag\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {OpenSeadragon.Point} delta - The x,y components of the difference between start drag and end drag.\n * @property {Number} speed - Current computed speed, in pixels per second.\n * @property {Number} direction - Current computed direction, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {Boolean} preventDefaultAction - Set to true to prevent default drag behaviour. Default: false.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-drag', canvasDragEventArgs);\n\n if ( !canvasDragEventArgs.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if( !this.panHorizontal ){\n event.delta.x = 0;\n }\n if( !this.panVertical ){\n event.delta.y = 0;\n }\n if(this.viewport.flipped){\n event.delta.x = -event.delta.x;\n }\n\n if( this.constrainDuringPan ){\n var delta = this.viewport.deltaPointsFromPixels( event.delta.negate() );\n\n this.viewport.centerSpringX.target.value += delta.x;\n this.viewport.centerSpringY.target.value += delta.y;\n\n var bounds = this.viewport.getBounds();\n var constrainedBounds = this.viewport.getConstrainedBounds();\n\n this.viewport.centerSpringX.target.value -= delta.x;\n this.viewport.centerSpringY.target.value -= delta.y;\n\n if (bounds.x != constrainedBounds.x) {\n event.delta.x = 0;\n }\n\n if (bounds.y != constrainedBounds.y) {\n event.delta.y = 0;\n }\n }\n\n this.viewport.panBy( this.viewport.deltaPointsFromPixels( event.delta.negate() ), gestureSettings.flickEnabled && !this.constrainDuringPan);\n }\n}\n\nfunction onCanvasDragEnd( event ) {\n if (!event.preventDefaultAction && this.viewport) {\n var gestureSettings = this.gestureSettingsByDeviceType(event.pointerType);\n if (gestureSettings.flickEnabled &&\n event.speed >= gestureSettings.flickMinSpeed) {\n var amplitudeX = 0;\n if (this.panHorizontal) {\n amplitudeX = gestureSettings.flickMomentum * event.speed *\n Math.cos(event.direction);\n }\n var amplitudeY = 0;\n if (this.panVertical) {\n amplitudeY = gestureSettings.flickMomentum * event.speed *\n Math.sin(event.direction);\n }\n var center = this.viewport.pixelFromPoint(\n this.viewport.getCenter(true));\n var target = this.viewport.pointFromPixel(\n new $.Point(center.x - amplitudeX, center.y - amplitudeY));\n this.viewport.panTo(target, false);\n }\n this.viewport.applyConstraints();\n }\n /**\n * Raised when a mouse or touch drag operation ends on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-drag-end\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} speed - Speed at the end of a drag gesture, in pixels per second.\n * @property {Number} direction - Direction at the end of a drag gesture, expressed as an angle counterclockwise relative to the positive X axis (-pi to pi, in radians). Only valid if speed > 0.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('canvas-drag-end', {\n tracker: event.eventSource,\n position: event.position,\n speed: event.speed,\n direction: event.direction,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasEnter( event ) {\n /**\n * Raised when a pointer enters the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-enter\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-enter', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasExit( event ) {\n\n if (window.location != window.parent.location){\n $.MouseTracker.resetAllMouseTrackers();\n }\n\n /**\n * Raised when a pointer leaves the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-exit\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-exit', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasPress( event ) {\n /**\n * Raised when the primary mouse button is pressed or touch starts on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-press\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} insideElementReleased - True if the cursor still inside the tracked element when the button was released.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-press', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n insideElementPressed: event.insideElementPressed,\n insideElementReleased: event.insideElementReleased,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasRelease( event ) {\n /**\n * Raised when the primary mouse button is released or touch ends on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-release\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} insideElementReleased - True if the cursor still inside the tracked element when the button was released.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-release', {\n tracker: event.eventSource,\n pointerType: event.pointerType,\n position: event.position,\n insideElementPressed: event.insideElementPressed,\n insideElementReleased: event.insideElementReleased,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasNonPrimaryPress( event ) {\n /**\n * Raised when any non-primary pointer button is pressed on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-nonprimary-press\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {Number} button - Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @property {Number} buttons - Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-nonprimary-press', {\n tracker: event.eventSource,\n position: event.position,\n pointerType: event.pointerType,\n button: event.button,\n buttons: event.buttons,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasNonPrimaryRelease( event ) {\n /**\n * Raised when any non-primary pointer button is released on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-nonprimary-release\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {String} pointerType - \"mouse\", \"touch\", \"pen\", etc.\n * @property {Number} button - Button which caused the event.\n * -1: none, 0: primary/left, 1: aux/middle, 2: secondary/right, 3: X1/back, 4: X2/forward, 5: pen eraser.\n * @property {Number} buttons - Current buttons pressed.\n * Combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-nonprimary-release', {\n tracker: event.eventSource,\n position: event.position,\n pointerType: event.pointerType,\n button: event.button,\n buttons: event.buttons,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onCanvasPinch( event ) {\n var gestureSettings,\n centerPt,\n lastCenterPt,\n panByPt;\n\n if ( !event.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.pinchToZoom ) {\n centerPt = this.viewport.pointFromPixel( event.center, true );\n lastCenterPt = this.viewport.pointFromPixel( event.lastCenter, true );\n panByPt = lastCenterPt.minus( centerPt );\n if( !this.panHorizontal ) {\n panByPt.x = 0;\n }\n if( !this.panVertical ) {\n panByPt.y = 0;\n }\n this.viewport.zoomBy( event.distance / event.lastDistance, centerPt, true );\n if ( gestureSettings.zoomToRefPoint ) {\n this.viewport.panBy(panByPt, true);\n }\n this.viewport.applyConstraints();\n }\n if ( gestureSettings.pinchRotate ) {\n // Pinch rotate\n var angle1 = Math.atan2(event.gesturePoints[0].currentPos.y - event.gesturePoints[1].currentPos.y,\n event.gesturePoints[0].currentPos.x - event.gesturePoints[1].currentPos.x);\n var angle2 = Math.atan2(event.gesturePoints[0].lastPos.y - event.gesturePoints[1].lastPos.y,\n event.gesturePoints[0].lastPos.x - event.gesturePoints[1].lastPos.x);\n this.viewport.setRotation(this.viewport.getRotation() + ((angle1 - angle2) * (180 / Math.PI)));\n }\n }\n /**\n * Raised when a pinch event occurs on the {@link OpenSeadragon.Viewer#canvas} element.\n *\n * @event canvas-pinch\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {Array.} gesturePoints - Gesture points associated with the gesture. Velocity data can be found here.\n * @property {OpenSeadragon.Point} lastCenter - The previous center point of the two pinch contact points relative to the tracked element.\n * @property {OpenSeadragon.Point} center - The center point of the two pinch contact points relative to the tracked element.\n * @property {Number} lastDistance - The previous distance between the two pinch contact points in CSS pixels.\n * @property {Number} distance - The distance between the two pinch contact points in CSS pixels.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('canvas-pinch', {\n tracker: event.eventSource,\n gesturePoints: event.gesturePoints,\n lastCenter: event.lastCenter,\n center: event.center,\n lastDistance: event.lastDistance,\n distance: event.distance,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n //cancels event\n return false;\n}\n\nfunction onCanvasScroll( event ) {\n var gestureSettings,\n factor,\n thisScrollTime,\n deltaScrollTime;\n\n /* Certain scroll devices fire the scroll event way too fast so we are injecting a simple adjustment to keep things\n * partially normalized. If we have already fired an event within the last 'minScrollDelta' milliseconds we skip\n * this one and wait for the next event. */\n thisScrollTime = $.now();\n deltaScrollTime = thisScrollTime - this._lastScrollTime;\n if (deltaScrollTime > this.minScrollDeltaTime) {\n this._lastScrollTime = thisScrollTime;\n\n if(this.viewport.flipped){\n event.position.x = this.viewport.getContainerSize().x - event.position.x;\n }\n\n if ( !event.preventDefaultAction && this.viewport ) {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if ( gestureSettings.scrollToZoom ) {\n factor = Math.pow( this.zoomPerScroll, event.scroll );\n this.viewport.zoomBy(\n factor,\n gestureSettings.zoomToRefPoint ? this.viewport.pointFromPixel( event.position, true ) : null\n );\n this.viewport.applyConstraints();\n }\n }\n /**\n * Raised when a scroll event occurs on the {@link OpenSeadragon.Viewer#canvas} element (mouse wheel).\n *\n * @event canvas-scroll\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} scroll - The scroll delta for the event.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'canvas-scroll', {\n tracker: event.eventSource,\n position: event.position,\n scroll: event.scroll,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n if (gestureSettings && gestureSettings.scrollToZoom) {\n //cancels event\n return false;\n }\n }\n else {\n gestureSettings = this.gestureSettingsByDeviceType( event.pointerType );\n if (gestureSettings && gestureSettings.scrollToZoom) {\n return false; // We are swallowing this event\n }\n }\n}\n\nfunction onContainerEnter( event ) {\n THIS[ this.hash ].mouseInside = true;\n abortControlsAutoHide( this );\n /**\n * Raised when the cursor enters the {@link OpenSeadragon.Viewer#container} element.\n *\n * @event container-enter\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'container-enter', {\n tracker: event.eventSource,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\nfunction onContainerExit( event ) {\n if ( event.pointers < 1 ) {\n THIS[ this.hash ].mouseInside = false;\n if ( !THIS[ this.hash ].animating ) {\n beginControlsAutoHide( this );\n }\n }\n /**\n * Raised when the cursor leaves the {@link OpenSeadragon.Viewer#container} element.\n *\n * @event container-exit\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} buttons - Current buttons pressed. A combination of bit flags 0: none, 1: primary (or touch contact), 2: secondary, 4: aux (often middle), 8: X1 (often back), 16: X2 (often forward), 32: pen eraser.\n * @property {Number} pointers - Number of pointers (all types) active in the tracked element.\n * @property {Boolean} insideElementPressed - True if the left mouse button is currently being pressed and was initiated inside the tracked element, otherwise false.\n * @property {Boolean} buttonDownAny - Was the button down anywhere in the screen during the event. Deprecated. Use buttons instead.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'container-exit', {\n tracker: event.eventSource,\n position: event.position,\n buttons: event.buttons,\n pointers: event.pointers,\n insideElementPressed: event.insideElementPressed,\n buttonDownAny: event.buttonDownAny,\n originalEvent: event.originalEvent\n });\n}\n\n\n///////////////////////////////////////////////////////////////////////////////\n// Page update routines ( aka Views - for future reference )\n///////////////////////////////////////////////////////////////////////////////\n\nfunction updateMulti( viewer ) {\n updateOnce( viewer );\n\n // Request the next frame, unless we've been closed\n if ( viewer.isOpen() ) {\n viewer._updateRequestId = scheduleUpdate( viewer, updateMulti );\n } else {\n viewer._updateRequestId = false;\n }\n}\n\nfunction updateOnce( viewer ) {\n\n //viewer.profiler.beginUpdate();\n\n if (viewer._opening) {\n return;\n }\n\n if (viewer.autoResize) {\n var containerSize = _getSafeElemSize(viewer.container);\n var prevContainerSize = THIS[viewer.hash].prevContainerSize;\n if (!containerSize.equals(prevContainerSize)) {\n var viewport = viewer.viewport;\n if (viewer.preserveImageSizeOnResize) {\n var resizeRatio = prevContainerSize.x / containerSize.x;\n var zoom = viewport.getZoom() * resizeRatio;\n var center = viewport.getCenter();\n viewport.resize(containerSize, false);\n viewport.zoomTo(zoom, null, true);\n viewport.panTo(center, true);\n } else {\n // maintain image position\n var oldBounds = viewport.getBounds();\n viewport.resize(containerSize, true);\n viewport.fitBoundsWithConstraints(oldBounds, true);\n }\n THIS[viewer.hash].prevContainerSize = containerSize;\n THIS[viewer.hash].forceRedraw = true;\n }\n }\n\n var viewportChange = viewer.viewport.update();\n var animated = viewer.world.update() || viewportChange;\n\n if (viewportChange) {\n /**\n * Raised when any spring animation update occurs (zoom, pan, etc.),\n * before the viewer has drawn the new location.\n *\n * @event viewport-change\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent('viewport-change');\n }\n\n if( viewer.referenceStrip ){\n animated = viewer.referenceStrip.update( viewer.viewport ) || animated;\n }\n\n if ( !THIS[ viewer.hash ].animating && animated ) {\n /**\n * Raised when any spring animation starts (zoom, pan, etc.).\n *\n * @event animation-start\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( \"animation-start\" );\n abortControlsAutoHide( viewer );\n }\n\n if ( animated || THIS[ viewer.hash ].forceRedraw || viewer.world.needsDraw() ) {\n drawWorld( viewer );\n viewer._drawOverlays();\n if( viewer.navigator ){\n viewer.navigator.update( viewer.viewport );\n }\n\n THIS[ viewer.hash ].forceRedraw = false;\n\n if (animated) {\n /**\n * Raised when any spring animation update occurs (zoom, pan, etc.),\n * after the viewer has drawn the new location.\n *\n * @event animation\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( \"animation\" );\n }\n }\n\n if ( THIS[ viewer.hash ].animating && !animated ) {\n /**\n * Raised when any spring animation ends (zoom, pan, etc.).\n *\n * @event animation-finish\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( \"animation-finish\" );\n\n if ( !THIS[ viewer.hash ].mouseInside ) {\n beginControlsAutoHide( viewer );\n }\n }\n\n THIS[ viewer.hash ].animating = animated;\n\n //viewer.profiler.endUpdate();\n}\n\nfunction drawWorld( viewer ) {\n viewer.imageLoader.clear();\n viewer.drawer.clear();\n viewer.world.draw();\n\n /**\n * - Needs documentation -\n *\n * @event update-viewport\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n viewer.raiseEvent( 'update-viewport', {} );\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// Navigation Controls\n///////////////////////////////////////////////////////////////////////////////\nfunction resolveUrl( prefix, url ) {\n return prefix ? prefix + url : url;\n}\n\n\n\nfunction beginZoomingIn() {\n THIS[ this.hash ].lastZoomTime = $.now();\n THIS[ this.hash ].zoomFactor = this.zoomPerSecond;\n THIS[ this.hash ].zooming = true;\n scheduleZoom( this );\n}\n\n\nfunction beginZoomingOut() {\n THIS[ this.hash ].lastZoomTime = $.now();\n THIS[ this.hash ].zoomFactor = 1.0 / this.zoomPerSecond;\n THIS[ this.hash ].zooming = true;\n scheduleZoom( this );\n}\n\n\nfunction endZooming() {\n THIS[ this.hash ].zooming = false;\n}\n\n\nfunction scheduleZoom( viewer ) {\n $.requestAnimationFrame( $.delegate( viewer, doZoom ) );\n}\n\n\nfunction doZoom() {\n var currentTime,\n deltaTime,\n adjustedFactor;\n\n if ( THIS[ this.hash ].zooming && this.viewport) {\n currentTime = $.now();\n deltaTime = currentTime - THIS[ this.hash ].lastZoomTime;\n adjustedFactor = Math.pow( THIS[ this.hash ].zoomFactor, deltaTime / 1000 );\n\n this.viewport.zoomBy( adjustedFactor );\n this.viewport.applyConstraints();\n THIS[ this.hash ].lastZoomTime = currentTime;\n scheduleZoom( this );\n }\n}\n\n\nfunction doSingleZoomIn() {\n if ( this.viewport ) {\n THIS[ this.hash ].zooming = false;\n this.viewport.zoomBy(\n this.zoomPerClick / 1.0\n );\n this.viewport.applyConstraints();\n }\n}\n\n\nfunction doSingleZoomOut() {\n if ( this.viewport ) {\n THIS[ this.hash ].zooming = false;\n this.viewport.zoomBy(\n 1.0 / this.zoomPerClick\n );\n this.viewport.applyConstraints();\n }\n}\n\n\nfunction lightUp() {\n this.buttons.emulateEnter();\n this.buttons.emulateExit();\n}\n\n\nfunction onHome() {\n if ( this.viewport ) {\n this.viewport.goHome();\n }\n}\n\n\nfunction onFullScreen() {\n if ( this.isFullPage() && !$.isFullScreen() ) {\n // Is fullPage but not fullScreen\n this.setFullPage( false );\n } else {\n this.setFullScreen( !this.isFullPage() );\n }\n // correct for no mouseout event on change\n if ( this.buttons ) {\n this.buttons.emulateExit();\n }\n this.fullPageButton.element.focus();\n if ( this.viewport ) {\n this.viewport.applyConstraints();\n }\n}\n\n/**\n * Note: The current rotation feature is limited to 90 degree turns.\n */\nfunction onRotateLeft() {\n if ( this.viewport ) {\n var currRotation = this.viewport.getRotation();\n\n if ( this.viewport.flipped ){\n currRotation = $.positiveModulo(currRotation + 90, 360);\n } else {\n currRotation = $.positiveModulo(currRotation - 90, 360);\n }\n this.viewport.setRotation(currRotation);\n }\n}\n\n/**\n * Note: The current rotation feature is limited to 90 degree turns.\n */\nfunction onRotateRight() {\n if ( this.viewport ) {\n var currRotation = this.viewport.getRotation();\n\n if ( this.viewport.flipped ){\n currRotation = $.positiveModulo(currRotation - 90, 360);\n } else {\n currRotation = $.positiveModulo(currRotation + 90, 360);\n }\n this.viewport.setRotation(currRotation);\n }\n}\n\n/**\n * Note: When pressed flip control button\n */\nfunction onFlip() {\n this.viewport.toggleFlip();\n}\n\nfunction onPrevious(){\n var previous = this._sequenceIndex - 1;\n if(this.navPrevNextWrap && previous < 0){\n previous += this.tileSources.length;\n }\n this.goToPage( previous );\n}\n\n\nfunction onNext(){\n var next = this._sequenceIndex + 1;\n if(this.navPrevNextWrap && next >= this.tileSources.length){\n next = 0;\n }\n this.goToPage( next );\n}\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Navigator\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Navigator\n * @classdesc The Navigator provides a small view of the current image as fixed\n * while representing the viewport as a moving box serving as a frame\n * of reference in the larger viewport as to which portion of the image\n * is currently being examined. The navigator's viewport can be interacted\n * with using the keyboard or the mouse.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.Viewer\n * @extends OpenSeadragon.EventSource\n * @param {Object} options\n */\n$.Navigator = function( options ){\n\n var viewer = options.viewer,\n _this = this,\n viewerSize,\n navigatorSize;\n\n //We may need to create a new element and id if they did not\n //provide the id for the existing element\n if( !options.id ){\n options.id = 'navigator-' + $.now();\n this.element = $.makeNeutralElement( \"div\" );\n options.controlOptions = {\n anchor: $.ControlAnchor.TOP_RIGHT,\n attachToViewer: true,\n autoFade: options.autoFade\n };\n\n if( options.position ){\n if( 'BOTTOM_RIGHT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.BOTTOM_RIGHT;\n } else if( 'BOTTOM_LEFT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.BOTTOM_LEFT;\n } else if( 'TOP_RIGHT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.TOP_RIGHT;\n } else if( 'TOP_LEFT' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.TOP_LEFT;\n } else if( 'ABSOLUTE' == options.position ){\n options.controlOptions.anchor = $.ControlAnchor.ABSOLUTE;\n options.controlOptions.top = options.top;\n options.controlOptions.left = options.left;\n options.controlOptions.height = options.height;\n options.controlOptions.width = options.width;\n }\n }\n\n } else {\n this.element = document.getElementById( options.id );\n options.controlOptions = {\n anchor: $.ControlAnchor.NONE,\n attachToViewer: false,\n autoFade: false\n };\n }\n this.element.id = options.id;\n this.element.className += ' navigator';\n\n options = $.extend( true, {\n sizeRatio: $.DEFAULT_SETTINGS.navigatorSizeRatio\n }, options, {\n element: this.element,\n tabIndex: -1, // No keyboard navigation, omit from tab order\n //These need to be overridden to prevent recursion since\n //the navigator is a viewer and a viewer has a navigator\n showNavigator: false,\n mouseNavEnabled: false,\n showNavigationControl: false,\n showSequenceControl: false,\n immediateRender: true,\n blendTime: 0,\n animationTime: 0,\n autoResize: options.autoResize,\n // prevent resizing the navigator from adding unwanted space around the image\n minZoomImageRatio: 1.0\n });\n\n options.minPixelRatio = this.minPixelRatio = viewer.minPixelRatio;\n\n $.setElementTouchActionNone( this.element );\n\n this.borderWidth = 2;\n //At some browser magnification levels the display regions lines up correctly, but at some there appears to\n //be a one pixel gap.\n this.fudge = new $.Point(1, 1);\n this.totalBorderWidths = new $.Point(this.borderWidth * 2, this.borderWidth * 2).minus(this.fudge);\n\n\n if ( options.controlOptions.anchor != $.ControlAnchor.NONE ) {\n (function( style, borderWidth ){\n style.margin = '0px';\n style.border = borderWidth + 'px solid #555';\n style.padding = '0px';\n style.background = '#000';\n style.opacity = 0.8;\n style.overflow = 'hidden';\n }( this.element.style, this.borderWidth));\n }\n\n this.displayRegion = $.makeNeutralElement( \"div\" );\n this.displayRegion.id = this.element.id + '-displayregion';\n this.displayRegion.className = 'displayregion';\n\n (function( style, borderWidth ){\n style.position = 'relative';\n style.top = '0px';\n style.left = '0px';\n style.fontSize = '0px';\n style.overflow = 'hidden';\n style.border = borderWidth + 'px solid #900';\n style.margin = '0px';\n style.padding = '0px';\n //TODO: IE doesnt like this property being set\n //try{ style.outline = '2px auto #909'; }catch(e){/*ignore*/}\n\n style.background = 'transparent';\n\n // We use square bracket notation on the statement below, because float is a keyword.\n // This is important for the Google Closure compiler, if nothing else.\n /*jshint sub:true */\n style['float'] = 'left'; //Webkit\n\n style.cssFloat = 'left'; //Firefox\n style.styleFloat = 'left'; //IE\n style.zIndex = 999999999;\n style.cursor = 'default';\n }( this.displayRegion.style, this.borderWidth ));\n\n this.displayRegionContainer = $.makeNeutralElement(\"div\");\n this.displayRegionContainer.id = this.element.id + '-displayregioncontainer';\n this.displayRegionContainer.className = \"displayregioncontainer\";\n this.displayRegionContainer.style.width = \"100%\";\n this.displayRegionContainer.style.height = \"100%\";\n\n viewer.addControl(\n this.element,\n options.controlOptions\n );\n\n this._resizeWithViewer = options.controlOptions.anchor != $.ControlAnchor.ABSOLUTE &&\n options.controlOptions.anchor != $.ControlAnchor.NONE;\n\n if ( this._resizeWithViewer ) {\n if ( options.width && options.height ) {\n this.element.style.height = typeof (options.height) == \"number\" ? (options.height + 'px') : options.height;\n this.element.style.width = typeof (options.width) == \"number\" ? (options.width + 'px') : options.width;\n } else {\n viewerSize = $.getElementSize( viewer.element );\n this.element.style.height = Math.round( viewerSize.y * options.sizeRatio ) + 'px';\n this.element.style.width = Math.round( viewerSize.x * options.sizeRatio ) + 'px';\n this.oldViewerSize = viewerSize;\n }\n navigatorSize = $.getElementSize( this.element );\n this.elementArea = navigatorSize.x * navigatorSize.y;\n }\n\n this.oldContainerSize = new $.Point( 0, 0 );\n\n $.Viewer.apply( this, [ options ] );\n\n this.displayRegionContainer.appendChild(this.displayRegion);\n this.element.getElementsByTagName('div')[0].appendChild(this.displayRegionContainer);\n\n function rotate(degrees) {\n _setTransformRotate(_this.displayRegionContainer, degrees);\n _setTransformRotate(_this.displayRegion, -degrees);\n _this.viewport.setRotation(degrees);\n }\n if (options.navigatorRotate) {\n var degrees = options.viewer.viewport ?\n options.viewer.viewport.getRotation() :\n options.viewer.degrees || 0;\n\n rotate(degrees);\n options.viewer.addHandler(\"rotate\", function (args) {\n rotate(args.degrees);\n });\n }\n\n\n // Remove the base class' (Viewer's) innerTracker and replace it with our own\n this.innerTracker.destroy();\n this.innerTracker = new $.MouseTracker({\n element: this.element,\n dragHandler: $.delegate( this, onCanvasDrag ),\n clickHandler: $.delegate( this, onCanvasClick ),\n releaseHandler: $.delegate( this, onCanvasRelease ),\n scrollHandler: $.delegate( this, onCanvasScroll )\n });\n\n this.addHandler(\"reset-size\", function() {\n if (_this.viewport) {\n _this.viewport.goHome(true);\n }\n });\n\n viewer.world.addHandler(\"item-index-change\", function(event) {\n window.setTimeout(function(){\n var item = _this.world.getItemAt(event.previousIndex);\n _this.world.setItemIndex(item, event.newIndex);\n }, 1);\n });\n\n viewer.world.addHandler(\"remove-item\", function(event) {\n var theirItem = event.item;\n var myItem = _this._getMatchingItem(theirItem);\n if (myItem) {\n _this.world.removeItem(myItem);\n }\n });\n\n this.update(viewer.viewport);\n};\n\n$.extend( $.Navigator.prototype, $.EventSource.prototype, $.Viewer.prototype, /** @lends OpenSeadragon.Navigator.prototype */{\n\n /**\n * Used to notify the navigator when its size has changed.\n * Especially useful when {@link OpenSeadragon.Options}.navigatorAutoResize is set to false and the navigator is resizable.\n * @function\n */\n updateSize: function () {\n if ( this.viewport ) {\n var containerSize = new $.Point(\n (this.container.clientWidth === 0 ? 1 : this.container.clientWidth),\n (this.container.clientHeight === 0 ? 1 : this.container.clientHeight)\n );\n\n if ( !containerSize.equals( this.oldContainerSize ) ) {\n this.viewport.resize( containerSize, true );\n this.viewport.goHome(true);\n this.oldContainerSize = containerSize;\n this.drawer.clear();\n this.world.draw();\n }\n }\n },\n /**\n /* Flip navigator element\n * @param {Boolean} state - Flip state to set.\n */\n setFlip: function(state) {\n this.viewport.setFlip(state);\n\n this.setDisplayTransform(this.viewer.viewport.getFlip() ? \"scale(-1,1)\" : \"scale(1,1)\");\n return this;\n },\n\n setDisplayTransform: function(rule) {\n setElementTransform(this.displayRegion, rule);\n setElementTransform(this.canvas, rule);\n setElementTransform(this.element, rule);\n },\n\n /**\n * Used to update the navigator minimap's viewport rectangle when a change in the viewer's viewport occurs.\n * @function\n * @param {OpenSeadragon.Viewport} The viewport this navigator is tracking.\n */\n update: function( viewport ) {\n\n var viewerSize,\n newWidth,\n newHeight,\n bounds,\n topleft,\n bottomright;\n\n viewerSize = $.getElementSize( this.viewer.element );\n if ( this._resizeWithViewer && viewerSize.x && viewerSize.y && !viewerSize.equals( this.oldViewerSize ) ) {\n this.oldViewerSize = viewerSize;\n\n if ( this.maintainSizeRatio || !this.elementArea) {\n newWidth = viewerSize.x * this.sizeRatio;\n newHeight = viewerSize.y * this.sizeRatio;\n } else {\n newWidth = Math.sqrt(this.elementArea * (viewerSize.x / viewerSize.y));\n newHeight = this.elementArea / newWidth;\n }\n\n this.element.style.width = Math.round( newWidth ) + 'px';\n this.element.style.height = Math.round( newHeight ) + 'px';\n\n if (!this.elementArea) {\n this.elementArea = newWidth * newHeight;\n }\n\n this.updateSize();\n }\n\n if (viewport && this.viewport) {\n bounds = viewport.getBoundsNoRotate(true);\n topleft = this.viewport.pixelFromPointNoRotate(bounds.getTopLeft(), false);\n bottomright = this.viewport.pixelFromPointNoRotate(bounds.getBottomRight(), false)\n .minus( this.totalBorderWidths );\n\n //update style for navigator-box\n var style = this.displayRegion.style;\n style.display = this.world.getItemCount() ? 'block' : 'none';\n\n style.top = Math.round( topleft.y ) + 'px';\n style.left = Math.round( topleft.x ) + 'px';\n\n var width = Math.abs( topleft.x - bottomright.x );\n var height = Math.abs( topleft.y - bottomright.y );\n // make sure width and height are non-negative so IE doesn't throw\n style.width = Math.round( Math.max( width, 0 ) ) + 'px';\n style.height = Math.round( Math.max( height, 0 ) ) + 'px';\n }\n\n },\n\n // overrides Viewer.addTiledImage\n addTiledImage: function(options) {\n var _this = this;\n\n var original = options.originalTiledImage;\n delete options.original;\n\n var optionsClone = $.extend({}, options, {\n success: function(event) {\n var myItem = event.item;\n myItem._originalForNavigator = original;\n _this._matchBounds(myItem, original, true);\n\n function matchBounds() {\n _this._matchBounds(myItem, original);\n }\n\n function matchOpacity() {\n _this._matchOpacity(myItem, original);\n }\n\n function matchCompositeOperation() {\n _this._matchCompositeOperation(myItem, original);\n }\n\n original.addHandler('bounds-change', matchBounds);\n original.addHandler('clip-change', matchBounds);\n original.addHandler('opacity-change', matchOpacity);\n original.addHandler('composite-operation-change', matchCompositeOperation);\n }\n });\n\n return $.Viewer.prototype.addTiledImage.apply(this, [optionsClone]);\n },\n\n // private\n _getMatchingItem: function(theirItem) {\n var count = this.world.getItemCount();\n var item;\n for (var i = 0; i < count; i++) {\n item = this.world.getItemAt(i);\n if (item._originalForNavigator === theirItem) {\n return item;\n }\n }\n\n return null;\n },\n\n // private\n _matchBounds: function(myItem, theirItem, immediately) {\n var bounds = theirItem.getBoundsNoRotate();\n myItem.setPosition(bounds.getTopLeft(), immediately);\n myItem.setWidth(bounds.width, immediately);\n myItem.setRotation(theirItem.getRotation(), immediately);\n myItem.setClip(theirItem.getClip());\n },\n\n // private\n _matchOpacity: function(myItem, theirItem) {\n myItem.setOpacity(theirItem.opacity);\n },\n\n // private\n _matchCompositeOperation: function(myItem, theirItem) {\n myItem.setCompositeOperation(theirItem.compositeOperation);\n }\n});\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasClick( event ) {\n if ( event.quick && this.viewer.viewport ) {\n if(this.viewer.viewport.flipped){\n event.position.x = this.viewport.getContainerSize().x - event.position.x;\n }\n this.viewer.viewport.panTo(this.viewport.pointFromPixel(event.position));\n this.viewer.viewport.applyConstraints();\n }\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasDrag( event ) {\n if ( this.viewer.viewport ) {\n if( !this.panHorizontal ){\n event.delta.x = 0;\n }\n if( !this.panVertical ){\n event.delta.y = 0;\n }\n\n if(this.viewer.viewport.flipped){\n event.delta.x = -event.delta.x;\n }\n\n this.viewer.viewport.panBy(\n this.viewport.deltaPointsFromPixels(\n event.delta\n )\n );\n if( this.viewer.constrainDuringPan ){\n this.viewer.viewport.applyConstraints();\n }\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasRelease( event ) {\n if ( event.insideElementPressed && this.viewer.viewport ) {\n this.viewer.viewport.applyConstraints();\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onCanvasScroll( event ) {\n /**\n * Raised when a scroll event occurs on the {@link OpenSeadragon.Viewer#navigator} element (mouse wheel, touch pinch, etc.).\n *\n * @event navigator-scroll\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.MouseTracker} tracker - A reference to the MouseTracker which originated this event.\n * @property {OpenSeadragon.Point} position - The position of the event relative to the tracked element.\n * @property {Number} scroll - The scroll delta for the event.\n * @property {Boolean} shift - True if the shift key was pressed during this event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'navigator-scroll', {\n tracker: event.eventSource,\n position: event.position,\n scroll: event.scroll,\n shift: event.shift,\n originalEvent: event.originalEvent\n });\n\n //dont scroll the page up and down if the user is scrolling\n //in the navigator\n return false;\n}\n\n/**\n * @function\n * @private\n * @param {Object} element\n * @param {Number} degrees\n */\nfunction _setTransformRotate( element, degrees ) {\n setElementTransform(element, \"rotate(\" + degrees + \"deg)\");\n}\n\nfunction setElementTransform( element, rule ) {\n element.style.webkitTransform = rule;\n element.style.mozTransform = rule;\n element.style.msTransform = rule;\n element.style.oTransform = rule;\n element.style.transform = rule;\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - getString/setString\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n//TODO: I guess this is where the i18n needs to be reimplemented. I'll look\n// into existing patterns for i18n in javascript but i think that mimicking\n// pythons gettext might be a reasonable approach.\nvar I18N = {\n Errors: {\n Dzc: \"Sorry, we don't support Deep Zoom Collections!\",\n Dzi: \"Hmm, this doesn't appear to be a valid Deep Zoom Image.\",\n Xml: \"Hmm, this doesn't appear to be a valid Deep Zoom Image.\",\n ImageFormat: \"Sorry, we don't support {0}-based Deep Zoom Images.\",\n Security: \"It looks like a security restriction stopped us from \" +\n \"loading this Deep Zoom Image.\",\n Status: \"This space unintentionally left blank ({0} {1}).\",\n OpenFailed: \"Unable to open {0}: {1}\"\n },\n\n Tooltips: {\n FullPage: \"Toggle full page\",\n Home: \"Go home\",\n ZoomIn: \"Zoom in\",\n ZoomOut: \"Zoom out\",\n NextPage: \"Next page\",\n PreviousPage: \"Previous page\",\n RotateLeft: \"Rotate left\",\n RotateRight: \"Rotate right\",\n Flip: \"Flip Horizontally\"\n }\n};\n\n$.extend( $, /** @lends OpenSeadragon */{\n\n /**\n * @function\n * @param {String} property\n */\n getString: function( prop ) {\n\n var props = prop.split('.'),\n string = null,\n args = arguments,\n container = I18N,\n i;\n\n for (i = 0; i < props.length - 1; i++) {\n // in case not a subproperty\n container = container[ props[ i ] ] || {};\n }\n string = container[ props[ i ] ];\n\n if ( typeof ( string ) != \"string\" ) {\n $.console.log( \"Untranslated source string:\", prop );\n string = \"\"; // FIXME: this breaks gettext()-style convention, which would return source\n }\n\n return string.replace(/\\{\\d+\\}/g, function(capture) {\n var i = parseInt( capture.match( /\\d+/ ), 10 ) + 1;\n return i < args.length ?\n args[ i ] :\n \"\";\n });\n },\n\n /**\n * @function\n * @param {String} property\n * @param {*} value\n */\n setString: function( prop, value ) {\n\n var props = prop.split('.'),\n container = I18N,\n i;\n\n for ( i = 0; i < props.length - 1; i++ ) {\n if ( !container[ props[ i ] ] ) {\n container[ props[ i ] ] = {};\n }\n container = container[ props[ i ] ];\n }\n\n container[ props[ i ] ] = value;\n }\n\n});\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Point\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Point\n * @classdesc A Point is really used as a 2-dimensional vector, equally useful for\n * representing a point on a plane, or the height and width of a plane\n * not requiring any other frame of reference.\n *\n * @memberof OpenSeadragon\n * @param {Number} [x] The vector component 'x'. Defaults to the origin at 0.\n * @param {Number} [y] The vector component 'y'. Defaults to the origin at 0.\n */\n$.Point = function( x, y ) {\n /**\n * The vector component 'x'.\n * @member {Number} x\n * @memberof OpenSeadragon.Point#\n */\n this.x = typeof ( x ) == \"number\" ? x : 0;\n /**\n * The vector component 'y'.\n * @member {Number} y\n * @memberof OpenSeadragon.Point#\n */\n this.y = typeof ( y ) == \"number\" ? y : 0;\n};\n\n/** @lends OpenSeadragon.Point.prototype */\n$.Point.prototype = {\n /**\n * @function\n * @returns {OpenSeadragon.Point} a duplicate of this Point\n */\n clone: function() {\n return new $.Point(this.x, this.y);\n },\n\n /**\n * Add another Point to this point and return a new Point.\n * @function\n * @param {OpenSeadragon.Point} point The point to add vector components.\n * @returns {OpenSeadragon.Point} A new point representing the sum of the\n * vector components\n */\n plus: function( point ) {\n return new $.Point(\n this.x + point.x,\n this.y + point.y\n );\n },\n\n /**\n * Substract another Point to this point and return a new Point.\n * @function\n * @param {OpenSeadragon.Point} point The point to substract vector components.\n * @returns {OpenSeadragon.Point} A new point representing the substraction of the\n * vector components\n */\n minus: function( point ) {\n return new $.Point(\n this.x - point.x,\n this.y - point.y\n );\n },\n\n /**\n * Multiply this point by a factor and return a new Point.\n * @function\n * @param {Number} factor The factor to multiply vector components.\n * @returns {OpenSeadragon.Point} A new point representing the multiplication\n * of the vector components by the factor\n */\n times: function( factor ) {\n return new $.Point(\n this.x * factor,\n this.y * factor\n );\n },\n\n /**\n * Divide this point by a factor and return a new Point.\n * @function\n * @param {Number} factor The factor to divide vector components.\n * @returns {OpenSeadragon.Point} A new point representing the division of the\n * vector components by the factor\n */\n divide: function( factor ) {\n return new $.Point(\n this.x / factor,\n this.y / factor\n );\n },\n\n /**\n * Compute the opposite of this point and return a new Point.\n * @function\n * @returns {OpenSeadragon.Point} A new point representing the opposite of the\n * vector components\n */\n negate: function() {\n return new $.Point( -this.x, -this.y );\n },\n\n /**\n * Compute the distance between this point and another point.\n * @function\n * @param {OpenSeadragon.Point} point The point to compute the distance with.\n * @returns {Number} The distance between the 2 points\n */\n distanceTo: function( point ) {\n return Math.sqrt(\n Math.pow( this.x - point.x, 2 ) +\n Math.pow( this.y - point.y, 2 )\n );\n },\n\n /**\n * Compute the squared distance between this point and another point.\n * Useful for optimizing things like comparing distances.\n * @function\n * @param {OpenSeadragon.Point} point The point to compute the squared distance with.\n * @returns {Number} The squared distance between the 2 points\n */\n squaredDistanceTo: function( point ) {\n return Math.pow( this.x - point.x, 2 ) +\n Math.pow( this.y - point.y, 2 );\n },\n\n /**\n * Apply a function to each coordinate of this point and return a new point.\n * @function\n * @param {function} func The function to apply to each coordinate.\n * @returns {OpenSeadragon.Point} A new point with the coordinates computed\n * by the specified function\n */\n apply: function( func ) {\n return new $.Point( func( this.x ), func( this.y ) );\n },\n\n /**\n * Check if this point is equal to another one.\n * @function\n * @param {OpenSeadragon.Point} point The point to compare this point with.\n * @returns {Boolean} true if they are equal, false otherwise.\n */\n equals: function( point ) {\n return (\n point instanceof $.Point\n ) && (\n this.x === point.x\n ) && (\n this.y === point.y\n );\n },\n\n /**\n * Rotates the point around the specified pivot\n * From http://stackoverflow.com/questions/4465931/rotate-rectangle-around-a-point\n * @function\n * @param {Number} degress to rotate around the pivot.\n * @param {OpenSeadragon.Point} [pivot=(0,0)] Point around which to rotate.\n * Defaults to the origin.\n * @returns {OpenSeadragon.Point}. A new point representing the point rotated around the specified pivot\n */\n rotate: function (degrees, pivot) {\n pivot = pivot || new $.Point(0, 0);\n var cos;\n var sin;\n // Avoid float computations when possible\n if (degrees % 90 === 0) {\n var d = $.positiveModulo(degrees, 360);\n switch (d) {\n case 0:\n cos = 1;\n sin = 0;\n break;\n case 90:\n cos = 0;\n sin = 1;\n break;\n case 180:\n cos = -1;\n sin = 0;\n break;\n case 270:\n cos = 0;\n sin = -1;\n break;\n }\n } else {\n var angle = degrees * Math.PI / 180.0;\n cos = Math.cos(angle);\n sin = Math.sin(angle);\n }\n var x = cos * (this.x - pivot.x) - sin * (this.y - pivot.y) + pivot.x;\n var y = sin * (this.x - pivot.x) + cos * (this.y - pivot.y) + pivot.y;\n return new $.Point(x, y);\n },\n\n /**\n * Convert this point to a string in the format (x,y) where x and y are\n * rounded to the nearest integer.\n * @function\n * @returns {String} A string representation of this point.\n */\n toString: function() {\n return \"(\" + (Math.round(this.x * 100) / 100) + \",\" + (Math.round(this.y * 100) / 100) + \")\";\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n\n/**\n * @class TileSource\n * @classdesc The TileSource contains the most basic implementation required to create a\n * smooth transition between layers in an image pyramid. It has only a single key\n * interface that must be implemented to complete its key functionality:\n * 'getTileUrl'. It also has several optional interfaces that can be\n * implemented if a new TileSource wishes to support configuration via a simple\n * object or array ('configure') and if the tile source supports or requires\n * configuration via retrieval of a document on the network ala AJAX or JSONP,\n * ('getImageInfo').\n *
\n * By default the image pyramid is split into N layers where the image's longest\n * side in M (in pixels), where N is the smallest integer which satisfies\n * 2^(N+1) >= M.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @param {Object} options\n * You can either specify a URL, or literally define the TileSource (by specifying\n * width, height, tileSize, tileOverlap, minLevel, and maxLevel). For the former,\n * the extending class is expected to implement 'getImageInfo' and 'configure'.\n * For the latter, the construction is assumed to occur through\n * the extending classes implementation of 'configure'.\n * @param {String} [options.url]\n * The URL for the data necessary for this TileSource.\n * @param {String} [options.referenceStripThumbnailUrl]\n * The URL for a thumbnail image to be used by the reference strip\n * @param {Function} [options.success]\n * A function to be called upon successful creation.\n * @param {Boolean} [options.ajaxWithCredentials]\n * If this TileSource needs to make an AJAX call, this specifies whether to set\n * the XHR's withCredentials (for accessing secure data).\n * @param {Object} [options.ajaxHeaders]\n * A set of headers to include in AJAX requests.\n * @param {Number} [options.width]\n * Width of the source image at max resolution in pixels.\n * @param {Number} [options.height]\n * Height of the source image at max resolution in pixels.\n * @param {Number} [options.tileSize]\n * The size of the tiles to assumed to make up each pyramid layer in pixels.\n * Tile size determines the point at which the image pyramid must be\n * divided into a matrix of smaller images.\n * Use options.tileWidth and options.tileHeight to support non-square tiles.\n * @param {Number} [options.tileWidth]\n * The width of the tiles to assumed to make up each pyramid layer in pixels.\n * @param {Number} [options.tileHeight]\n * The height of the tiles to assumed to make up each pyramid layer in pixels.\n * @param {Number} [options.tileOverlap]\n * The number of pixels each tile is expected to overlap touching tiles.\n * @param {Number} [options.minLevel]\n * The minimum level to attempt to load.\n * @param {Number} [options.maxLevel]\n * The maximum level to attempt to load.\n */\n$.TileSource = function( width, height, tileSize, tileOverlap, minLevel, maxLevel ) {\n var _this = this;\n\n var args = arguments,\n options,\n i;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: args[0],\n height: args[1],\n tileSize: args[2],\n tileOverlap: args[3],\n minLevel: args[4],\n maxLevel: args[5]\n };\n }\n\n //Tile sources supply some events, namely 'ready' when they must be configured\n //by asynchronously fetching their configuration data.\n $.EventSource.call( this );\n\n //we allow options to override anything we dont treat as\n //required via idiomatic options or which is functionally\n //set depending on the state of the readiness of this tile\n //source\n $.extend( true, this, options );\n\n if (!this.success) {\n //Any functions that are passed as arguments are bound to the ready callback\n for ( i = 0; i < arguments.length; i++ ) {\n if ( $.isFunction( arguments[ i ] ) ) {\n this.success = arguments[ i ];\n //only one callback per constructor\n break;\n }\n }\n }\n\n if (this.success) {\n this.addHandler( 'ready', function ( event ) {\n _this.success( event );\n } );\n }\n\n /**\n * Ratio of width to height\n * @member {Number} aspectRatio\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * Vector storing x and y dimensions ( width and height respectively ).\n * @member {OpenSeadragon.Point} dimensions\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * The overlap in pixels each tile shares with its adjacent neighbors.\n * @member {Number} tileOverlap\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * The minimum pyramid level this tile source supports or should attempt to load.\n * @member {Number} minLevel\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n * The maximum pyramid level this tile source supports or should attempt to load.\n * @member {Number} maxLevel\n * @memberof OpenSeadragon.TileSource#\n */\n /**\n *\n * @member {Boolean} ready\n * @memberof OpenSeadragon.TileSource#\n */\n\n if( 'string' == $.type( arguments[ 0 ] ) ){\n this.url = arguments[0];\n }\n\n if (this.url) {\n //in case the getImageInfo method is overriden and/or implies an\n //async mechanism set some safe defaults first\n this.aspectRatio = 1;\n this.dimensions = new $.Point( 10, 10 );\n this._tileWidth = 0;\n this._tileHeight = 0;\n this.tileOverlap = 0;\n this.minLevel = 0;\n this.maxLevel = 0;\n this.ready = false;\n //configuration via url implies the extending class\n //implements and 'configure'\n this.getImageInfo( this.url );\n\n } else {\n\n //explicit configuration via positional args in constructor\n //or the more idiomatic 'options' object\n this.ready = true;\n this.aspectRatio = (options.width && options.height) ?\n (options.width / options.height) : 1;\n this.dimensions = new $.Point( options.width, options.height );\n\n if ( this.tileSize ){\n this._tileWidth = this._tileHeight = this.tileSize;\n delete this.tileSize;\n } else {\n if( this.tileWidth ){\n // We were passed tileWidth in options, but we want to rename it\n // with a leading underscore to make clear that it is not safe to directly modify it\n this._tileWidth = this.tileWidth;\n delete this.tileWidth;\n } else {\n this._tileWidth = 0;\n }\n\n if( this.tileHeight ){\n // See note above about renaming this.tileWidth\n this._tileHeight = this.tileHeight;\n delete this.tileHeight;\n } else {\n this._tileHeight = 0;\n }\n }\n\n this.tileOverlap = options.tileOverlap ? options.tileOverlap : 0;\n this.minLevel = options.minLevel ? options.minLevel : 0;\n this.maxLevel = ( undefined !== options.maxLevel && null !== options.maxLevel ) ?\n options.maxLevel : (\n ( options.width && options.height ) ? Math.ceil(\n Math.log( Math.max( options.width, options.height ) ) /\n Math.log( 2 )\n ) : 0\n );\n if( this.success && $.isFunction( this.success ) ){\n this.success( this );\n }\n }\n\n\n};\n\n/** @lends OpenSeadragon.TileSource.prototype */\n$.TileSource.prototype = {\n\n getTileSize: function( level ) {\n $.console.error(\n \"[TileSource.getTileSize] is deprecated.\" +\n \"Use TileSource.getTileWidth() and TileSource.getTileHeight() instead\"\n );\n return this._tileWidth;\n },\n\n /**\n * Return the tileWidth for a given level.\n * Subclasses should override this if tileWidth can be different at different levels\n * such as in IIIFTileSource. Code should use this function rather than reading\n * from ._tileWidth directly.\n * @function\n * @param {Number} level\n */\n getTileWidth: function( level ) {\n if (!this._tileWidth) {\n return this.getTileSize(level);\n }\n return this._tileWidth;\n },\n\n /**\n * Return the tileHeight for a given level.\n * Subclasses should override this if tileHeight can be different at different levels\n * such as in IIIFTileSource. Code should use this function rather than reading\n * from ._tileHeight directly.\n * @function\n * @param {Number} level\n */\n getTileHeight: function( level ) {\n if (!this._tileHeight) {\n return this.getTileSize(level);\n }\n return this._tileHeight;\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function( level ) {\n\n // see https://github.com/openseadragon/openseadragon/issues/22\n // we use the tilesources implementation of getLevelScale to generate\n // a memoized re-implementation\n var levelScaleCache = {},\n i;\n for( i = 0; i <= this.maxLevel; i++ ){\n levelScaleCache[ i ] = 1 / Math.pow(2, this.maxLevel - i);\n }\n this.getLevelScale = function( _level ){\n return levelScaleCache[ _level ];\n };\n return this.getLevelScale( level );\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function( level ) {\n var scale = this.getLevelScale( level ),\n x = Math.ceil( scale * this.dimensions.x / this.getTileWidth(level) ),\n y = Math.ceil( scale * this.dimensions.y / this.getTileHeight(level) );\n\n return new $.Point( x, y );\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getPixelRatio: function( level ) {\n var imageSizeScaled = this.dimensions.times( this.getLevelScale( level ) ),\n rx = 1.0 / imageSizeScaled.x,\n ry = 1.0 / imageSizeScaled.y;\n\n return new $.Point(rx, ry);\n },\n\n\n /**\n * @function\n * @returns {Number} The highest level in this tile source that can be contained in a single tile.\n */\n getClosestLevel: function() {\n var i,\n tiles;\n\n for (i = this.minLevel + 1; i <= this.maxLevel; i++){\n tiles = this.getNumTiles(i);\n if (tiles.x > 1 || tiles.y > 1) {\n break;\n }\n }\n\n return i - 1;\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {OpenSeadragon.Point} point\n */\n getTileAtPoint: function(level, point) {\n var validPoint = point.x >= 0 && point.x <= 1 &&\n point.y >= 0 && point.y <= 1 / this.aspectRatio;\n $.console.assert(validPoint, \"[TileSource.getTileAtPoint] must be called with a valid point.\");\n\n var widthScaled = this.dimensions.x * this.getLevelScale(level);\n var pixelX = point.x * widthScaled;\n var pixelY = point.y * widthScaled;\n\n var x = Math.floor(pixelX / this.getTileWidth(level));\n var y = Math.floor(pixelY / this.getTileHeight(level));\n\n // When point.x == 1 or point.y == 1 / this.aspectRatio we want to\n // return the last tile of the row/column\n if (point.x >= 1) {\n x = this.getNumTiles(level).x - 1;\n }\n var EPSILON = 1e-15;\n if (point.y >= 1 / this.aspectRatio - EPSILON) {\n y = this.getNumTiles(level).y - 1;\n }\n\n return new $.Point(x, y);\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @param {Boolean} [isSource=false] Whether to return the source bounds of the tile.\n * @returns {OpenSeadragon.Rect} Either where this tile fits (in normalized coordinates) or the\n * portion of the tile to use as the source of the drawing operation (in pixels), depending on\n * the isSource parameter.\n */\n getTileBounds: function( level, x, y, isSource ) {\n var dimensionsScaled = this.dimensions.times( this.getLevelScale( level ) ),\n tileWidth = this.getTileWidth(level),\n tileHeight = this.getTileHeight(level),\n px = ( x === 0 ) ? 0 : tileWidth * x - this.tileOverlap,\n py = ( y === 0 ) ? 0 : tileHeight * y - this.tileOverlap,\n sx = tileWidth + ( x === 0 ? 1 : 2 ) * this.tileOverlap,\n sy = tileHeight + ( y === 0 ? 1 : 2 ) * this.tileOverlap,\n scale = 1.0 / dimensionsScaled.x;\n\n sx = Math.min( sx, dimensionsScaled.x - px );\n sy = Math.min( sy, dimensionsScaled.y - py );\n\n if (isSource) {\n return new $.Rect(0, 0, sx, sy);\n }\n\n return new $.Rect( px * scale, py * scale, sx * scale, sy * scale );\n },\n\n\n /**\n * Responsible for retrieving, and caching the\n * image metadata pertinent to this TileSources implementation.\n * @function\n * @param {String} url\n * @throws {Error}\n */\n getImageInfo: function( url ) {\n var _this = this,\n callbackName,\n callback,\n readySource,\n options,\n urlParts,\n filename,\n lastDot;\n\n\n if( url ) {\n urlParts = url.split( '/' );\n filename = urlParts[ urlParts.length - 1 ];\n lastDot = filename.lastIndexOf( '.' );\n if ( lastDot > -1 ) {\n urlParts[ urlParts.length - 1 ] = filename.slice( 0, lastDot );\n }\n }\n\n callback = function( data ){\n if( typeof (data) === \"string\" ) {\n data = $.parseXml( data );\n }\n var $TileSource = $.TileSource.determineType( _this, data, url );\n if ( !$TileSource ) {\n /**\n * Raised when an error occurs loading a TileSource.\n *\n * @event open-failed\n * @memberof OpenSeadragon.TileSource\n * @type {object}\n * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.\n * @property {String} message\n * @property {String} source\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'open-failed', { message: \"Unable to load TileSource\", source: url } );\n return;\n }\n\n options = $TileSource.prototype.configure.apply( _this, [ data, url ]);\n if (options.ajaxWithCredentials === undefined) {\n options.ajaxWithCredentials = _this.ajaxWithCredentials;\n }\n\n readySource = new $TileSource( options );\n _this.ready = true;\n /**\n * Raised when a TileSource is opened and initialized.\n *\n * @event ready\n * @memberof OpenSeadragon.TileSource\n * @type {object}\n * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.\n * @property {Object} tileSource\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'ready', { tileSource: readySource } );\n };\n\n if( url.match(/\\.js$/) ){\n //TODO: Its not very flexible to require tile sources to end jsonp\n // request for info with a url that ends with '.js' but for\n // now it's the only way I see to distinguish uniformly.\n callbackName = url.split('/').pop().replace('.js', '');\n $.jsonp({\n url: url,\n async: false,\n callbackName: callbackName,\n callback: callback\n });\n } else {\n // request info via xhr asynchronously.\n $.makeAjaxRequest( {\n url: url,\n withCredentials: this.ajaxWithCredentials,\n headers: this.ajaxHeaders,\n success: function( xhr ) {\n var data = processResponse( xhr );\n callback( data );\n },\n error: function ( xhr, exc ) {\n var msg;\n\n /*\n IE < 10 will block XHR requests to different origins. Any property access on the request\n object will raise an exception which we'll attempt to handle by formatting the original\n exception rather than the second one raised when we try to access xhr.status\n */\n try {\n msg = \"HTTP \" + xhr.status + \" attempting to load TileSource\";\n } catch ( e ) {\n var formattedExc;\n if ( typeof ( exc ) == \"undefined\" || !exc.toString ) {\n formattedExc = \"Unknown error\";\n } else {\n formattedExc = exc.toString();\n }\n\n msg = formattedExc + \" attempting to load TileSource\";\n }\n\n /***\n * Raised when an error occurs loading a TileSource.\n *\n * @event open-failed\n * @memberof OpenSeadragon.TileSource\n * @type {object}\n * @property {OpenSeadragon.TileSource} eventSource - A reference to the TileSource which raised the event.\n * @property {String} message\n * @property {String} source\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( 'open-failed', {\n message: msg,\n source: url\n });\n }\n });\n }\n\n },\n\n /**\n * Responsible determining if a the particular TileSource supports the\n * data format ( and allowed to apply logic against the url the data was\n * loaded from, if any ). Overriding implementations are expected to do\n * something smart with data and / or url to determine support. Also\n * understand that iteration order of TileSources is not guarunteed so\n * please make sure your data or url is expressive enough to ensure a simple\n * and sufficient mechanisim for clear determination.\n * @function\n * @param {String|Object|Array|Document} data\n * @param {String} url - the url the data was loaded\n * from if any.\n * @return {Boolean}\n */\n supports: function( data, url ) {\n return false;\n },\n\n /**\n * Responsible for parsing and configuring the\n * image metadata pertinent to this TileSources implementation.\n * This method is not implemented by this class other than to throw an Error\n * announcing you have to implement it. Because of the variety of tile\n * server technologies, and various specifications for building image\n * pyramids, this method is here to allow easy integration.\n * @function\n * @param {String|Object|Array|Document} data\n * @param {String} url - the url the data was loaded\n * from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n * @throws {Error}\n */\n configure: function( data, url ) {\n throw new Error( \"Method not implemented.\" );\n },\n\n /**\n * Responsible for retrieving the url which will return an image for the\n * region specified by the given x, y, and level components.\n * This method is not implemented by this class other than to throw an Error\n * announcing you have to implement it. Because of the variety of tile\n * server technologies, and various specifications for building image\n * pyramids, this method is here to allow easy integration.\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @throws {Error}\n */\n getTileUrl: function( level, x, y ) {\n throw new Error( \"Method not implemented.\" );\n },\n\n /**\n * Responsible for retrieving the headers which will be attached to the image request for the\n * region specified by the given x, y, and level components.\n * This option is only relevant if {@link OpenSeadragon.Options}.loadTilesWithAjax is set to true.\n * The headers returned here will override headers specified at the Viewer or TiledImage level.\n * Specifying a falsy value for a header will clear its existing value set at the Viewer or\n * TiledImage level (if any).\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @returns {Object}\n */\n getTileAjaxHeaders: function( level, x, y ) {\n return {};\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n tileExists: function( level, x, y ) {\n var numTiles = this.getNumTiles( level );\n return level >= this.minLevel &&\n level <= this.maxLevel &&\n x >= 0 &&\n y >= 0 &&\n x < numTiles.x &&\n y < numTiles.y;\n }\n};\n\n\n$.extend( true, $.TileSource.prototype, $.EventSource.prototype );\n\n\n/**\n * Decides whether to try to process the response as xml, json, or hand back\n * the text\n * @private\n * @inner\n * @function\n * @param {XMLHttpRequest} xhr - the completed network request\n */\nfunction processResponse( xhr ){\n var responseText = xhr.responseText,\n status = xhr.status,\n statusText,\n data;\n\n if ( !xhr ) {\n throw new Error( $.getString( \"Errors.Security\" ) );\n } else if ( xhr.status !== 200 && xhr.status !== 0 ) {\n status = xhr.status;\n statusText = ( status == 404 ) ?\n \"Not Found\" :\n xhr.statusText;\n throw new Error( $.getString( \"Errors.Status\", status, statusText ) );\n }\n\n if( responseText.match(/\\s*<.*/) ){\n try{\n data = ( xhr.responseXML && xhr.responseXML.documentElement ) ?\n xhr.responseXML :\n $.parseXml( responseText );\n } catch (e){\n data = xhr.responseText;\n }\n }else if( responseText.match(/\\s*[\\{\\[].*/) ){\n try{\n data = $.parseJSON(responseText);\n } catch(e){\n data = responseText;\n }\n }else{\n data = responseText;\n }\n return data;\n}\n\n\n/**\n * Determines the TileSource Implementation by introspection of OpenSeadragon\n * namespace, calling each TileSource implementation of 'isType'\n * @private\n * @inner\n * @function\n * @param {Object|Array|Document} data - the tile source configuration object\n * @param {String} url - the url where the tile source configuration object was\n * loaded from, if any.\n */\n$.TileSource.determineType = function( tileSource, data, url ){\n var property;\n for( property in OpenSeadragon ){\n if( property.match(/.+TileSource$/) &&\n $.isFunction( OpenSeadragon[ property ] ) &&\n $.isFunction( OpenSeadragon[ property ].prototype.supports ) &&\n OpenSeadragon[ property ].prototype.supports.call( tileSource, data, url )\n ){\n return OpenSeadragon[ property ];\n }\n }\n\n $.console.error( \"No TileSource was able to open %s %s\", url, data );\n};\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - DziTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class DziTileSource\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number|Object} width - the pixel width of the image or the idiomatic\n * options object which is used instead of positional arguments.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {Number} tileOverlap\n * @param {String} tilesUrl\n * @param {String} fileFormat\n * @param {OpenSeadragon.DisplayRect[]} displayRects\n * @property {String} tilesUrl\n * @property {String} fileFormat\n * @property {OpenSeadragon.DisplayRect[]} displayRects\n */\n$.DziTileSource = function( width, height, tileSize, tileOverlap, tilesUrl, fileFormat, displayRects, minLevel, maxLevel ) {\n var i,\n rect,\n level,\n options;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: arguments[ 0 ],\n height: arguments[ 1 ],\n tileSize: arguments[ 2 ],\n tileOverlap: arguments[ 3 ],\n tilesUrl: arguments[ 4 ],\n fileFormat: arguments[ 5 ],\n displayRects: arguments[ 6 ],\n minLevel: arguments[ 7 ],\n maxLevel: arguments[ 8 ]\n };\n }\n\n this._levelRects = {};\n this.tilesUrl = options.tilesUrl;\n this.fileFormat = options.fileFormat;\n this.displayRects = options.displayRects;\n\n if ( this.displayRects ) {\n for ( i = this.displayRects.length - 1; i >= 0; i-- ) {\n rect = this.displayRects[ i ];\n for ( level = rect.minLevel; level <= rect.maxLevel; level++ ) {\n if ( !this._levelRects[ level ] ) {\n this._levelRects[ level ] = [];\n }\n this._levelRects[ level ].push( rect );\n }\n }\n }\n\n $.TileSource.apply( this, [ options ] );\n\n};\n\n$.extend( $.DziTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.DziTileSource.prototype */{\n\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n var ns;\n if ( data.Image ) {\n ns = data.Image.xmlns;\n } else if ( data.documentElement) {\n if (\"Image\" == data.documentElement.localName || \"Image\" == data.documentElement.tagName) {\n ns = data.documentElement.namespaceURI;\n }\n }\n\n ns = (ns || '').toLowerCase();\n\n return (ns.indexOf('schemas.microsoft.com/deepzoom/2008') !== -1 ||\n ns.indexOf('schemas.microsoft.com/deepzoom/2009') !== -1);\n },\n\n /**\n *\n * @function\n * @param {Object|XMLDocument} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( data, url ){\n\n var options;\n\n if( !$.isPlainObject(data) ){\n\n options = configureFromXML( this, data );\n\n }else{\n\n options = configureFromObject( this, data );\n }\n\n if (url && !options.tilesUrl) {\n options.tilesUrl = url.replace(\n /([^\\/]+?)(\\.(dzi|xml|js)?(\\?[^\\/]*)?)?\\/?$/, '$1_files/');\n\n if (url.search(/\\.(dzi|xml|js)\\?/) != -1) {\n options.queryParams = url.match(/\\?.*/);\n }else{\n options.queryParams = '';\n }\n }\n\n return options;\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function( level, x, y ) {\n return [ this.tilesUrl, level, '/', x, '_', y, '.', this.fileFormat, this.queryParams ].join( '' );\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n tileExists: function( level, x, y ) {\n var rects = this._levelRects[ level ],\n rect,\n scale,\n xMin,\n yMin,\n xMax,\n yMax,\n i;\n\n if ( !rects || !rects.length ) {\n return true;\n }\n\n for ( i = rects.length - 1; i >= 0; i-- ) {\n rect = rects[ i ];\n\n if ( level < rect.minLevel || level > rect.maxLevel ) {\n continue;\n }\n\n scale = this.getLevelScale( level );\n xMin = rect.x * scale;\n yMin = rect.y * scale;\n xMax = xMin + rect.width * scale;\n yMax = yMin + rect.height * scale;\n\n xMin = Math.floor( xMin / this._tileWidth );\n yMin = Math.floor( yMin / this._tileWidth ); // DZI tiles are square, so we just use _tileWidth\n xMax = Math.ceil( xMax / this._tileWidth );\n yMax = Math.ceil( yMax / this._tileWidth );\n\n if ( xMin <= x && x < xMax && yMin <= y && y < yMax ) {\n return true;\n }\n }\n\n return false;\n }\n});\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromXML( tileSource, xmlDoc ){\n\n if ( !xmlDoc || !xmlDoc.documentElement ) {\n throw new Error( $.getString( \"Errors.Xml\" ) );\n }\n\n var root = xmlDoc.documentElement,\n rootName = root.localName || root.tagName,\n ns = xmlDoc.documentElement.namespaceURI,\n configuration = null,\n displayRects = [],\n dispRectNodes,\n dispRectNode,\n rectNode,\n sizeNode,\n i;\n\n if ( rootName == \"Image\" ) {\n\n try {\n sizeNode = root.getElementsByTagName(\"Size\" )[ 0 ];\n if (sizeNode === undefined) {\n sizeNode = root.getElementsByTagNameNS(ns, \"Size\" )[ 0 ];\n }\n\n configuration = {\n Image: {\n xmlns: \"http://schemas.microsoft.com/deepzoom/2008\",\n Url: root.getAttribute( \"Url\" ),\n Format: root.getAttribute( \"Format\" ),\n DisplayRect: null,\n Overlap: parseInt( root.getAttribute( \"Overlap\" ), 10 ),\n TileSize: parseInt( root.getAttribute( \"TileSize\" ), 10 ),\n Size: {\n Height: parseInt( sizeNode.getAttribute( \"Height\" ), 10 ),\n Width: parseInt( sizeNode.getAttribute( \"Width\" ), 10 )\n }\n }\n };\n\n if ( !$.imageFormatSupported( configuration.Image.Format ) ) {\n throw new Error(\n $.getString( \"Errors.ImageFormat\", configuration.Image.Format.toUpperCase() )\n );\n }\n\n dispRectNodes = root.getElementsByTagName(\"DisplayRect\" );\n if (dispRectNodes === undefined) {\n dispRectNodes = root.getElementsByTagNameNS(ns, \"DisplayRect\" )[ 0 ];\n }\n\n for ( i = 0; i < dispRectNodes.length; i++ ) {\n dispRectNode = dispRectNodes[ i ];\n rectNode = dispRectNode.getElementsByTagName(\"Rect\" )[ 0 ];\n if (rectNode === undefined) {\n rectNode = dispRectNode.getElementsByTagNameNS(ns, \"Rect\" )[ 0 ];\n }\n\n displayRects.push({\n Rect: {\n X: parseInt( rectNode.getAttribute( \"X\" ), 10 ),\n Y: parseInt( rectNode.getAttribute( \"Y\" ), 10 ),\n Width: parseInt( rectNode.getAttribute( \"Width\" ), 10 ),\n Height: parseInt( rectNode.getAttribute( \"Height\" ), 10 ),\n MinLevel: parseInt( dispRectNode.getAttribute( \"MinLevel\" ), 10 ),\n MaxLevel: parseInt( dispRectNode.getAttribute( \"MaxLevel\" ), 10 )\n }\n });\n }\n\n if( displayRects.length ){\n configuration.Image.DisplayRect = displayRects;\n }\n\n return configureFromObject( tileSource, configuration );\n\n } catch ( e ) {\n throw (e instanceof Error) ?\n e :\n new Error( $.getString(\"Errors.Dzi\") );\n }\n } else if ( rootName == \"Collection\" ) {\n throw new Error( $.getString( \"Errors.Dzc\" ) );\n } else if ( rootName == \"Error\" ) {\n var messageNode = root.getElementsByTagName(\"Message\")[0];\n var message = messageNode.firstChild.nodeValue;\n throw new Error(message);\n }\n\n throw new Error( $.getString( \"Errors.Dzi\" ) );\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromObject( tileSource, configuration ){\n var imageData = configuration.Image,\n tilesUrl = imageData.Url,\n fileFormat = imageData.Format,\n sizeData = imageData.Size,\n dispRectData = imageData.DisplayRect || [],\n width = parseInt( sizeData.Width, 10 ),\n height = parseInt( sizeData.Height, 10 ),\n tileSize = parseInt( imageData.TileSize, 10 ),\n tileOverlap = parseInt( imageData.Overlap, 10 ),\n displayRects = [],\n rectData,\n i;\n\n //TODO: need to figure out out to better handle image format compatibility\n // which actually includes additional file formats like xml and pdf\n // and plain text for various tilesource implementations to avoid low\n // level errors.\n //\n // For now, just don't perform the check.\n //\n /*if ( !imageFormatSupported( fileFormat ) ) {\n throw new Error(\n $.getString( \"Errors.ImageFormat\", fileFormat.toUpperCase() )\n );\n }*/\n\n for ( i = 0; i < dispRectData.length; i++ ) {\n rectData = dispRectData[ i ].Rect;\n\n displayRects.push( new $.DisplayRect(\n parseInt( rectData.X, 10 ),\n parseInt( rectData.Y, 10 ),\n parseInt( rectData.Width, 10 ),\n parseInt( rectData.Height, 10 ),\n parseInt( rectData.MinLevel, 10 ),\n parseInt( rectData.MaxLevel, 10 )\n ));\n }\n\n return $.extend(true, {\n width: width, /* width *required */\n height: height, /* height *required */\n tileSize: tileSize, /* tileSize *required */\n tileOverlap: tileOverlap, /* tileOverlap *required */\n minLevel: null, /* minLevel */\n maxLevel: null, /* maxLevel */\n tilesUrl: tilesUrl, /* tilesUrl */\n fileFormat: fileFormat, /* fileFormat */\n displayRects: displayRects /* displayRects */\n }, configuration );\n\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - IIIFTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class IIIFTileSource\n * @classdesc A client implementation of the International Image Interoperability Framework\n * Format: Image API 1.0 - 2.1\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @see http://iiif.io/api/image/\n */\n$.IIIFTileSource = function( options ){\n\n /* eslint-disable camelcase */\n\n $.extend( true, this, options );\n\n if ( !( this.height && this.width && this['@id'] ) ) {\n throw new Error( 'IIIF required parameters not provided.' );\n }\n\n options.tileSizePerScaleFactor = {};\n\n // N.B. 2.0 renamed scale_factors to scaleFactors\n if ( this.tile_width && this.tile_height ) {\n options.tileWidth = this.tile_width;\n options.tileHeight = this.tile_height;\n } else if ( this.tile_width ) {\n options.tileSize = this.tile_width;\n } else if ( this.tile_height ) {\n options.tileSize = this.tile_height;\n } else if ( this.tiles ) {\n // Version 2.0 forwards\n if ( this.tiles.length == 1 ) {\n options.tileWidth = this.tiles[0].width;\n // Use height if provided, otherwise assume square tiles and use width.\n options.tileHeight = this.tiles[0].height || this.tiles[0].width;\n this.scale_factors = this.tiles[0].scaleFactors;\n } else {\n // Multiple tile sizes at different levels\n this.scale_factors = [];\n for (var t = 0; t < this.tiles.length; t++ ) {\n for (var sf = 0; sf < this.tiles[t].scaleFactors.length; sf++) {\n var scaleFactor = this.tiles[t].scaleFactors[sf];\n this.scale_factors.push(scaleFactor);\n options.tileSizePerScaleFactor[scaleFactor] = {\n width: this.tiles[t].width,\n height: this.tiles[t].height || this.tiles[t].width\n };\n }\n }\n }\n } else if ( canBeTiled(options.profile) ) {\n // use the largest of tileOptions that is smaller than the short dimension\n var shortDim = Math.min( this.height, this.width ),\n tileOptions = [256, 512, 1024],\n smallerTiles = [];\n\n for ( var c = 0; c < tileOptions.length; c++ ) {\n if ( tileOptions[c] <= shortDim ) {\n smallerTiles.push( tileOptions[c] );\n }\n }\n\n if ( smallerTiles.length > 0 ) {\n options.tileSize = Math.max.apply( null, smallerTiles );\n } else {\n // If we're smaller than 256, just use the short side.\n options.tileSize = shortDim;\n }\n } else if (this.sizes && this.sizes.length > 0) {\n // This info.json can't be tiled, but we can still construct a legacy pyramid from the sizes array.\n // In this mode, IIIFTileSource will call functions from the abstract baseTileSource or the\n // LegacyTileSource instead of performing IIIF tiling.\n this.emulateLegacyImagePyramid = true;\n\n options.levels = constructLevels( this );\n // use the largest available size to define tiles\n $.extend( true, options, {\n width: options.levels[ options.levels.length - 1 ].width,\n height: options.levels[ options.levels.length - 1 ].height,\n tileSize: Math.max( options.height, options.width ),\n tileOverlap: 0,\n minLevel: 0,\n maxLevel: options.levels.length - 1\n });\n this.levels = options.levels;\n } else {\n $.console.error(\"Nothing in the info.json to construct image pyramids from\");\n }\n\n if (!options.maxLevel && !this.emulateLegacyImagePyramid) {\n if (!this.scale_factors) {\n options.maxLevel = Number(Math.ceil(Math.log(Math.max(this.width, this.height), 2)));\n } else {\n var maxScaleFactor = Math.max.apply(null, this.scale_factors);\n options.maxLevel = Math.round(Math.log(maxScaleFactor) * Math.LOG2E);\n }\n }\n\n $.TileSource.apply( this, [ options ] );\n};\n\n$.extend( $.IIIFTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.IIIFTileSource.prototype */{\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n\n supports: function( data, url ) {\n // Version 2.0 and forwards\n if (data.protocol && data.protocol == 'http://iiif.io/api/image') {\n return true;\n // Version 1.1\n } else if ( data['@context'] && (\n data['@context'] == \"http://library.stanford.edu/iiif/image-api/1.1/context.json\" ||\n data['@context'] == \"http://iiif.io/api/image/1/context.json\") ) {\n // N.B. the iiif.io context is wrong, but where the representation lives so likely to be used\n return true;\n\n // Version 1.0\n } else if ( data.profile &&\n data.profile.indexOf(\"http://library.stanford.edu/iiif/image-api/compliance.html\") === 0) {\n return true;\n } else if ( data.identifier && data.width && data.height ) {\n return true;\n } else if ( data.documentElement &&\n \"info\" == data.documentElement.tagName &&\n \"http://library.stanford.edu/iiif/image-api/ns/\" ==\n data.documentElement.namespaceURI) {\n return true;\n\n // Not IIIF\n } else {\n return false;\n }\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @example IIIF 1.1 Info Looks like this\n * {\n * \"@context\" : \"http://library.stanford.edu/iiif/image-api/1.1/context.json\",\n * \"@id\" : \"http://iiif.example.com/prefix/1E34750D-38DB-4825-A38A-B60A345E591C\",\n * \"width\" : 6000,\n * \"height\" : 4000,\n * \"scale_factors\" : [ 1, 2, 4 ],\n * \"tile_width\" : 1024,\n * \"tile_height\" : 1024,\n * \"formats\" : [ \"jpg\", \"png\" ],\n * \"qualities\" : [ \"native\", \"grey\" ],\n * \"profile\" : \"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0\"\n * }\n */\n configure: function( data, url ){\n // Try to deduce our version and fake it upwards if needed\n if ( !$.isPlainObject(data) ) {\n var options = configureFromXml10( data );\n options['@context'] = \"http://iiif.io/api/image/1.0/context.json\";\n options['@id'] = url.replace('/info.xml', '');\n return options;\n } else if ( !data['@context'] ) {\n data['@context'] = 'http://iiif.io/api/image/1.0/context.json';\n data['@id'] = url.replace('/info.json', '');\n return data;\n } else {\n return data;\n }\n },\n\n /**\n * Return the tileWidth for the given level.\n * @function\n * @param {Number} level\n */\n getTileWidth: function( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n return $.TileSource.prototype.getTileWidth.call(this, level);\n }\n\n var scaleFactor = Math.pow(2, this.maxLevel - level);\n\n if (this.tileSizePerScaleFactor && this.tileSizePerScaleFactor[scaleFactor]) {\n return this.tileSizePerScaleFactor[scaleFactor].width;\n }\n return this._tileWidth;\n },\n\n /**\n * Return the tileHeight for the given level.\n * @function\n * @param {Number} level\n */\n getTileHeight: function( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n return $.TileSource.prototype.getTileHeight.call(this, level);\n }\n\n var scaleFactor = Math.pow(2, this.maxLevel - level);\n\n if (this.tileSizePerScaleFactor && this.tileSizePerScaleFactor[scaleFactor]) {\n return this.tileSizePerScaleFactor[scaleFactor].height;\n }\n return this._tileHeight;\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function ( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n var levelScale = NaN;\n if (this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel) {\n levelScale =\n this.levels[level].width /\n this.levels[this.maxLevel].width;\n }\n return levelScale;\n }\n\n return $.TileSource.prototype.getLevelScale.call(this, level);\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function( level ) {\n\n if(this.emulateLegacyImagePyramid) {\n var scale = this.getLevelScale(level);\n if (scale) {\n return new $.Point(1, 1);\n } else {\n return new $.Point(0, 0);\n }\n }\n\n return $.TileSource.prototype.getNumTiles.call(this, level);\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {OpenSeadragon.Point} point\n */\n getTileAtPoint: function( level, point ) {\n\n if(this.emulateLegacyImagePyramid) {\n return new $.Point(0, 0);\n }\n\n return $.TileSource.prototype.getTileAtPoint.call(this, level, point);\n },\n\n\n /**\n * Responsible for retrieving the url which will return an image for the\n * region specified by the given x, y, and level components.\n * @function\n * @param {Number} level - z index\n * @param {Number} x\n * @param {Number} y\n * @throws {Error}\n */\n getTileUrl: function( level, x, y ){\n\n if(this.emulateLegacyImagePyramid) {\n var url = null;\n if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {\n url = this.levels[ level ].url;\n }\n return url;\n }\n\n //# constants\n var IIIF_ROTATION = '0',\n //## get the scale (level as a decimal)\n scale = Math.pow( 0.5, this.maxLevel - level ),\n\n //# image dimensions at this level\n levelWidth = Math.ceil( this.width * scale ),\n levelHeight = Math.ceil( this.height * scale ),\n\n //## iiif region\n tileWidth,\n tileHeight,\n iiifTileSizeWidth,\n iiifTileSizeHeight,\n iiifRegion,\n iiifTileX,\n iiifTileY,\n iiifTileW,\n iiifTileH,\n iiifSize,\n iiifQuality,\n uri;\n\n tileWidth = this.getTileWidth(level);\n tileHeight = this.getTileHeight(level);\n iiifTileSizeWidth = Math.ceil( tileWidth / scale );\n iiifTileSizeHeight = Math.ceil( tileHeight / scale );\n\n if ( this['@context'].indexOf('/1.0/context.json') > -1 ||\n this['@context'].indexOf('/1.1/context.json') > -1 ||\n this['@context'].indexOf('/1/context.json') > -1 ) {\n iiifQuality = \"native.jpg\";\n } else {\n iiifQuality = \"default.jpg\";\n }\n\n if ( levelWidth < tileWidth && levelHeight < tileHeight ){\n iiifSize = levelWidth + \",\";\n iiifRegion = 'full';\n } else {\n iiifTileX = x * iiifTileSizeWidth;\n iiifTileY = y * iiifTileSizeHeight;\n iiifTileW = Math.min( iiifTileSizeWidth, this.width - iiifTileX );\n iiifTileH = Math.min( iiifTileSizeHeight, this.height - iiifTileY );\n iiifSize = Math.ceil( iiifTileW * scale ) + \",\";\n iiifRegion = [ iiifTileX, iiifTileY, iiifTileW, iiifTileH ].join( ',' );\n }\n uri = [ this['@id'], iiifRegion, iiifSize, IIIF_ROTATION, iiifQuality ].join( '/' );\n\n return uri;\n }\n\n });\n\n /**\n * Determine whether arbitrary tile requests can be made against a service with the given profile\n * @function\n * @param {object} profile - IIIF profile object\n * @throws {Error}\n */\n function canBeTiled (profile ) {\n var level0Profiles = [\n \"http://library.stanford.edu/iiif/image-api/compliance.html#level0\",\n \"http://library.stanford.edu/iiif/image-api/1.1/compliance.html#level0\",\n \"http://iiif.io/api/image/2/level0.json\"\n ];\n var isLevel0 = (level0Profiles.indexOf(profile[0]) != -1);\n return !isLevel0 || (profile.indexOf(\"sizeByW\") != -1);\n }\n\n /**\n * Build the legacy pyramid URLs (one tile per level)\n * @function\n * @param {object} options - infoJson\n * @throws {Error}\n */\n function constructLevels(options) {\n var levels = [];\n for(var i = 0; i < options.sizes.length; i++) {\n levels.push({\n url: options['@id'] + '/full/' + options.sizes[i].width + ',/0/default.jpg',\n width: options.sizes[i].width,\n height: options.sizes[i].height\n });\n }\n return levels.sort(function(a, b) {\n return a.width - b.width;\n });\n }\n\n\n function configureFromXml10(xmlDoc) {\n //parse the xml\n if ( !xmlDoc || !xmlDoc.documentElement ) {\n throw new Error( $.getString( \"Errors.Xml\" ) );\n }\n\n var root = xmlDoc.documentElement,\n rootName = root.tagName,\n configuration = null;\n\n if ( rootName == \"info\" ) {\n try {\n configuration = {};\n parseXML10( root, configuration );\n return configuration;\n\n } catch ( e ) {\n throw (e instanceof Error) ?\n e :\n new Error( $.getString(\"Errors.IIIF\") );\n }\n }\n throw new Error( $.getString( \"Errors.IIIF\" ) );\n }\n\n function parseXML10( node, configuration, property ) {\n var i,\n value;\n if ( node.nodeType == 3 && property ) {//text node\n value = node.nodeValue.trim();\n if( value.match(/^\\d*$/)){\n value = Number( value );\n }\n if( !configuration[ property ] ){\n configuration[ property ] = value;\n }else{\n if( !$.isArray( configuration[ property ] ) ){\n configuration[ property ] = [ configuration[ property ] ];\n }\n configuration[ property ].push( value );\n }\n } else if( node.nodeType == 1 ){\n for( i = 0; i < node.childNodes.length; i++ ){\n parseXML10( node.childNodes[ i ], configuration, node.nodeName );\n }\n }\n }\n\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - OsmTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Derived from the OSM tile source in Rainer Simon's seajax-utils project\n * . Rainer Simon has contributed\n * the included code to the OpenSeadragon project under the New BSD license;\n * see .\n */\n\n\n(function( $ ){\n\n/**\n * @class OsmTileSource\n * @classdesc A tilesource implementation for OpenStreetMap.

\n *\n * Note 1. Zoomlevels. Deep Zoom and OSM define zoom levels differently. In Deep\n * Zoom, level 0 equals an image of 1x1 pixels. In OSM, level 0 equals an image of\n * 256x256 levels (see http://gasi.ch/blog/inside-deep-zoom-2). I.e. there is a\n * difference of log2(256)=8 levels.

\n *\n * Note 2. Image dimension. According to the OSM Wiki\n * (http://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#Zoom_levels)\n * the highest Mapnik zoom level has 256.144x256.144 tiles, with a 256x256\n * pixel size. I.e. the Deep Zoom image dimension is 65.572.864x65.572.864\n * pixels.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number|Object} width - the pixel width of the image or the idiomatic\n * options object which is used instead of positional arguments.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {Number} tileOverlap\n * @param {String} tilesUrl\n */\n$.OsmTileSource = function( width, height, tileSize, tileOverlap, tilesUrl ) {\n var options;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: arguments[0],\n height: arguments[1],\n tileSize: arguments[2],\n tileOverlap: arguments[3],\n tilesUrl: arguments[4]\n };\n }\n //apply default setting for standard public OpenStreatMaps service\n //but allow them to be specified so fliks can host there own instance\n //or apply against other services supportting the same standard\n if( !options.width || !options.height ){\n options.width = 65572864;\n options.height = 65572864;\n }\n if( !options.tileSize ){\n options.tileSize = 256;\n options.tileOverlap = 0;\n }\n if( !options.tilesUrl ){\n options.tilesUrl = \"http://tile.openstreetmap.org/\";\n }\n options.minLevel = 8;\n\n $.TileSource.apply( this, [ options ] );\n\n};\n\n$.extend( $.OsmTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.OsmTileSource.prototype */{\n\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n return (\n data.type &&\n \"openstreetmaps\" == data.type\n );\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( data, url ){\n return data;\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function( level, x, y ) {\n return this.tilesUrl + (level - 8) + \"/\" + x + \"/\" + y + \".png\";\n }\n});\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TmsTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n/*\n * Derived from the TMS tile source in Rainer Simon's seajax-utils project\n * . Rainer Simon has contributed\n * the included code to the OpenSeadragon project under the New BSD license;\n * see .\n */\n\n\n(function( $ ){\n\n/**\n * @class TmsTileSource\n * @classdesc A tilesource implementation for Tiled Map Services (TMS).\n * TMS tile scheme ( [ as supported by OpenLayers ] is described here\n * ( http://openlayers.org/dev/examples/tms.html ).\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number|Object} width - the pixel width of the image or the idiomatic\n * options object which is used instead of positional arguments.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {Number} tileOverlap\n * @param {String} tilesUrl\n */\n$.TmsTileSource = function( width, height, tileSize, tileOverlap, tilesUrl ) {\n var options;\n\n if( $.isPlainObject( width ) ){\n options = width;\n }else{\n options = {\n width: arguments[0],\n height: arguments[1],\n tileSize: arguments[2],\n tileOverlap: arguments[3],\n tilesUrl: arguments[4]\n };\n }\n // TMS has integer multiples of 256 for width/height and adds buffer\n // if necessary -> account for this!\n var bufferedWidth = Math.ceil(options.width / 256) * 256,\n bufferedHeight = Math.ceil(options.height / 256) * 256,\n max;\n\n // Compute number of zoomlevels in this tileset\n if (bufferedWidth > bufferedHeight) {\n max = bufferedWidth / 256;\n } else {\n max = bufferedHeight / 256;\n }\n options.maxLevel = Math.ceil(Math.log(max) / Math.log(2)) - 1;\n options.tileSize = 256;\n options.width = bufferedWidth;\n options.height = bufferedHeight;\n\n $.TileSource.apply( this, [ options ] );\n\n};\n\n$.extend( $.TmsTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.TmsTileSource.prototype */{\n\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n return ( data.type && \"tiledmapservice\" == data.type );\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( data, url ){\n return data;\n },\n\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function( level, x, y ) {\n // Convert from Deep Zoom definition to TMS zoom definition\n var yTiles = this.getNumTiles( level ).y - 1;\n\n return this.tilesUrl + level + \"/\" + x + \"/\" + (yTiles - y) + \".png\";\n }\n});\n\n\n}( OpenSeadragon ));\n\n(function($) {\n\n /**\n * @class ZoomifyTileSource\n * @classdesc A tilesource implementation for the zoomify format.\n *\n * A description of the format can be found here:\n * https://ecommons.cornell.edu/bitstream/handle/1813/5410/Introducing_Zoomify_Image.pdf\n *\n * There are two ways of creating a zoomify tilesource for openseadragon\n *\n * 1) Supplying all necessary information in the tilesource object. A minimal example object for this method looks like this:\n *\n * {\n * type: \"zoomifytileservice\",\n * width: 1000,\n * height: 1000,\n * tilesUrl: \"/test/data/zoomify/\"\n * }\n *\n * The tileSize is currently hardcoded to 256 (the usual Zoomify default). The tileUrl must the path to the image _directory_.\n *\n * 2) Loading image metadata from xml file: (CURRENTLY NOT SUPPORTED)\n *\n * When creating zoomify formatted images one \"xml\" like file with name ImageProperties.xml\n * will be created as well. Here is an example of such a file:\n *\n * \n *\n * To use this xml file as metadata source you must supply the path to the ImageProperties.xml file and leave out all other parameters:\n * As stated above, this method of loading a zoomify tilesource is currently not supported\n *\n * {\n * type: \"zoomifytileservice\",\n * tilesUrl: \"/test/data/zoomify/ImageProperties.xml\"\n * }\n\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Number} width - the pixel width of the image.\n * @param {Number} height\n * @param {Number} tileSize\n * @param {String} tilesUrl\n */\n $.ZoomifyTileSource = function(options) {\n options.tileSize = 256;\n\n var currentImageSize = {\n x: options.width,\n y: options.height\n };\n options.imageSizes = [{\n x: options.width,\n y: options.height\n }];\n options.gridSize = [this._getGridSize(options.width, options.height, options.tileSize)];\n\n while (parseInt(currentImageSize.x, 10) > options.tileSize || parseInt(currentImageSize.y, 10) > options.tileSize) {\n currentImageSize.x = Math.floor(currentImageSize.x / 2);\n currentImageSize.y = Math.floor(currentImageSize.y / 2);\n options.imageSizes.push({\n x: currentImageSize.x,\n y: currentImageSize.y\n });\n options.gridSize.push(this._getGridSize(currentImageSize.x, currentImageSize.y, options.tileSize));\n }\n options.imageSizes.reverse();\n options.gridSize.reverse();\n options.minLevel = 0;\n options.maxLevel = options.gridSize.length - 1;\n\n OpenSeadragon.TileSource.apply(this, [options]);\n };\n\n $.extend($.ZoomifyTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.ZoomifyTileSource.prototype */ {\n\n //private\n _getGridSize: function(width, height, tileSize) {\n return {\n x: Math.ceil(width / tileSize),\n y: Math.ceil(height / tileSize)\n };\n },\n\n //private\n _calculateAbsoluteTileNumber: function(level, x, y) {\n var num = 0;\n var size = {};\n\n //Sum up all tiles below the level we want the number of tiles\n for (var z = 0; z < level; z++) {\n size = this.gridSize[z];\n num += size.x * size.y;\n }\n //Add the tiles of the level\n size = this.gridSize[level];\n num += size.x * y + x;\n return num;\n },\n\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function(data, url) {\n return (data.type && \"zoomifytileservice\" == data.type);\n },\n\n /**\n *\n * @function\n * @param {Object} data - the raw configuration\n * @param {String} url - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function(data, url) {\n return data;\n },\n\n /**\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n */\n getTileUrl: function(level, x, y) {\n //console.log(level);\n var result = 0;\n var num = this._calculateAbsoluteTileNumber(level, x, y);\n result = Math.floor(num / 256);\n return this.tilesUrl + 'TileGroup' + result + '/' + level + '-' + x + '-' + y + '.jpg';\n\n }\n });\n\n}(OpenSeadragon));\n\n\n/*\n * OpenSeadragon - LegacyTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class LegacyTileSource\n * @classdesc The LegacyTileSource allows simple, traditional image pyramids to be loaded\n * into an OpenSeadragon Viewer. Basically, this translates to the historically\n * common practice of starting with a 'master' image, maybe a tiff for example,\n * and generating a set of 'service' images like one or more thumbnails, a medium\n * resolution image and a high resolution image in standard web formats like\n * png or jpg.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Array} levels An array of file descriptions, each is an object with\n * a 'url', a 'width', and a 'height'. Overriding classes can expect more\n * properties but these properties are sufficient for this implementation.\n * Additionally, the levels are required to be listed in order from\n * smallest to largest.\n * @property {Number} aspectRatio\n * @property {Number} dimensions\n * @property {Number} tileSize\n * @property {Number} tileOverlap\n * @property {Number} minLevel\n * @property {Number} maxLevel\n * @property {Array} levels\n */\n$.LegacyTileSource = function( levels ) {\n\n var options,\n width,\n height;\n\n if( $.isArray( levels ) ){\n options = {\n type: 'legacy-image-pyramid',\n levels: levels\n };\n }\n\n //clean up the levels to make sure we support all formats\n options.levels = filterFiles( options.levels );\n\n if ( options.levels.length > 0 ) {\n width = options.levels[ options.levels.length - 1 ].width;\n height = options.levels[ options.levels.length - 1 ].height;\n }\n else {\n width = 0;\n height = 0;\n $.console.error( \"No supported image formats found\" );\n }\n\n $.extend( true, options, {\n width: width,\n height: height,\n tileSize: Math.max( height, width ),\n tileOverlap: 0,\n minLevel: 0,\n maxLevel: options.levels.length > 0 ? options.levels.length - 1 : 0\n } );\n\n $.TileSource.apply( this, [ options ] );\n\n this.levels = options.levels;\n};\n\n$.extend( $.LegacyTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.LegacyTileSource.prototype */{\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function( data, url ){\n return (\n data.type &&\n \"legacy-image-pyramid\" == data.type\n ) || (\n data.documentElement &&\n \"legacy-image-pyramid\" == data.documentElement.getAttribute('type')\n );\n },\n\n\n /**\n *\n * @function\n * @param {Object|XMLDocument} configuration - the raw configuration\n * @param {String} dataUrl - the url the data was retreived from if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function( configuration, dataUrl ){\n\n var options;\n\n if( !$.isPlainObject(configuration) ){\n\n options = configureFromXML( this, configuration );\n\n }else{\n\n options = configureFromObject( this, configuration );\n }\n\n return options;\n\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function ( level ) {\n var levelScale = NaN;\n if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {\n levelScale =\n this.levels[ level ].width /\n this.levels[ this.maxLevel ].width;\n }\n return levelScale;\n },\n\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function( level ) {\n var scale = this.getLevelScale( level );\n if ( scale ){\n return new $.Point( 1, 1 );\n } else {\n return new $.Point( 0, 0 );\n }\n },\n\n /**\n * This method is not implemented by this class other than to throw an Error\n * announcing you have to implement it. Because of the variety of tile\n * server technologies, and various specifications for building image\n * pyramids, this method is here to allow easy integration.\n * @function\n * @param {Number} level\n * @param {Number} x\n * @param {Number} y\n * @throws {Error}\n */\n getTileUrl: function ( level, x, y ) {\n var url = null;\n if ( this.levels.length > 0 && level >= this.minLevel && level <= this.maxLevel ) {\n url = this.levels[ level ].url;\n }\n return url;\n }\n} );\n\n/**\n * This method removes any files from the Array which dont conform to our\n * basic requirements for a 'level' in the LegacyTileSource.\n * @private\n * @inner\n * @function\n */\nfunction filterFiles( files ){\n var filtered = [],\n file,\n i;\n for( i = 0; i < files.length; i++ ){\n file = files[ i ];\n if( file.height &&\n file.width &&\n file.url ){\n //This is sufficient to serve as a level\n filtered.push({\n url: file.url,\n width: Number( file.width ),\n height: Number( file.height )\n });\n }\n else {\n $.console.error( 'Unsupported image format: %s', file.url ? file.url : '' );\n }\n }\n\n return filtered.sort(function(a, b) {\n return a.height - b.height;\n });\n\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromXML( tileSource, xmlDoc ){\n\n if ( !xmlDoc || !xmlDoc.documentElement ) {\n throw new Error( $.getString( \"Errors.Xml\" ) );\n }\n\n var root = xmlDoc.documentElement,\n rootName = root.tagName,\n conf = null,\n levels = [],\n level,\n i;\n\n if ( rootName == \"image\" ) {\n\n try {\n conf = {\n type: root.getAttribute( \"type\" ),\n levels: []\n };\n\n levels = root.getElementsByTagName( \"level\" );\n for ( i = 0; i < levels.length; i++ ) {\n level = levels[ i ];\n\n conf.levels.push({\n url: level.getAttribute( \"url\" ),\n width: parseInt( level.getAttribute( \"width\" ), 10 ),\n height: parseInt( level.getAttribute( \"height\" ), 10 )\n });\n }\n\n return configureFromObject( tileSource, conf );\n\n } catch ( e ) {\n throw (e instanceof Error) ?\n e :\n new Error( 'Unknown error parsing Legacy Image Pyramid XML.' );\n }\n } else if ( rootName == \"collection\" ) {\n throw new Error( 'Legacy Image Pyramid Collections not yet supported.' );\n } else if ( rootName == \"error\" ) {\n throw new Error( 'Error: ' + xmlDoc );\n }\n\n throw new Error( 'Unknown element ' + rootName );\n}\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction configureFromObject( tileSource, configuration ){\n\n return configuration.levels;\n\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ImageTileSource\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function ($) {\n\n /**\n * @class ImageTileSource\n * @classdesc The ImageTileSource allows a simple image to be loaded\n * into an OpenSeadragon Viewer.\n * There are 2 ways to open an ImageTileSource:\n * 1. viewer.open({type: 'image', url: fooUrl});\n * 2. viewer.open(new OpenSeadragon.ImageTileSource({url: fooUrl}));\n *\n * With the first syntax, the crossOriginPolicy, ajaxWithCredentials and\n * useCanvas options are inherited from the viewer if they are not\n * specified directly in the options object.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.TileSource\n * @param {Object} options Options object.\n * @param {String} options.url URL of the image\n * @param {Boolean} [options.buildPyramid=true] If set to true (default), a\n * pyramid will be built internally to provide a better downsampling.\n * @param {String|Boolean} [options.crossOriginPolicy=false] Valid values are\n * 'Anonymous', 'use-credentials', and false. If false, image requests will\n * not use CORS preventing internal pyramid building for images from other\n * domains.\n * @param {String|Boolean} [options.ajaxWithCredentials=false] Whether to set\n * the withCredentials XHR flag for AJAX requests (when loading tile sources).\n * @param {Boolean} [options.useCanvas=true] Set to false to prevent any use\n * of the canvas API.\n */\n $.ImageTileSource = function (options) {\n\n options = $.extend({\n buildPyramid: true,\n crossOriginPolicy: false,\n ajaxWithCredentials: false,\n useCanvas: true\n }, options);\n $.TileSource.apply(this, [options]);\n\n };\n\n $.extend($.ImageTileSource.prototype, $.TileSource.prototype, /** @lends OpenSeadragon.ImageTileSource.prototype */{\n /**\n * Determine if the data and/or url imply the image service is supported by\n * this tile source.\n * @function\n * @param {Object|Array} data\n * @param {String} optional - url\n */\n supports: function (data, url) {\n return data.type && data.type === \"image\";\n },\n /**\n *\n * @function\n * @param {Object} options - the options\n * @param {String} dataUrl - the url the image was retreived from, if any.\n * @return {Object} options - A dictionary of keyword arguments sufficient\n * to configure this tile sources constructor.\n */\n configure: function (options, dataUrl) {\n return options;\n },\n /**\n * Responsible for retrieving, and caching the\n * image metadata pertinent to this TileSources implementation.\n * @function\n * @param {String} url\n * @throws {Error}\n */\n getImageInfo: function (url) {\n var image = this._image = new Image();\n var _this = this;\n\n if (this.crossOriginPolicy) {\n image.crossOrigin = this.crossOriginPolicy;\n }\n if (this.ajaxWithCredentials) {\n image.useCredentials = this.ajaxWithCredentials;\n }\n\n $.addEvent(image, 'load', function () {\n /* IE8 fix since it has no naturalWidth and naturalHeight */\n _this.width = Object.prototype.hasOwnProperty.call(image, 'naturalWidth') ? image.naturalWidth : image.width;\n _this.height = Object.prototype.hasOwnProperty.call(image, 'naturalHeight') ? image.naturalHeight : image.height;\n _this.aspectRatio = _this.width / _this.height;\n _this.dimensions = new $.Point(_this.width, _this.height);\n _this._tileWidth = _this.width;\n _this._tileHeight = _this.height;\n _this.tileOverlap = 0;\n _this.minLevel = 0;\n _this.levels = _this._buildLevels();\n _this.maxLevel = _this.levels.length - 1;\n\n _this.ready = true;\n\n // Note: this event is documented elsewhere, in TileSource\n _this.raiseEvent('ready', {tileSource: _this});\n });\n\n $.addEvent(image, 'error', function () {\n // Note: this event is documented elsewhere, in TileSource\n _this.raiseEvent('open-failed', {\n message: \"Error loading image at \" + url,\n source: url\n });\n });\n\n image.src = url;\n },\n /**\n * @function\n * @param {Number} level\n */\n getLevelScale: function (level) {\n var levelScale = NaN;\n if (level >= this.minLevel && level <= this.maxLevel) {\n levelScale =\n this.levels[level].width /\n this.levels[this.maxLevel].width;\n }\n return levelScale;\n },\n /**\n * @function\n * @param {Number} level\n */\n getNumTiles: function (level) {\n var scale = this.getLevelScale(level);\n if (scale) {\n return new $.Point(1, 1);\n } else {\n return new $.Point(0, 0);\n }\n },\n /**\n * Retrieves a tile url\n * @function\n * @param {Number} level Level of the tile\n * @param {Number} x x coordinate of the tile\n * @param {Number} y y coordinate of the tile\n */\n getTileUrl: function (level, x, y) {\n var url = null;\n if (level >= this.minLevel && level <= this.maxLevel) {\n url = this.levels[level].url;\n }\n return url;\n },\n /**\n * Retrieves a tile context 2D\n * @function\n * @param {Number} level Level of the tile\n * @param {Number} x x coordinate of the tile\n * @param {Number} y y coordinate of the tile\n */\n getContext2D: function (level, x, y) {\n var context = null;\n if (level >= this.minLevel && level <= this.maxLevel) {\n context = this.levels[level].context2D;\n }\n return context;\n },\n\n // private\n //\n // Builds the differents levels of the pyramid if possible\n // (i.e. if canvas API enabled and no canvas tainting issue).\n _buildLevels: function () {\n var levels = [{\n url: this._image.src,\n /* IE8 fix since it has no naturalWidth and naturalHeight */\n width: Object.prototype.hasOwnProperty.call(this._image, 'naturalWidth') ? this._image.naturalWidth : this._image.width,\n height: Object.prototype.hasOwnProperty.call(this._image, 'naturalHeight') ? this._image.naturalHeight : this._image.height\n }];\n\n if (!this.buildPyramid || !$.supportsCanvas || !this.useCanvas) {\n // We don't need the image anymore. Allows it to be GC.\n delete this._image;\n return levels;\n }\n\n /* IE8 fix since it has no naturalWidth and naturalHeight */\n var currentWidth = Object.prototype.hasOwnProperty.call(this._image, 'naturalWidth') ? this._image.naturalWidth : this._image.width;\n var currentHeight = Object.prototype.hasOwnProperty.call(this._image, 'naturalHeight') ? this._image.naturalHeight : this._image.height;\n\n\n var bigCanvas = document.createElement(\"canvas\");\n var bigContext = bigCanvas.getContext(\"2d\");\n\n bigCanvas.width = currentWidth;\n bigCanvas.height = currentHeight;\n bigContext.drawImage(this._image, 0, 0, currentWidth, currentHeight);\n // We cache the context of the highest level because the browser\n // is a lot faster at downsampling something it already has\n // downsampled before.\n levels[0].context2D = bigContext;\n // We don't need the image anymore. Allows it to be GC.\n delete this._image;\n\n if ($.isCanvasTainted(bigCanvas)) {\n // If the canvas is tainted, we can't compute the pyramid.\n return levels;\n }\n\n // We build smaller levels until either width or height becomes\n // 1 pixel wide.\n while (currentWidth >= 2 && currentHeight >= 2) {\n currentWidth = Math.floor(currentWidth / 2);\n currentHeight = Math.floor(currentHeight / 2);\n var smallCanvas = document.createElement(\"canvas\");\n var smallContext = smallCanvas.getContext(\"2d\");\n smallCanvas.width = currentWidth;\n smallCanvas.height = currentHeight;\n smallContext.drawImage(bigCanvas, 0, 0, currentWidth, currentHeight);\n\n levels.splice(0, 0, {\n context2D: smallContext,\n width: currentWidth,\n height: currentHeight\n });\n\n bigCanvas = smallCanvas;\n bigContext = smallContext;\n }\n return levels;\n }\n });\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - TileSourceCollection\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n// deprecated\n$.TileSourceCollection = function(tileSize, tileSources, rows, layout) {\n $.console.error('TileSourceCollection is deprecated; use World instead');\n};\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Button\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * An enumeration of button states\n * @member ButtonState\n * @memberof OpenSeadragon\n * @static\n * @type {Object}\n * @property {Number} REST\n * @property {Number} GROUP\n * @property {Number} HOVER\n * @property {Number} DOWN\n */\n$.ButtonState = {\n REST: 0,\n GROUP: 1,\n HOVER: 2,\n DOWN: 3\n};\n\n/**\n * @class Button\n * @classdesc Manages events, hover states for individual buttons, tool-tips, as well\n * as fading the buttons out when the user has not interacted with them\n * for a specified period.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @param {Object} options\n * @param {Element} [options.element=null] Element to use as the button. If not specified, an HTML <div> element is created.\n * @param {String} [options.tooltip=null] Provides context help for the button when the\n * user hovers over it.\n * @param {String} [options.srcRest=null] URL of image to use in 'rest' state.\n * @param {String} [options.srcGroup=null] URL of image to use in 'up' state.\n * @param {String} [options.srcHover=null] URL of image to use in 'hover' state.\n * @param {String} [options.srcDown=null] URL of image to use in 'down' state.\n * @param {Number} [options.fadeDelay=0] How long to wait before fading.\n * @param {Number} [options.fadeLength=2000] How long should it take to fade the button.\n * @param {OpenSeadragon.EventHandler} [options.onPress=null] Event handler callback for {@link OpenSeadragon.Button.event:press}.\n * @param {OpenSeadragon.EventHandler} [options.onRelease=null] Event handler callback for {@link OpenSeadragon.Button.event:release}.\n * @param {OpenSeadragon.EventHandler} [options.onClick=null] Event handler callback for {@link OpenSeadragon.Button.event:click}.\n * @param {OpenSeadragon.EventHandler} [options.onEnter=null] Event handler callback for {@link OpenSeadragon.Button.event:enter}.\n * @param {OpenSeadragon.EventHandler} [options.onExit=null] Event handler callback for {@link OpenSeadragon.Button.event:exit}.\n * @param {OpenSeadragon.EventHandler} [options.onFocus=null] Event handler callback for {@link OpenSeadragon.Button.event:focus}.\n * @param {OpenSeadragon.EventHandler} [options.onBlur=null] Event handler callback for {@link OpenSeadragon.Button.event:blur}.\n */\n$.Button = function( options ) {\n\n var _this = this;\n\n $.EventSource.call( this );\n\n $.extend( true, this, {\n\n tooltip: null,\n srcRest: null,\n srcGroup: null,\n srcHover: null,\n srcDown: null,\n clickTimeThreshold: $.DEFAULT_SETTINGS.clickTimeThreshold,\n clickDistThreshold: $.DEFAULT_SETTINGS.clickDistThreshold,\n /**\n * How long to wait before fading.\n * @member {Number} fadeDelay\n * @memberof OpenSeadragon.Button#\n */\n fadeDelay: 0,\n /**\n * How long should it take to fade the button.\n * @member {Number} fadeLength\n * @memberof OpenSeadragon.Button#\n */\n fadeLength: 2000,\n onPress: null,\n onRelease: null,\n onClick: null,\n onEnter: null,\n onExit: null,\n onFocus: null,\n onBlur: null\n\n }, options );\n\n /**\n * The button element.\n * @member {Element} element\n * @memberof OpenSeadragon.Button#\n */\n this.element = options.element || $.makeNeutralElement(\"div\");\n\n //if the user has specified the element to bind the control to explicitly\n //then do not add the default control images\n if ( !options.element ) {\n this.imgRest = $.makeTransparentImage( this.srcRest );\n this.imgGroup = $.makeTransparentImage( this.srcGroup );\n this.imgHover = $.makeTransparentImage( this.srcHover );\n this.imgDown = $.makeTransparentImage( this.srcDown );\n\n this.imgRest.alt =\n this.imgGroup.alt =\n this.imgHover.alt =\n this.imgDown.alt =\n this.tooltip;\n\n this.element.style.position = \"relative\";\n $.setElementTouchActionNone( this.element );\n\n this.imgGroup.style.position =\n this.imgHover.style.position =\n this.imgDown.style.position =\n \"absolute\";\n\n this.imgGroup.style.top =\n this.imgHover.style.top =\n this.imgDown.style.top =\n \"0px\";\n\n this.imgGroup.style.left =\n this.imgHover.style.left =\n this.imgDown.style.left =\n \"0px\";\n\n this.imgHover.style.visibility =\n this.imgDown.style.visibility =\n \"hidden\";\n\n if ($.Browser.vendor == $.BROWSERS.FIREFOX && $.Browser.version < 3) {\n this.imgGroup.style.top =\n this.imgHover.style.top =\n this.imgDown.style.top =\n \"\";\n }\n\n this.element.appendChild( this.imgRest );\n this.element.appendChild( this.imgGroup );\n this.element.appendChild( this.imgHover );\n this.element.appendChild( this.imgDown );\n }\n\n\n this.addHandler(\"press\", this.onPress);\n this.addHandler(\"release\", this.onRelease);\n this.addHandler(\"click\", this.onClick);\n this.addHandler(\"enter\", this.onEnter);\n this.addHandler(\"exit\", this.onExit);\n this.addHandler(\"focus\", this.onFocus);\n this.addHandler(\"blur\", this.onBlur);\n\n /**\n * The button's current state.\n * @member {OpenSeadragon.ButtonState} currentState\n * @memberof OpenSeadragon.Button#\n */\n this.currentState = $.ButtonState.GROUP;\n\n // When the button last began to fade.\n this.fadeBeginTime = null;\n // Whether this button should fade after user stops interacting with the viewport.\n this.shouldFade = false;\n\n this.element.style.display = \"inline-block\";\n this.element.style.position = \"relative\";\n this.element.title = this.tooltip;\n\n /**\n * Tracks mouse/touch/key events on the button.\n * @member {OpenSeadragon.MouseTracker} tracker\n * @memberof OpenSeadragon.Button#\n */\n this.tracker = new $.MouseTracker({\n\n element: this.element,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n\n enterHandler: function( event ) {\n if ( event.insideElementPressed ) {\n inTo( _this, $.ButtonState.DOWN );\n /**\n * Raised when the cursor enters the Button element.\n *\n * @event enter\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"enter\", { originalEvent: event.originalEvent } );\n } else if ( !event.buttonDownAny ) {\n inTo( _this, $.ButtonState.HOVER );\n }\n },\n\n focusHandler: function ( event ) {\n this.enterHandler( event );\n /**\n * Raised when the Button element receives focus.\n *\n * @event focus\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"focus\", { originalEvent: event.originalEvent } );\n },\n\n exitHandler: function( event ) {\n outTo( _this, $.ButtonState.GROUP );\n if ( event.insideElementPressed ) {\n /**\n * Raised when the cursor leaves the Button element.\n *\n * @event exit\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"exit\", { originalEvent: event.originalEvent } );\n }\n },\n\n blurHandler: function ( event ) {\n this.exitHandler( event );\n /**\n * Raised when the Button element loses focus.\n *\n * @event blur\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"blur\", { originalEvent: event.originalEvent } );\n },\n\n pressHandler: function ( event ) {\n inTo( _this, $.ButtonState.DOWN );\n /**\n * Raised when a mouse button is pressed or touch occurs in the Button element.\n *\n * @event press\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"press\", { originalEvent: event.originalEvent } );\n },\n\n releaseHandler: function( event ) {\n if ( event.insideElementPressed && event.insideElementReleased ) {\n outTo( _this, $.ButtonState.HOVER );\n /**\n * Raised when the mouse button is released or touch ends in the Button element.\n *\n * @event release\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"release\", { originalEvent: event.originalEvent } );\n } else if ( event.insideElementPressed ) {\n outTo( _this, $.ButtonState.GROUP );\n } else {\n inTo( _this, $.ButtonState.HOVER );\n }\n },\n\n clickHandler: function( event ) {\n if ( event.quick ) {\n /**\n * Raised when a mouse button is pressed and released or touch is initiated and ended in the Button element within the time and distance threshold.\n *\n * @event click\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent(\"click\", { originalEvent: event.originalEvent });\n }\n },\n\n keyHandler: function( event ){\n //console.log( \"%s : handling key %s!\", _this.tooltip, event.keyCode);\n if( 13 === event.keyCode ){\n /***\n * Raised when a mouse button is pressed and released or touch is initiated and ended in the Button element within the time and distance threshold.\n *\n * @event click\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"click\", { originalEvent: event.originalEvent } );\n /***\n * Raised when the mouse button is released or touch ends in the Button element.\n *\n * @event release\n * @memberof OpenSeadragon.Button\n * @type {object}\n * @property {OpenSeadragon.Button} eventSource - A reference to the Button which raised the event.\n * @property {Object} originalEvent - The original DOM event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.raiseEvent( \"release\", { originalEvent: event.originalEvent } );\n return false;\n }\n return true;\n }\n\n });\n\n outTo( this, $.ButtonState.REST );\n};\n\n$.extend( $.Button.prototype, $.EventSource.prototype, /** @lends OpenSeadragon.Button.prototype */{\n\n /**\n * TODO: Determine what this function is intended to do and if it's actually\n * useful as an API point.\n * @function\n */\n notifyGroupEnter: function() {\n inTo( this, $.ButtonState.GROUP );\n },\n\n /**\n * TODO: Determine what this function is intended to do and if it's actually\n * useful as an API point.\n * @function\n */\n notifyGroupExit: function() {\n outTo( this, $.ButtonState.REST );\n },\n\n /**\n * @function\n */\n disable: function(){\n this.notifyGroupExit();\n this.element.disabled = true;\n $.setElementOpacity( this.element, 0.2, true );\n },\n\n /**\n * @function\n */\n enable: function(){\n this.element.disabled = false;\n $.setElementOpacity( this.element, 1.0, true );\n this.notifyGroupEnter();\n }\n\n});\n\n\nfunction scheduleFade( button ) {\n $.requestAnimationFrame(function(){\n updateFade( button );\n });\n}\n\nfunction updateFade( button ) {\n var currentTime,\n deltaTime,\n opacity;\n\n if ( button.shouldFade ) {\n currentTime = $.now();\n deltaTime = currentTime - button.fadeBeginTime;\n opacity = 1.0 - deltaTime / button.fadeLength;\n opacity = Math.min( 1.0, opacity );\n opacity = Math.max( 0.0, opacity );\n\n if( button.imgGroup ){\n $.setElementOpacity( button.imgGroup, opacity, true );\n }\n if ( opacity > 0 ) {\n // fade again\n scheduleFade( button );\n }\n }\n}\n\nfunction beginFading( button ) {\n button.shouldFade = true;\n button.fadeBeginTime = $.now() + button.fadeDelay;\n window.setTimeout( function(){\n scheduleFade( button );\n }, button.fadeDelay );\n}\n\nfunction stopFading( button ) {\n button.shouldFade = false;\n if( button.imgGroup ){\n $.setElementOpacity( button.imgGroup, 1.0, true );\n }\n}\n\nfunction inTo( button, newState ) {\n\n if( button.element.disabled ){\n return;\n }\n\n if ( newState >= $.ButtonState.GROUP &&\n button.currentState == $.ButtonState.REST ) {\n stopFading( button );\n button.currentState = $.ButtonState.GROUP;\n }\n\n if ( newState >= $.ButtonState.HOVER &&\n button.currentState == $.ButtonState.GROUP ) {\n if( button.imgHover ){\n button.imgHover.style.visibility = \"\";\n }\n button.currentState = $.ButtonState.HOVER;\n }\n\n if ( newState >= $.ButtonState.DOWN &&\n button.currentState == $.ButtonState.HOVER ) {\n if( button.imgDown ){\n button.imgDown.style.visibility = \"\";\n }\n button.currentState = $.ButtonState.DOWN;\n }\n}\n\n\nfunction outTo( button, newState ) {\n\n if( button.element.disabled ){\n return;\n }\n\n if ( newState <= $.ButtonState.HOVER &&\n button.currentState == $.ButtonState.DOWN ) {\n if( button.imgDown ){\n button.imgDown.style.visibility = \"hidden\";\n }\n button.currentState = $.ButtonState.HOVER;\n }\n\n if ( newState <= $.ButtonState.GROUP &&\n button.currentState == $.ButtonState.HOVER ) {\n if( button.imgHover ){\n button.imgHover.style.visibility = \"hidden\";\n }\n button.currentState = $.ButtonState.GROUP;\n }\n\n if ( newState <= $.ButtonState.REST &&\n button.currentState == $.ButtonState.GROUP ) {\n beginFading( button );\n button.currentState = $.ButtonState.REST;\n }\n}\n\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ButtonGroup\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n/**\n * @class ButtonGroup\n * @classdesc Manages events on groups of buttons.\n *\n * @memberof OpenSeadragon\n * @param {Object} options - A dictionary of settings applied against the entire group of buttons.\n * @param {Array} options.buttons Array of buttons\n * @param {Element} [options.element] Element to use as the container\n **/\n$.ButtonGroup = function( options ) {\n\n $.extend( true, this, {\n /**\n * An array containing the buttons themselves.\n * @member {Array} buttons\n * @memberof OpenSeadragon.ButtonGroup#\n */\n buttons: [],\n clickTimeThreshold: $.DEFAULT_SETTINGS.clickTimeThreshold,\n clickDistThreshold: $.DEFAULT_SETTINGS.clickDistThreshold,\n labelText: \"\"\n }, options );\n\n // copy the button elements TODO: Why?\n var buttons = this.buttons.concat([]),\n _this = this,\n i;\n\n /**\n * The shared container for the buttons.\n * @member {Element} element\n * @memberof OpenSeadragon.ButtonGroup#\n */\n this.element = options.element || $.makeNeutralElement( \"div\" );\n\n // TODO What if there IS an options.group specified?\n if( !options.group ){\n this.label = $.makeNeutralElement( \"label\" );\n //TODO: support labels for ButtonGroups\n //this.label.innerHTML = this.labelText;\n this.element.style.display = \"inline-block\";\n this.element.appendChild( this.label );\n for ( i = 0; i < buttons.length; i++ ) {\n this.element.appendChild( buttons[ i ].element );\n }\n }\n\n $.setElementTouchActionNone( this.element );\n\n /**\n * Tracks mouse/touch/key events accross the group of buttons.\n * @member {OpenSeadragon.MouseTracker} tracker\n * @memberof OpenSeadragon.ButtonGroup#\n */\n this.tracker = new $.MouseTracker({\n element: this.element,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n enterHandler: function ( event ) {\n var i;\n for ( i = 0; i < _this.buttons.length; i++ ) {\n _this.buttons[ i ].notifyGroupEnter();\n }\n },\n exitHandler: function ( event ) {\n var i;\n if ( !event.insideElementPressed ) {\n for ( i = 0; i < _this.buttons.length; i++ ) {\n _this.buttons[ i ].notifyGroupExit();\n }\n }\n },\n });\n};\n\n/** @lends OpenSeadragon.ButtonGroup.prototype */\n$.ButtonGroup.prototype = {\n\n /**\n * TODO: Figure out why this is used on the public API and if a more useful\n * api can be created.\n * @function\n * @private\n */\n emulateEnter: function() {\n this.tracker.enterHandler( { eventSource: this.tracker } );\n },\n\n /**\n * TODO: Figure out why this is used on the public API and if a more useful\n * api can be created.\n * @function\n * @private\n */\n emulateExit: function() {\n this.tracker.exitHandler( { eventSource: this.tracker } );\n }\n};\n\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Rect\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n/**\n * @class Rect\n * @classdesc A Rectangle is described by it top left coordinates (x, y), width,\n * height and degrees of rotation around (x, y).\n * Note that the coordinate system used is the one commonly used with images:\n * x increases when going to the right\n * y increases when going to the bottom\n * degrees increases clockwise with 0 being the horizontal\n *\n * The constructor normalizes the rectangle to always have 0 <= degrees < 90\n *\n * @memberof OpenSeadragon\n * @param {Number} [x=0] The vector component 'x'.\n * @param {Number} [y=0] The vector component 'y'.\n * @param {Number} [width=0] The vector component 'width'.\n * @param {Number} [height=0] The vector component 'height'.\n * @param {Number} [degrees=0] Rotation of the rectangle around (x,y) in degrees.\n */\n$.Rect = function(x, y, width, height, degrees) {\n /**\n * The vector component 'x'.\n * @member {Number} x\n * @memberof OpenSeadragon.Rect#\n */\n this.x = typeof (x) === \"number\" ? x : 0;\n /**\n * The vector component 'y'.\n * @member {Number} y\n * @memberof OpenSeadragon.Rect#\n */\n this.y = typeof (y) === \"number\" ? y : 0;\n /**\n * The vector component 'width'.\n * @member {Number} width\n * @memberof OpenSeadragon.Rect#\n */\n this.width = typeof (width) === \"number\" ? width : 0;\n /**\n * The vector component 'height'.\n * @member {Number} height\n * @memberof OpenSeadragon.Rect#\n */\n this.height = typeof (height) === \"number\" ? height : 0;\n\n this.degrees = typeof (degrees) === \"number\" ? degrees : 0;\n\n // Normalizes the rectangle.\n this.degrees = $.positiveModulo(this.degrees, 360);\n var newTopLeft, newWidth;\n if (this.degrees >= 270) {\n newTopLeft = this.getTopRight();\n this.x = newTopLeft.x;\n this.y = newTopLeft.y;\n newWidth = this.height;\n this.height = this.width;\n this.width = newWidth;\n this.degrees -= 270;\n } else if (this.degrees >= 180) {\n newTopLeft = this.getBottomRight();\n this.x = newTopLeft.x;\n this.y = newTopLeft.y;\n this.degrees -= 180;\n } else if (this.degrees >= 90) {\n newTopLeft = this.getBottomLeft();\n this.x = newTopLeft.x;\n this.y = newTopLeft.y;\n newWidth = this.height;\n this.height = this.width;\n this.width = newWidth;\n this.degrees -= 90;\n }\n};\n\n/**\n * Builds a rectangle having the 3 specified points as summits.\n * @static\n * @memberof OpenSeadragon.Rect\n * @param {OpenSeadragon.Point} topLeft\n * @param {OpenSeadragon.Point} topRight\n * @param {OpenSeadragon.Point} bottomLeft\n * @returns {OpenSeadragon.Rect}\n */\n$.Rect.fromSummits = function(topLeft, topRight, bottomLeft) {\n var width = topLeft.distanceTo(topRight);\n var height = topLeft.distanceTo(bottomLeft);\n var diff = topRight.minus(topLeft);\n var radians = Math.atan(diff.y / diff.x);\n if (diff.x < 0) {\n radians += Math.PI;\n } else if (diff.y < 0) {\n radians += 2 * Math.PI;\n }\n return new $.Rect(\n topLeft.x,\n topLeft.y,\n width,\n height,\n radians / Math.PI * 180);\n};\n\n/** @lends OpenSeadragon.Rect.prototype */\n$.Rect.prototype = {\n /**\n * @function\n * @returns {OpenSeadragon.Rect} a duplicate of this Rect\n */\n clone: function() {\n return new $.Rect(\n this.x,\n this.y,\n this.width,\n this.height,\n this.degrees);\n },\n\n /**\n * The aspect ratio is simply the ratio of width to height.\n * @function\n * @returns {Number} The ratio of width to height.\n */\n getAspectRatio: function() {\n return this.width / this.height;\n },\n\n /**\n * Provides the coordinates of the upper-left corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the upper-left corner of\n * the rectangle.\n */\n getTopLeft: function() {\n return new $.Point(\n this.x,\n this.y\n );\n },\n\n /**\n * Provides the coordinates of the bottom-right corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the bottom-right corner of\n * the rectangle.\n */\n getBottomRight: function() {\n return new $.Point(this.x + this.width, this.y + this.height)\n .rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Provides the coordinates of the top-right corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the top-right corner of\n * the rectangle.\n */\n getTopRight: function() {\n return new $.Point(this.x + this.width, this.y)\n .rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Provides the coordinates of the bottom-left corner of the rectangle as a\n * point.\n * @function\n * @returns {OpenSeadragon.Point} The coordinate of the bottom-left corner of\n * the rectangle.\n */\n getBottomLeft: function() {\n return new $.Point(this.x, this.y + this.height)\n .rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Computes the center of the rectangle.\n * @function\n * @returns {OpenSeadragon.Point} The center of the rectangle as represented\n * as represented by a 2-dimensional vector (x,y)\n */\n getCenter: function() {\n return new $.Point(\n this.x + this.width / 2.0,\n this.y + this.height / 2.0\n ).rotate(this.degrees, this.getTopLeft());\n },\n\n /**\n * Returns the width and height component as a vector OpenSeadragon.Point\n * @function\n * @returns {OpenSeadragon.Point} The 2 dimensional vector representing the\n * the width and height of the rectangle.\n */\n getSize: function() {\n return new $.Point(this.width, this.height);\n },\n\n /**\n * Determines if two Rectangles have equivalent components.\n * @function\n * @param {OpenSeadragon.Rect} rectangle The Rectangle to compare to.\n * @return {Boolean} 'true' if all components are equal, otherwise 'false'.\n */\n equals: function(other) {\n return (other instanceof $.Rect) &&\n this.x === other.x &&\n this.y === other.y &&\n this.width === other.width &&\n this.height === other.height &&\n this.degrees === other.degrees;\n },\n\n /**\n * Multiply all dimensions (except degrees) in this Rect by a factor and\n * return a new Rect.\n * @function\n * @param {Number} factor The factor to multiply vector components.\n * @returns {OpenSeadragon.Rect} A new rect representing the multiplication\n * of the vector components by the factor\n */\n times: function(factor) {\n return new $.Rect(\n this.x * factor,\n this.y * factor,\n this.width * factor,\n this.height * factor,\n this.degrees);\n },\n\n /**\n * Translate/move this Rect by a vector and return new Rect.\n * @function\n * @param {OpenSeadragon.Point} delta The translation vector.\n * @returns {OpenSeadragon.Rect} A new rect with altered position\n */\n translate: function(delta) {\n return new $.Rect(\n this.x + delta.x,\n this.y + delta.y,\n this.width,\n this.height,\n this.degrees);\n },\n\n /**\n * Returns the smallest rectangle that will contain this and the given\n * rectangle bounding boxes.\n * @param {OpenSeadragon.Rect} rect\n * @return {OpenSeadragon.Rect} The new rectangle.\n */\n union: function(rect) {\n var thisBoundingBox = this.getBoundingBox();\n var otherBoundingBox = rect.getBoundingBox();\n\n var left = Math.min(thisBoundingBox.x, otherBoundingBox.x);\n var top = Math.min(thisBoundingBox.y, otherBoundingBox.y);\n var right = Math.max(\n thisBoundingBox.x + thisBoundingBox.width,\n otherBoundingBox.x + otherBoundingBox.width);\n var bottom = Math.max(\n thisBoundingBox.y + thisBoundingBox.height,\n otherBoundingBox.y + otherBoundingBox.height);\n\n return new $.Rect(\n left,\n top,\n right - left,\n bottom - top);\n },\n\n /**\n * Returns the bounding box of the intersection of this rectangle with the\n * given rectangle.\n * @param {OpenSeadragon.Rect} rect\n * @return {OpenSeadragon.Rect} the bounding box of the intersection\n * or null if the rectangles don't intersect.\n */\n intersection: function(rect) {\n // Simplified version of Weiler Atherton clipping algorithm\n // https://en.wikipedia.org/wiki/Weiler%E2%80%93Atherton_clipping_algorithm\n // Because we just want the bounding box of the intersection,\n // we can just compute the bounding box of:\n // 1. all the summits of this which are inside rect\n // 2. all the summits of rect which are inside this\n // 3. all the intersections of rect and this\n var EPSILON = 0.0000000001;\n\n var intersectionPoints = [];\n\n var thisTopLeft = this.getTopLeft();\n if (rect.containsPoint(thisTopLeft, EPSILON)) {\n intersectionPoints.push(thisTopLeft);\n }\n var thisTopRight = this.getTopRight();\n if (rect.containsPoint(thisTopRight, EPSILON)) {\n intersectionPoints.push(thisTopRight);\n }\n var thisBottomLeft = this.getBottomLeft();\n if (rect.containsPoint(thisBottomLeft, EPSILON)) {\n intersectionPoints.push(thisBottomLeft);\n }\n var thisBottomRight = this.getBottomRight();\n if (rect.containsPoint(thisBottomRight, EPSILON)) {\n intersectionPoints.push(thisBottomRight);\n }\n\n var rectTopLeft = rect.getTopLeft();\n if (this.containsPoint(rectTopLeft, EPSILON)) {\n intersectionPoints.push(rectTopLeft);\n }\n var rectTopRight = rect.getTopRight();\n if (this.containsPoint(rectTopRight, EPSILON)) {\n intersectionPoints.push(rectTopRight);\n }\n var rectBottomLeft = rect.getBottomLeft();\n if (this.containsPoint(rectBottomLeft, EPSILON)) {\n intersectionPoints.push(rectBottomLeft);\n }\n var rectBottomRight = rect.getBottomRight();\n if (this.containsPoint(rectBottomRight, EPSILON)) {\n intersectionPoints.push(rectBottomRight);\n }\n\n var thisSegments = this._getSegments();\n var rectSegments = rect._getSegments();\n for (var i = 0; i < thisSegments.length; i++) {\n var thisSegment = thisSegments[i];\n for (var j = 0; j < rectSegments.length; j++) {\n var rectSegment = rectSegments[j];\n var intersect = getIntersection(thisSegment[0], thisSegment[1],\n rectSegment[0], rectSegment[1]);\n if (intersect) {\n intersectionPoints.push(intersect);\n }\n }\n }\n\n // Get intersection point of segments [a,b] and [c,d]\n function getIntersection(a, b, c, d) {\n // http://stackoverflow.com/a/1968345/1440403\n var abVector = b.minus(a);\n var cdVector = d.minus(c);\n\n var denom = -cdVector.x * abVector.y + abVector.x * cdVector.y;\n if (denom === 0) {\n return null;\n }\n\n var s = (abVector.x * (a.y - c.y) - abVector.y * (a.x - c.x)) / denom;\n var t = (cdVector.x * (a.y - c.y) - cdVector.y * (a.x - c.x)) / denom;\n\n if (-EPSILON <= s && s <= 1 - EPSILON &&\n -EPSILON <= t && t <= 1 - EPSILON) {\n return new $.Point(a.x + t * abVector.x, a.y + t * abVector.y);\n }\n return null;\n }\n\n if (intersectionPoints.length === 0) {\n return null;\n }\n\n var minX = intersectionPoints[0].x;\n var maxX = intersectionPoints[0].x;\n var minY = intersectionPoints[0].y;\n var maxY = intersectionPoints[0].y;\n for (var k = 1; k < intersectionPoints.length; k++) {\n var point = intersectionPoints[k];\n if (point.x < minX) {\n minX = point.x;\n }\n if (point.x > maxX) {\n maxX = point.x;\n }\n if (point.y < minY) {\n minY = point.y;\n }\n if (point.y > maxY) {\n maxY = point.y;\n }\n }\n return new $.Rect(minX, minY, maxX - minX, maxY - minY);\n },\n\n // private\n _getSegments: function() {\n var topLeft = this.getTopLeft();\n var topRight = this.getTopRight();\n var bottomLeft = this.getBottomLeft();\n var bottomRight = this.getBottomRight();\n return [[topLeft, topRight],\n [topRight, bottomRight],\n [bottomRight, bottomLeft],\n [bottomLeft, topLeft]];\n },\n\n /**\n * Rotates a rectangle around a point.\n * @function\n * @param {Number} degrees The angle in degrees to rotate.\n * @param {OpenSeadragon.Point} [pivot] The point about which to rotate.\n * Defaults to the center of the rectangle.\n * @return {OpenSeadragon.Rect}\n */\n rotate: function(degrees, pivot) {\n degrees = $.positiveModulo(degrees, 360);\n if (degrees === 0) {\n return this.clone();\n }\n\n pivot = pivot || this.getCenter();\n var newTopLeft = this.getTopLeft().rotate(degrees, pivot);\n var newTopRight = this.getTopRight().rotate(degrees, pivot);\n\n var diff = newTopRight.minus(newTopLeft);\n // Handle floating point error\n diff = diff.apply(function(x) {\n var EPSILON = 1e-15;\n return Math.abs(x) < EPSILON ? 0 : x;\n });\n var radians = Math.atan(diff.y / diff.x);\n if (diff.x < 0) {\n radians += Math.PI;\n } else if (diff.y < 0) {\n radians += 2 * Math.PI;\n }\n return new $.Rect(\n newTopLeft.x,\n newTopLeft.y,\n this.width,\n this.height,\n radians / Math.PI * 180);\n },\n\n /**\n * Retrieves the smallest horizontal (degrees=0) rectangle which contains\n * this rectangle.\n * @returns {OpenSeadragon.Rect}\n */\n getBoundingBox: function() {\n if (this.degrees === 0) {\n return this.clone();\n }\n var topLeft = this.getTopLeft();\n var topRight = this.getTopRight();\n var bottomLeft = this.getBottomLeft();\n var bottomRight = this.getBottomRight();\n var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);\n var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);\n var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);\n var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);\n return new $.Rect(\n minX,\n minY,\n maxX - minX,\n maxY - minY);\n },\n\n /**\n * Retrieves the smallest horizontal (degrees=0) rectangle which contains\n * this rectangle and has integers x, y, width and height\n * @returns {OpenSeadragon.Rect}\n */\n getIntegerBoundingBox: function() {\n var boundingBox = this.getBoundingBox();\n var x = Math.floor(boundingBox.x);\n var y = Math.floor(boundingBox.y);\n var width = Math.ceil(boundingBox.width + boundingBox.x - x);\n var height = Math.ceil(boundingBox.height + boundingBox.y - y);\n return new $.Rect(x, y, width, height);\n },\n\n /**\n * Determines whether a point is inside this rectangle (edge included).\n * @function\n * @param {OpenSeadragon.Point} point\n * @param {Number} [epsilon=0] the margin of error allowed\n * @returns {Boolean} true if the point is inside this rectangle, false\n * otherwise.\n */\n containsPoint: function(point, epsilon) {\n epsilon = epsilon || 0;\n\n // See http://stackoverflow.com/a/2752754/1440403 for explanation\n var topLeft = this.getTopLeft();\n var topRight = this.getTopRight();\n var bottomLeft = this.getBottomLeft();\n var topDiff = topRight.minus(topLeft);\n var leftDiff = bottomLeft.minus(topLeft);\n\n return ((point.x - topLeft.x) * topDiff.x +\n (point.y - topLeft.y) * topDiff.y >= -epsilon) &&\n\n ((point.x - topRight.x) * topDiff.x +\n (point.y - topRight.y) * topDiff.y <= epsilon) &&\n\n ((point.x - topLeft.x) * leftDiff.x +\n (point.y - topLeft.y) * leftDiff.y >= -epsilon) &&\n\n ((point.x - bottomLeft.x) * leftDiff.x +\n (point.y - bottomLeft.y) * leftDiff.y <= epsilon);\n },\n\n /**\n * Provides a string representation of the rectangle which is useful for\n * debugging.\n * @function\n * @returns {String} A string representation of the rectangle.\n */\n toString: function() {\n return \"[\" +\n (Math.round(this.x * 100) / 100) + \", \" +\n (Math.round(this.y * 100) / 100) + \", \" +\n (Math.round(this.width * 100) / 100) + \"x\" +\n (Math.round(this.height * 100) / 100) + \", \" +\n (Math.round(this.degrees * 100) / 100) + \"deg\" +\n \"]\";\n }\n};\n\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - ReferenceStrip\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function ( $ ) {\n\n// dictionary from id to private properties\nvar THIS = {};\n\n/**\n * The CollectionDrawer is a reimplementation if the Drawer API that\n * focuses on allowing a viewport to be redefined as a collection\n * of smaller viewports, defined by a clear number of rows and / or\n * columns of which each item in the matrix of viewports has its own\n * source.\n *\n * This idea is a reexpression of the idea of dzi collections\n * which allows a clearer algorithm to reuse the tile sources already\n * supported by OpenSeadragon, in heterogenious or homogenious\n * sequences just like mixed groups already supported by the viewer\n * for the purpose of image sequnces.\n *\n * TODO: The difficult part of this feature is figuring out how to express\n * this functionality as a combination of the functionality already\n * provided by Drawer, Viewport, TileSource, and Navigator. It may\n * require better abstraction at those points in order to effeciently\n * reuse those paradigms.\n */\n/**\n * @class ReferenceStrip\n * @memberof OpenSeadragon\n * @param {Object} options\n */\n$.ReferenceStrip = function ( options ) {\n\n var _this = this,\n viewer = options.viewer,\n viewerSize = $.getElementSize( viewer.element ),\n element,\n style,\n i;\n\n //We may need to create a new element and id if they did not\n //provide the id for the existing element\n if ( !options.id ) {\n options.id = 'referencestrip-' + $.now();\n this.element = $.makeNeutralElement( \"div\" );\n this.element.id = options.id;\n this.element.className = 'referencestrip';\n }\n\n options = $.extend( true, {\n sizeRatio: $.DEFAULT_SETTINGS.referenceStripSizeRatio,\n position: $.DEFAULT_SETTINGS.referenceStripPosition,\n scroll: $.DEFAULT_SETTINGS.referenceStripScroll,\n clickTimeThreshold: $.DEFAULT_SETTINGS.clickTimeThreshold\n }, options, {\n //required overrides\n element: this.element,\n //These need to be overridden to prevent recursion since\n //the navigator is a viewer and a viewer has a navigator\n showNavigator: false,\n mouseNavEnabled: false,\n showNavigationControl: false,\n showSequenceControl: false\n } );\n\n $.extend( this, options );\n //Private state properties\n THIS[this.id] = {\n \"animating\": false\n };\n\n this.minPixelRatio = this.viewer.minPixelRatio;\n\n style = this.element.style;\n style.marginTop = '0px';\n style.marginRight = '0px';\n style.marginBottom = '0px';\n style.marginLeft = '0px';\n style.left = '0px';\n style.bottom = '0px';\n style.border = '0px';\n style.background = '#000';\n style.position = 'relative';\n\n $.setElementTouchActionNone( this.element );\n\n $.setElementOpacity( this.element, 0.8 );\n\n this.viewer = viewer;\n this.innerTracker = new $.MouseTracker( {\n element: this.element,\n dragHandler: $.delegate( this, onStripDrag ),\n scrollHandler: $.delegate( this, onStripScroll ),\n enterHandler: $.delegate( this, onStripEnter ),\n exitHandler: $.delegate( this, onStripExit ),\n keyDownHandler: $.delegate( this, onKeyDown ),\n keyHandler: $.delegate( this, onKeyPress )\n } );\n\n //Controls the position and orientation of the reference strip and sets the\n //appropriate width and height\n if ( options.width && options.height ) {\n this.element.style.width = options.width + 'px';\n this.element.style.height = options.height + 'px';\n viewer.addControl(\n this.element,\n { anchor: $.ControlAnchor.BOTTOM_LEFT }\n );\n } else {\n if ( \"horizontal\" == options.scroll ) {\n this.element.style.width = (\n viewerSize.x *\n options.sizeRatio *\n viewer.tileSources.length\n ) + ( 12 * viewer.tileSources.length ) + 'px';\n\n this.element.style.height = (\n viewerSize.y *\n options.sizeRatio\n ) + 'px';\n\n viewer.addControl(\n this.element,\n { anchor: $.ControlAnchor.BOTTOM_LEFT }\n );\n } else {\n this.element.style.height = (\n viewerSize.y *\n options.sizeRatio *\n viewer.tileSources.length\n ) + ( 12 * viewer.tileSources.length ) + 'px';\n\n this.element.style.width = (\n viewerSize.x *\n options.sizeRatio\n ) + 'px';\n\n viewer.addControl(\n this.element,\n { anchor: $.ControlAnchor.TOP_LEFT }\n );\n\n }\n }\n\n this.panelWidth = ( viewerSize.x * this.sizeRatio ) + 8;\n this.panelHeight = ( viewerSize.y * this.sizeRatio ) + 8;\n this.panels = [];\n this.miniViewers = {};\n\n /*jshint loopfunc:true*/\n for ( i = 0; i < viewer.tileSources.length; i++ ) {\n\n element = $.makeNeutralElement( 'div' );\n element.id = this.element.id + \"-\" + i;\n\n element.style.width = _this.panelWidth + 'px';\n element.style.height = _this.panelHeight + 'px';\n element.style.display = 'inline';\n element.style.float = 'left'; //Webkit\n element.style.cssFloat = 'left'; //Firefox\n element.style.styleFloat = 'left'; //IE\n element.style.padding = '2px';\n $.setElementTouchActionNone( element );\n\n element.innerTracker = new $.MouseTracker( {\n element: element,\n clickTimeThreshold: this.clickTimeThreshold,\n clickDistThreshold: this.clickDistThreshold,\n pressHandler: function ( event ) {\n event.eventSource.dragging = $.now();\n },\n releaseHandler: function ( event ) {\n var tracker = event.eventSource,\n id = tracker.element.id,\n page = Number( id.split( '-' )[2] ),\n now = $.now();\n\n if ( event.insideElementPressed &&\n event.insideElementReleased &&\n tracker.dragging &&\n ( now - tracker.dragging ) < tracker.clickTimeThreshold ) {\n tracker.dragging = null;\n viewer.goToPage( page );\n }\n }\n } );\n\n this.element.appendChild( element );\n\n element.activePanel = false;\n\n this.panels.push( element );\n\n }\n loadPanels( this, this.scroll == 'vertical' ? viewerSize.y : viewerSize.x, 0 );\n this.setFocus( 0 );\n\n};\n\n$.extend( $.ReferenceStrip.prototype, $.EventSource.prototype, $.Viewer.prototype, /** @lends OpenSeadragon.ReferenceStrip.prototype */{\n\n /**\n * @function\n */\n setFocus: function ( page ) {\n var element = $.getElement( this.element.id + '-' + page ),\n viewerSize = $.getElementSize( this.viewer.canvas ),\n scrollWidth = Number( this.element.style.width.replace( 'px', '' ) ),\n scrollHeight = Number( this.element.style.height.replace( 'px', '' ) ),\n offsetLeft = -Number( this.element.style.marginLeft.replace( 'px', '' ) ),\n offsetTop = -Number( this.element.style.marginTop.replace( 'px', '' ) ),\n offset;\n\n if ( this.currentSelected !== element ) {\n if ( this.currentSelected ) {\n this.currentSelected.style.background = '#000';\n }\n this.currentSelected = element;\n this.currentSelected.style.background = '#999';\n\n if ( 'horizontal' == this.scroll ) {\n //right left\n offset = ( Number( page ) ) * ( this.panelWidth + 3 );\n if ( offset > offsetLeft + viewerSize.x - this.panelWidth ) {\n offset = Math.min( offset, ( scrollWidth - viewerSize.x ) );\n this.element.style.marginLeft = -offset + 'px';\n loadPanels( this, viewerSize.x, -offset );\n } else if ( offset < offsetLeft ) {\n offset = Math.max( 0, offset - viewerSize.x / 2 );\n this.element.style.marginLeft = -offset + 'px';\n loadPanels( this, viewerSize.x, -offset );\n }\n } else {\n offset = ( Number( page ) ) * ( this.panelHeight + 3 );\n if ( offset > offsetTop + viewerSize.y - this.panelHeight ) {\n offset = Math.min( offset, ( scrollHeight - viewerSize.y ) );\n this.element.style.marginTop = -offset + 'px';\n loadPanels( this, viewerSize.y, -offset );\n } else if ( offset < offsetTop ) {\n offset = Math.max( 0, offset - viewerSize.y / 2 );\n this.element.style.marginTop = -offset + 'px';\n loadPanels( this, viewerSize.y, -offset );\n }\n }\n\n this.currentPage = page;\n onStripEnter.call( this, { eventSource: this.innerTracker } );\n }\n },\n\n /**\n * @function\n */\n update: function () {\n if ( THIS[this.id].animating ) {\n $.console.log( 'image reference strip update' );\n return true;\n }\n return false;\n },\n\n // Overrides Viewer.destroy\n destroy: function() {\n if (this.miniViewers) {\n for (var key in this.miniViewers) {\n this.miniViewers[key].destroy();\n }\n }\n\n if (this.element) {\n this.element.parentNode.removeChild(this.element);\n }\n }\n\n} );\n\n\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripDrag( event ) {\n\n var offsetLeft = Number( this.element.style.marginLeft.replace( 'px', '' ) ),\n offsetTop = Number( this.element.style.marginTop.replace( 'px', '' ) ),\n scrollWidth = Number( this.element.style.width.replace( 'px', '' ) ),\n scrollHeight = Number( this.element.style.height.replace( 'px', '' ) ),\n viewerSize = $.getElementSize( this.viewer.canvas );\n this.dragging = true;\n if ( this.element ) {\n if ( 'horizontal' == this.scroll ) {\n if ( -event.delta.x > 0 ) {\n //forward\n if ( offsetLeft > -( scrollWidth - viewerSize.x ) ) {\n this.element.style.marginLeft = ( offsetLeft + ( event.delta.x * 2 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft + ( event.delta.x * 2 ) );\n }\n } else if ( -event.delta.x < 0 ) {\n //reverse\n if ( offsetLeft < 0 ) {\n this.element.style.marginLeft = ( offsetLeft + ( event.delta.x * 2 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft + ( event.delta.x * 2 ) );\n }\n }\n } else {\n if ( -event.delta.y > 0 ) {\n //forward\n if ( offsetTop > -( scrollHeight - viewerSize.y ) ) {\n this.element.style.marginTop = ( offsetTop + ( event.delta.y * 2 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.delta.y * 2 ) );\n }\n } else if ( -event.delta.y < 0 ) {\n //reverse\n if ( offsetTop < 0 ) {\n this.element.style.marginTop = ( offsetTop + ( event.delta.y * 2 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.delta.y * 2 ) );\n }\n }\n }\n }\n return false;\n\n}\n\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripScroll( event ) {\n var offsetLeft = Number( this.element.style.marginLeft.replace( 'px', '' ) ),\n offsetTop = Number( this.element.style.marginTop.replace( 'px', '' ) ),\n scrollWidth = Number( this.element.style.width.replace( 'px', '' ) ),\n scrollHeight = Number( this.element.style.height.replace( 'px', '' ) ),\n viewerSize = $.getElementSize( this.viewer.canvas );\n if ( this.element ) {\n if ( 'horizontal' == this.scroll ) {\n if ( event.scroll > 0 ) {\n //forward\n if ( offsetLeft > -( scrollWidth - viewerSize.x ) ) {\n this.element.style.marginLeft = ( offsetLeft - ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft - ( event.scroll * 60 ) );\n }\n } else if ( event.scroll < 0 ) {\n //reverse\n if ( offsetLeft < 0 ) {\n this.element.style.marginLeft = ( offsetLeft - ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.x, offsetLeft - ( event.scroll * 60 ) );\n }\n }\n } else {\n if ( event.scroll < 0 ) {\n //scroll up\n if ( offsetTop > viewerSize.y - scrollHeight ) {\n this.element.style.marginTop = ( offsetTop + ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.scroll * 60 ) );\n }\n } else if ( event.scroll > 0 ) {\n //scroll dowm\n if ( offsetTop < 0 ) {\n this.element.style.marginTop = ( offsetTop + ( event.scroll * 60 ) ) + 'px';\n loadPanels( this, viewerSize.y, offsetTop + ( event.scroll * 60 ) );\n }\n }\n }\n }\n //cancels event\n return false;\n}\n\n\nfunction loadPanels( strip, viewerSize, scroll ) {\n var panelSize,\n activePanelsStart,\n activePanelsEnd,\n miniViewer,\n style,\n i,\n element;\n if ( 'horizontal' == strip.scroll ) {\n panelSize = strip.panelWidth;\n } else {\n panelSize = strip.panelHeight;\n }\n activePanelsStart = Math.ceil( viewerSize / panelSize ) + 5;\n activePanelsEnd = Math.ceil( ( Math.abs( scroll ) + viewerSize ) / panelSize ) + 1;\n activePanelsStart = activePanelsEnd - activePanelsStart;\n activePanelsStart = activePanelsStart < 0 ? 0 : activePanelsStart;\n\n for ( i = activePanelsStart; i < activePanelsEnd && i < strip.panels.length; i++ ) {\n element = strip.panels[i];\n if ( !element.activePanel ) {\n var miniTileSource;\n var originalTileSource = strip.viewer.tileSources[i];\n if (originalTileSource.referenceStripThumbnailUrl) {\n miniTileSource = {\n type: 'image',\n url: originalTileSource.referenceStripThumbnailUrl\n };\n } else {\n miniTileSource = originalTileSource;\n }\n miniViewer = new $.Viewer( {\n id: element.id,\n tileSources: [miniTileSource],\n element: element,\n navigatorSizeRatio: strip.sizeRatio,\n showNavigator: false,\n mouseNavEnabled: false,\n showNavigationControl: false,\n showSequenceControl: false,\n immediateRender: true,\n blendTime: 0,\n animationTime: 0\n } );\n\n miniViewer.displayRegion = $.makeNeutralElement( \"div\" );\n miniViewer.displayRegion.id = element.id + '-displayregion';\n miniViewer.displayRegion.className = 'displayregion';\n\n style = miniViewer.displayRegion.style;\n style.position = 'relative';\n style.top = '0px';\n style.left = '0px';\n style.fontSize = '0px';\n style.overflow = 'hidden';\n style.float = 'left'; //Webkit\n style.cssFloat = 'left'; //Firefox\n style.styleFloat = 'left'; //IE\n style.zIndex = 999999999;\n style.cursor = 'default';\n style.width = ( strip.panelWidth - 4 ) + 'px';\n style.height = ( strip.panelHeight - 4 ) + 'px';\n\n // TODO: What is this for? Future keyboard navigation support?\n miniViewer.displayRegion.innerTracker = new $.MouseTracker( {\n element: miniViewer.displayRegion,\n startDisabled: true\n } );\n\n element.getElementsByTagName( 'div' )[0].appendChild(\n miniViewer.displayRegion\n );\n\n strip.miniViewers[element.id] = miniViewer;\n\n element.activePanel = true;\n }\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripEnter( event ) {\n var element = event.eventSource.element;\n\n //$.setElementOpacity(element, 0.8);\n\n //element.style.border = '1px solid #555';\n //element.style.background = '#000';\n\n if ( 'horizontal' == this.scroll ) {\n\n //element.style.paddingTop = \"0px\";\n element.style.marginBottom = \"0px\";\n\n } else {\n\n //element.style.paddingRight = \"0px\";\n element.style.marginLeft = \"0px\";\n\n }\n return false;\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onStripExit( event ) {\n var element = event.eventSource.element;\n\n if ( 'horizontal' == this.scroll ) {\n\n //element.style.paddingTop = \"10px\";\n element.style.marginBottom = \"-\" + ( $.getElementSize( element ).y / 2 ) + \"px\";\n\n } else {\n\n //element.style.paddingRight = \"10px\";\n element.style.marginLeft = \"-\" + ( $.getElementSize( element ).x / 2 ) + \"px\";\n\n }\n return false;\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onKeyDown( event ) {\n //console.log( event.keyCode );\n\n if ( !event.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch ( event.keyCode ) {\n case 38: //up arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n case 40: //down arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 37: //left arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 39: //right arrow\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n default:\n //console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\n\n\n/**\n * @private\n * @inner\n * @function\n */\nfunction onKeyPress( event ) {\n //console.log( event.keyCode );\n\n if ( !event.preventDefaultAction && !event.ctrl && !event.alt && !event.meta ) {\n switch ( event.keyCode ) {\n case 61: //=|+\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n case 45: //-|_\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 48: //0|)\n case 119: //w\n case 87: //W\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n case 115: //s\n case 83: //S\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 97: //a\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: -1, shift: null } );\n return false;\n case 100: //d\n onStripScroll.call( this, { eventSource: this.tracker, position: null, scroll: 1, shift: null } );\n return false;\n default:\n //console.log( 'navigator keycode %s', event.keyCode );\n return true;\n }\n } else {\n return true;\n }\n}\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - DisplayRect\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class DisplayRect\n * @classdesc A display rectangle is very similar to {@link OpenSeadragon.Rect} but adds two\n * fields, 'minLevel' and 'maxLevel' which denote the supported zoom levels\n * for this rectangle.\n *\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.Rect\n * @param {Number} x The vector component 'x'.\n * @param {Number} y The vector component 'y'.\n * @param {Number} width The vector component 'height'.\n * @param {Number} height The vector component 'width'.\n * @param {Number} minLevel The lowest zoom level supported.\n * @param {Number} maxLevel The highest zoom level supported.\n */\n$.DisplayRect = function( x, y, width, height, minLevel, maxLevel ) {\n $.Rect.apply( this, [ x, y, width, height ] );\n\n /**\n * The lowest zoom level supported.\n * @member {Number} minLevel\n * @memberof OpenSeadragon.DisplayRect#\n */\n this.minLevel = minLevel;\n /**\n * The highest zoom level supported.\n * @member {Number} maxLevel\n * @memberof OpenSeadragon.DisplayRect#\n */\n this.maxLevel = maxLevel;\n};\n\n$.extend( $.DisplayRect.prototype, $.Rect.prototype );\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Spring\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Spring\n * @memberof OpenSeadragon\n * @param {Object} options - Spring configuration settings.\n * @param {Number} options.springStiffness - Spring stiffness. Must be greater than zero.\n * The closer to zero, the closer to linear animation.\n * @param {Number} options.animationTime - Animation duration per spring, in seconds.\n * Must be zero or greater.\n * @param {Number} [options.initial=0] - Initial value of spring.\n * @param {Boolean} [options.exponential=false] - Whether this spring represents\n * an exponential scale (such as zoom) and should be animated accordingly. Note that\n * exponential springs must have non-zero values.\n */\n$.Spring = function( options ) {\n var args = arguments;\n\n if( typeof ( options ) != 'object' ){\n //allows backward compatible use of ( initialValue, config ) as\n //constructor parameters\n options = {\n initial: args.length && typeof ( args[ 0 ] ) == \"number\" ?\n args[ 0 ] :\n undefined,\n /**\n * Spring stiffness.\n * @member {Number} springStiffness\n * @memberof OpenSeadragon.Spring#\n */\n springStiffness: args.length > 1 ?\n args[ 1 ].springStiffness :\n 5.0,\n /**\n * Animation duration per spring.\n * @member {Number} animationTime\n * @memberof OpenSeadragon.Spring#\n */\n animationTime: args.length > 1 ?\n args[ 1 ].animationTime :\n 1.5\n };\n }\n\n $.console.assert(typeof options.springStiffness === \"number\" && options.springStiffness !== 0,\n \"[OpenSeadragon.Spring] options.springStiffness must be a non-zero number\");\n\n $.console.assert(typeof options.animationTime === \"number\" && options.animationTime >= 0,\n \"[OpenSeadragon.Spring] options.animationTime must be a number greater than or equal to 0\");\n\n if (options.exponential) {\n this._exponential = true;\n delete options.exponential;\n }\n\n $.extend( true, this, options);\n\n /**\n * @member {Object} current\n * @memberof OpenSeadragon.Spring#\n * @property {Number} value\n * @property {Number} time\n */\n this.current = {\n value: typeof ( this.initial ) == \"number\" ?\n this.initial :\n (this._exponential ? 0 : 1),\n time: $.now() // always work in milliseconds\n };\n\n $.console.assert(!this._exponential || this.current.value !== 0,\n \"[OpenSeadragon.Spring] value must be non-zero for exponential springs\");\n\n /**\n * @member {Object} start\n * @memberof OpenSeadragon.Spring#\n * @property {Number} value\n * @property {Number} time\n */\n this.start = {\n value: this.current.value,\n time: this.current.time\n };\n\n /**\n * @member {Object} target\n * @memberof OpenSeadragon.Spring#\n * @property {Number} value\n * @property {Number} time\n */\n this.target = {\n value: this.current.value,\n time: this.current.time\n };\n\n if (this._exponential) {\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n this.current._logValue = Math.log(this.current.value);\n }\n};\n\n/** @lends OpenSeadragon.Spring.prototype */\n$.Spring.prototype = {\n\n /**\n * @function\n * @param {Number} target\n */\n resetTo: function( target ) {\n $.console.assert(!this._exponential || target !== 0,\n \"[OpenSeadragon.Spring.resetTo] target must be non-zero for exponential springs\");\n\n this.start.value = this.target.value = this.current.value = target;\n this.start.time = this.target.time = this.current.time = $.now();\n\n if (this._exponential) {\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n this.current._logValue = Math.log(this.current.value);\n }\n },\n\n /**\n * @function\n * @param {Number} target\n */\n springTo: function( target ) {\n $.console.assert(!this._exponential || target !== 0,\n \"[OpenSeadragon.Spring.springTo] target must be non-zero for exponential springs\");\n\n this.start.value = this.current.value;\n this.start.time = this.current.time;\n this.target.value = target;\n this.target.time = this.start.time + 1000 * this.animationTime;\n\n if (this._exponential) {\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n }\n },\n\n /**\n * @function\n * @param {Number} delta\n */\n shiftBy: function( delta ) {\n this.start.value += delta;\n this.target.value += delta;\n\n if (this._exponential) {\n $.console.assert(this.target.value !== 0 && this.start.value !== 0,\n \"[OpenSeadragon.Spring.shiftBy] spring value must be non-zero for exponential springs\");\n\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n }\n },\n\n setExponential: function(value) {\n this._exponential = value;\n\n if (this._exponential) {\n $.console.assert(this.current.value !== 0 && this.target.value !== 0 && this.start.value !== 0,\n \"[OpenSeadragon.Spring.setExponential] spring value must be non-zero for exponential springs\");\n\n this.start._logValue = Math.log(this.start.value);\n this.target._logValue = Math.log(this.target.value);\n this.current._logValue = Math.log(this.current.value);\n }\n },\n\n /**\n * @function\n * @returns true if the value got updated, false otherwise\n */\n update: function() {\n this.current.time = $.now();\n\n var startValue, targetValue;\n if (this._exponential) {\n startValue = this.start._logValue;\n targetValue = this.target._logValue;\n } else {\n startValue = this.start.value;\n targetValue = this.target.value;\n }\n\n var currentValue = (this.current.time >= this.target.time) ?\n targetValue :\n startValue +\n ( targetValue - startValue ) *\n transform(\n this.springStiffness,\n ( this.current.time - this.start.time ) /\n ( this.target.time - this.start.time )\n );\n\n var oldValue = this.current.value;\n if (this._exponential) {\n this.current.value = Math.exp(currentValue);\n } else {\n this.current.value = currentValue;\n }\n\n return oldValue != this.current.value;\n },\n\n /**\n * Returns whether the spring is at the target value\n * @function\n * @returns {Boolean} True if at target value, false otherwise\n */\n isAtTargetValue: function() {\n return this.current.value === this.target.value;\n }\n};\n\n/**\n * @private\n */\nfunction transform( stiffness, x ) {\n return ( 1.0 - Math.exp( stiffness * -x ) ) /\n ( 1.0 - Math.exp( -stiffness ) );\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - ImageLoader\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($){\n\n/**\n * @private\n * @class ImageJob\n * @classdesc Handles downloading of a single image.\n * @param {Object} options - Options for this ImageJob.\n * @param {String} [options.src] - URL of image to download.\n * @param {String} [options.loadWithAjax] - Whether to load this image with AJAX.\n * @param {String} [options.ajaxHeaders] - Headers to add to the image request if using AJAX.\n * @param {String} [options.crossOriginPolicy] - CORS policy to use for downloads\n * @param {Function} [options.callback] - Called once image has been downloaded.\n * @param {Function} [options.abort] - Called when this image job is aborted.\n * @param {Number} [options.timeout] - The max number of milliseconds that this image job may take to complete.\n */\nfunction ImageJob (options) {\n\n $.extend(true, this, {\n timeout: $.DEFAULT_SETTINGS.timeout,\n makeAjaxRequest: $.makeAjaxRequest,\n jobId: null\n }, options);\n\n /**\n * Image object which will contain downloaded image.\n * @member {Image} image\n * @memberof OpenSeadragon.ImageJob#\n */\n this.image = null;\n}\n\nImageJob.prototype = {\n errorMsg: null,\n\n /**\n * Starts the image job.\n * @method\n */\n start: function(){\n var self = this;\n var selfAbort = this.abort;\n\n this.image = new Image();\n\n this.image.onload = function(){\n self.finish(true);\n };\n this.image.onabort = this.image.onerror = function() {\n self.errorMsg = \"Image load aborted\";\n self.finish(false);\n };\n\n this.jobId = window.setTimeout(function(){\n self.errorMsg = \"Image load exceeded timeout\";\n self.finish(false);\n }, this.timeout);\n\n // Load the tile with an AJAX request if the loadWithAjax option is\n // set. Otherwise load the image by setting the source proprety of the image object.\n if (this.loadWithAjax) {\n this.request = self.makeAjaxRequest({\n url: this.src,\n withCredentials: this.ajaxWithCredentials,\n headers: this.ajaxHeaders,\n responseType: \"arraybuffer\",\n success: function(request) {\n var blb;\n // Make the raw data into a blob.\n // BlobBuilder fallback adapted from\n // http://stackoverflow.com/questions/15293694/blob-constructor-browser-compatibility\n try {\n // Store the original response\n self.image._array = request.response;\n blb = new window.Blob([request.response]);\n } catch (e) {\n var BlobBuilder = (\n window.BlobBuilder ||\n window.WebKitBlobBuilder ||\n window.MozBlobBuilder ||\n window.MSBlobBuilder\n );\n if (e.name === 'TypeError' && BlobBuilder) {\n var bb = new BlobBuilder();\n bb.append(request.response);\n blb = bb.getBlob();\n }\n }\n // If the blob is empty for some reason consider the image load a failure.\n if (blb === undefined || blb.size === 0) {\n self.errorMsg = \"Empty image response.\";\n self.finish(false);\n }\n\n // Create a URL for the blob data and make it the source of the image object.\n // This will still trigger Image.onload to indicate a successful tile load.\n var url = (window.URL || window.webkitURL).createObjectURL(blb);\n self.image.src = url;\n },\n error: function(request) {\n self.errorMsg = \"Image load aborted - XHR error\";\n self.finish(false);\n }\n });\n\n // Provide a function to properly abort the request.\n this.abort = function() {\n self.request.abort();\n\n // Call the existing abort function if available\n if (typeof selfAbort === \"function\") {\n selfAbort();\n }\n };\n } else {\n if (this.crossOriginPolicy !== false) {\n this.image.crossOrigin = this.crossOriginPolicy;\n }\n\n this.image.src = this.src;\n }\n },\n\n finish: function(successful) {\n this.image.onload = this.image.onerror = this.image.onabort = null;\n if (!successful) {\n this.image = null;\n }\n\n if (this.jobId) {\n window.clearTimeout(this.jobId);\n }\n\n this.callback(this);\n }\n\n};\n\n/**\n * @class ImageLoader\n * @memberof OpenSeadragon\n * @classdesc Handles downloading of a set of images using asynchronous queue pattern.\n * You generally won't have to interact with the ImageLoader directly.\n * @param {Object} options - Options for this ImageLoader.\n * @param {Number} [options.jobLimit] - The number of concurrent image requests. See imageLoaderLimit in {@link OpenSeadragon.Options} for details.\n * @param {Number} [options.timeout] - The max number of milliseconds that an image job may take to complete.\n */\n$.ImageLoader = function(options) {\n\n $.extend(true, this, {\n jobLimit: $.DEFAULT_SETTINGS.imageLoaderLimit,\n timeout: $.DEFAULT_SETTINGS.timeout,\n jobQueue: [],\n jobsInProgress: 0\n }, options);\n\n};\n\n/** @lends OpenSeadragon.ImageLoader.prototype */\n$.ImageLoader.prototype = {\n\n /**\n * Add an unloaded image to the loader queue.\n * @method\n * @param {Object} options - Options for this job.\n * @param {String} [options.src] - URL of image to download.\n * @param {String} [options.loadWithAjax] - Whether to load this image with AJAX.\n * @param {String} [options.ajaxHeaders] - Headers to add to the image request if using AJAX.\n * @param {String|Boolean} [options.crossOriginPolicy] - CORS policy to use for downloads\n * @param {Boolean} [options.ajaxWithCredentials] - Whether to set withCredentials on AJAX\n * requests.\n * @param {Function} [options.callback] - Called once image has been downloaded.\n * @param {Function} [options.abort] - Called when this image job is aborted.\n */\n addJob: function(options) {\n var _this = this,\n complete = function(job) {\n completeJob(_this, job, options.callback);\n },\n jobOptions = {\n src: options.src,\n loadWithAjax: options.loadWithAjax,\n ajaxHeaders: options.loadWithAjax ? options.ajaxHeaders : null,\n crossOriginPolicy: options.crossOriginPolicy,\n ajaxWithCredentials: options.ajaxWithCredentials,\n makeAjaxRequest: options.makeAjaxRequest,\n callback: complete,\n abort: options.abort,\n timeout: this.timeout\n },\n newJob = new ImageJob(jobOptions);\n\n if ( !this.jobLimit || this.jobsInProgress < this.jobLimit ) {\n newJob.start();\n this.jobsInProgress++;\n }\n else {\n this.jobQueue.push( newJob );\n }\n },\n\n /**\n * Clear any unstarted image loading jobs from the queue.\n * @method\n */\n clear: function() {\n for( var i = 0; i < this.jobQueue.length; i++ ) {\n var job = this.jobQueue[i];\n if ( typeof job.abort === \"function\" ) {\n job.abort();\n }\n }\n\n this.jobQueue = [];\n }\n};\n\n/**\n * Cleans up ImageJob once completed.\n * @method\n * @private\n * @param loader - ImageLoader used to start job.\n * @param job - The ImageJob that has completed.\n * @param callback - Called once cleanup is finished.\n */\nfunction completeJob(loader, job, callback) {\n var nextJob;\n\n loader.jobsInProgress--;\n\n if ((!loader.jobLimit || loader.jobsInProgress < loader.jobLimit) && loader.jobQueue.length > 0) {\n nextJob = loader.jobQueue.shift();\n nextJob.start();\n loader.jobsInProgress++;\n }\n\n callback(job.image, job.errorMsg, job.request);\n}\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Tile\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Tile\n * @memberof OpenSeadragon\n * @param {Number} level The zoom level this tile belongs to.\n * @param {Number} x The vector component 'x'.\n * @param {Number} y The vector component 'y'.\n * @param {OpenSeadragon.Rect} bounds Where this tile fits, in normalized\n * coordinates.\n * @param {Boolean} exists Is this tile a part of a sparse image? ( Also has\n * this tile failed to load? )\n * @param {String} url The URL of this tile's image.\n * @param {CanvasRenderingContext2D} context2D The context2D of this tile if it\n * is provided directly by the tile source.\n * @param {Boolean} loadWithAjax Whether this tile image should be loaded with an AJAX request .\n * @param {Object} ajaxHeaders The headers to send with this tile's AJAX request (if applicable).\n * @param {OpenSeadragon.Rect} sourceBounds The portion of the tile to use as the source of the\n * drawing operation, in pixels. Note that this only works when drawing with canvas; when drawing\n * with HTML the entire tile is always used.\n */\n$.Tile = function(level, x, y, bounds, exists, url, context2D, loadWithAjax, ajaxHeaders, sourceBounds) {\n /**\n * The zoom level this tile belongs to.\n * @member {Number} level\n * @memberof OpenSeadragon.Tile#\n */\n this.level = level;\n /**\n * The vector component 'x'.\n * @member {Number} x\n * @memberof OpenSeadragon.Tile#\n */\n this.x = x;\n /**\n * The vector component 'y'.\n * @member {Number} y\n * @memberof OpenSeadragon.Tile#\n */\n this.y = y;\n /**\n * Where this tile fits, in normalized coordinates\n * @member {OpenSeadragon.Rect} bounds\n * @memberof OpenSeadragon.Tile#\n */\n this.bounds = bounds;\n /**\n * The portion of the tile to use as the source of the drawing operation, in pixels. Note that\n * this only works when drawing with canvas; when drawing with HTML the entire tile is always used.\n * @member {OpenSeadragon.Rect} sourceBounds\n * @memberof OpenSeadragon.Tile#\n */\n this.sourceBounds = sourceBounds;\n /**\n * Is this tile a part of a sparse image? Also has this tile failed to load?\n * @member {Boolean} exists\n * @memberof OpenSeadragon.Tile#\n */\n this.exists = exists;\n /**\n * The URL of this tile's image.\n * @member {String} url\n * @memberof OpenSeadragon.Tile#\n */\n this.url = url;\n /**\n * The context2D of this tile if it is provided directly by the tile source.\n * @member {CanvasRenderingContext2D} context2D\n * @memberOf OpenSeadragon.Tile#\n */\n this.context2D = context2D;\n /**\n * Whether to load this tile's image with an AJAX request.\n * @member {Boolean} loadWithAjax\n * @memberof OpenSeadragon.Tile#\n */\n this.loadWithAjax = loadWithAjax;\n /**\n * The headers to be used in requesting this tile's image.\n * Only used if loadWithAjax is set to true.\n * @member {Object} ajaxHeaders\n * @memberof OpenSeadragon.Tile#\n */\n this.ajaxHeaders = ajaxHeaders;\n /**\n * The unique cache key for this tile.\n * @member {String} cacheKey\n * @memberof OpenSeadragon.Tile#\n */\n if (this.ajaxHeaders) {\n this.cacheKey = this.url + \"+\" + JSON.stringify(this.ajaxHeaders);\n } else {\n this.cacheKey = this.url;\n }\n /**\n * Is this tile loaded?\n * @member {Boolean} loaded\n * @memberof OpenSeadragon.Tile#\n */\n this.loaded = false;\n /**\n * Is this tile loading?\n * @member {Boolean} loading\n * @memberof OpenSeadragon.Tile#\n */\n this.loading = false;\n\n /**\n * The HTML div element for this tile\n * @member {Element} element\n * @memberof OpenSeadragon.Tile#\n */\n this.element = null;\n /**\n * The HTML img element for this tile.\n * @member {Element} imgElement\n * @memberof OpenSeadragon.Tile#\n */\n this.imgElement = null;\n /**\n * The Image object for this tile.\n * @member {Object} image\n * @memberof OpenSeadragon.Tile#\n */\n this.image = null;\n\n /**\n * The alias of this.element.style.\n * @member {String} style\n * @memberof OpenSeadragon.Tile#\n */\n this.style = null;\n /**\n * This tile's position on screen, in pixels.\n * @member {OpenSeadragon.Point} position\n * @memberof OpenSeadragon.Tile#\n */\n this.position = null;\n /**\n * This tile's size on screen, in pixels.\n * @member {OpenSeadragon.Point} size\n * @memberof OpenSeadragon.Tile#\n */\n this.size = null;\n /**\n * The start time of this tile's blending.\n * @member {Number} blendStart\n * @memberof OpenSeadragon.Tile#\n */\n this.blendStart = null;\n /**\n * The current opacity this tile should be.\n * @member {Number} opacity\n * @memberof OpenSeadragon.Tile#\n */\n this.opacity = null;\n /**\n * The squared distance of this tile to the viewport center.\n * Use for comparing tiles.\n * @private\n * @member {Number} squaredDistance\n * @memberof OpenSeadragon.Tile#\n */\n this.squaredDistance = null;\n /**\n * The visibility score of this tile.\n * @member {Number} visibility\n * @memberof OpenSeadragon.Tile#\n */\n this.visibility = null;\n\n /**\n * Whether this tile is currently being drawn.\n * @member {Boolean} beingDrawn\n * @memberof OpenSeadragon.Tile#\n */\n this.beingDrawn = false;\n\n /**\n * Timestamp the tile was last touched.\n * @member {Number} lastTouchTime\n * @memberof OpenSeadragon.Tile#\n */\n this.lastTouchTime = 0;\n\n /**\n * Whether this tile is in the right-most column for its level.\n * @member {Boolean} isRightMost\n * @memberof OpenSeadragon.Tile#\n */\n this.isRightMost = false;\n\n /**\n * Whether this tile is in the bottom-most row for its level.\n * @member {Boolean} isBottomMost\n * @memberof OpenSeadragon.Tile#\n */\n this.isBottomMost = false;\n};\n\n/** @lends OpenSeadragon.Tile.prototype */\n$.Tile.prototype = {\n\n /**\n * Provides a string representation of this tiles level and (x,y)\n * components.\n * @function\n * @returns {String}\n */\n toString: function() {\n return this.level + \"/\" + this.x + \"_\" + this.y;\n },\n\n // private\n _hasTransparencyChannel: function() {\n return !!this.context2D || this.url.match('.png');\n },\n\n /**\n * Renders the tile in an html container.\n * @function\n * @param {Element} container\n */\n drawHTML: function( container ) {\n if (!this.cacheImageRecord) {\n $.console.warn(\n '[Tile.drawHTML] attempting to draw tile %s when it\\'s not cached',\n this.toString());\n return;\n }\n\n if ( !this.loaded ) {\n $.console.warn(\n \"Attempting to draw tile %s when it's not yet loaded.\",\n this.toString()\n );\n return;\n }\n\n //EXPERIMENTAL - trying to figure out how to scale the container\n // content during animation of the container size.\n\n if ( !this.element ) {\n this.element = $.makeNeutralElement( \"div\" );\n this.imgElement = this.cacheImageRecord.getImage().cloneNode();\n this.imgElement.style.msInterpolationMode = \"nearest-neighbor\";\n this.imgElement.style.width = \"100%\";\n this.imgElement.style.height = \"100%\";\n\n this.style = this.element.style;\n this.style.position = \"absolute\";\n }\n if ( this.element.parentNode != container ) {\n container.appendChild( this.element );\n }\n if ( this.imgElement.parentNode != this.element ) {\n this.element.appendChild( this.imgElement );\n }\n\n this.style.top = this.position.y + \"px\";\n this.style.left = this.position.x + \"px\";\n this.style.height = this.size.y + \"px\";\n this.style.width = this.size.x + \"px\";\n\n $.setElementOpacity( this.element, this.opacity );\n },\n\n /**\n * Renders the tile in a canvas-based context.\n * @function\n * @param {Canvas} context\n * @param {Function} drawingHandler - Method for firing the drawing event.\n * drawingHandler({context, tile, rendered})\n * where rendered is the context with the pre-drawn image.\n * @param {Number} [scale=1] - Apply a scale to position and size\n * @param {OpenSeadragon.Point} [translate] - A translation vector\n */\n drawCanvas: function( context, drawingHandler, scale, translate ) {\n\n var position = this.position.times($.pixelDensityRatio),\n size = this.size.times($.pixelDensityRatio),\n rendered;\n\n if (!this.context2D && !this.cacheImageRecord) {\n $.console.warn(\n '[Tile.drawCanvas] attempting to draw tile %s when it\\'s not cached',\n this.toString());\n return;\n }\n\n rendered = this.context2D || this.cacheImageRecord.getRenderedContext();\n\n if ( !this.loaded || !rendered ){\n $.console.warn(\n \"Attempting to draw tile %s when it's not yet loaded.\",\n this.toString()\n );\n\n return;\n }\n\n context.save();\n\n context.globalAlpha = this.opacity;\n\n if (typeof scale === 'number' && scale !== 1) {\n // draw tile at a different scale\n position = position.times(scale);\n size = size.times(scale);\n }\n\n if (translate instanceof $.Point) {\n // shift tile position slightly\n position = position.plus(translate);\n }\n\n //if we are supposed to be rendering fully opaque rectangle,\n //ie its done fading or fading is turned off, and if we are drawing\n //an image with an alpha channel, then the only way\n //to avoid seeing the tile underneath is to clear the rectangle\n if (context.globalAlpha === 1 && this._hasTransparencyChannel()) {\n //clearing only the inside of the rectangle occupied\n //by the png prevents edge flikering\n context.clearRect(\n position.x,\n position.y,\n size.x,\n size.y\n );\n }\n\n // This gives the application a chance to make image manipulation\n // changes as we are rendering the image\n drawingHandler({context: context, tile: this, rendered: rendered});\n\n var sourceWidth, sourceHeight;\n if (this.sourceBounds) {\n sourceWidth = Math.min(this.sourceBounds.width, rendered.canvas.width);\n sourceHeight = Math.min(this.sourceBounds.height, rendered.canvas.height);\n } else {\n sourceWidth = rendered.canvas.width;\n sourceHeight = rendered.canvas.height;\n }\n\n context.drawImage(\n rendered.canvas,\n 0,\n 0,\n sourceWidth,\n sourceHeight,\n position.x,\n position.y,\n size.x,\n size.y\n );\n\n context.restore();\n },\n\n /**\n * Get the ratio between current and original size.\n * @function\n * @return {Float}\n */\n getScaleForEdgeSmoothing: function() {\n var context;\n if (this.cacheImageRecord) {\n context = this.cacheImageRecord.getRenderedContext();\n } else if (this.context2D) {\n context = this.context2D;\n } else {\n $.console.warn(\n '[Tile.drawCanvas] attempting to get tile scale %s when tile\\'s not cached',\n this.toString());\n return 1;\n }\n return context.canvas.width / (this.size.x * $.pixelDensityRatio);\n },\n\n /**\n * Get a translation vector that when applied to the tile position produces integer coordinates.\n * Needed to avoid swimming and twitching.\n * @function\n * @param {Number} [scale=1] - Scale to be applied to position.\n * @return {OpenSeadragon.Point}\n */\n getTranslationForEdgeSmoothing: function(scale, canvasSize, sketchCanvasSize) {\n // The translation vector must have positive values, otherwise the image goes a bit off\n // the sketch canvas to the top and left and we must use negative coordinates to repaint it\n // to the main canvas. In that case, some browsers throw:\n // INDEX_SIZE_ERR: DOM Exception 1: Index or size was negative, or greater than the allowed value.\n var x = Math.max(1, Math.ceil((sketchCanvasSize.x - canvasSize.x) / 2));\n var y = Math.max(1, Math.ceil((sketchCanvasSize.y - canvasSize.y) / 2));\n return new $.Point(x, y).minus(\n this.position\n .times($.pixelDensityRatio)\n .times(scale || 1)\n .apply(function(x) {\n return x % 1;\n })\n );\n },\n\n /**\n * Removes tile from its container.\n * @function\n */\n unload: function() {\n if ( this.imgElement && this.imgElement.parentNode ) {\n this.imgElement.parentNode.removeChild( this.imgElement );\n }\n if ( this.element && this.element.parentNode ) {\n this.element.parentNode.removeChild( this.element );\n }\n\n this.element = null;\n this.imgElement = null;\n this.loaded = false;\n this.loading = false;\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Overlay\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function($) {\n\n /**\n * An enumeration of positions that an overlay may be assigned relative to\n * the viewport.\n * It is identical to OpenSeadragon.Placement but is kept for backward\n * compatibility.\n * @member OverlayPlacement\n * @memberof OpenSeadragon\n * @see OpenSeadragon.Placement\n * @static\n * @readonly\n * @type {Object}\n * @property {Number} CENTER\n * @property {Number} TOP_LEFT\n * @property {Number} TOP\n * @property {Number} TOP_RIGHT\n * @property {Number} RIGHT\n * @property {Number} BOTTOM_RIGHT\n * @property {Number} BOTTOM\n * @property {Number} BOTTOM_LEFT\n * @property {Number} LEFT\n */\n $.OverlayPlacement = $.Placement;\n\n /**\n * An enumeration of possible ways to handle overlays rotation\n * @member OverlayRotationMode\n * @memberOf OpenSeadragon\n * @static\n * @readonly\n * @property {Number} NO_ROTATION The overlay ignore the viewport rotation.\n * @property {Number} EXACT The overlay use CSS 3 transforms to rotate with\n * the viewport. If the overlay contains text, it will get rotated as well.\n * @property {Number} BOUNDING_BOX The overlay adjusts for rotation by\n * taking the size of the bounding box of the rotated bounds.\n * Only valid for overlays with Rect location and scalable in both directions.\n */\n $.OverlayRotationMode = $.freezeObject({\n NO_ROTATION: 1,\n EXACT: 2,\n BOUNDING_BOX: 3\n });\n\n /**\n * @class Overlay\n * @classdesc Provides a way to float an HTML element on top of the viewer element.\n *\n * @memberof OpenSeadragon\n * @param {Object} options\n * @param {Element} options.element\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect} options.location - The\n * location of the overlay on the image. If a {@link OpenSeadragon.Point}\n * is specified, the overlay will be located at this location with respect\n * to the placement option. If a {@link OpenSeadragon.Rect} is specified,\n * the overlay will be placed at this location with the corresponding width\n * and height and placement TOP_LEFT.\n * @param {OpenSeadragon.Placement} [options.placement=OpenSeadragon.Placement.TOP_LEFT]\n * Defines what part of the overlay should be at the specified options.location\n * @param {OpenSeadragon.Overlay.OnDrawCallback} [options.onDraw]\n * @param {Boolean} [options.checkResize=true] Set to false to avoid to\n * check the size of the overlay everytime it is drawn in the directions\n * which are not scaled. It will improve performances but will cause a\n * misalignment if the overlay size changes.\n * @param {Number} [options.width] The width of the overlay in viewport\n * coordinates. If specified, the width of the overlay will be adjusted when\n * the zoom changes.\n * @param {Number} [options.height] The height of the overlay in viewport\n * coordinates. If specified, the height of the overlay will be adjusted when\n * the zoom changes.\n * @param {Boolean} [options.rotationMode=OpenSeadragon.OverlayRotationMode.EXACT]\n * How to handle the rotation of the viewport.\n */\n $.Overlay = function(element, location, placement) {\n\n /**\n * onDraw callback signature used by {@link OpenSeadragon.Overlay}.\n *\n * @callback OnDrawCallback\n * @memberof OpenSeadragon.Overlay\n * @param {OpenSeadragon.Point} position\n * @param {OpenSeadragon.Point} size\n * @param {Element} element\n */\n\n var options;\n if ($.isPlainObject(element)) {\n options = element;\n } else {\n options = {\n element: element,\n location: location,\n placement: placement\n };\n }\n\n this.element = options.element;\n this.style = options.element.style;\n this._init(options);\n };\n\n /** @lends OpenSeadragon.Overlay.prototype */\n $.Overlay.prototype = {\n\n // private\n _init: function(options) {\n this.location = options.location;\n this.placement = options.placement === undefined ?\n $.Placement.TOP_LEFT : options.placement;\n this.onDraw = options.onDraw;\n this.checkResize = options.checkResize === undefined ?\n true : options.checkResize;\n\n // When this.width is not null, the overlay get scaled horizontally\n this.width = options.width === undefined ? null : options.width;\n\n // When this.height is not null, the overlay get scaled vertically\n this.height = options.height === undefined ? null : options.height;\n\n this.rotationMode = options.rotationMode || $.OverlayRotationMode.EXACT;\n\n // Having a rect as location is a syntactic sugar\n if (this.location instanceof $.Rect) {\n this.width = this.location.width;\n this.height = this.location.height;\n this.location = this.location.getTopLeft();\n this.placement = $.Placement.TOP_LEFT;\n }\n\n // Deprecated properties kept for backward compatibility.\n this.scales = this.width !== null && this.height !== null;\n this.bounds = new $.Rect(\n this.location.x, this.location.y, this.width, this.height);\n this.position = this.location;\n },\n\n /**\n * Internal function to adjust the position of an overlay\n * depending on it size and placement.\n * @function\n * @param {OpenSeadragon.Point} position\n * @param {OpenSeadragon.Point} size\n */\n adjust: function(position, size) {\n var properties = $.Placement.properties[this.placement];\n if (!properties) {\n return;\n }\n if (properties.isHorizontallyCentered) {\n position.x -= size.x / 2;\n } else if (properties.isRight) {\n position.x -= size.x;\n }\n if (properties.isVerticallyCentered) {\n position.y -= size.y / 2;\n } else if (properties.isBottom) {\n position.y -= size.y;\n }\n },\n\n /**\n * @function\n */\n destroy: function() {\n var element = this.element;\n var style = this.style;\n\n if (element.parentNode) {\n element.parentNode.removeChild(element);\n //this should allow us to preserve overlays when required between\n //pages\n if (element.prevElementParent) {\n style.display = 'none';\n //element.prevElementParent.insertBefore(\n // element,\n // element.prevNextSibling\n //);\n document.body.appendChild(element);\n }\n }\n\n // clear the onDraw callback\n this.onDraw = null;\n\n style.top = \"\";\n style.left = \"\";\n style.position = \"\";\n\n if (this.width !== null) {\n style.width = \"\";\n }\n if (this.height !== null) {\n style.height = \"\";\n }\n var transformOriginProp = $.getCssPropertyWithVendorPrefix(\n 'transformOrigin');\n var transformProp = $.getCssPropertyWithVendorPrefix(\n 'transform');\n if (transformOriginProp && transformProp) {\n style[transformOriginProp] = \"\";\n style[transformProp] = \"\";\n }\n },\n\n /**\n * @function\n * @param {Element} container\n */\n drawHTML: function(container, viewport) {\n var element = this.element;\n if (element.parentNode !== container) {\n //save the source parent for later if we need it\n element.prevElementParent = element.parentNode;\n element.prevNextSibling = element.nextSibling;\n container.appendChild(element);\n\n // have to set position before calculating size, fix #1116\n this.style.position = \"absolute\";\n // this.size is used by overlays which don't get scaled in at\n // least one direction when this.checkResize is set to false.\n this.size = $.getElementSize(element);\n }\n\n var positionAndSize = this._getOverlayPositionAndSize(viewport);\n\n var position = positionAndSize.position;\n var size = this.size = positionAndSize.size;\n var rotate = positionAndSize.rotate;\n\n // call the onDraw callback if it exists to allow one to overwrite\n // the drawing/positioning/sizing of the overlay\n if (this.onDraw) {\n this.onDraw(position, size, this.element);\n } else {\n var style = this.style;\n style.left = position.x + \"px\";\n style.top = position.y + \"px\";\n if (this.width !== null) {\n style.width = size.x + \"px\";\n }\n if (this.height !== null) {\n style.height = size.y + \"px\";\n }\n var transformOriginProp = $.getCssPropertyWithVendorPrefix(\n 'transformOrigin');\n var transformProp = $.getCssPropertyWithVendorPrefix(\n 'transform');\n if (transformOriginProp && transformProp) {\n if (rotate) {\n style[transformOriginProp] = this._getTransformOrigin();\n style[transformProp] = \"rotate(\" + rotate + \"deg)\";\n } else {\n style[transformOriginProp] = \"\";\n style[transformProp] = \"\";\n }\n }\n\n if (style.display !== 'none') {\n style.display = 'block';\n }\n }\n },\n\n // private\n _getOverlayPositionAndSize: function(viewport) {\n var position = viewport.pixelFromPoint(this.location, true);\n var size = this._getSizeInPixels(viewport);\n this.adjust(position, size);\n\n var rotate = 0;\n if (viewport.degrees &&\n this.rotationMode !== $.OverlayRotationMode.NO_ROTATION) {\n // BOUNDING_BOX is only valid if both directions get scaled.\n // Get replaced by EXACT otherwise.\n if (this.rotationMode === $.OverlayRotationMode.BOUNDING_BOX &&\n this.width !== null && this.height !== null) {\n var rect = new $.Rect(position.x, position.y, size.x, size.y);\n var boundingBox = this._getBoundingBox(rect, viewport.degrees);\n position = boundingBox.getTopLeft();\n size = boundingBox.getSize();\n } else {\n rotate = viewport.degrees;\n }\n }\n\n return {\n position: position,\n size: size,\n rotate: rotate\n };\n },\n\n // private\n _getSizeInPixels: function(viewport) {\n var width = this.size.x;\n var height = this.size.y;\n if (this.width !== null || this.height !== null) {\n var scaledSize = viewport.deltaPixelsFromPointsNoRotate(\n new $.Point(this.width || 0, this.height || 0), true);\n if (this.width !== null) {\n width = scaledSize.x;\n }\n if (this.height !== null) {\n height = scaledSize.y;\n }\n }\n if (this.checkResize &&\n (this.width === null || this.height === null)) {\n var eltSize = this.size = $.getElementSize(this.element);\n if (this.width === null) {\n width = eltSize.x;\n }\n if (this.height === null) {\n height = eltSize.y;\n }\n }\n return new $.Point(width, height);\n },\n\n // private\n _getBoundingBox: function(rect, degrees) {\n var refPoint = this._getPlacementPoint(rect);\n return rect.rotate(degrees, refPoint).getBoundingBox();\n },\n\n // private\n _getPlacementPoint: function(rect) {\n var result = new $.Point(rect.x, rect.y);\n var properties = $.Placement.properties[this.placement];\n if (properties) {\n if (properties.isHorizontallyCentered) {\n result.x += rect.width / 2;\n } else if (properties.isRight) {\n result.x += rect.width;\n }\n if (properties.isVerticallyCentered) {\n result.y += rect.height / 2;\n } else if (properties.isBottom) {\n result.y += rect.height;\n }\n }\n return result;\n },\n\n // private\n _getTransformOrigin: function() {\n var result = \"\";\n var properties = $.Placement.properties[this.placement];\n if (!properties) {\n return result;\n }\n if (properties.isLeft) {\n result = \"left\";\n } else if (properties.isRight) {\n result = \"right\";\n }\n if (properties.isTop) {\n result += \" top\";\n } else if (properties.isBottom) {\n result += \" bottom\";\n }\n return result;\n },\n\n /**\n * Changes the overlay settings.\n * @function\n * @param {OpenSeadragon.Point|OpenSeadragon.Rect|Object} location\n * If an object is specified, the options are the same than the constructor\n * except for the element which can not be changed.\n * @param {OpenSeadragon.Placement} placement\n */\n update: function(location, placement) {\n var options = $.isPlainObject(location) ? location : {\n location: location,\n placement: placement\n };\n this._init({\n location: options.location || this.location,\n placement: options.placement !== undefined ?\n options.placement : this.placement,\n onDraw: options.onDraw || this.onDraw,\n checkResize: options.checkResize || this.checkResize,\n width: options.width !== undefined ? options.width : this.width,\n height: options.height !== undefined ? options.height : this.height,\n rotationMode: options.rotationMode || this.rotationMode\n });\n },\n\n /**\n * Returns the current bounds of the overlay in viewport coordinates\n * @function\n * @param {OpenSeadragon.Viewport} viewport the viewport\n * @returns {OpenSeadragon.Rect} overlay bounds\n */\n getBounds: function(viewport) {\n $.console.assert(viewport,\n 'A viewport must now be passed to Overlay.getBounds.');\n var width = this.width;\n var height = this.height;\n if (width === null || height === null) {\n var size = viewport.deltaPointsFromPixelsNoRotate(this.size, true);\n if (width === null) {\n width = size.x;\n }\n if (height === null) {\n height = size.y;\n }\n }\n var location = this.location.clone();\n this.adjust(location, new $.Point(width, height));\n return this._adjustBoundsForRotation(\n viewport, new $.Rect(location.x, location.y, width, height));\n },\n\n // private\n _adjustBoundsForRotation: function(viewport, bounds) {\n if (!viewport ||\n viewport.degrees === 0 ||\n this.rotationMode === $.OverlayRotationMode.EXACT) {\n return bounds;\n }\n if (this.rotationMode === $.OverlayRotationMode.BOUNDING_BOX) {\n // If overlay not fully scalable, BOUNDING_BOX falls back to EXACT\n if (this.width === null || this.height === null) {\n return bounds;\n }\n // It is easier to just compute the position and size and\n // convert to viewport coordinates.\n var positionAndSize = this._getOverlayPositionAndSize(viewport);\n return viewport.viewerElementToViewportRectangle(new $.Rect(\n positionAndSize.position.x,\n positionAndSize.position.y,\n positionAndSize.size.x,\n positionAndSize.size.y));\n }\n\n // NO_ROTATION case\n return bounds.rotate(-viewport.degrees,\n this._getPlacementPoint(bounds));\n }\n };\n\n}(OpenSeadragon));\n\n/*\n * OpenSeadragon - Drawer\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class Drawer\n * @memberof OpenSeadragon\n * @classdesc Handles rendering of tiles for an {@link OpenSeadragon.Viewer}.\n * @param {Object} options - Options for this Drawer.\n * @param {OpenSeadragon.Viewer} options.viewer - The Viewer that owns this Drawer.\n * @param {OpenSeadragon.Viewport} options.viewport - Reference to Viewer viewport.\n * @param {Element} options.element - Parent element.\n * @param {Number} [options.debugGridColor] - See debugGridColor in {@link OpenSeadragon.Options} for details.\n */\n$.Drawer = function( options ) {\n\n $.console.assert( options.viewer, \"[Drawer] options.viewer is required\" );\n\n //backward compatibility for positional args while prefering more\n //idiomatic javascript options object as the only argument\n var args = arguments;\n\n if( !$.isPlainObject( options ) ){\n options = {\n source: args[ 0 ], // Reference to Viewer tile source.\n viewport: args[ 1 ], // Reference to Viewer viewport.\n element: args[ 2 ] // Parent element.\n };\n }\n\n $.console.assert( options.viewport, \"[Drawer] options.viewport is required\" );\n $.console.assert( options.element, \"[Drawer] options.element is required\" );\n\n if ( options.source ) {\n $.console.error( \"[Drawer] options.source is no longer accepted; use TiledImage instead\" );\n }\n\n this.viewer = options.viewer;\n this.viewport = options.viewport;\n this.debugGridColor = typeof options.debugGridColor === 'string' ? [options.debugGridColor] : options.debugGridColor || $.DEFAULT_SETTINGS.debugGridColor;\n if (options.opacity) {\n $.console.error( \"[Drawer] options.opacity is no longer accepted; set the opacity on the TiledImage instead\" );\n }\n\n this.useCanvas = $.supportsCanvas && ( this.viewer ? this.viewer.useCanvas : true );\n /**\n * The parent element of this Drawer instance, passed in when the Drawer was created.\n * The parent of {@link OpenSeadragon.Drawer#canvas}.\n * @member {Element} container\n * @memberof OpenSeadragon.Drawer#\n */\n this.container = $.getElement( options.element );\n /**\n * A <canvas> element if the browser supports them, otherwise a <div> element.\n * Child element of {@link OpenSeadragon.Drawer#container}.\n * @member {Element} canvas\n * @memberof OpenSeadragon.Drawer#\n */\n this.canvas = $.makeNeutralElement( this.useCanvas ? \"canvas\" : \"div\" );\n /**\n * 2d drawing context for {@link OpenSeadragon.Drawer#canvas} if it's a <canvas> element, otherwise null.\n * @member {Object} context\n * @memberof OpenSeadragon.Drawer#\n */\n this.context = this.useCanvas ? this.canvas.getContext( \"2d\" ) : null;\n\n /**\n * Sketch canvas used to temporarily draw tiles which cannot be drawn directly\n * to the main canvas due to opacity. Lazily initialized.\n */\n this.sketchCanvas = null;\n this.sketchContext = null;\n\n /**\n * @member {Element} element\n * @memberof OpenSeadragon.Drawer#\n * @deprecated Alias for {@link OpenSeadragon.Drawer#container}.\n */\n this.element = this.container;\n\n // We force our container to ltr because our drawing math doesn't work in rtl.\n // This issue only affects our canvas renderer, but we do it always for consistency.\n // Note that this means overlays you want to be rtl need to be explicitly set to rtl.\n this.container.dir = 'ltr';\n\n // check canvas available width and height, set canvas width and height such that the canvas backing store is set to the proper pixel density\n if (this.useCanvas) {\n var viewportSize = this._calculateCanvasSize();\n this.canvas.width = viewportSize.x;\n this.canvas.height = viewportSize.y;\n }\n\n this.canvas.style.width = \"100%\";\n this.canvas.style.height = \"100%\";\n this.canvas.style.position = \"absolute\";\n $.setElementOpacity( this.canvas, this.opacity, true );\n\n // explicit left-align\n this.container.style.textAlign = \"left\";\n this.container.appendChild( this.canvas );\n};\n\n/** @lends OpenSeadragon.Drawer.prototype */\n$.Drawer.prototype = {\n // deprecated\n addOverlay: function( element, location, placement, onDraw ) {\n $.console.error(\"drawer.addOverlay is deprecated. Use viewer.addOverlay instead.\");\n this.viewer.addOverlay( element, location, placement, onDraw );\n return this;\n },\n\n // deprecated\n updateOverlay: function( element, location, placement ) {\n $.console.error(\"drawer.updateOverlay is deprecated. Use viewer.updateOverlay instead.\");\n this.viewer.updateOverlay( element, location, placement );\n return this;\n },\n\n // deprecated\n removeOverlay: function( element ) {\n $.console.error(\"drawer.removeOverlay is deprecated. Use viewer.removeOverlay instead.\");\n this.viewer.removeOverlay( element );\n return this;\n },\n\n // deprecated\n clearOverlays: function() {\n $.console.error(\"drawer.clearOverlays is deprecated. Use viewer.clearOverlays instead.\");\n this.viewer.clearOverlays();\n return this;\n },\n\n /**\n * Set the opacity of the drawer.\n * @param {Number} opacity\n * @return {OpenSeadragon.Drawer} Chainable.\n */\n setOpacity: function( opacity ) {\n $.console.error(\"drawer.setOpacity is deprecated. Use tiledImage.setOpacity instead.\");\n var world = this.viewer.world;\n for (var i = 0; i < world.getItemCount(); i++) {\n world.getItemAt( i ).setOpacity( opacity );\n }\n return this;\n },\n\n /**\n * Get the opacity of the drawer.\n * @returns {Number}\n */\n getOpacity: function() {\n $.console.error(\"drawer.getOpacity is deprecated. Use tiledImage.getOpacity instead.\");\n var world = this.viewer.world;\n var maxOpacity = 0;\n for (var i = 0; i < world.getItemCount(); i++) {\n var opacity = world.getItemAt( i ).getOpacity();\n if ( opacity > maxOpacity ) {\n maxOpacity = opacity;\n }\n }\n return maxOpacity;\n },\n\n // deprecated\n needsUpdate: function() {\n $.console.error( \"[Drawer.needsUpdate] this function is deprecated. Use World.needsDraw instead.\" );\n return this.viewer.world.needsDraw();\n },\n\n // deprecated\n numTilesLoaded: function() {\n $.console.error( \"[Drawer.numTilesLoaded] this function is deprecated. Use TileCache.numTilesLoaded instead.\" );\n return this.viewer.tileCache.numTilesLoaded();\n },\n\n // deprecated\n reset: function() {\n $.console.error( \"[Drawer.reset] this function is deprecated. Use World.resetItems instead.\" );\n this.viewer.world.resetItems();\n return this;\n },\n\n // deprecated\n update: function() {\n $.console.error( \"[Drawer.update] this function is deprecated. Use Drawer.clear and World.draw instead.\" );\n this.clear();\n this.viewer.world.draw();\n return this;\n },\n\n /**\n * @return {Boolean} True if rotation is supported.\n */\n canRotate: function() {\n return this.useCanvas;\n },\n\n /**\n * Destroy the drawer (unload current loaded tiles)\n */\n destroy: function() {\n //force unloading of current canvas (1x1 will be gc later, trick not necessarily needed)\n this.canvas.width = 1;\n this.canvas.height = 1;\n this.sketchCanvas = null;\n this.sketchContext = null;\n },\n\n /**\n * Clears the Drawer so it's ready to draw another frame.\n */\n clear: function() {\n this.canvas.innerHTML = \"\";\n if ( this.useCanvas ) {\n var viewportSize = this._calculateCanvasSize();\n if( this.canvas.width != viewportSize.x ||\n this.canvas.height != viewportSize.y ) {\n this.canvas.width = viewportSize.x;\n this.canvas.height = viewportSize.y;\n if ( this.sketchCanvas !== null ) {\n var sketchCanvasSize = this._calculateSketchCanvasSize();\n this.sketchCanvas.width = sketchCanvasSize.x;\n this.sketchCanvas.height = sketchCanvasSize.y;\n }\n }\n this._clear();\n }\n },\n\n _clear: function (useSketch, bounds) {\n if (!this.useCanvas) {\n return;\n }\n var context = this._getContext(useSketch);\n if (bounds) {\n context.clearRect(bounds.x, bounds.y, bounds.width, bounds.height);\n } else {\n var canvas = context.canvas;\n context.clearRect(0, 0, canvas.width, canvas.height);\n }\n },\n\n /**\n * Scale from OpenSeadragon viewer rectangle to drawer rectangle\n * (ignoring rotation)\n * @param {OpenSeadragon.Rect} rectangle - The rectangle in viewport coordinate system.\n * @return {OpenSeadragon.Rect} Rectangle in drawer coordinate system.\n */\n viewportToDrawerRectangle: function(rectangle) {\n var topLeft = this.viewport.pixelFromPointNoRotate(rectangle.getTopLeft(), true);\n var size = this.viewport.deltaPixelsFromPointsNoRotate(rectangle.getSize(), true);\n\n return new $.Rect(\n topLeft.x * $.pixelDensityRatio,\n topLeft.y * $.pixelDensityRatio,\n size.x * $.pixelDensityRatio,\n size.y * $.pixelDensityRatio\n );\n },\n\n /**\n * Draws the given tile.\n * @param {OpenSeadragon.Tile} tile - The tile to draw.\n * @param {Function} drawingHandler - Method for firing the drawing event if using canvas.\n * drawingHandler({context, tile, rendered})\n * @param {Boolean} useSketch - Whether to use the sketch canvas or not.\n * where rendered is the context with the pre-drawn image.\n * @param {Float} [scale=1] - Apply a scale to tile position and size. Defaults to 1.\n * @param {OpenSeadragon.Point} [translate] A translation vector to offset tile position\n */\n drawTile: function(tile, drawingHandler, useSketch, scale, translate) {\n $.console.assert(tile, '[Drawer.drawTile] tile is required');\n $.console.assert(drawingHandler, '[Drawer.drawTile] drawingHandler is required');\n\n if (this.useCanvas) {\n var context = this._getContext(useSketch);\n scale = scale || 1;\n tile.drawCanvas(context, drawingHandler, scale, translate);\n } else {\n tile.drawHTML( this.canvas );\n }\n },\n\n _getContext: function( useSketch ) {\n var context = this.context;\n if ( useSketch ) {\n if (this.sketchCanvas === null) {\n this.sketchCanvas = document.createElement( \"canvas\" );\n var sketchCanvasSize = this._calculateSketchCanvasSize();\n this.sketchCanvas.width = sketchCanvasSize.x;\n this.sketchCanvas.height = sketchCanvasSize.y;\n this.sketchContext = this.sketchCanvas.getContext( \"2d\" );\n\n // If the viewport is not currently rotated, the sketchCanvas\n // will have the same size as the main canvas. However, if\n // the viewport get rotated later on, we will need to resize it.\n if (this.viewport.getRotation() === 0) {\n var self = this;\n this.viewer.addHandler('rotate', function resizeSketchCanvas() {\n if (self.viewport.getRotation() === 0) {\n return;\n }\n self.viewer.removeHandler('rotate', resizeSketchCanvas);\n var sketchCanvasSize = self._calculateSketchCanvasSize();\n self.sketchCanvas.width = sketchCanvasSize.x;\n self.sketchCanvas.height = sketchCanvasSize.y;\n });\n }\n }\n context = this.sketchContext;\n }\n return context;\n },\n\n // private\n saveContext: function( useSketch ) {\n if (!this.useCanvas) {\n return;\n }\n\n this._getContext( useSketch ).save();\n },\n\n // private\n restoreContext: function( useSketch ) {\n if (!this.useCanvas) {\n return;\n }\n\n this._getContext( useSketch ).restore();\n },\n\n // private\n setClip: function(rect, useSketch) {\n if (!this.useCanvas) {\n return;\n }\n\n var context = this._getContext( useSketch );\n context.beginPath();\n context.rect(rect.x, rect.y, rect.width, rect.height);\n context.clip();\n },\n\n // private\n drawRectangle: function(rect, fillStyle, useSketch) {\n if (!this.useCanvas) {\n return;\n }\n\n var context = this._getContext( useSketch );\n context.save();\n context.fillStyle = fillStyle;\n context.fillRect(rect.x, rect.y, rect.width, rect.height);\n context.restore();\n },\n\n /**\n * Blends the sketch canvas in the main canvas.\n * @param {Object} options The options\n * @param {Float} options.opacity The opacity of the blending.\n * @param {Float} [options.scale=1] The scale at which tiles were drawn on\n * the sketch. Default is 1.\n * Use scale to draw at a lower scale and then enlarge onto the main canvas.\n * @param {OpenSeadragon.Point} [options.translate] A translation vector\n * that was used to draw the tiles\n * @param {String} [options.compositeOperation] - How the image is\n * composited onto other images; see compositeOperation in\n * {@link OpenSeadragon.Options} for possible values.\n * @param {OpenSeadragon.Rect} [options.bounds] The part of the sketch\n * canvas to blend in the main canvas. If specified, options.scale and\n * options.translate get ignored.\n */\n blendSketch: function(opacity, scale, translate, compositeOperation) {\n var options = opacity;\n if (!$.isPlainObject(options)) {\n options = {\n opacity: opacity,\n scale: scale,\n translate: translate,\n compositeOperation: compositeOperation\n };\n }\n if (!this.useCanvas || !this.sketchCanvas) {\n return;\n }\n opacity = options.opacity;\n compositeOperation = options.compositeOperation;\n var bounds = options.bounds;\n\n this.context.save();\n this.context.globalAlpha = opacity;\n if (compositeOperation) {\n this.context.globalCompositeOperation = compositeOperation;\n }\n if (bounds) {\n // Internet Explorer, Microsoft Edge, and Safari have problems\n // when you call context.drawImage with negative x or y\n // or x + width or y + height greater than the canvas width or height respectively.\n if (bounds.x < 0) {\n bounds.width += bounds.x;\n bounds.x = 0;\n }\n if (bounds.x + bounds.width > this.canvas.width) {\n bounds.width = this.canvas.width - bounds.x;\n }\n if (bounds.y < 0) {\n bounds.height += bounds.y;\n bounds.y = 0;\n }\n if (bounds.y + bounds.height > this.canvas.height) {\n bounds.height = this.canvas.height - bounds.y;\n }\n\n this.context.drawImage(\n this.sketchCanvas,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height\n );\n } else {\n scale = options.scale || 1;\n translate = options.translate;\n var position = translate instanceof $.Point ?\n translate : new $.Point(0, 0);\n\n var widthExt = 0;\n var heightExt = 0;\n if (translate) {\n var widthDiff = this.sketchCanvas.width - this.canvas.width;\n var heightDiff = this.sketchCanvas.height - this.canvas.height;\n widthExt = Math.round(widthDiff / 2);\n heightExt = Math.round(heightDiff / 2);\n }\n this.context.drawImage(\n this.sketchCanvas,\n position.x - widthExt * scale,\n position.y - heightExt * scale,\n (this.canvas.width + 2 * widthExt) * scale,\n (this.canvas.height + 2 * heightExt) * scale,\n -widthExt,\n -heightExt,\n this.canvas.width + 2 * widthExt,\n this.canvas.height + 2 * heightExt\n );\n }\n this.context.restore();\n },\n\n // private\n drawDebugInfo: function(tile, count, i, tiledImage) {\n if ( !this.useCanvas ) {\n return;\n }\n\n var colorIndex = this.viewer.world.getIndexOfItem(tiledImage) % this.debugGridColor.length;\n var context = this.context;\n context.save();\n context.lineWidth = 2 * $.pixelDensityRatio;\n context.font = 'small-caps bold ' + (13 * $.pixelDensityRatio) + 'px arial';\n context.strokeStyle = this.debugGridColor[colorIndex];\n context.fillStyle = this.debugGridColor[colorIndex];\n\n if ( this.viewport.degrees !== 0 ) {\n this._offsetForRotation({degrees: this.viewport.degrees});\n } else{\n if(this.viewer.viewport.flipped) {\n this._flip();\n }\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n this._offsetForRotation({\n degrees: tiledImage.getRotation(true),\n point: tiledImage.viewport.pixelFromPointNoRotate(\n tiledImage._getRotationPoint(true), true)\n });\n }\n\n context.strokeRect(\n tile.position.x * $.pixelDensityRatio,\n tile.position.y * $.pixelDensityRatio,\n tile.size.x * $.pixelDensityRatio,\n tile.size.y * $.pixelDensityRatio\n );\n\n var tileCenterX = (tile.position.x + (tile.size.x / 2)) * $.pixelDensityRatio;\n var tileCenterY = (tile.position.y + (tile.size.y / 2)) * $.pixelDensityRatio;\n\n // Rotate the text the right way around.\n context.translate( tileCenterX, tileCenterY );\n context.rotate( Math.PI / 180 * -this.viewport.degrees );\n context.translate( -tileCenterX, -tileCenterY );\n\n if( tile.x === 0 && tile.y === 0 ){\n context.fillText(\n \"Zoom: \" + this.viewport.getZoom(),\n tile.position.x * $.pixelDensityRatio,\n (tile.position.y - 30) * $.pixelDensityRatio\n );\n context.fillText(\n \"Pan: \" + this.viewport.getBounds().toString(),\n tile.position.x * $.pixelDensityRatio,\n (tile.position.y - 20) * $.pixelDensityRatio\n );\n }\n context.fillText(\n \"Level: \" + tile.level,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 20) * $.pixelDensityRatio\n );\n context.fillText(\n \"Column: \" + tile.x,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 30) * $.pixelDensityRatio\n );\n context.fillText(\n \"Row: \" + tile.y,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 40) * $.pixelDensityRatio\n );\n context.fillText(\n \"Order: \" + i + \" of \" + count,\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 50) * $.pixelDensityRatio\n );\n context.fillText(\n \"Size: \" + tile.size.toString(),\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 60) * $.pixelDensityRatio\n );\n context.fillText(\n \"Position: \" + tile.position.toString(),\n (tile.position.x + 10) * $.pixelDensityRatio,\n (tile.position.y + 70) * $.pixelDensityRatio\n );\n\n if ( this.viewport.degrees !== 0 ) {\n this._restoreRotationChanges();\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n this._restoreRotationChanges();\n }\n context.restore();\n },\n\n // private\n debugRect: function(rect) {\n if ( this.useCanvas ) {\n var context = this.context;\n context.save();\n context.lineWidth = 2 * $.pixelDensityRatio;\n context.strokeStyle = this.debugGridColor[0];\n context.fillStyle = this.debugGridColor[0];\n\n context.strokeRect(\n rect.x * $.pixelDensityRatio,\n rect.y * $.pixelDensityRatio,\n rect.width * $.pixelDensityRatio,\n rect.height * $.pixelDensityRatio\n );\n\n context.restore();\n }\n },\n\n /**\n * Get the canvas size\n * @param {Boolean} sketch If set to true return the size of the sketch canvas\n * @returns {OpenSeadragon.Point} The size of the canvas\n */\n getCanvasSize: function(sketch) {\n var canvas = this._getContext(sketch).canvas;\n return new $.Point(canvas.width, canvas.height);\n },\n\n getCanvasCenter: function() {\n return new $.Point(this.canvas.width / 2, this.canvas.height / 2);\n },\n\n // private\n _offsetForRotation: function(options) {\n var point = options.point ?\n options.point.times($.pixelDensityRatio) :\n this.getCanvasCenter();\n\n var context = this._getContext(options.useSketch);\n context.save();\n\n context.translate(point.x, point.y);\n if(this.viewer.viewport.flipped){\n context.rotate(Math.PI / 180 * -options.degrees);\n context.scale(-1, 1);\n } else{\n context.rotate(Math.PI / 180 * options.degrees);\n }\n context.translate(-point.x, -point.y);\n },\n\n // private\n _flip: function(options) {\n options = options || {};\n var point = options.point ?\n options.point.times($.pixelDensityRatio) :\n this.getCanvasCenter();\n var context = this._getContext(options.useSketch);\n\n context.translate(point.x, 0);\n context.scale(-1, 1);\n context.translate(-point.x, 0);\n },\n\n // private\n _restoreRotationChanges: function(useSketch) {\n var context = this._getContext(useSketch);\n context.restore();\n },\n\n // private\n _calculateCanvasSize: function() {\n var pixelDensityRatio = $.pixelDensityRatio;\n var viewportSize = this.viewport.getContainerSize();\n return {\n x: viewportSize.x * pixelDensityRatio,\n y: viewportSize.y * pixelDensityRatio\n };\n },\n\n // private\n _calculateSketchCanvasSize: function() {\n var canvasSize = this._calculateCanvasSize();\n if (this.viewport.getRotation() === 0) {\n return canvasSize;\n }\n // If the viewport is rotated, we need a larger sketch canvas in order\n // to support edge smoothing.\n var sketchCanvasSize = Math.ceil(Math.sqrt(\n canvasSize.x * canvasSize.x +\n canvasSize.y * canvasSize.y));\n return {\n x: sketchCanvasSize,\n y: sketchCanvasSize\n };\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - Viewport\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n\n/**\n * @class Viewport\n * @memberof OpenSeadragon\n * @classdesc Handles coordinate-related functionality (zoom, pan, rotation, etc.)\n * for an {@link OpenSeadragon.Viewer}.\n * @param {Object} options - Options for this Viewport.\n * @param {Object} [options.margins] - See viewportMargins in {@link OpenSeadragon.Options}.\n * @param {Number} [options.springStiffness] - See springStiffness in {@link OpenSeadragon.Options}.\n * @param {Number} [options.animationTime] - See animationTime in {@link OpenSeadragon.Options}.\n * @param {Number} [options.minZoomImageRatio] - See minZoomImageRatio in {@link OpenSeadragon.Options}.\n * @param {Number} [options.maxZoomPixelRatio] - See maxZoomPixelRatio in {@link OpenSeadragon.Options}.\n * @param {Number} [options.visibilityRatio] - See visibilityRatio in {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapHorizontal] - See wrapHorizontal in {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapVertical] - See wrapVertical in {@link OpenSeadragon.Options}.\n * @param {Number} [options.defaultZoomLevel] - See defaultZoomLevel in {@link OpenSeadragon.Options}.\n * @param {Number} [options.minZoomLevel] - See minZoomLevel in {@link OpenSeadragon.Options}.\n * @param {Number} [options.maxZoomLevel] - See maxZoomLevel in {@link OpenSeadragon.Options}.\n * @param {Number} [options.degrees] - See degrees in {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.homeFillsViewer] - See homeFillsViewer in {@link OpenSeadragon.Options}.\n */\n$.Viewport = function( options ) {\n\n //backward compatibility for positional args while prefering more\n //idiomatic javascript options object as the only argument\n var args = arguments;\n if (args.length && args[0] instanceof $.Point) {\n options = {\n containerSize: args[0],\n contentSize: args[1],\n config: args[2]\n };\n }\n\n //options.config and the general config argument are deprecated\n //in favor of the more direct specification of optional settings\n //being passed directly on the options object\n if ( options.config ){\n $.extend( true, options, options.config );\n delete options.config;\n }\n\n this._margins = $.extend({\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n }, options.margins || {});\n\n delete options.margins;\n\n $.extend( true, this, {\n\n //required settings\n containerSize: null,\n contentSize: null,\n\n //internal state properties\n zoomPoint: null,\n viewer: null,\n\n //configurable options\n springStiffness: $.DEFAULT_SETTINGS.springStiffness,\n animationTime: $.DEFAULT_SETTINGS.animationTime,\n minZoomImageRatio: $.DEFAULT_SETTINGS.minZoomImageRatio,\n maxZoomPixelRatio: $.DEFAULT_SETTINGS.maxZoomPixelRatio,\n visibilityRatio: $.DEFAULT_SETTINGS.visibilityRatio,\n wrapHorizontal: $.DEFAULT_SETTINGS.wrapHorizontal,\n wrapVertical: $.DEFAULT_SETTINGS.wrapVertical,\n defaultZoomLevel: $.DEFAULT_SETTINGS.defaultZoomLevel,\n minZoomLevel: $.DEFAULT_SETTINGS.minZoomLevel,\n maxZoomLevel: $.DEFAULT_SETTINGS.maxZoomLevel,\n degrees: $.DEFAULT_SETTINGS.degrees,\n flipped: $.DEFAULT_SETTINGS.flipped,\n homeFillsViewer: $.DEFAULT_SETTINGS.homeFillsViewer\n\n }, options );\n\n this._updateContainerInnerSize();\n\n this.centerSpringX = new $.Spring({\n initial: 0,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n this.centerSpringY = new $.Spring({\n initial: 0,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n this.zoomSpring = new $.Spring({\n exponential: true,\n initial: 1,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._oldCenterX = this.centerSpringX.current.value;\n this._oldCenterY = this.centerSpringY.current.value;\n this._oldZoom = this.zoomSpring.current.value;\n\n this._setContentBounds(new $.Rect(0, 0, 1, 1), 1);\n\n this.goHome(true);\n this.update();\n};\n\n/** @lends OpenSeadragon.Viewport.prototype */\n$.Viewport.prototype = {\n /**\n * Updates the viewport's home bounds and constraints for the given content size.\n * @function\n * @param {OpenSeadragon.Point} contentSize - size of the content in content units\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:reset-size\n */\n resetContentSize: function(contentSize) {\n $.console.assert(contentSize, \"[Viewport.resetContentSize] contentSize is required\");\n $.console.assert(contentSize instanceof $.Point, \"[Viewport.resetContentSize] contentSize must be an OpenSeadragon.Point\");\n $.console.assert(contentSize.x > 0, \"[Viewport.resetContentSize] contentSize.x must be greater than 0\");\n $.console.assert(contentSize.y > 0, \"[Viewport.resetContentSize] contentSize.y must be greater than 0\");\n\n this._setContentBounds(new $.Rect(0, 0, 1, contentSize.y / contentSize.x), contentSize.x);\n return this;\n },\n\n // deprecated\n setHomeBounds: function(bounds, contentFactor) {\n $.console.error(\"[Viewport.setHomeBounds] this function is deprecated; The content bounds should not be set manually.\");\n this._setContentBounds(bounds, contentFactor);\n },\n\n // Set the viewport's content bounds\n // @param {OpenSeadragon.Rect} bounds - the new bounds in viewport coordinates\n // without rotation\n // @param {Number} contentFactor - how many content units per viewport unit\n // @fires OpenSeadragon.Viewer.event:reset-size\n // @private\n _setContentBounds: function(bounds, contentFactor) {\n $.console.assert(bounds, \"[Viewport._setContentBounds] bounds is required\");\n $.console.assert(bounds instanceof $.Rect, \"[Viewport._setContentBounds] bounds must be an OpenSeadragon.Rect\");\n $.console.assert(bounds.width > 0, \"[Viewport._setContentBounds] bounds.width must be greater than 0\");\n $.console.assert(bounds.height > 0, \"[Viewport._setContentBounds] bounds.height must be greater than 0\");\n\n this._contentBoundsNoRotate = bounds.clone();\n this._contentSizeNoRotate = this._contentBoundsNoRotate.getSize().times(\n contentFactor);\n\n this._contentBounds = bounds.rotate(this.degrees).getBoundingBox();\n this._contentSize = this._contentBounds.getSize().times(contentFactor);\n this._contentAspectRatio = this._contentSize.x / this._contentSize.y;\n\n if (this.viewer) {\n /**\n * Raised when the viewer's content size or home bounds are reset\n * (see {@link OpenSeadragon.Viewport#resetContentSize}).\n *\n * @event reset-size\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.Point} contentSize\n * @property {OpenSeadragon.Rect} contentBounds - Content bounds.\n * @property {OpenSeadragon.Rect} homeBounds - Content bounds.\n * Deprecated use contentBounds instead.\n * @property {Number} contentFactor\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('reset-size', {\n contentSize: this._contentSizeNoRotate.clone(),\n contentFactor: contentFactor,\n homeBounds: this._contentBoundsNoRotate.clone(),\n contentBounds: this._contentBounds.clone()\n });\n }\n },\n\n /**\n * Returns the home zoom in \"viewport zoom\" value.\n * @function\n * @returns {Number} The home zoom in \"viewport zoom\".\n */\n getHomeZoom: function() {\n if (this.defaultZoomLevel) {\n return this.defaultZoomLevel;\n }\n\n var aspectFactor = this._contentAspectRatio / this.getAspectRatio();\n var output;\n if (this.homeFillsViewer) { // fill the viewer and clip the image\n output = aspectFactor >= 1 ? aspectFactor : 1;\n } else {\n output = aspectFactor >= 1 ? 1 : aspectFactor;\n }\n\n return output / this._contentBounds.width;\n },\n\n /**\n * Returns the home bounds in viewport coordinates.\n * @function\n * @returns {OpenSeadragon.Rect} The home bounds in vewport coordinates.\n */\n getHomeBounds: function() {\n return this.getHomeBoundsNoRotate().rotate(-this.getRotation());\n },\n\n /**\n * Returns the home bounds in viewport coordinates.\n * This method ignores the viewport rotation. Use\n * {@link OpenSeadragon.Viewport#getHomeBounds} to take it into account.\n * @function\n * @returns {OpenSeadragon.Rect} The home bounds in vewport coordinates.\n */\n getHomeBoundsNoRotate: function() {\n var center = this._contentBounds.getCenter();\n var width = 1.0 / this.getHomeZoom();\n var height = width / this.getAspectRatio();\n\n return new $.Rect(\n center.x - (width / 2.0),\n center.y - (height / 2.0),\n width,\n height\n );\n },\n\n /**\n * @function\n * @param {Boolean} immediately\n * @fires OpenSeadragon.Viewer.event:home\n */\n goHome: function(immediately) {\n if (this.viewer) {\n /**\n * Raised when the \"home\" operation occurs (see {@link OpenSeadragon.Viewport#goHome}).\n *\n * @event home\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Boolean} immediately\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('home', {\n immediately: immediately\n });\n }\n return this.fitBounds(this.getHomeBounds(), immediately);\n },\n\n /**\n * @function\n */\n getMinZoom: function() {\n var homeZoom = this.getHomeZoom(),\n zoom = this.minZoomLevel ?\n this.minZoomLevel :\n this.minZoomImageRatio * homeZoom;\n\n return zoom;\n },\n\n /**\n * @function\n */\n getMaxZoom: function() {\n var zoom = this.maxZoomLevel;\n if (!zoom) {\n zoom = this._contentSize.x * this.maxZoomPixelRatio / this._containerInnerSize.x;\n zoom /= this._contentBounds.width;\n }\n\n return Math.max( zoom, this.getHomeZoom() );\n },\n\n /**\n * @function\n */\n getAspectRatio: function() {\n return this._containerInnerSize.x / this._containerInnerSize.y;\n },\n\n /**\n * @function\n * @returns {OpenSeadragon.Point} The size of the container, in screen coordinates.\n */\n getContainerSize: function() {\n return new $.Point(\n this.containerSize.x,\n this.containerSize.y\n );\n },\n\n /**\n * The margins push the \"home\" region in from the sides by the specified amounts.\n * @function\n * @returns {Object} Properties (Numbers, in screen coordinates): left, top, right, bottom.\n */\n getMargins: function() {\n return $.extend({}, this._margins); // Make a copy so we are not returning our original\n },\n\n /**\n * The margins push the \"home\" region in from the sides by the specified amounts.\n * @function\n * @param {Object} margins - Properties (Numbers, in screen coordinates): left, top, right, bottom.\n */\n setMargins: function(margins) {\n $.console.assert($.type(margins) === 'object', '[Viewport.setMargins] margins must be an object');\n\n this._margins = $.extend({\n left: 0,\n top: 0,\n right: 0,\n bottom: 0\n }, margins);\n\n this._updateContainerInnerSize();\n if (this.viewer) {\n this.viewer.forceRedraw();\n }\n },\n\n /**\n * Returns the bounds of the visible area in viewport coordinates.\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to, in viewport coordinates.\n */\n getBounds: function(current) {\n return this.getBoundsNoRotate(current).rotate(-this.getRotation());\n },\n\n /**\n * Returns the bounds of the visible area in viewport coordinates.\n * This method ignores the viewport rotation. Use\n * {@link OpenSeadragon.Viewport#getBounds} to take it into account.\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to, in viewport coordinates.\n */\n getBoundsNoRotate: function(current) {\n var center = this.getCenter(current);\n var width = 1.0 / this.getZoom(current);\n var height = width / this.getAspectRatio();\n\n return new $.Rect(\n center.x - (width / 2.0),\n center.y - (height / 2.0),\n width,\n height\n );\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to,\n * including the space taken by margins, in viewport coordinates.\n */\n getBoundsWithMargins: function(current) {\n return this.getBoundsNoRotateWithMargins(current).rotate(\n -this.getRotation(), this.getCenter(current));\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @returns {OpenSeadragon.Rect} The location you are zoomed/panned to,\n * including the space taken by margins, in viewport coordinates.\n */\n getBoundsNoRotateWithMargins: function(current) {\n var bounds = this.getBoundsNoRotate(current);\n var factor = this._containerInnerSize.x * this.getZoom(current);\n bounds.x -= this._margins.left / factor;\n bounds.y -= this._margins.top / factor;\n bounds.width += (this._margins.left + this._margins.right) / factor;\n bounds.height += (this._margins.top + this._margins.bottom) / factor;\n return bounds;\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n */\n getCenter: function( current ) {\n var centerCurrent = new $.Point(\n this.centerSpringX.current.value,\n this.centerSpringY.current.value\n ),\n centerTarget = new $.Point(\n this.centerSpringX.target.value,\n this.centerSpringY.target.value\n ),\n oldZoomPixel,\n zoom,\n width,\n height,\n bounds,\n newZoomPixel,\n deltaZoomPixels,\n deltaZoomPoints;\n\n if ( current ) {\n return centerCurrent;\n } else if ( !this.zoomPoint ) {\n return centerTarget;\n }\n\n oldZoomPixel = this.pixelFromPoint(this.zoomPoint, true);\n\n zoom = this.getZoom();\n width = 1.0 / zoom;\n height = width / this.getAspectRatio();\n bounds = new $.Rect(\n centerCurrent.x - width / 2.0,\n centerCurrent.y - height / 2.0,\n width,\n height\n );\n\n newZoomPixel = this._pixelFromPoint(this.zoomPoint, bounds);\n deltaZoomPixels = newZoomPixel.minus( oldZoomPixel );\n deltaZoomPoints = deltaZoomPixels.divide( this._containerInnerSize.x * zoom );\n\n return centerTarget.plus( deltaZoomPoints );\n },\n\n /**\n * @function\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n */\n getZoom: function( current ) {\n if ( current ) {\n return this.zoomSpring.current.value;\n } else {\n return this.zoomSpring.target.value;\n }\n },\n\n // private\n _applyZoomConstraints: function(zoom) {\n return Math.max(\n Math.min(zoom, this.getMaxZoom()),\n this.getMinZoom());\n },\n\n /**\n * @function\n * @private\n * @param {OpenSeadragon.Rect} bounds\n * @return {OpenSeadragon.Rect} constrained bounds.\n */\n _applyBoundaryConstraints: function(bounds) {\n var newBounds = new $.Rect(\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height);\n\n if (this.wrapHorizontal) {\n //do nothing\n } else {\n var horizontalThreshold = this.visibilityRatio * newBounds.width;\n var boundsRight = newBounds.x + newBounds.width;\n var contentRight = this._contentBoundsNoRotate.x + this._contentBoundsNoRotate.width;\n var leftDx = this._contentBoundsNoRotate.x - boundsRight + horizontalThreshold;\n var rightDx = contentRight - newBounds.x - horizontalThreshold;\n\n if (horizontalThreshold > this._contentBoundsNoRotate.width) {\n newBounds.x += (leftDx + rightDx) / 2;\n } else if (rightDx < 0) {\n newBounds.x += rightDx;\n } else if (leftDx > 0) {\n newBounds.x += leftDx;\n }\n }\n\n if (this.wrapVertical) {\n //do nothing\n } else {\n var verticalThreshold = this.visibilityRatio * newBounds.height;\n var boundsBottom = newBounds.y + newBounds.height;\n var contentBottom = this._contentBoundsNoRotate.y + this._contentBoundsNoRotate.height;\n var topDy = this._contentBoundsNoRotate.y - boundsBottom + verticalThreshold;\n var bottomDy = contentBottom - newBounds.y - verticalThreshold;\n\n if (verticalThreshold > this._contentBoundsNoRotate.height) {\n newBounds.y += (topDy + bottomDy) / 2;\n } else if (bottomDy < 0) {\n newBounds.y += bottomDy;\n } else if (topDy > 0) {\n newBounds.y += topDy;\n }\n }\n\n return newBounds;\n },\n\n /**\n * @function\n * @private\n * @param {Boolean} [immediately=false] - whether the function that triggered this event was\n * called with the \"immediately\" flag\n */\n _raiseConstraintsEvent: function(immediately) {\n if (this.viewer) {\n /**\n * Raised when the viewport constraints are applied (see {@link OpenSeadragon.Viewport#applyConstraints}).\n *\n * @event constrain\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Boolean} immediately - whether the function that triggered this event was\n * called with the \"immediately\" flag\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'constrain', {\n immediately: immediately\n });\n }\n },\n\n /**\n * Enforces the minZoom, maxZoom and visibilityRatio constraints by\n * zooming and panning to the closest acceptable zoom and location.\n * @function\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:constrain\n */\n applyConstraints: function(immediately) {\n var actualZoom = this.getZoom();\n var constrainedZoom = this._applyZoomConstraints(actualZoom);\n\n if (actualZoom !== constrainedZoom) {\n this.zoomTo(constrainedZoom, this.zoomPoint, immediately);\n }\n\n var bounds = this.getBoundsNoRotate();\n var constrainedBounds = this._applyBoundaryConstraints(bounds);\n this._raiseConstraintsEvent(immediately);\n\n if (bounds.x !== constrainedBounds.x ||\n bounds.y !== constrainedBounds.y ||\n immediately) {\n this.fitBounds(\n constrainedBounds.rotate(-this.getRotation()),\n immediately);\n }\n return this;\n },\n\n /**\n * Equivalent to {@link OpenSeadragon.Viewport#applyConstraints}\n * @function\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:constrain\n */\n ensureVisible: function(immediately) {\n return this.applyConstraints(immediately);\n },\n\n /**\n * @function\n * @private\n * @param {OpenSeadragon.Rect} bounds\n * @param {Object} options (immediately=false, constraints=false)\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n _fitBounds: function(bounds, options) {\n options = options || {};\n var immediately = options.immediately || false;\n var constraints = options.constraints || false;\n\n var aspect = this.getAspectRatio();\n var center = bounds.getCenter();\n\n // Compute width and height of bounding box.\n var newBounds = new $.Rect(\n bounds.x,\n bounds.y,\n bounds.width,\n bounds.height,\n bounds.degrees + this.getRotation())\n .getBoundingBox();\n\n if (newBounds.getAspectRatio() >= aspect) {\n newBounds.height = newBounds.width / aspect;\n } else {\n newBounds.width = newBounds.height * aspect;\n }\n\n // Compute x and y from width, height and center position\n newBounds.x = center.x - newBounds.width / 2;\n newBounds.y = center.y - newBounds.height / 2;\n var newZoom = 1.0 / newBounds.width;\n\n if (constraints) {\n var newBoundsAspectRatio = newBounds.getAspectRatio();\n var newConstrainedZoom = this._applyZoomConstraints(newZoom);\n\n if (newZoom !== newConstrainedZoom) {\n newZoom = newConstrainedZoom;\n newBounds.width = 1.0 / newZoom;\n newBounds.x = center.x - newBounds.width / 2;\n newBounds.height = newBounds.width / newBoundsAspectRatio;\n newBounds.y = center.y - newBounds.height / 2;\n }\n\n newBounds = this._applyBoundaryConstraints(newBounds);\n center = newBounds.getCenter();\n this._raiseConstraintsEvent(immediately);\n }\n\n if (immediately) {\n this.panTo(center, true);\n return this.zoomTo(newZoom, null, true);\n }\n\n this.panTo(this.getCenter(true), true);\n this.zoomTo(this.getZoom(true), null, true);\n\n var oldBounds = this.getBounds();\n var oldZoom = this.getZoom();\n\n if (oldZoom === 0 || Math.abs(newZoom / oldZoom - 1) < 0.00000001) {\n this.zoomTo(newZoom, true);\n return this.panTo(center, immediately);\n }\n\n newBounds = newBounds.rotate(-this.getRotation());\n var referencePoint = newBounds.getTopLeft().times(newZoom)\n .minus(oldBounds.getTopLeft().times(oldZoom))\n .divide(newZoom - oldZoom);\n\n return this.zoomTo(newZoom, referencePoint, immediately);\n },\n\n /**\n * Makes the viewport zoom and pan so that the specified bounds take\n * as much space as possible in the viewport.\n * Note: this method ignores the constraints (minZoom, maxZoom and\n * visibilityRatio).\n * Use {@link OpenSeadragon.Viewport#fitBoundsWithConstraints} to enforce\n * them.\n * @function\n * @param {OpenSeadragon.Rect} bounds\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitBounds: function(bounds, immediately) {\n return this._fitBounds(bounds, {\n immediately: immediately,\n constraints: false\n });\n },\n\n /**\n * Makes the viewport zoom and pan so that the specified bounds take\n * as much space as possible in the viewport while enforcing the constraints\n * (minZoom, maxZoom and visibilityRatio).\n * Note: because this method enforces the constraints, part of the\n * provided bounds may end up outside of the viewport.\n * Use {@link OpenSeadragon.Viewport#fitBounds} to ignore them.\n * @function\n * @param {OpenSeadragon.Rect} bounds\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitBoundsWithConstraints: function(bounds, immediately) {\n return this._fitBounds(bounds, {\n immediately: immediately,\n constraints: true\n });\n },\n\n /**\n * Zooms so the image just fills the viewer vertically.\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitVertically: function(immediately) {\n var box = new $.Rect(\n this._contentBounds.x + (this._contentBounds.width / 2),\n this._contentBounds.y,\n 0,\n this._contentBounds.height);\n return this.fitBounds(box, immediately);\n },\n\n /**\n * Zooms so the image just fills the viewer horizontally.\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n fitHorizontally: function(immediately) {\n var box = new $.Rect(\n this._contentBounds.x,\n this._contentBounds.y + (this._contentBounds.height / 2),\n this._contentBounds.width,\n 0);\n return this.fitBounds(box, immediately);\n },\n\n\n /**\n * Returns bounds taking constraints into account\n * Added to improve constrained panning\n * @param {Boolean} current - Pass true for the current location; defaults to false (target location).\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n getConstrainedBounds: function(current) {\n var bounds,\n constrainedBounds;\n\n bounds = this.getBounds(current);\n\n constrainedBounds = this._applyBoundaryConstraints(bounds);\n\n return constrainedBounds;\n },\n\n /**\n * @function\n * @param {OpenSeadragon.Point} delta\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:pan\n */\n panBy: function( delta, immediately ) {\n var center = new $.Point(\n this.centerSpringX.target.value,\n this.centerSpringY.target.value\n );\n return this.panTo( center.plus( delta ), immediately );\n },\n\n /**\n * @function\n * @param {OpenSeadragon.Point} center\n * @param {Boolean} immediately\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:pan\n */\n panTo: function( center, immediately ) {\n if ( immediately ) {\n this.centerSpringX.resetTo( center.x );\n this.centerSpringY.resetTo( center.y );\n } else {\n this.centerSpringX.springTo( center.x );\n this.centerSpringY.springTo( center.y );\n }\n\n if( this.viewer ){\n /**\n * Raised when the viewport is panned (see {@link OpenSeadragon.Viewport#panBy} and {@link OpenSeadragon.Viewport#panTo}).\n *\n * @event pan\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.Point} center\n * @property {Boolean} immediately\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'pan', {\n center: center,\n immediately: immediately\n });\n }\n\n return this;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:zoom\n */\n zoomBy: function(factor, refPoint, immediately) {\n return this.zoomTo(\n this.zoomSpring.target.value * factor, refPoint, immediately);\n },\n\n /**\n * Zooms to the specified zoom level\n * @function\n * @param {Number} zoom The zoom level to zoom to.\n * @param {OpenSeadragon.Point} [refPoint] The point which will stay at\n * the same screen location. Defaults to the viewport center.\n * @param {Boolean} [immediately=false]\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:zoom\n */\n zoomTo: function(zoom, refPoint, immediately) {\n var _this = this;\n\n this.zoomPoint = refPoint instanceof $.Point &&\n !isNaN(refPoint.x) &&\n !isNaN(refPoint.y) ?\n refPoint :\n null;\n\n if (immediately) {\n this._adjustCenterSpringsForZoomPoint(function() {\n _this.zoomSpring.resetTo(zoom);\n });\n } else {\n this.zoomSpring.springTo(zoom);\n }\n\n if (this.viewer) {\n /**\n * Raised when the viewport zoom level changes (see {@link OpenSeadragon.Viewport#zoomBy} and {@link OpenSeadragon.Viewport#zoomTo}).\n *\n * @event zoom\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {Number} zoom\n * @property {OpenSeadragon.Point} refPoint\n * @property {Boolean} immediately\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('zoom', {\n zoom: zoom,\n refPoint: refPoint,\n immediately: immediately\n });\n }\n\n return this;\n },\n\n /**\n * Rotates this viewport to the angle specified.\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n setRotation: function(degrees) {\n if (!this.viewer || !this.viewer.drawer.canRotate()) {\n return this;\n }\n this.degrees = $.positiveModulo(degrees, 360);\n this._setContentBounds(\n this.viewer.world.getHomeBounds(),\n this.viewer.world.getContentFactor());\n this.viewer.forceRedraw();\n\n /**\n * Raised when rotation has been changed.\n *\n * @event rotate\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Number} degrees - The number of degrees the rotation was set to.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('rotate', {\"degrees\": degrees});\n return this;\n },\n\n /**\n * Gets the current rotation in degrees.\n * @function\n * @return {Number} The current rotation in degrees.\n */\n getRotation: function() {\n return this.degrees;\n },\n\n /**\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n * @fires OpenSeadragon.Viewer.event:resize\n */\n resize: function( newContainerSize, maintain ) {\n var oldBounds = this.getBoundsNoRotate(),\n newBounds = oldBounds,\n widthDeltaFactor;\n\n this.containerSize.x = newContainerSize.x;\n this.containerSize.y = newContainerSize.y;\n\n this._updateContainerInnerSize();\n\n if ( maintain ) {\n // TODO: widthDeltaFactor will always be 1; probably not what's intended\n widthDeltaFactor = newContainerSize.x / this.containerSize.x;\n newBounds.width = oldBounds.width * widthDeltaFactor;\n newBounds.height = newBounds.width / this.getAspectRatio();\n }\n\n if( this.viewer ){\n /**\n * Raised when the viewer is resized (see {@link OpenSeadragon.Viewport#resize}).\n *\n * @event resize\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised this event.\n * @property {OpenSeadragon.Point} newContainerSize\n * @property {Boolean} maintain\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent( 'resize', {\n newContainerSize: newContainerSize,\n maintain: maintain\n });\n }\n\n return this.fitBounds( newBounds, true );\n },\n\n // private\n _updateContainerInnerSize: function() {\n this._containerInnerSize = new $.Point(\n Math.max(1, this.containerSize.x - (this._margins.left + this._margins.right)),\n Math.max(1, this.containerSize.y - (this._margins.top + this._margins.bottom))\n );\n },\n\n /**\n * Update the zoom and center (X and Y) springs.\n * @function\n * @returns {Boolean} True if any change has been made, false otherwise.\n */\n update: function() {\n var _this = this;\n this._adjustCenterSpringsForZoomPoint(function() {\n _this.zoomSpring.update();\n });\n\n this.centerSpringX.update();\n this.centerSpringY.update();\n\n var changed = this.centerSpringX.current.value !== this._oldCenterX ||\n this.centerSpringY.current.value !== this._oldCenterY ||\n this.zoomSpring.current.value !== this._oldZoom;\n\n this._oldCenterX = this.centerSpringX.current.value;\n this._oldCenterY = this.centerSpringY.current.value;\n this._oldZoom = this.zoomSpring.current.value;\n\n return changed;\n },\n\n _adjustCenterSpringsForZoomPoint: function(zoomSpringHandler) {\n if (this.zoomPoint) {\n var oldZoomPixel = this.pixelFromPoint(this.zoomPoint, true);\n zoomSpringHandler();\n var newZoomPixel = this.pixelFromPoint(this.zoomPoint, true);\n\n var deltaZoomPixels = newZoomPixel.minus(oldZoomPixel);\n var deltaZoomPoints = this.deltaPointsFromPixels(\n deltaZoomPixels, true);\n\n this.centerSpringX.shiftBy(deltaZoomPoints.x);\n this.centerSpringY.shiftBy(deltaZoomPoints.y);\n\n if (this.zoomSpring.isAtTargetValue()) {\n this.zoomPoint = null;\n }\n } else {\n zoomSpringHandler();\n }\n },\n\n /**\n * Convert a delta (translation vector) from viewport coordinates to pixels\n * coordinates. This method does not take rotation into account.\n * Consider using deltaPixelsFromPoints if you need to account for rotation.\n * @param {OpenSeadragon.Point} deltaPoints - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPixelsFromPointsNoRotate: function(deltaPoints, current) {\n return deltaPoints.times(\n this._containerInnerSize.x * this.getZoom(current)\n );\n },\n\n /**\n * Convert a delta (translation vector) from viewport coordinates to pixels\n * coordinates.\n * @param {OpenSeadragon.Point} deltaPoints - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPixelsFromPoints: function(deltaPoints, current) {\n return this.deltaPixelsFromPointsNoRotate(\n deltaPoints.rotate(this.getRotation()),\n current);\n },\n\n /**\n * Convert a delta (translation vector) from pixels coordinates to viewport\n * coordinates. This method does not take rotation into account.\n * Consider using deltaPointsFromPixels if you need to account for rotation.\n * @param {OpenSeadragon.Point} deltaPixels - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPointsFromPixelsNoRotate: function(deltaPixels, current) {\n return deltaPixels.divide(\n this._containerInnerSize.x * this.getZoom(current)\n );\n },\n\n /**\n * Convert a delta (translation vector) from pixels coordinates to viewport\n * coordinates.\n * @param {OpenSeadragon.Point} deltaPixels - The translation vector to convert.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n deltaPointsFromPixels: function(deltaPixels, current) {\n return this.deltaPointsFromPixelsNoRotate(deltaPixels, current)\n .rotate(-this.getRotation());\n },\n\n /**\n * Convert viewport coordinates to pixels coordinates.\n * This method does not take rotation into account.\n * Consider using pixelFromPoint if you need to account for rotation.\n * @param {OpenSeadragon.Point} point the viewport coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pixelFromPointNoRotate: function(point, current) {\n return this._pixelFromPointNoRotate(\n point, this.getBoundsNoRotate(current));\n },\n\n /**\n * Convert viewport coordinates to pixel coordinates.\n * @param {OpenSeadragon.Point} point the viewport coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pixelFromPoint: function(point, current) {\n return this._pixelFromPoint(point, this.getBoundsNoRotate(current));\n },\n\n // private\n _pixelFromPointNoRotate: function(point, bounds) {\n return point.minus(\n bounds.getTopLeft()\n ).times(\n this._containerInnerSize.x / bounds.width\n ).plus(\n new $.Point(this._margins.left, this._margins.top)\n );\n },\n\n // private\n _pixelFromPoint: function(point, bounds) {\n return this._pixelFromPointNoRotate(\n point.rotate(this.getRotation(), this.getCenter(true)),\n bounds);\n },\n\n /**\n * Convert pixel coordinates to viewport coordinates.\n * This method does not take rotation into account.\n * Consider using pointFromPixel if you need to account for rotation.\n * @param {OpenSeadragon.Point} pixel Pixel coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pointFromPixelNoRotate: function(pixel, current) {\n var bounds = this.getBoundsNoRotate(current);\n return pixel.minus(\n new $.Point(this._margins.left, this._margins.top)\n ).divide(\n this._containerInnerSize.x / bounds.width\n ).plus(\n bounds.getTopLeft()\n );\n },\n\n /**\n * Convert pixel coordinates to viewport coordinates.\n * @param {OpenSeadragon.Point} pixel Pixel coordinates\n * @param {Boolean} [current=false] - Pass true for the current location;\n * defaults to false (target location).\n * @returns {OpenSeadragon.Point}\n */\n pointFromPixel: function(pixel, current) {\n return this.pointFromPixelNoRotate(pixel, current).rotate(\n -this.getRotation(),\n this.getCenter(true)\n );\n },\n\n // private\n _viewportToImageDelta: function( viewerX, viewerY ) {\n var scale = this._contentBoundsNoRotate.width;\n return new $.Point(\n viewerX * this._contentSizeNoRotate.x / scale,\n viewerY * this._contentSizeNoRotate.x / scale);\n },\n\n /**\n * Translates from OpenSeadragon viewer coordinate system to image coordinate system.\n * This method can be called either by passing X,Y coordinates or an\n * OpenSeadragon.Point\n * Note: not accurate with multi-image; use TiledImage.viewportToImageCoordinates instead.\n * @function\n * @param {(OpenSeadragon.Point|Number)} viewerX either a point or the X\n * coordinate in viewport coordinate system.\n * @param {Number} [viewerY] Y coordinate in viewport coordinate system.\n * @return {OpenSeadragon.Point} a point representing the coordinates in the image.\n */\n viewportToImageCoordinates: function(viewerX, viewerY) {\n if (viewerX instanceof $.Point) {\n //they passed a point instead of individual components\n return this.viewportToImageCoordinates(viewerX.x, viewerX.y);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.viewportToImageCoordinates] is not accurate ' +\n 'with multi-image; use TiledImage.viewportToImageCoordinates instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageCoordinates\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.viewportToImageCoordinates(viewerX, viewerY, true);\n }\n }\n\n return this._viewportToImageDelta(\n viewerX - this._contentBoundsNoRotate.x,\n viewerY - this._contentBoundsNoRotate.y);\n },\n\n // private\n _imageToViewportDelta: function( imageX, imageY ) {\n var scale = this._contentBoundsNoRotate.width;\n return new $.Point(\n imageX / this._contentSizeNoRotate.x * scale,\n imageY / this._contentSizeNoRotate.x * scale);\n },\n\n /**\n * Translates from image coordinate system to OpenSeadragon viewer coordinate system\n * This method can be called either by passing X,Y coordinates or an\n * OpenSeadragon.Point\n * Note: not accurate with multi-image; use TiledImage.imageToViewportCoordinates instead.\n * @function\n * @param {(OpenSeadragon.Point | Number)} imageX the point or the\n * X coordinate in image coordinate system.\n * @param {Number} [imageY] Y coordinate in image coordinate system.\n * @return {OpenSeadragon.Point} a point representing the coordinates in the viewport.\n */\n imageToViewportCoordinates: function(imageX, imageY) {\n if (imageX instanceof $.Point) {\n //they passed a point instead of individual components\n return this.imageToViewportCoordinates(imageX.x, imageX.y);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.imageToViewportCoordinates] is not accurate ' +\n 'with multi-image; use TiledImage.imageToViewportCoordinates instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageCoordinates\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.imageToViewportCoordinates(imageX, imageY, true);\n }\n }\n\n var point = this._imageToViewportDelta(imageX, imageY);\n point.x += this._contentBoundsNoRotate.x;\n point.y += this._contentBoundsNoRotate.y;\n return point;\n },\n\n /**\n * Translates from a rectangle which describes a portion of the image in\n * pixel coordinates to OpenSeadragon viewport rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an\n * OpenSeadragon.Rect\n * Note: not accurate with multi-image; use TiledImage.imageToViewportRectangle instead.\n * @function\n * @param {(OpenSeadragon.Rect | Number)} imageX the rectangle or the X\n * coordinate of the top left corner of the rectangle in image coordinate system.\n * @param {Number} [imageY] the Y coordinate of the top left corner of the rectangle\n * in image coordinate system.\n * @param {Number} [pixelWidth] the width in pixel of the rectangle.\n * @param {Number} [pixelHeight] the height in pixel of the rectangle.\n * @returns {OpenSeadragon.Rect} This image's bounds in viewport coordinates\n */\n imageToViewportRectangle: function(imageX, imageY, pixelWidth, pixelHeight) {\n var rect = imageX;\n if (!(rect instanceof $.Rect)) {\n //they passed individual components instead of a rectangle\n rect = new $.Rect(imageX, imageY, pixelWidth, pixelHeight);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.imageToViewportRectangle] is not accurate ' +\n 'with multi-image; use TiledImage.imageToViewportRectangle instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.imageToViewportRectangle\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.imageToViewportRectangle(\n imageX, imageY, pixelWidth, pixelHeight, true);\n }\n }\n\n var coordA = this.imageToViewportCoordinates(rect.x, rect.y);\n var coordB = this._imageToViewportDelta(rect.width, rect.height);\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees\n );\n },\n\n /**\n * Translates from a rectangle which describes a portion of\n * the viewport in point coordinates to image rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an\n * OpenSeadragon.Rect\n * Note: not accurate with multi-image; use TiledImage.viewportToImageRectangle instead.\n * @function\n * @param {(OpenSeadragon.Rect | Number)} viewerX either a rectangle or\n * the X coordinate of the top left corner of the rectangle in viewport\n * coordinate system.\n * @param {Number} [viewerY] the Y coordinate of the top left corner of the rectangle\n * in viewport coordinate system.\n * @param {Number} [pointWidth] the width of the rectangle in viewport coordinate system.\n * @param {Number} [pointHeight] the height of the rectangle in viewport coordinate system.\n */\n viewportToImageRectangle: function(viewerX, viewerY, pointWidth, pointHeight) {\n var rect = viewerX;\n if (!(rect instanceof $.Rect)) {\n //they passed individual components instead of a rectangle\n rect = new $.Rect(viewerX, viewerY, pointWidth, pointHeight);\n }\n\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.viewportToImageRectangle] is not accurate ' +\n 'with multi-image; use TiledImage.viewportToImageRectangle instead.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageCoordinates\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.viewportToImageRectangle(\n viewerX, viewerY, pointWidth, pointHeight, true);\n }\n }\n\n var coordA = this.viewportToImageCoordinates(rect.x, rect.y);\n var coordB = this._viewportToImageDelta(rect.width, rect.height);\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees\n );\n },\n\n /**\n * Convert pixel coordinates relative to the viewer element to image\n * coordinates.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n viewerElementToImageCoordinates: function( pixel ) {\n var point = this.pointFromPixel( pixel, true );\n return this.viewportToImageCoordinates( point );\n },\n\n /**\n * Convert pixel coordinates relative to the image to\n * viewer element coordinates.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToViewerElementCoordinates: function( pixel ) {\n var point = this.imageToViewportCoordinates( pixel );\n return this.pixelFromPoint( point, true );\n },\n\n /**\n * Convert pixel coordinates relative to the window to image coordinates.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n windowToImageCoordinates: function(pixel) {\n $.console.assert(this.viewer,\n \"[Viewport.windowToImageCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = pixel.minus(\n $.getElementPosition(this.viewer.element));\n return this.viewerElementToImageCoordinates(viewerCoordinates);\n },\n\n /**\n * Convert image coordinates to pixel coordinates relative to the window.\n * Note: not accurate with multi-image.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToWindowCoordinates: function(pixel) {\n $.console.assert(this.viewer,\n \"[Viewport.imageToWindowCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = this.imageToViewerElementCoordinates(pixel);\n return viewerCoordinates.plus(\n $.getElementPosition(this.viewer.element));\n },\n\n /**\n * Convert pixel coordinates relative to the viewer element to viewport\n * coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n viewerElementToViewportCoordinates: function( pixel ) {\n return this.pointFromPixel( pixel, true );\n },\n\n /**\n * Convert viewport coordinates to pixel coordinates relative to the\n * viewer element.\n * @param {OpenSeadragon.Point} point\n * @returns {OpenSeadragon.Point}\n */\n viewportToViewerElementCoordinates: function( point ) {\n return this.pixelFromPoint( point, true );\n },\n\n /**\n * Convert a rectangle in pixel coordinates relative to the viewer element\n * to viewport coordinates.\n * @param {OpenSeadragon.Rect} rectangle the rectangle to convert\n * @returns {OpenSeadragon.Rect} the converted rectangle\n */\n viewerElementToViewportRectangle: function(rectangle) {\n return $.Rect.fromSummits(\n this.pointFromPixel(rectangle.getTopLeft(), true),\n this.pointFromPixel(rectangle.getTopRight(), true),\n this.pointFromPixel(rectangle.getBottomLeft(), true)\n );\n },\n\n /**\n * Convert a rectangle in viewport coordinates to pixel coordinates relative\n * to the viewer element.\n * @param {OpenSeadragon.Rect} rectangle the rectangle to convert\n * @returns {OpenSeadragon.Rect} the converted rectangle\n */\n viewportToViewerElementRectangle: function(rectangle) {\n return $.Rect.fromSummits(\n this.pixelFromPoint(rectangle.getTopLeft(), true),\n this.pixelFromPoint(rectangle.getTopRight(), true),\n this.pixelFromPoint(rectangle.getBottomLeft(), true)\n );\n },\n\n /**\n * Convert pixel coordinates relative to the window to viewport coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n windowToViewportCoordinates: function(pixel) {\n $.console.assert(this.viewer,\n \"[Viewport.windowToViewportCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = pixel.minus(\n $.getElementPosition(this.viewer.element));\n return this.viewerElementToViewportCoordinates(viewerCoordinates);\n },\n\n /**\n * Convert viewport coordinates to pixel coordinates relative to the window.\n * @param {OpenSeadragon.Point} point\n * @returns {OpenSeadragon.Point}\n */\n viewportToWindowCoordinates: function(point) {\n $.console.assert(this.viewer,\n \"[Viewport.viewportToWindowCoordinates] the viewport must have a viewer.\");\n var viewerCoordinates = this.viewportToViewerElementCoordinates(point);\n return viewerCoordinates.plus(\n $.getElementPosition(this.viewer.element));\n },\n\n /**\n * Convert a viewport zoom to an image zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * Note: not accurate with multi-image.\n * @function\n * @param {Number} viewportZoom The viewport zoom\n * target zoom.\n * @returns {Number} imageZoom The image zoom\n */\n viewportToImageZoom: function(viewportZoom) {\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.viewportToImageZoom] is not ' +\n 'accurate with multi-image.');\n } else if (count === 1) {\n // It is better to use TiledImage.viewportToImageZoom\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.viewportToImageZoom(viewportZoom);\n }\n }\n\n var imageWidth = this._contentSizeNoRotate.x;\n var containerWidth = this._containerInnerSize.x;\n var scale = this._contentBoundsNoRotate.width;\n var viewportToImageZoomRatio = (containerWidth / imageWidth) * scale;\n return viewportZoom * viewportToImageZoomRatio;\n },\n\n /**\n * Convert an image zoom to a viewport zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * Note: not accurate with multi-image.\n * @function\n * @param {Number} imageZoom The image zoom\n * target zoom.\n * @returns {Number} viewportZoom The viewport zoom\n */\n imageToViewportZoom: function(imageZoom) {\n if (this.viewer) {\n var count = this.viewer.world.getItemCount();\n if (count > 1) {\n $.console.error('[Viewport.imageToViewportZoom] is not accurate ' +\n 'with multi-image.');\n } else if (count === 1) {\n // It is better to use TiledImage.imageToViewportZoom\n // because this._contentBoundsNoRotate can not be relied on\n // with clipping.\n var item = this.viewer.world.getItemAt(0);\n return item.imageToViewportZoom(imageZoom);\n }\n }\n\n var imageWidth = this._contentSizeNoRotate.x;\n var containerWidth = this._containerInnerSize.x;\n var scale = this._contentBoundsNoRotate.width;\n var viewportToImageZoomRatio = (imageWidth / containerWidth) / scale;\n return imageZoom * viewportToImageZoomRatio;\n },\n\n /**\n * Toggles flip state and demands a new drawing on navigator and viewer objects.\n * @function\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n toggleFlip: function() {\n this.setFlip(!this.getFlip());\n return this;\n },\n\n /**\n * Gets flip state stored on viewport.\n * @function\n * @return {Boolean} Flip state.\n */\n getFlip: function() {\n return this.flipped;\n },\n\n /**\n * Sets flip state according to the state input argument.\n * @function\n * @param {Boolean} state - Flip state to set.\n * @return {OpenSeadragon.Viewport} Chainable.\n */\n setFlip: function( state ) {\n if ( this.flipped === state ) {\n return this;\n }\n\n this.flipped = state;\n if(this.viewer.navigator){\n this.viewer.navigator.setFlip(this.getFlip());\n }\n this.viewer.forceRedraw();\n\n /**\n * Raised when flip state has been changed.\n *\n * @event flip\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {Number} flipped - The flip state after this change.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.viewer.raiseEvent('flip', {\"flipped\": state});\n return this;\n }\n\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TiledImage\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * You shouldn't have to create a TiledImage instance directly; get it asynchronously by\n * using {@link OpenSeadragon.Viewer#open} or {@link OpenSeadragon.Viewer#addTiledImage} instead.\n * @class TiledImage\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @classdesc Handles rendering of tiles for an {@link OpenSeadragon.Viewer}.\n * A new instance is created for each TileSource opened.\n * @param {Object} options - Configuration for this TiledImage.\n * @param {OpenSeadragon.TileSource} options.source - The TileSource that defines this TiledImage.\n * @param {OpenSeadragon.Viewer} options.viewer - The Viewer that owns this TiledImage.\n * @param {OpenSeadragon.TileCache} options.tileCache - The TileCache for this TiledImage to use.\n * @param {OpenSeadragon.Drawer} options.drawer - The Drawer for this TiledImage to draw onto.\n * @param {OpenSeadragon.ImageLoader} options.imageLoader - The ImageLoader for this TiledImage to use.\n * @param {Number} [options.x=0] - Left position, in viewport coordinates.\n * @param {Number} [options.y=0] - Top position, in viewport coordinates.\n * @param {Number} [options.width=1] - Width, in viewport coordinates.\n * @param {Number} [options.height] - Height, in viewport coordinates.\n * @param {OpenSeadragon.Rect} [options.fitBounds] The bounds in viewport coordinates\n * to fit the image into. If specified, x, y, width and height get ignored.\n * @param {OpenSeadragon.Placement} [options.fitBoundsPlacement=OpenSeadragon.Placement.CENTER]\n * How to anchor the image in the bounds if options.fitBounds is set.\n * @param {OpenSeadragon.Rect} [options.clip] - An area, in image pixels, to clip to\n * (portions of the image outside of this area will not be visible). Only works on\n * browsers that support the HTML5 canvas.\n * @param {Number} [options.springStiffness] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.animationTime] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.minZoomImageRatio] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapHorizontal] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.wrapVertical] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.immediateRender] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.blendTime] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.alwaysBlend] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.minPixelRatio] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.smoothTileEdgesMinZoom] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.iOSDevice] - See {@link OpenSeadragon.Options}.\n * @param {Number} [options.opacity=1] - Set to draw at proportional opacity. If zero, images will not draw.\n * @param {Boolean} [options.preload=false] - Set true to load even when the image is hidden by zero opacity.\n * @param {String} [options.compositeOperation] - How the image is composited onto other images; see compositeOperation in {@link OpenSeadragon.Options} for possible values.\n * @param {Boolean} [options.debugMode] - See {@link OpenSeadragon.Options}.\n * @param {String|CanvasGradient|CanvasPattern|Function} [options.placeholderFillStyle] - See {@link OpenSeadragon.Options}.\n * @param {String|Boolean} [options.crossOriginPolicy] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.ajaxWithCredentials] - See {@link OpenSeadragon.Options}.\n * @param {Boolean} [options.loadTilesWithAjax]\n * Whether to load tile data using AJAX requests.\n * Defaults to the setting in {@link OpenSeadragon.Options}.\n * @param {Object} [options.ajaxHeaders={}]\n * A set of headers to include when making tile AJAX requests.\n */\n$.TiledImage = function( options ) {\n var _this = this;\n\n $.console.assert( options.tileCache, \"[TiledImage] options.tileCache is required\" );\n $.console.assert( options.drawer, \"[TiledImage] options.drawer is required\" );\n $.console.assert( options.viewer, \"[TiledImage] options.viewer is required\" );\n $.console.assert( options.imageLoader, \"[TiledImage] options.imageLoader is required\" );\n $.console.assert( options.source, \"[TiledImage] options.source is required\" );\n $.console.assert(!options.clip || options.clip instanceof $.Rect,\n \"[TiledImage] options.clip must be an OpenSeadragon.Rect if present\");\n\n $.EventSource.call( this );\n\n this._tileCache = options.tileCache;\n delete options.tileCache;\n\n this._drawer = options.drawer;\n delete options.drawer;\n\n this._imageLoader = options.imageLoader;\n delete options.imageLoader;\n\n if (options.clip instanceof $.Rect) {\n this._clip = options.clip.clone();\n }\n\n delete options.clip;\n\n var x = options.x || 0;\n delete options.x;\n var y = options.y || 0;\n delete options.y;\n\n // Ratio of zoomable image height to width.\n this.normHeight = options.source.dimensions.y / options.source.dimensions.x;\n this.contentAspectX = options.source.dimensions.x / options.source.dimensions.y;\n\n var scale = 1;\n if ( options.width ) {\n scale = options.width;\n delete options.width;\n\n if ( options.height ) {\n $.console.error( \"specifying both width and height to a tiledImage is not supported\" );\n delete options.height;\n }\n } else if ( options.height ) {\n scale = options.height / this.normHeight;\n delete options.height;\n }\n\n var fitBounds = options.fitBounds;\n delete options.fitBounds;\n var fitBoundsPlacement = options.fitBoundsPlacement || OpenSeadragon.Placement.CENTER;\n delete options.fitBoundsPlacement;\n\n var degrees = options.degrees || 0;\n delete options.degrees;\n\n $.extend( true, this, {\n\n //internal state properties\n viewer: null,\n tilesMatrix: {}, // A '3d' dictionary [level][x][y] --> Tile.\n coverage: {}, // A '3d' dictionary [level][x][y] --> Boolean; shows what areas have been drawn.\n loadingCoverage: {}, // A '3d' dictionary [level][x][y] --> Boolean; shows what areas are loaded or are being loaded/blended.\n lastDrawn: [], // An unordered list of Tiles drawn last frame.\n lastResetTime: 0, // Last time for which the tiledImage was reset.\n _midDraw: false, // Is the tiledImage currently updating the viewport?\n _needsDraw: true, // Does the tiledImage need to update the viewport again?\n _hasOpaqueTile: false, // Do we have even one fully opaque tile?\n _tilesLoading: 0, // The number of pending tile requests.\n //configurable settings\n springStiffness: $.DEFAULT_SETTINGS.springStiffness,\n animationTime: $.DEFAULT_SETTINGS.animationTime,\n minZoomImageRatio: $.DEFAULT_SETTINGS.minZoomImageRatio,\n wrapHorizontal: $.DEFAULT_SETTINGS.wrapHorizontal,\n wrapVertical: $.DEFAULT_SETTINGS.wrapVertical,\n immediateRender: $.DEFAULT_SETTINGS.immediateRender,\n blendTime: $.DEFAULT_SETTINGS.blendTime,\n alwaysBlend: $.DEFAULT_SETTINGS.alwaysBlend,\n minPixelRatio: $.DEFAULT_SETTINGS.minPixelRatio,\n smoothTileEdgesMinZoom: $.DEFAULT_SETTINGS.smoothTileEdgesMinZoom,\n iOSDevice: $.DEFAULT_SETTINGS.iOSDevice,\n debugMode: $.DEFAULT_SETTINGS.debugMode,\n crossOriginPolicy: $.DEFAULT_SETTINGS.crossOriginPolicy,\n ajaxWithCredentials: $.DEFAULT_SETTINGS.ajaxWithCredentials,\n placeholderFillStyle: $.DEFAULT_SETTINGS.placeholderFillStyle,\n opacity: $.DEFAULT_SETTINGS.opacity,\n preload: $.DEFAULT_SETTINGS.preload,\n compositeOperation: $.DEFAULT_SETTINGS.compositeOperation\n }, options );\n\n this._preload = this.preload;\n delete this.preload;\n\n this._fullyLoaded = false;\n\n this._xSpring = new $.Spring({\n initial: x,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._ySpring = new $.Spring({\n initial: y,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._scaleSpring = new $.Spring({\n initial: scale,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._degreesSpring = new $.Spring({\n initial: degrees,\n springStiffness: this.springStiffness,\n animationTime: this.animationTime\n });\n\n this._updateForScale();\n\n if (fitBounds) {\n this.fitBounds(fitBounds, fitBoundsPlacement, true);\n }\n\n // We need a callback to give image manipulation a chance to happen\n this._drawingHandler = function(args) {\n /**\n * This event is fired just before the tile is drawn giving the application a chance to alter the image.\n *\n * NOTE: This event is only fired when the drawer is using a <canvas>.\n *\n * @event tile-drawing\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.Tile} tile - The Tile being drawn.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {OpenSeadragon.Tile} context - The HTML canvas context being drawn into.\n * @property {OpenSeadragon.Tile} rendered - The HTML canvas context containing the tile imagery.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n _this.viewer.raiseEvent('tile-drawing', $.extend({\n tiledImage: _this\n }, args));\n };\n};\n\n$.extend($.TiledImage.prototype, $.EventSource.prototype, /** @lends OpenSeadragon.TiledImage.prototype */{\n /**\n * @returns {Boolean} Whether the TiledImage needs to be drawn.\n */\n needsDraw: function() {\n return this._needsDraw;\n },\n\n /**\n * @returns {Boolean} Whether all tiles necessary for this TiledImage to draw at the current view have been loaded.\n */\n getFullyLoaded: function() {\n return this._fullyLoaded;\n },\n\n // private\n _setFullyLoaded: function(flag) {\n if (flag === this._fullyLoaded) {\n return;\n }\n\n this._fullyLoaded = flag;\n\n /**\n * Fired when the TiledImage's \"fully loaded\" flag (whether all tiles necessary for this TiledImage\n * to draw at the current view have been loaded) changes.\n *\n * @event fully-loaded-change\n * @memberof OpenSeadragon.TiledImage\n * @type {object}\n * @property {Boolean} fullyLoaded - The new \"fully loaded\" value.\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('fully-loaded-change', {\n fullyLoaded: this._fullyLoaded\n });\n },\n\n /**\n * Clears all tiles and triggers an update on the next call to\n * {@link OpenSeadragon.TiledImage#update}.\n */\n reset: function() {\n this._tileCache.clearTilesFor(this);\n this.lastResetTime = $.now();\n this._needsDraw = true;\n },\n\n /**\n * Updates the TiledImage's bounds, animating if needed.\n * @returns {Boolean} Whether the TiledImage animated.\n */\n update: function() {\n var xUpdated = this._xSpring.update();\n var yUpdated = this._ySpring.update();\n var scaleUpdated = this._scaleSpring.update();\n var degreesUpdated = this._degreesSpring.update();\n\n if (xUpdated || yUpdated || scaleUpdated || degreesUpdated) {\n this._updateForScale();\n this._needsDraw = true;\n return true;\n }\n\n return false;\n },\n\n /**\n * Draws the TiledImage to its Drawer.\n */\n draw: function() {\n if (this.opacity !== 0 || this._preload) {\n this._midDraw = true;\n this._updateViewport();\n this._midDraw = false;\n }\n // Images with opacity 0 should not need to be drawn in future. this._needsDraw = false is set in this._updateViewport() for other images.\n else {\n this._needsDraw = false;\n }\n },\n\n /**\n * Destroy the TiledImage (unload current loaded tiles).\n */\n destroy: function() {\n this.reset();\n },\n\n /**\n * Get this TiledImage's bounds in viewport coordinates.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * false for target location.\n * @returns {OpenSeadragon.Rect} This TiledImage's bounds in viewport coordinates.\n */\n getBounds: function(current) {\n return this.getBoundsNoRotate(current)\n .rotate(this.getRotation(current), this._getRotationPoint(current));\n },\n\n /**\n * Get this TiledImage's bounds in viewport coordinates without taking\n * rotation into account.\n * @param {Boolean} [current=false] - Pass true for the current location;\n * false for target location.\n * @returns {OpenSeadragon.Rect} This TiledImage's bounds in viewport coordinates.\n */\n getBoundsNoRotate: function(current) {\n return current ?\n new $.Rect(\n this._xSpring.current.value,\n this._ySpring.current.value,\n this._worldWidthCurrent,\n this._worldHeightCurrent) :\n new $.Rect(\n this._xSpring.target.value,\n this._ySpring.target.value,\n this._worldWidthTarget,\n this._worldHeightTarget);\n },\n\n // deprecated\n getWorldBounds: function() {\n $.console.error('[TiledImage.getWorldBounds] is deprecated; use TiledImage.getBounds instead');\n return this.getBounds();\n },\n\n /**\n * Get the bounds of the displayed part of the tiled image.\n * @param {Boolean} [current=false] Pass true for the current location,\n * false for the target location.\n * @returns {$.Rect} The clipped bounds in viewport coordinates.\n */\n getClippedBounds: function(current) {\n var bounds = this.getBoundsNoRotate(current);\n if (this._clip) {\n var worldWidth = current ?\n this._worldWidthCurrent : this._worldWidthTarget;\n var ratio = worldWidth / this.source.dimensions.x;\n var clip = this._clip.times(ratio);\n bounds = new $.Rect(\n bounds.x + clip.x,\n bounds.y + clip.y,\n clip.width,\n clip.height);\n }\n return bounds.rotate(this.getRotation(current), this._getRotationPoint(current));\n },\n\n /**\n * @returns {OpenSeadragon.Point} This TiledImage's content size, in original pixels.\n */\n getContentSize: function() {\n return new $.Point(this.source.dimensions.x, this.source.dimensions.y);\n },\n\n // private\n _viewportToImageDelta: function( viewerX, viewerY, current ) {\n var scale = (current ? this._scaleSpring.current.value : this._scaleSpring.target.value);\n return new $.Point(viewerX * (this.source.dimensions.x / scale),\n viewerY * ((this.source.dimensions.y * this.contentAspectX) / scale));\n },\n\n /**\n * Translates from OpenSeadragon viewer coordinate system to image coordinate system.\n * This method can be called either by passing X,Y coordinates or an {@link OpenSeadragon.Point}.\n * @param {Number|OpenSeadragon.Point} viewerX - The X coordinate or point in viewport coordinate system.\n * @param {Number} [viewerY] - The Y coordinate in viewport coordinate system.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Point} A point representing the coordinates in the image.\n */\n viewportToImageCoordinates: function(viewerX, viewerY, current) {\n var point;\n if (viewerX instanceof $.Point) {\n //they passed a point instead of individual components\n current = viewerY;\n point = viewerX;\n } else {\n point = new $.Point(viewerX, viewerY);\n }\n\n point = point.rotate(-this.getRotation(current), this._getRotationPoint(current));\n return current ?\n this._viewportToImageDelta(\n point.x - this._xSpring.current.value,\n point.y - this._ySpring.current.value) :\n this._viewportToImageDelta(\n point.x - this._xSpring.target.value,\n point.y - this._ySpring.target.value);\n },\n\n // private\n _imageToViewportDelta: function( imageX, imageY, current ) {\n var scale = (current ? this._scaleSpring.current.value : this._scaleSpring.target.value);\n return new $.Point((imageX / this.source.dimensions.x) * scale,\n (imageY / this.source.dimensions.y / this.contentAspectX) * scale);\n },\n\n /**\n * Translates from image coordinate system to OpenSeadragon viewer coordinate system\n * This method can be called either by passing X,Y coordinates or an {@link OpenSeadragon.Point}.\n * @param {Number|OpenSeadragon.Point} imageX - The X coordinate or point in image coordinate system.\n * @param {Number} [imageY] - The Y coordinate in image coordinate system.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Point} A point representing the coordinates in the viewport.\n */\n imageToViewportCoordinates: function(imageX, imageY, current) {\n if (imageX instanceof $.Point) {\n //they passed a point instead of individual components\n current = imageY;\n imageY = imageX.y;\n imageX = imageX.x;\n }\n\n var point = this._imageToViewportDelta(imageX, imageY);\n if (current) {\n point.x += this._xSpring.current.value;\n point.y += this._ySpring.current.value;\n } else {\n point.x += this._xSpring.target.value;\n point.y += this._ySpring.target.value;\n }\n\n return point.rotate(this.getRotation(current), this._getRotationPoint(current));\n },\n\n /**\n * Translates from a rectangle which describes a portion of the image in\n * pixel coordinates to OpenSeadragon viewport rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an {@link OpenSeadragon.Rect}.\n * @param {Number|OpenSeadragon.Rect} imageX - The left coordinate or rectangle in image coordinate system.\n * @param {Number} [imageY] - The top coordinate in image coordinate system.\n * @param {Number} [pixelWidth] - The width in pixel of the rectangle.\n * @param {Number} [pixelHeight] - The height in pixel of the rectangle.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Rect} A rect representing the coordinates in the viewport.\n */\n imageToViewportRectangle: function(imageX, imageY, pixelWidth, pixelHeight, current) {\n var rect = imageX;\n if (rect instanceof $.Rect) {\n //they passed a rect instead of individual components\n current = imageY;\n } else {\n rect = new $.Rect(imageX, imageY, pixelWidth, pixelHeight);\n }\n\n var coordA = this.imageToViewportCoordinates(rect.getTopLeft(), current);\n var coordB = this._imageToViewportDelta(rect.width, rect.height, current);\n\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees + this.getRotation(current)\n );\n },\n\n /**\n * Translates from a rectangle which describes a portion of\n * the viewport in point coordinates to image rectangle coordinates.\n * This method can be called either by passing X,Y,width,height or an {@link OpenSeadragon.Rect}.\n * @param {Number|OpenSeadragon.Rect} viewerX - The left coordinate or rectangle in viewport coordinate system.\n * @param {Number} [viewerY] - The top coordinate in viewport coordinate system.\n * @param {Number} [pointWidth] - The width in viewport coordinate system.\n * @param {Number} [pointHeight] - The height in viewport coordinate system.\n * @param {Boolean} [current=false] - Pass true to use the current location; false for target location.\n * @return {OpenSeadragon.Rect} A rect representing the coordinates in the image.\n */\n viewportToImageRectangle: function( viewerX, viewerY, pointWidth, pointHeight, current ) {\n var rect = viewerX;\n if (viewerX instanceof $.Rect) {\n //they passed a rect instead of individual components\n current = viewerY;\n } else {\n rect = new $.Rect(viewerX, viewerY, pointWidth, pointHeight);\n }\n\n var coordA = this.viewportToImageCoordinates(rect.getTopLeft(), current);\n var coordB = this._viewportToImageDelta(rect.width, rect.height, current);\n\n return new $.Rect(\n coordA.x,\n coordA.y,\n coordB.x,\n coordB.y,\n rect.degrees - this.getRotation(current)\n );\n },\n\n /**\n * Convert pixel coordinates relative to the viewer element to image\n * coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n viewerElementToImageCoordinates: function( pixel ) {\n var point = this.viewport.pointFromPixel( pixel, true );\n return this.viewportToImageCoordinates( point );\n },\n\n /**\n * Convert pixel coordinates relative to the image to\n * viewer element coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToViewerElementCoordinates: function( pixel ) {\n var point = this.imageToViewportCoordinates( pixel );\n return this.viewport.pixelFromPoint( point, true );\n },\n\n /**\n * Convert pixel coordinates relative to the window to image coordinates.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n windowToImageCoordinates: function( pixel ) {\n var viewerCoordinates = pixel.minus(\n OpenSeadragon.getElementPosition( this.viewer.element ));\n return this.viewerElementToImageCoordinates( viewerCoordinates );\n },\n\n /**\n * Convert image coordinates to pixel coordinates relative to the window.\n * @param {OpenSeadragon.Point} pixel\n * @returns {OpenSeadragon.Point}\n */\n imageToWindowCoordinates: function( pixel ) {\n var viewerCoordinates = this.imageToViewerElementCoordinates( pixel );\n return viewerCoordinates.plus(\n OpenSeadragon.getElementPosition( this.viewer.element ));\n },\n\n // private\n // Convert rectangle in viewport coordinates to this tiled image point\n // coordinates (x in [0, 1] and y in [0, aspectRatio])\n _viewportToTiledImageRectangle: function(rect) {\n var scale = this._scaleSpring.current.value;\n rect = rect.rotate(-this.getRotation(true), this._getRotationPoint(true));\n return new $.Rect(\n (rect.x - this._xSpring.current.value) / scale,\n (rect.y - this._ySpring.current.value) / scale,\n rect.width / scale,\n rect.height / scale,\n rect.degrees);\n },\n\n /**\n * Convert a viewport zoom to an image zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * @function\n * @param {Number} viewportZoom The viewport zoom\n * @returns {Number} imageZoom The image zoom\n */\n viewportToImageZoom: function( viewportZoom ) {\n var ratio = this._scaleSpring.current.value *\n this.viewport._containerInnerSize.x / this.source.dimensions.x;\n return ratio * viewportZoom;\n },\n\n /**\n * Convert an image zoom to a viewport zoom.\n * Image zoom: ratio of the original image size to displayed image size.\n * 1 means original image size, 0.5 half size...\n * Viewport zoom: ratio of the displayed image's width to viewport's width.\n * 1 means identical width, 2 means image's width is twice the viewport's width...\n * Note: not accurate with multi-image.\n * @function\n * @param {Number} imageZoom The image zoom\n * @returns {Number} viewportZoom The viewport zoom\n */\n imageToViewportZoom: function( imageZoom ) {\n var ratio = this._scaleSpring.current.value *\n this.viewport._containerInnerSize.x / this.source.dimensions.x;\n return imageZoom / ratio;\n },\n\n /**\n * Sets the TiledImage's position in the world.\n * @param {OpenSeadragon.Point} position - The new position, in viewport coordinates.\n * @param {Boolean} [immediately=false] - Whether to animate to the new position or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setPosition: function(position, immediately) {\n var sameTarget = (this._xSpring.target.value === position.x &&\n this._ySpring.target.value === position.y);\n\n if (immediately) {\n if (sameTarget && this._xSpring.current.value === position.x &&\n this._ySpring.current.value === position.y) {\n return;\n }\n\n this._xSpring.resetTo(position.x);\n this._ySpring.resetTo(position.y);\n this._needsDraw = true;\n } else {\n if (sameTarget) {\n return;\n }\n\n this._xSpring.springTo(position.x);\n this._ySpring.springTo(position.y);\n this._needsDraw = true;\n }\n\n if (!sameTarget) {\n this._raiseBoundsChange();\n }\n },\n\n /**\n * Sets the TiledImage's width in the world, adjusting the height to match based on aspect ratio.\n * @param {Number} width - The new width, in viewport coordinates.\n * @param {Boolean} [immediately=false] - Whether to animate to the new size or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setWidth: function(width, immediately) {\n this._setScale(width, immediately);\n },\n\n /**\n * Sets the TiledImage's height in the world, adjusting the width to match based on aspect ratio.\n * @param {Number} height - The new height, in viewport coordinates.\n * @param {Boolean} [immediately=false] - Whether to animate to the new size or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setHeight: function(height, immediately) {\n this._setScale(height / this.normHeight, immediately);\n },\n\n /**\n * Positions and scales the TiledImage to fit in the specified bounds.\n * Note: this method fires OpenSeadragon.TiledImage.event:bounds-change\n * twice\n * @param {OpenSeadragon.Rect} bounds The bounds to fit the image into.\n * @param {OpenSeadragon.Placement} [anchor=OpenSeadragon.Placement.CENTER]\n * How to anchor the image in the bounds.\n * @param {Boolean} [immediately=false] Whether to animate to the new size\n * or snap immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n fitBounds: function(bounds, anchor, immediately) {\n anchor = anchor || $.Placement.CENTER;\n var anchorProperties = $.Placement.properties[anchor];\n var aspectRatio = this.contentAspectX;\n var xOffset = 0;\n var yOffset = 0;\n var displayedWidthRatio = 1;\n var displayedHeightRatio = 1;\n if (this._clip) {\n aspectRatio = this._clip.getAspectRatio();\n displayedWidthRatio = this._clip.width / this.source.dimensions.x;\n displayedHeightRatio = this._clip.height / this.source.dimensions.y;\n if (bounds.getAspectRatio() > aspectRatio) {\n xOffset = this._clip.x / this._clip.height * bounds.height;\n yOffset = this._clip.y / this._clip.height * bounds.height;\n } else {\n xOffset = this._clip.x / this._clip.width * bounds.width;\n yOffset = this._clip.y / this._clip.width * bounds.width;\n }\n }\n\n if (bounds.getAspectRatio() > aspectRatio) {\n // We will have margins on the X axis\n var height = bounds.height / displayedHeightRatio;\n var marginLeft = 0;\n if (anchorProperties.isHorizontallyCentered) {\n marginLeft = (bounds.width - bounds.height * aspectRatio) / 2;\n } else if (anchorProperties.isRight) {\n marginLeft = bounds.width - bounds.height * aspectRatio;\n }\n this.setPosition(\n new $.Point(bounds.x - xOffset + marginLeft, bounds.y - yOffset),\n immediately);\n this.setHeight(height, immediately);\n } else {\n // We will have margins on the Y axis\n var width = bounds.width / displayedWidthRatio;\n var marginTop = 0;\n if (anchorProperties.isVerticallyCentered) {\n marginTop = (bounds.height - bounds.width / aspectRatio) / 2;\n } else if (anchorProperties.isBottom) {\n marginTop = bounds.height - bounds.width / aspectRatio;\n }\n this.setPosition(\n new $.Point(bounds.x - xOffset, bounds.y - yOffset + marginTop),\n immediately);\n this.setWidth(width, immediately);\n }\n },\n\n /**\n * @returns {OpenSeadragon.Rect|null} The TiledImage's current clip rectangle,\n * in image pixels, or null if none.\n */\n getClip: function() {\n if (this._clip) {\n return this._clip.clone();\n }\n\n return null;\n },\n\n /**\n * @param {OpenSeadragon.Rect|null} newClip - An area, in image pixels, to clip to\n * (portions of the image outside of this area will not be visible). Only works on\n * browsers that support the HTML5 canvas.\n * @fires OpenSeadragon.TiledImage.event:clip-change\n */\n setClip: function(newClip) {\n $.console.assert(!newClip || newClip instanceof $.Rect,\n \"[TiledImage.setClip] newClip must be an OpenSeadragon.Rect or null\");\n\n if (newClip instanceof $.Rect) {\n this._clip = newClip.clone();\n } else {\n this._clip = null;\n }\n\n this._needsDraw = true;\n /**\n * Raised when the TiledImage's clip is changed.\n * @event clip-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('clip-change');\n },\n\n /**\n * @returns {Number} The TiledImage's current opacity.\n */\n getOpacity: function() {\n return this.opacity;\n },\n\n /**\n * @param {Number} opacity Opacity the tiled image should be drawn at.\n * @fires OpenSeadragon.TiledImage.event:opacity-change\n */\n setOpacity: function(opacity) {\n if (opacity === this.opacity) {\n return;\n }\n\n this.opacity = opacity;\n this._needsDraw = true;\n /**\n * Raised when the TiledImage's opacity is changed.\n * @event opacity-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {Number} opacity - The new opacity value.\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('opacity-change', {\n opacity: this.opacity\n });\n },\n\n /**\n * @returns {Boolean} whether the tiledImage can load its tiles even when it has zero opacity.\n */\n getPreload: function() {\n return this._preload;\n },\n\n /**\n * Set true to load even when hidden. Set false to block loading when hidden.\n */\n setPreload: function(preload) {\n this._preload = !!preload;\n this._needsDraw = true;\n },\n\n /**\n * Get the rotation of this tiled image in degrees.\n * @param {Boolean} [current=false] True for current rotation, false for target.\n * @returns {Number} the rotation of this tiled image in degrees.\n */\n getRotation: function(current) {\n return current ?\n this._degreesSpring.current.value :\n this._degreesSpring.target.value;\n },\n\n /**\n * Set the current rotation of this tiled image in degrees.\n * @param {Number} degrees the rotation in degrees.\n * @param {Boolean} [immediately=false] Whether to animate to the new angle\n * or rotate immediately.\n * @fires OpenSeadragon.TiledImage.event:bounds-change\n */\n setRotation: function(degrees, immediately) {\n if (this._degreesSpring.target.value === degrees &&\n this._degreesSpring.isAtTargetValue()) {\n return;\n }\n if (immediately) {\n this._degreesSpring.resetTo(degrees);\n } else {\n this._degreesSpring.springTo(degrees);\n }\n this._needsDraw = true;\n this._raiseBoundsChange();\n },\n\n /**\n * Get the point around which this tiled image is rotated\n * @private\n * @param {Boolean} current True for current rotation point, false for target.\n * @returns {OpenSeadragon.Point}\n */\n _getRotationPoint: function(current) {\n return this.getBoundsNoRotate(current).getCenter();\n },\n\n /**\n * @returns {String} The TiledImage's current compositeOperation.\n */\n getCompositeOperation: function() {\n return this.compositeOperation;\n },\n\n /**\n * @param {String} compositeOperation the tiled image should be drawn with this globalCompositeOperation.\n * @fires OpenSeadragon.TiledImage.event:composite-operation-change\n */\n setCompositeOperation: function(compositeOperation) {\n if (compositeOperation === this.compositeOperation) {\n return;\n }\n\n this.compositeOperation = compositeOperation;\n this._needsDraw = true;\n /**\n * Raised when the TiledImage's opacity is changed.\n * @event composite-operation-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {String} compositeOperation - The new compositeOperation value.\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('composite-operation-change', {\n compositeOperation: this.compositeOperation\n });\n },\n\n // private\n _setScale: function(scale, immediately) {\n var sameTarget = (this._scaleSpring.target.value === scale);\n if (immediately) {\n if (sameTarget && this._scaleSpring.current.value === scale) {\n return;\n }\n\n this._scaleSpring.resetTo(scale);\n this._updateForScale();\n this._needsDraw = true;\n } else {\n if (sameTarget) {\n return;\n }\n\n this._scaleSpring.springTo(scale);\n this._updateForScale();\n this._needsDraw = true;\n }\n\n if (!sameTarget) {\n this._raiseBoundsChange();\n }\n },\n\n // private\n _updateForScale: function() {\n this._worldWidthTarget = this._scaleSpring.target.value;\n this._worldHeightTarget = this.normHeight * this._scaleSpring.target.value;\n this._worldWidthCurrent = this._scaleSpring.current.value;\n this._worldHeightCurrent = this.normHeight * this._scaleSpring.current.value;\n },\n\n // private\n _raiseBoundsChange: function() {\n /**\n * Raised when the TiledImage's bounds are changed.\n * Note that this event is triggered only when the animation target is changed;\n * not for every frame of animation.\n * @event bounds-change\n * @memberOf OpenSeadragon.TiledImage\n * @type {object}\n * @property {OpenSeadragon.TiledImage} eventSource - A reference to the\n * TiledImage which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('bounds-change');\n },\n\n // private\n _isBottomItem: function() {\n return this.viewer.world.getItemAt(0) === this;\n },\n\n // private\n _getLevelsInterval: function() {\n var lowestLevel = Math.max(\n this.source.minLevel,\n Math.floor(Math.log(this.minZoomImageRatio) / Math.log(2))\n );\n var currentZeroRatio = this.viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(0), true).x *\n this._scaleSpring.current.value;\n var highestLevel = Math.min(\n Math.abs(this.source.maxLevel),\n Math.abs(Math.floor(\n Math.log(currentZeroRatio / this.minPixelRatio) / Math.log(2)\n ))\n );\n\n // Calculations for the interval of levels to draw\n // can return invalid intervals; fix that here if necessary\n lowestLevel = Math.min(lowestLevel, highestLevel);\n return {\n lowestLevel: lowestLevel,\n highestLevel: highestLevel\n };\n },\n\n /**\n * @private\n * @inner\n * Pretty much every other line in this needs to be documented so it's clear\n * how each piece of this routine contributes to the drawing process. That's\n * why there are so many TODO's inside this function.\n */\n _updateViewport: function() {\n this._needsDraw = false;\n this._tilesLoading = 0;\n this.loadingCoverage = {};\n\n // Reset tile's internal drawn state\n while (this.lastDrawn.length > 0) {\n var tile = this.lastDrawn.pop();\n tile.beingDrawn = false;\n }\n\n var viewport = this.viewport;\n var drawArea = this._viewportToTiledImageRectangle(\n viewport.getBoundsWithMargins(true));\n\n if (!this.wrapHorizontal && !this.wrapVertical) {\n var tiledImageBounds = this._viewportToTiledImageRectangle(\n this.getClippedBounds(true));\n drawArea = drawArea.intersection(tiledImageBounds);\n if (drawArea === null) {\n return;\n }\n }\n\n var levelsInterval = this._getLevelsInterval();\n var lowestLevel = levelsInterval.lowestLevel;\n var highestLevel = levelsInterval.highestLevel;\n var bestTile = null;\n var haveDrawn = false;\n var currentTime = $.now();\n\n // Update any level that will be drawn\n for (var level = highestLevel; level >= lowestLevel; level--) {\n var drawLevel = false;\n\n //Avoid calculations for draw if we have already drawn this\n var currentRenderPixelRatio = viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(level),\n true\n ).x * this._scaleSpring.current.value;\n\n if (level === lowestLevel ||\n (!haveDrawn && currentRenderPixelRatio >= this.minPixelRatio)) {\n drawLevel = true;\n haveDrawn = true;\n } else if (!haveDrawn) {\n continue;\n }\n\n //Perform calculations for draw if we haven't drawn this\n var targetRenderPixelRatio = viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(level),\n false\n ).x * this._scaleSpring.current.value;\n\n var targetZeroRatio = viewport.deltaPixelsFromPointsNoRotate(\n this.source.getPixelRatio(\n Math.max(\n this.source.getClosestLevel(),\n 0\n )\n ),\n false\n ).x * this._scaleSpring.current.value;\n\n var optimalRatio = this.immediateRender ? 1 : targetZeroRatio;\n var levelOpacity = Math.min(1, (currentRenderPixelRatio - 0.5) / 0.5);\n var levelVisibility = optimalRatio / Math.abs(\n optimalRatio - targetRenderPixelRatio\n );\n\n // Update the level and keep track of 'best' tile to load\n bestTile = updateLevel(\n this,\n haveDrawn,\n drawLevel,\n level,\n levelOpacity,\n levelVisibility,\n drawArea,\n currentTime,\n bestTile\n );\n\n // Stop the loop if lower-res tiles would all be covered by\n // already drawn tiles\n if (providesCoverage(this.coverage, level)) {\n break;\n }\n }\n\n // Perform the actual drawing\n drawTiles(this, this.lastDrawn);\n\n // Load the new 'best' tile\n if (bestTile && !bestTile.context2D) {\n loadTile(this, bestTile, currentTime);\n this._needsDraw = true;\n this._setFullyLoaded(false);\n } else {\n this._setFullyLoaded(this._tilesLoading === 0);\n }\n },\n\n // private\n _getCornerTiles: function(level, topLeftBound, bottomRightBound) {\n var leftX;\n var rightX;\n if (this.wrapHorizontal) {\n leftX = $.positiveModulo(topLeftBound.x, 1);\n rightX = $.positiveModulo(bottomRightBound.x, 1);\n } else {\n leftX = Math.max(0, topLeftBound.x);\n rightX = Math.min(1, bottomRightBound.x);\n }\n var topY;\n var bottomY;\n var aspectRatio = 1 / this.source.aspectRatio;\n if (this.wrapVertical) {\n topY = $.positiveModulo(topLeftBound.y, aspectRatio);\n bottomY = $.positiveModulo(bottomRightBound.y, aspectRatio);\n } else {\n topY = Math.max(0, topLeftBound.y);\n bottomY = Math.min(aspectRatio, bottomRightBound.y);\n }\n\n var topLeftTile = this.source.getTileAtPoint(level, new $.Point(leftX, topY));\n var bottomRightTile = this.source.getTileAtPoint(level, new $.Point(rightX, bottomY));\n var numTiles = this.source.getNumTiles(level);\n\n if (this.wrapHorizontal) {\n topLeftTile.x += numTiles.x * Math.floor(topLeftBound.x);\n bottomRightTile.x += numTiles.x * Math.floor(bottomRightBound.x);\n }\n if (this.wrapVertical) {\n topLeftTile.y += numTiles.y * Math.floor(topLeftBound.y / aspectRatio);\n bottomRightTile.y += numTiles.y * Math.floor(bottomRightBound.y / aspectRatio);\n }\n\n return {\n topLeft: topLeftTile,\n bottomRight: bottomRightTile,\n };\n }\n});\n\n/**\n * @private\n * @inner\n * Updates all tiles at a given resolution level.\n * @param {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @param {Boolean} haveDrawn\n * @param {Boolean} drawLevel\n * @param {Number} level\n * @param {Number} levelOpacity\n * @param {Number} levelVisibility\n * @param {OpenSeadragon.Point} viewportTL - The index of the most top-left visible tile.\n * @param {OpenSeadragon.Point} viewportBR - The index of the most bottom-right visible tile.\n * @param {Number} currentTime\n * @param {OpenSeadragon.Tile} best - The current \"best\" tile to draw.\n */\nfunction updateLevel(tiledImage, haveDrawn, drawLevel, level, levelOpacity,\n levelVisibility, drawArea, currentTime, best) {\n\n var topLeftBound = drawArea.getBoundingBox().getTopLeft();\n var bottomRightBound = drawArea.getBoundingBox().getBottomRight();\n\n if (tiledImage.viewer) {\n /**\n * - Needs documentation -\n *\n * @event update-level\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {Object} havedrawn\n * @property {Object} level\n * @property {Object} opacity\n * @property {Object} visibility\n * @property {OpenSeadragon.Rect} drawArea\n * @property {Object} topleft deprecated, use drawArea instead\n * @property {Object} bottomright deprecated, use drawArea instead\n * @property {Object} currenttime\n * @property {Object} best\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n tiledImage.viewer.raiseEvent('update-level', {\n tiledImage: tiledImage,\n havedrawn: haveDrawn,\n level: level,\n opacity: levelOpacity,\n visibility: levelVisibility,\n drawArea: drawArea,\n topleft: topLeftBound,\n bottomright: bottomRightBound,\n currenttime: currentTime,\n best: best\n });\n }\n\n resetCoverage(tiledImage.coverage, level);\n resetCoverage(tiledImage.loadingCoverage, level);\n\n //OK, a new drawing so do your calculations\n var cornerTiles = tiledImage._getCornerTiles(level, topLeftBound, bottomRightBound);\n var topLeftTile = cornerTiles.topLeft;\n var bottomRightTile = cornerTiles.bottomRight;\n var numberOfTiles = tiledImage.source.getNumTiles(level);\n\n var viewportCenter = tiledImage.viewport.pixelFromPoint(\n tiledImage.viewport.getCenter());\n for (var x = topLeftTile.x; x <= bottomRightTile.x; x++) {\n for (var y = topLeftTile.y; y <= bottomRightTile.y; y++) {\n\n // Optimisation disabled with wrapping because getTileBounds does not\n // work correctly with x and y outside of the number of tiles\n if (!tiledImage.wrapHorizontal && !tiledImage.wrapVertical) {\n var tileBounds = tiledImage.source.getTileBounds(level, x, y);\n if (drawArea.intersection(tileBounds) === null) {\n // This tile is outside of the viewport, no need to draw it\n continue;\n }\n }\n\n best = updateTile(\n tiledImage,\n drawLevel,\n haveDrawn,\n x, y,\n level,\n levelOpacity,\n levelVisibility,\n viewportCenter,\n numberOfTiles,\n currentTime,\n best\n );\n\n }\n }\n\n return best;\n}\n\n/**\n * @private\n * @inner\n * Update a single tile at a particular resolution level.\n * @param {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @param {Boolean} haveDrawn\n * @param {Boolean} drawLevel\n * @param {Number} x\n * @param {Number} y\n * @param {Number} level\n * @param {Number} levelOpacity\n * @param {Number} levelVisibility\n * @param {OpenSeadragon.Point} viewportCenter\n * @param {Number} numberOfTiles\n * @param {Number} currentTime\n * @param {OpenSeadragon.Tile} best - The current \"best\" tile to draw.\n */\nfunction updateTile( tiledImage, haveDrawn, drawLevel, x, y, level, levelOpacity, levelVisibility, viewportCenter, numberOfTiles, currentTime, best){\n\n var tile = getTile(\n x, y,\n level,\n tiledImage,\n tiledImage.source,\n tiledImage.tilesMatrix,\n currentTime,\n numberOfTiles,\n tiledImage._worldWidthCurrent,\n tiledImage._worldHeightCurrent\n ),\n drawTile = drawLevel;\n\n if( tiledImage.viewer ){\n /**\n * - Needs documentation -\n *\n * @event update-tile\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {OpenSeadragon.Tile} tile\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n tiledImage.viewer.raiseEvent( 'update-tile', {\n tiledImage: tiledImage,\n tile: tile\n });\n }\n\n setCoverage( tiledImage.coverage, level, x, y, false );\n\n var loadingCoverage = tile.loaded || tile.loading || isCovered(tiledImage.loadingCoverage, level, x, y);\n setCoverage(tiledImage.loadingCoverage, level, x, y, loadingCoverage);\n\n if ( !tile.exists ) {\n return best;\n }\n\n if ( haveDrawn && !drawTile ) {\n if ( isCovered( tiledImage.coverage, level, x, y ) ) {\n setCoverage( tiledImage.coverage, level, x, y, true );\n } else {\n drawTile = true;\n }\n }\n\n if ( !drawTile ) {\n return best;\n }\n\n positionTile(\n tile,\n tiledImage.source.tileOverlap,\n tiledImage.viewport,\n viewportCenter,\n levelVisibility,\n tiledImage\n );\n\n if (!tile.loaded) {\n if (tile.context2D) {\n setTileLoaded(tiledImage, tile);\n } else {\n var imageRecord = tiledImage._tileCache.getImageRecord(tile.cacheKey);\n if (imageRecord) {\n var image = imageRecord.getImage();\n setTileLoaded(tiledImage, tile, image);\n }\n }\n }\n\n if ( tile.loaded ) {\n var needsDraw = blendTile(\n tiledImage,\n tile,\n x, y,\n level,\n levelOpacity,\n currentTime\n );\n\n if ( needsDraw ) {\n tiledImage._needsDraw = true;\n }\n } else if ( tile.loading ) {\n // the tile is already in the download queue\n tiledImage._tilesLoading++;\n } else if (!loadingCoverage) {\n best = compareTiles( best, tile );\n }\n\n return best;\n}\n\n/**\n * @private\n * @inner\n * Obtains a tile at the given location.\n * @param {Number} x\n * @param {Number} y\n * @param {Number} level\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.TileSource} tileSource\n * @param {Object} tilesMatrix - A '3d' dictionary [level][x][y] --> Tile.\n * @param {Number} time\n * @param {Number} numTiles\n * @param {Number} worldWidth\n * @param {Number} worldHeight\n * @returns {OpenSeadragon.Tile}\n */\nfunction getTile(\n x, y,\n level,\n tiledImage,\n tileSource,\n tilesMatrix,\n time,\n numTiles,\n worldWidth,\n worldHeight\n) {\n var xMod,\n yMod,\n bounds,\n sourceBounds,\n exists,\n url,\n ajaxHeaders,\n context2D,\n tile;\n\n if ( !tilesMatrix[ level ] ) {\n tilesMatrix[ level ] = {};\n }\n if ( !tilesMatrix[ level ][ x ] ) {\n tilesMatrix[ level ][ x ] = {};\n }\n\n if ( !tilesMatrix[ level ][ x ][ y ] ) {\n xMod = ( numTiles.x + ( x % numTiles.x ) ) % numTiles.x;\n yMod = ( numTiles.y + ( y % numTiles.y ) ) % numTiles.y;\n bounds = tileSource.getTileBounds( level, xMod, yMod );\n sourceBounds = tileSource.getTileBounds( level, xMod, yMod, true );\n exists = tileSource.tileExists( level, xMod, yMod );\n url = tileSource.getTileUrl( level, xMod, yMod );\n\n // Headers are only applicable if loadTilesWithAjax is set\n if (tiledImage.loadTilesWithAjax) {\n ajaxHeaders = tileSource.getTileAjaxHeaders( level, xMod, yMod );\n // Combine tile AJAX headers with tiled image AJAX headers (if applicable)\n if ($.isPlainObject(tiledImage.ajaxHeaders)) {\n ajaxHeaders = $.extend({}, tiledImage.ajaxHeaders, ajaxHeaders);\n }\n } else {\n ajaxHeaders = null;\n }\n\n context2D = tileSource.getContext2D ?\n tileSource.getContext2D(level, xMod, yMod) : undefined;\n\n bounds.x += ( x - xMod ) / numTiles.x;\n bounds.y += (worldHeight / worldWidth) * (( y - yMod ) / numTiles.y);\n\n tile = new $.Tile(\n level,\n x,\n y,\n bounds,\n exists,\n url,\n context2D,\n tiledImage.loadTilesWithAjax,\n ajaxHeaders,\n sourceBounds\n );\n\n if (xMod === numTiles.x - 1) {\n tile.isRightMost = true;\n }\n\n if (yMod === numTiles.y - 1) {\n tile.isBottomMost = true;\n }\n\n tilesMatrix[ level ][ x ][ y ] = tile;\n }\n\n tile = tilesMatrix[ level ][ x ][ y ];\n tile.lastTouchTime = time;\n\n return tile;\n}\n\n/**\n * @private\n * @inner\n * Dispatch a job to the ImageLoader to load the Image for a Tile.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Number} time\n */\nfunction loadTile( tiledImage, tile, time ) {\n tile.loading = true;\n var customAjax;\n\n // Bind tiledImage if filtering Ajax\n if ($.isFunction(tiledImage.makeAjaxRequest)) {\n customAjax = tiledImage.makeAjaxRequest;\n }\n\n tiledImage._imageLoader.addJob({\n src: tile.url,\n makeAjaxRequest: customAjax,\n loadWithAjax: tile.loadWithAjax,\n ajaxHeaders: tile.ajaxHeaders,\n crossOriginPolicy: tiledImage.crossOriginPolicy,\n ajaxWithCredentials: tiledImage.ajaxWithCredentials,\n callback: function( image, errorMsg, tileRequest ){\n onTileLoad( tiledImage, tile, time, image, errorMsg, tileRequest );\n },\n abort: function() {\n tile.loading = false;\n }\n });\n}\n\n/**\n * @private\n * @inner\n * Callback fired when a Tile's Image finished downloading.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Number} time\n * @param {Image} image\n * @param {String} errorMsg\n * @param {XMLHttpRequest} tileRequest\n */\nfunction onTileLoad( tiledImage, tile, time, image, errorMsg, tileRequest ) {\n if ( !image ) {\n $.console.log( \"Tile %s failed to load: %s - error: %s\", tile, tile.url, errorMsg );\n /**\n * Triggered when a tile fails to load.\n *\n * @event tile-load-failed\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Tile} tile - The tile that failed to load.\n * @property {OpenSeadragon.TiledImage} tiledImage - The tiled image the tile belongs to.\n * @property {number} time - The time in milliseconds when the tile load began.\n * @property {string} message - The error message.\n * @property {XMLHttpRequest} tileRequest - The XMLHttpRequest used to load the tile if available.\n */\n tiledImage.viewer.raiseEvent(\"tile-load-failed\", {\n tile: tile,\n tiledImage: tiledImage,\n time: time,\n message: errorMsg,\n tileRequest: tileRequest\n });\n tile.loading = false;\n tile.exists = false;\n return;\n }\n\n if ( time < tiledImage.lastResetTime ) {\n $.console.log( \"Ignoring tile %s loaded before reset: %s\", tile, tile.url );\n tile.loading = false;\n return;\n }\n\n var finish = function() {\n var cutoff = tiledImage.source.getClosestLevel();\n setTileLoaded(tiledImage, tile, image, cutoff, tileRequest);\n };\n\n // Check if we're mid-update; this can happen on IE8 because image load events for\n // cached images happen immediately there\n if ( !tiledImage._midDraw ) {\n finish();\n } else {\n // Wait until after the update, in case caching unloads any tiles\n window.setTimeout( finish, 1);\n }\n}\n\n/**\n * @private\n * @inner\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Image} image\n * @param {Number} cutoff\n */\nfunction setTileLoaded(tiledImage, tile, image, cutoff, tileRequest) {\n var increment = 0;\n\n function getCompletionCallback() {\n increment++;\n return completionCallback;\n }\n\n function completionCallback() {\n increment--;\n if (increment === 0) {\n tile.loading = false;\n tile.loaded = true;\n if (!tile.context2D) {\n tiledImage._tileCache.cacheTile({\n image: image,\n tile: tile,\n cutoff: cutoff,\n tiledImage: tiledImage\n });\n }\n tiledImage._needsDraw = true;\n }\n }\n\n /**\n * Triggered when a tile has just been loaded in memory. That means that the\n * image has been downloaded and can be modified before being drawn to the canvas.\n *\n * @event tile-loaded\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {Image} image - The image of the tile.\n * @property {OpenSeadragon.TiledImage} tiledImage - The tiled image of the loaded tile.\n * @property {OpenSeadragon.Tile} tile - The tile which has been loaded.\n * @property {XMLHttpRequest} tiledImage - The AJAX request that loaded this tile (if applicable).\n * @property {function} getCompletionCallback - A function giving a callback to call\n * when the asynchronous processing of the image is done. The image will be\n * marked as entirely loaded when the callback has been called once for each\n * call to getCompletionCallback.\n */\n tiledImage.viewer.raiseEvent(\"tile-loaded\", {\n tile: tile,\n tiledImage: tiledImage,\n tileRequest: tileRequest,\n image: image,\n getCompletionCallback: getCompletionCallback\n });\n // In case the completion callback is never called, we at least force it once.\n getCompletionCallback()();\n}\n\n/**\n * @private\n * @inner\n * @param {OpenSeadragon.Tile} tile\n * @param {Boolean} overlap\n * @param {OpenSeadragon.Viewport} viewport\n * @param {OpenSeadragon.Point} viewportCenter\n * @param {Number} levelVisibility\n * @param {OpenSeadragon.TiledImage} tiledImage\n */\nfunction positionTile( tile, overlap, viewport, viewportCenter, levelVisibility, tiledImage ){\n var boundsTL = tile.bounds.getTopLeft();\n\n boundsTL.x *= tiledImage._scaleSpring.current.value;\n boundsTL.y *= tiledImage._scaleSpring.current.value;\n boundsTL.x += tiledImage._xSpring.current.value;\n boundsTL.y += tiledImage._ySpring.current.value;\n\n var boundsSize = tile.bounds.getSize();\n\n boundsSize.x *= tiledImage._scaleSpring.current.value;\n boundsSize.y *= tiledImage._scaleSpring.current.value;\n\n var positionC = viewport.pixelFromPointNoRotate(boundsTL, true),\n positionT = viewport.pixelFromPointNoRotate(boundsTL, false),\n sizeC = viewport.deltaPixelsFromPointsNoRotate(boundsSize, true),\n sizeT = viewport.deltaPixelsFromPointsNoRotate(boundsSize, false),\n tileCenter = positionT.plus( sizeT.divide( 2 ) ),\n tileSquaredDistance = viewportCenter.squaredDistanceTo( tileCenter );\n\n if ( !overlap ) {\n sizeC = sizeC.plus( new $.Point( 1, 1 ) );\n }\n\n if (tile.isRightMost && tiledImage.wrapHorizontal) {\n sizeC.x += 0.75; // Otherwise Firefox and Safari show seams\n }\n\n if (tile.isBottomMost && tiledImage.wrapVertical) {\n sizeC.y += 0.75; // Otherwise Firefox and Safari show seams\n }\n\n tile.position = positionC;\n tile.size = sizeC;\n tile.squaredDistance = tileSquaredDistance;\n tile.visibility = levelVisibility;\n}\n\n/**\n * @private\n * @inner\n * Updates the opacity of a tile according to the time it has been on screen\n * to perform a fade-in.\n * Updates coverage once a tile is fully opaque.\n * Returns whether the fade-in has completed.\n *\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile} tile\n * @param {Number} x\n * @param {Number} y\n * @param {Number} level\n * @param {Number} levelOpacity\n * @param {Number} currentTime\n * @returns {Boolean}\n */\nfunction blendTile( tiledImage, tile, x, y, level, levelOpacity, currentTime ){\n var blendTimeMillis = 1000 * tiledImage.blendTime,\n deltaTime,\n opacity;\n\n if ( !tile.blendStart ) {\n tile.blendStart = currentTime;\n }\n\n deltaTime = currentTime - tile.blendStart;\n opacity = blendTimeMillis ? Math.min( 1, deltaTime / ( blendTimeMillis ) ) : 1;\n\n if ( tiledImage.alwaysBlend ) {\n opacity *= levelOpacity;\n }\n\n tile.opacity = opacity;\n\n tiledImage.lastDrawn.push( tile );\n\n if ( opacity == 1 ) {\n setCoverage( tiledImage.coverage, level, x, y, true );\n tiledImage._hasOpaqueTile = true;\n } else if ( deltaTime < blendTimeMillis ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * @private\n * @inner\n * Returns true if the given tile provides coverage to lower-level tiles of\n * lower resolution representing the same content. If neither x nor y is\n * given, returns true if the entire visible level provides coverage.\n *\n * Note that out-of-bounds tiles provide coverage in this sense, since\n * there's no content that they would need to cover. Tiles at non-existent\n * levels that are within the image bounds, however, do not.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of the tile.\n * @param {Number} x - The X position of the tile.\n * @param {Number} y - The Y position of the tile.\n * @returns {Boolean}\n */\nfunction providesCoverage( coverage, level, x, y ) {\n var rows,\n cols,\n i, j;\n\n if ( !coverage[ level ] ) {\n return false;\n }\n\n if ( x === undefined || y === undefined ) {\n rows = coverage[ level ];\n for ( i in rows ) {\n if ( rows.hasOwnProperty( i ) ) {\n cols = rows[ i ];\n for ( j in cols ) {\n if ( cols.hasOwnProperty( j ) && !cols[ j ] ) {\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n return (\n coverage[ level ][ x] === undefined ||\n coverage[ level ][ x ][ y ] === undefined ||\n coverage[ level ][ x ][ y ] === true\n );\n}\n\n/**\n * @private\n * @inner\n * Returns true if the given tile is completely covered by higher-level\n * tiles of higher resolution representing the same content. If neither x\n * nor y is given, returns true if the entire visible level is covered.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of the tile.\n * @param {Number} x - The X position of the tile.\n * @param {Number} y - The Y position of the tile.\n * @returns {Boolean}\n */\nfunction isCovered( coverage, level, x, y ) {\n if ( x === undefined || y === undefined ) {\n return providesCoverage( coverage, level + 1 );\n } else {\n return (\n providesCoverage( coverage, level + 1, 2 * x, 2 * y ) &&\n providesCoverage( coverage, level + 1, 2 * x, 2 * y + 1 ) &&\n providesCoverage( coverage, level + 1, 2 * x + 1, 2 * y ) &&\n providesCoverage( coverage, level + 1, 2 * x + 1, 2 * y + 1 )\n );\n }\n}\n\n/**\n * @private\n * @inner\n * Sets whether the given tile provides coverage or not.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of the tile.\n * @param {Number} x - The X position of the tile.\n * @param {Number} y - The Y position of the tile.\n * @param {Boolean} covers - Whether the tile provides coverage.\n */\nfunction setCoverage( coverage, level, x, y, covers ) {\n if ( !coverage[ level ] ) {\n $.console.warn(\n \"Setting coverage for a tile before its level's coverage has been reset: %s\",\n level\n );\n return;\n }\n\n if ( !coverage[ level ][ x ] ) {\n coverage[ level ][ x ] = {};\n }\n\n coverage[ level ][ x ][ y ] = covers;\n}\n\n/**\n * @private\n * @inner\n * Resets coverage information for the given level. This should be called\n * after every draw routine. Note that at the beginning of the next draw\n * routine, coverage for every visible tile should be explicitly set.\n *\n * @param {Object} coverage - A '3d' dictionary [level][x][y] --> Boolean.\n * @param {Number} level - The resolution level of tiles to completely reset.\n */\nfunction resetCoverage( coverage, level ) {\n coverage[ level ] = {};\n}\n\n/**\n * @private\n * @inner\n * Determines whether the 'last best' tile for the area is better than the\n * tile in question.\n *\n * @param {OpenSeadragon.Tile} previousBest\n * @param {OpenSeadragon.Tile} tile\n * @returns {OpenSeadragon.Tile} The new best tile.\n */\nfunction compareTiles( previousBest, tile ) {\n if ( !previousBest ) {\n return tile;\n }\n\n if ( tile.visibility > previousBest.visibility ) {\n return tile;\n } else if ( tile.visibility == previousBest.visibility ) {\n if ( tile.squaredDistance < previousBest.squaredDistance ) {\n return tile;\n }\n }\n\n return previousBest;\n}\n\n/**\n * @private\n * @inner\n * Draws a TiledImage.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile[]} lastDrawn - An unordered list of Tiles drawn last frame.\n */\nfunction drawTiles( tiledImage, lastDrawn ) {\n if (tiledImage.opacity === 0 || (lastDrawn.length === 0 && !tiledImage.placeholderFillStyle)) {\n return;\n }\n\n var tile = lastDrawn[0];\n var useSketch;\n\n if (tile) {\n useSketch = tiledImage.opacity < 1 ||\n (tiledImage.compositeOperation &&\n tiledImage.compositeOperation !== 'source-over') ||\n (!tiledImage._isBottomItem() && tile._hasTransparencyChannel());\n }\n\n var sketchScale;\n var sketchTranslate;\n\n var zoom = tiledImage.viewport.getZoom(true);\n var imageZoom = tiledImage.viewportToImageZoom(zoom);\n\n if (lastDrawn.length > 1 &&\n imageZoom > tiledImage.smoothTileEdgesMinZoom &&\n !tiledImage.iOSDevice &&\n tiledImage.getRotation(true) % 360 === 0 && // TODO: support tile edge smoothing with tiled image rotation.\n $.supportsCanvas) {\n // When zoomed in a lot (>100%) the tile edges are visible.\n // So we have to composite them at ~100% and scale them up together.\n // Note: Disabled on iOS devices per default as it causes a native crash\n useSketch = true;\n sketchScale = tile.getScaleForEdgeSmoothing();\n sketchTranslate = tile.getTranslationForEdgeSmoothing(sketchScale,\n tiledImage._drawer.getCanvasSize(false),\n tiledImage._drawer.getCanvasSize(true));\n }\n\n var bounds;\n if (useSketch) {\n if (!sketchScale) {\n // Except when edge smoothing, we only clean the part of the\n // sketch canvas we are going to use for performance reasons.\n bounds = tiledImage.viewport.viewportToViewerElementRectangle(\n tiledImage.getClippedBounds(true))\n .getIntegerBoundingBox()\n .times($.pixelDensityRatio);\n }\n tiledImage._drawer._clear(true, bounds);\n }\n\n // When scaling, we must rotate only when blending the sketch canvas to\n // avoid interpolation\n if (!sketchScale) {\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.viewport.degrees,\n useSketch: useSketch\n });\n } else {\n if(tiledImage._drawer.viewer.viewport.flipped) {\n tiledImage._drawer._flip({});\n }\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.getRotation(true),\n point: tiledImage.viewport.pixelFromPointNoRotate(\n tiledImage._getRotationPoint(true), true),\n useSketch: useSketch\n });\n }\n }\n\n var usedClip = false;\n if ( tiledImage._clip ) {\n tiledImage._drawer.saveContext(useSketch);\n\n var box = tiledImage.imageToViewportRectangle(tiledImage._clip, true);\n box = box.rotate(-tiledImage.getRotation(true), tiledImage._getRotationPoint(true));\n var clipRect = tiledImage._drawer.viewportToDrawerRectangle(box);\n if (sketchScale) {\n clipRect = clipRect.times(sketchScale);\n }\n if (sketchTranslate) {\n clipRect = clipRect.translate(sketchTranslate);\n }\n tiledImage._drawer.setClip(clipRect, useSketch);\n\n usedClip = true;\n }\n\n if ( tiledImage.placeholderFillStyle && tiledImage._hasOpaqueTile === false ) {\n var placeholderRect = tiledImage._drawer.viewportToDrawerRectangle(tiledImage.getBounds(true));\n if (sketchScale) {\n placeholderRect = placeholderRect.times(sketchScale);\n }\n if (sketchTranslate) {\n placeholderRect = placeholderRect.translate(sketchTranslate);\n }\n\n var fillStyle = null;\n if ( typeof tiledImage.placeholderFillStyle === \"function\" ) {\n fillStyle = tiledImage.placeholderFillStyle(tiledImage, tiledImage._drawer.context);\n }\n else {\n fillStyle = tiledImage.placeholderFillStyle;\n }\n\n tiledImage._drawer.drawRectangle(placeholderRect, fillStyle, useSketch);\n }\n\n for (var i = lastDrawn.length - 1; i >= 0; i--) {\n tile = lastDrawn[ i ];\n tiledImage._drawer.drawTile( tile, tiledImage._drawingHandler, useSketch, sketchScale, sketchTranslate );\n tile.beingDrawn = true;\n\n if( tiledImage.viewer ){\n /**\n * - Needs documentation -\n *\n * @event tile-drawn\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the Viewer which raised the event.\n * @property {OpenSeadragon.TiledImage} tiledImage - Which TiledImage is being drawn.\n * @property {OpenSeadragon.Tile} tile\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n tiledImage.viewer.raiseEvent( 'tile-drawn', {\n tiledImage: tiledImage,\n tile: tile\n });\n }\n }\n\n if ( usedClip ) {\n tiledImage._drawer.restoreContext( useSketch );\n }\n\n if (!sketchScale) {\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._restoreRotationChanges(useSketch);\n }\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._restoreRotationChanges(useSketch);\n } else{\n if(tiledImage._drawer.viewer.viewport.flipped) {\n tiledImage._drawer._flip({});\n }\n }\n }\n\n if (useSketch) {\n if (sketchScale) {\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.viewport.degrees,\n useSketch: false\n });\n }\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._offsetForRotation({\n degrees: tiledImage.getRotation(true),\n point: tiledImage.viewport.pixelFromPointNoRotate(\n tiledImage._getRotationPoint(true), true),\n useSketch: false\n });\n }\n }\n tiledImage._drawer.blendSketch({\n opacity: tiledImage.opacity,\n scale: sketchScale,\n translate: sketchTranslate,\n compositeOperation: tiledImage.compositeOperation,\n bounds: bounds\n });\n if (sketchScale) {\n if (tiledImage.getRotation(true) % 360 !== 0) {\n tiledImage._drawer._restoreRotationChanges(false);\n }\n if (tiledImage.viewport.degrees !== 0) {\n tiledImage._drawer._restoreRotationChanges(false);\n }\n }\n }\n drawDebugInfo( tiledImage, lastDrawn );\n}\n\n/**\n * @private\n * @inner\n * Draws special debug information for a TiledImage if in debug mode.\n * @param {OpenSeadragon.TiledImage} tiledImage\n * @param {OpenSeadragon.Tile[]} lastDrawn - An unordered list of Tiles drawn last frame.\n */\nfunction drawDebugInfo( tiledImage, lastDrawn ) {\n if( tiledImage.debugMode ) {\n for ( var i = lastDrawn.length - 1; i >= 0; i-- ) {\n var tile = lastDrawn[ i ];\n try {\n tiledImage._drawer.drawDebugInfo(\n tile, lastDrawn.length, i, tiledImage);\n } catch(e) {\n $.console.error(e);\n }\n }\n }\n}\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - TileCache\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n// private class\nvar TileRecord = function( options ) {\n $.console.assert( options, \"[TileCache.cacheTile] options is required\" );\n $.console.assert( options.tile, \"[TileCache.cacheTile] options.tile is required\" );\n $.console.assert( options.tiledImage, \"[TileCache.cacheTile] options.tiledImage is required\" );\n this.tile = options.tile;\n this.tiledImage = options.tiledImage;\n};\n\n// private class\nvar ImageRecord = function(options) {\n $.console.assert( options, \"[ImageRecord] options is required\" );\n $.console.assert( options.image, \"[ImageRecord] options.image is required\" );\n this._image = options.image;\n this._tiles = [];\n};\n\nImageRecord.prototype = {\n destroy: function() {\n this._image = null;\n this._renderedContext = null;\n this._tiles = null;\n },\n\n getImage: function() {\n return this._image;\n },\n\n getRenderedContext: function() {\n if (!this._renderedContext) {\n var canvas = document.createElement( 'canvas' );\n canvas.width = this._image.width;\n canvas.height = this._image.height;\n this._renderedContext = canvas.getContext('2d');\n this._renderedContext.drawImage( this._image, 0, 0 );\n //since we are caching the prerendered image on a canvas\n //allow the image to not be held in memory\n this._image = null;\n }\n return this._renderedContext;\n },\n\n setRenderedContext: function(renderedContext) {\n $.console.error(\"ImageRecord.setRenderedContext is deprecated. \" +\n \"The rendered context should be created by the ImageRecord \" +\n \"itself when calling ImageRecord.getRenderedContext.\");\n this._renderedContext = renderedContext;\n },\n\n addTile: function(tile) {\n $.console.assert(tile, '[ImageRecord.addTile] tile is required');\n this._tiles.push(tile);\n },\n\n removeTile: function(tile) {\n for (var i = 0; i < this._tiles.length; i++) {\n if (this._tiles[i] === tile) {\n this._tiles.splice(i, 1);\n return;\n }\n }\n\n $.console.warn('[ImageRecord.removeTile] trying to remove unknown tile', tile);\n },\n\n getTileCount: function() {\n return this._tiles.length;\n }\n};\n\n/**\n * @class TileCache\n * @memberof OpenSeadragon\n * @classdesc Stores all the tiles displayed in a {@link OpenSeadragon.Viewer}.\n * You generally won't have to interact with the TileCache directly.\n * @param {Object} options - Configuration for this TileCache.\n * @param {Number} [options.maxImageCacheCount] - See maxImageCacheCount in\n * {@link OpenSeadragon.Options} for details.\n */\n$.TileCache = function( options ) {\n options = options || {};\n\n this._maxImageCacheCount = options.maxImageCacheCount || $.DEFAULT_SETTINGS.maxImageCacheCount;\n this._tilesLoaded = [];\n this._imagesLoaded = [];\n this._imagesLoadedCount = 0;\n};\n\n/** @lends OpenSeadragon.TileCache.prototype */\n$.TileCache.prototype = {\n /**\n * @returns {Number} The total number of tiles that have been loaded by\n * this TileCache.\n */\n numTilesLoaded: function() {\n return this._tilesLoaded.length;\n },\n\n /**\n * Caches the specified tile, removing an old tile if necessary to stay under the\n * maxImageCacheCount specified on construction. Note that if multiple tiles reference\n * the same image, there may be more tiles than maxImageCacheCount; the goal is to keep\n * the number of images below that number. Note, as well, that even the number of images\n * may temporarily surpass that number, but should eventually come back down to the max specified.\n * @param {Object} options - Tile info.\n * @param {OpenSeadragon.Tile} options.tile - The tile to cache.\n * @param {String} options.tile.cacheKey - The unique key used to identify this tile in the cache.\n * @param {Image} options.image - The image of the tile to cache.\n * @param {OpenSeadragon.TiledImage} options.tiledImage - The TiledImage that owns that tile.\n * @param {Number} [options.cutoff=0] - If adding this tile goes over the cache max count, this\n * function will release an old tile. The cutoff option specifies a tile level at or below which\n * tiles will not be released.\n */\n cacheTile: function( options ) {\n $.console.assert( options, \"[TileCache.cacheTile] options is required\" );\n $.console.assert( options.tile, \"[TileCache.cacheTile] options.tile is required\" );\n $.console.assert( options.tile.cacheKey, \"[TileCache.cacheTile] options.tile.cacheKey is required\" );\n $.console.assert( options.tiledImage, \"[TileCache.cacheTile] options.tiledImage is required\" );\n\n var cutoff = options.cutoff || 0;\n var insertionIndex = this._tilesLoaded.length;\n\n var imageRecord = this._imagesLoaded[options.tile.cacheKey];\n if (!imageRecord) {\n $.console.assert( options.image, \"[TileCache.cacheTile] options.image is required to create an ImageRecord\" );\n imageRecord = this._imagesLoaded[options.tile.cacheKey] = new ImageRecord({\n image: options.image\n });\n\n this._imagesLoadedCount++;\n }\n\n imageRecord.addTile(options.tile);\n options.tile.cacheImageRecord = imageRecord;\n\n // Note that just because we're unloading a tile doesn't necessarily mean\n // we're unloading an image. With repeated calls it should sort itself out, though.\n if ( this._imagesLoadedCount > this._maxImageCacheCount ) {\n var worstTile = null;\n var worstTileIndex = -1;\n var worstTileRecord = null;\n var prevTile, worstTime, worstLevel, prevTime, prevLevel, prevTileRecord;\n\n for ( var i = this._tilesLoaded.length - 1; i >= 0; i-- ) {\n prevTileRecord = this._tilesLoaded[ i ];\n prevTile = prevTileRecord.tile;\n\n if ( prevTile.level <= cutoff || prevTile.beingDrawn ) {\n continue;\n } else if ( !worstTile ) {\n worstTile = prevTile;\n worstTileIndex = i;\n worstTileRecord = prevTileRecord;\n continue;\n }\n\n prevTime = prevTile.lastTouchTime;\n worstTime = worstTile.lastTouchTime;\n prevLevel = prevTile.level;\n worstLevel = worstTile.level;\n\n if ( prevTime < worstTime ||\n ( prevTime == worstTime && prevLevel > worstLevel ) ) {\n worstTile = prevTile;\n worstTileIndex = i;\n worstTileRecord = prevTileRecord;\n }\n }\n\n if ( worstTile && worstTileIndex >= 0 ) {\n this._unloadTile(worstTileRecord);\n insertionIndex = worstTileIndex;\n }\n }\n\n this._tilesLoaded[ insertionIndex ] = new TileRecord({\n tile: options.tile,\n tiledImage: options.tiledImage\n });\n },\n\n /**\n * Clears all tiles associated with the specified tiledImage.\n * @param {OpenSeadragon.TiledImage} tiledImage\n */\n clearTilesFor: function( tiledImage ) {\n $.console.assert(tiledImage, '[TileCache.clearTilesFor] tiledImage is required');\n var tileRecord;\n for ( var i = 0; i < this._tilesLoaded.length; ++i ) {\n tileRecord = this._tilesLoaded[ i ];\n if ( tileRecord.tiledImage === tiledImage ) {\n this._unloadTile(tileRecord);\n this._tilesLoaded.splice( i, 1 );\n i--;\n }\n }\n },\n\n // private\n getImageRecord: function(cacheKey) {\n $.console.assert(cacheKey, '[TileCache.getImageRecord] cacheKey is required');\n return this._imagesLoaded[cacheKey];\n },\n\n // private\n _unloadTile: function(tileRecord) {\n $.console.assert(tileRecord, '[TileCache._unloadTile] tileRecord is required');\n var tile = tileRecord.tile;\n var tiledImage = tileRecord.tiledImage;\n\n tile.unload();\n tile.cacheImageRecord = null;\n\n var imageRecord = this._imagesLoaded[tile.cacheKey];\n imageRecord.removeTile(tile);\n if (!imageRecord.getTileCount()) {\n imageRecord.destroy();\n delete this._imagesLoaded[tile.cacheKey];\n this._imagesLoadedCount--;\n }\n\n /**\n * Triggered when a tile has just been unloaded from memory.\n *\n * @event tile-unloaded\n * @memberof OpenSeadragon.Viewer\n * @type {object}\n * @property {OpenSeadragon.TiledImage} tiledImage - The tiled image of the unloaded tile.\n * @property {OpenSeadragon.Tile} tile - The tile which has been unloaded.\n */\n tiledImage.viewer.raiseEvent(\"tile-unloaded\", {\n tile: tile,\n tiledImage: tiledImage\n });\n }\n};\n\n}( OpenSeadragon ));\n\n/*\n * OpenSeadragon - World\n *\n * Copyright (C) 2009 CodePlex Foundation\n * Copyright (C) 2010-2013 OpenSeadragon contributors\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of CodePlex Foundation nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n(function( $ ){\n\n/**\n * @class World\n * @memberof OpenSeadragon\n * @extends OpenSeadragon.EventSource\n * @classdesc Keeps track of all of the tiled images in the scene.\n * @param {Object} options - World options.\n * @param {OpenSeadragon.Viewer} options.viewer - The Viewer that owns this World.\n **/\n$.World = function( options ) {\n var _this = this;\n\n $.console.assert( options.viewer, \"[World] options.viewer is required\" );\n\n $.EventSource.call( this );\n\n this.viewer = options.viewer;\n this._items = [];\n this._needsDraw = false;\n this._autoRefigureSizes = true;\n this._needsSizesFigured = false;\n this._delegatedFigureSizes = function(event) {\n if (_this._autoRefigureSizes) {\n _this._figureSizes();\n } else {\n _this._needsSizesFigured = true;\n }\n };\n\n this._figureSizes();\n};\n\n$.extend( $.World.prototype, $.EventSource.prototype, /** @lends OpenSeadragon.World.prototype */{\n /**\n * Add the specified item.\n * @param {OpenSeadragon.TiledImage} item - The item to add.\n * @param {Number} [options.index] - Index for the item. If not specified, goes at the top.\n * @fires OpenSeadragon.World.event:add-item\n * @fires OpenSeadragon.World.event:metrics-change\n */\n addItem: function( item, options ) {\n $.console.assert(item, \"[World.addItem] item is required\");\n $.console.assert(item instanceof $.TiledImage, \"[World.addItem] only TiledImages supported at this time\");\n\n options = options || {};\n if (options.index !== undefined) {\n var index = Math.max(0, Math.min(this._items.length, options.index));\n this._items.splice(index, 0, item);\n } else {\n this._items.push( item );\n }\n\n if (this._autoRefigureSizes) {\n this._figureSizes();\n } else {\n this._needsSizesFigured = true;\n }\n\n this._needsDraw = true;\n\n item.addHandler('bounds-change', this._delegatedFigureSizes);\n item.addHandler('clip-change', this._delegatedFigureSizes);\n\n /**\n * Raised when an item is added to the World.\n * @event add-item\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.Viewer} eventSource - A reference to the World which raised the event.\n * @property {OpenSeadragon.TiledImage} item - The item that has been added.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'add-item', {\n item: item\n } );\n },\n\n /**\n * Get the item at the specified index.\n * @param {Number} index - The item's index.\n * @returns {OpenSeadragon.TiledImage} The item at the specified index.\n */\n getItemAt: function( index ) {\n $.console.assert(index !== undefined, \"[World.getItemAt] index is required\");\n return this._items[ index ];\n },\n\n /**\n * Get the index of the given item or -1 if not present.\n * @param {OpenSeadragon.TiledImage} item - The item.\n * @returns {Number} The index of the item or -1 if not present.\n */\n getIndexOfItem: function( item ) {\n $.console.assert(item, \"[World.getIndexOfItem] item is required\");\n return $.indexOf( this._items, item );\n },\n\n /**\n * @returns {Number} The number of items used.\n */\n getItemCount: function() {\n return this._items.length;\n },\n\n /**\n * Change the index of a item so that it appears over or under others.\n * @param {OpenSeadragon.TiledImage} item - The item to move.\n * @param {Number} index - The new index.\n * @fires OpenSeadragon.World.event:item-index-change\n */\n setItemIndex: function( item, index ) {\n $.console.assert(item, \"[World.setItemIndex] item is required\");\n $.console.assert(index !== undefined, \"[World.setItemIndex] index is required\");\n\n var oldIndex = this.getIndexOfItem( item );\n\n if ( index >= this._items.length ) {\n throw new Error( \"Index bigger than number of layers.\" );\n }\n\n if ( index === oldIndex || oldIndex === -1 ) {\n return;\n }\n\n this._items.splice( oldIndex, 1 );\n this._items.splice( index, 0, item );\n this._needsDraw = true;\n\n /**\n * Raised when the order of the indexes has been changed.\n * @event item-index-change\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.\n * @property {OpenSeadragon.TiledImage} item - The item whose index has\n * been changed\n * @property {Number} previousIndex - The previous index of the item\n * @property {Number} newIndex - The new index of the item\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'item-index-change', {\n item: item,\n previousIndex: oldIndex,\n newIndex: index\n } );\n },\n\n /**\n * Remove an item.\n * @param {OpenSeadragon.TiledImage} item - The item to remove.\n * @fires OpenSeadragon.World.event:remove-item\n * @fires OpenSeadragon.World.event:metrics-change\n */\n removeItem: function( item ) {\n $.console.assert(item, \"[World.removeItem] item is required\");\n\n var index = $.indexOf(this._items, item );\n if ( index === -1 ) {\n return;\n }\n\n item.removeHandler('bounds-change', this._delegatedFigureSizes);\n item.removeHandler('clip-change', this._delegatedFigureSizes);\n item.destroy();\n this._items.splice( index, 1 );\n this._figureSizes();\n this._needsDraw = true;\n this._raiseRemoveItem(item);\n },\n\n /**\n * Remove all items.\n * @fires OpenSeadragon.World.event:remove-item\n * @fires OpenSeadragon.World.event:metrics-change\n */\n removeAll: function() {\n // We need to make sure any pending images are canceled so the world items don't get messed up\n this.viewer._cancelPendingImages();\n var item;\n var i;\n for (i = 0; i < this._items.length; i++) {\n item = this._items[i];\n item.removeHandler('bounds-change', this._delegatedFigureSizes);\n item.removeHandler('clip-change', this._delegatedFigureSizes);\n item.destroy();\n }\n\n var removedItems = this._items;\n this._items = [];\n this._figureSizes();\n this._needsDraw = true;\n\n for (i = 0; i < removedItems.length; i++) {\n item = removedItems[i];\n this._raiseRemoveItem(item);\n }\n },\n\n /**\n * Clears all tiles and triggers updates for all items.\n */\n resetItems: function() {\n for ( var i = 0; i < this._items.length; i++ ) {\n this._items[i].reset();\n }\n },\n\n /**\n * Updates (i.e. animates bounds of) all items.\n */\n update: function() {\n var animated = false;\n for ( var i = 0; i < this._items.length; i++ ) {\n animated = this._items[i].update() || animated;\n }\n\n return animated;\n },\n\n /**\n * Draws all items.\n */\n draw: function() {\n for ( var i = 0; i < this._items.length; i++ ) {\n this._items[i].draw();\n }\n\n this._needsDraw = false;\n },\n\n /**\n * @returns {Boolean} true if any items need updating.\n */\n needsDraw: function() {\n for ( var i = 0; i < this._items.length; i++ ) {\n if ( this._items[i].needsDraw() ) {\n return true;\n }\n }\n return this._needsDraw;\n },\n\n /**\n * @returns {OpenSeadragon.Rect} The smallest rectangle that encloses all items, in viewport coordinates.\n */\n getHomeBounds: function() {\n return this._homeBounds.clone();\n },\n\n /**\n * To facilitate zoom constraints, we keep track of the pixel density of the\n * densest item in the World (i.e. the item whose content size to viewport size\n * ratio is the highest) and save it as this \"content factor\".\n * @returns {Number} the number of content units per viewport unit.\n */\n getContentFactor: function() {\n return this._contentFactor;\n },\n\n /**\n * As a performance optimization, setting this flag to false allows the bounds-change event handler\n * on tiledImages to skip calculations on the world bounds. If a lot of images are going to be positioned in\n * rapid succession, this is a good idea. When finished, setAutoRefigureSizes should be called with true\n * or the system may behave oddly.\n * @param {Boolean} [value] The value to which to set the flag.\n */\n setAutoRefigureSizes: function(value) {\n this._autoRefigureSizes = value;\n if (value & this._needsSizesFigured) {\n this._figureSizes();\n this._needsSizesFigured = false;\n }\n },\n\n /**\n * Arranges all of the TiledImages with the specified settings.\n * @param {Object} options - Specifies how to arrange.\n * @param {Boolean} [options.immediately=false] - Whether to animate to the new arrangement.\n * @param {String} [options.layout] - See collectionLayout in {@link OpenSeadragon.Options}.\n * @param {Number} [options.rows] - See collectionRows in {@link OpenSeadragon.Options}.\n * @param {Number} [options.columns] - See collectionColumns in {@link OpenSeadragon.Options}.\n * @param {Number} [options.tileSize] - See collectionTileSize in {@link OpenSeadragon.Options}.\n * @param {Number} [options.tileMargin] - See collectionTileMargin in {@link OpenSeadragon.Options}.\n * @fires OpenSeadragon.World.event:metrics-change\n */\n arrange: function(options) {\n options = options || {};\n var immediately = options.immediately || false;\n var layout = options.layout || $.DEFAULT_SETTINGS.collectionLayout;\n var rows = options.rows || $.DEFAULT_SETTINGS.collectionRows;\n var columns = options.columns || $.DEFAULT_SETTINGS.collectionColumns;\n var tileSize = options.tileSize || $.DEFAULT_SETTINGS.collectionTileSize;\n var tileMargin = options.tileMargin || $.DEFAULT_SETTINGS.collectionTileMargin;\n var increment = tileSize + tileMargin;\n var wrap;\n if (!options.rows && columns) {\n wrap = columns;\n } else {\n wrap = Math.ceil(this._items.length / rows);\n }\n var x = 0;\n var y = 0;\n var item, box, width, height, position;\n\n this.setAutoRefigureSizes(false);\n for (var i = 0; i < this._items.length; i++) {\n if (i && (i % wrap) === 0) {\n if (layout === 'horizontal') {\n y += increment;\n x = 0;\n } else {\n x += increment;\n y = 0;\n }\n }\n\n item = this._items[i];\n box = item.getBounds();\n if (box.width > box.height) {\n width = tileSize;\n } else {\n width = tileSize * (box.width / box.height);\n }\n\n height = width * (box.height / box.width);\n position = new $.Point(x + ((tileSize - width) / 2),\n y + ((tileSize - height) / 2));\n\n item.setPosition(position, immediately);\n item.setWidth(width, immediately);\n\n if (layout === 'horizontal') {\n x += increment;\n } else {\n y += increment;\n }\n }\n this.setAutoRefigureSizes(true);\n },\n\n // private\n _figureSizes: function() {\n var oldHomeBounds = this._homeBounds ? this._homeBounds.clone() : null;\n var oldContentSize = this._contentSize ? this._contentSize.clone() : null;\n var oldContentFactor = this._contentFactor || 0;\n\n if (!this._items.length) {\n this._homeBounds = new $.Rect(0, 0, 1, 1);\n this._contentSize = new $.Point(1, 1);\n this._contentFactor = 1;\n } else {\n var item = this._items[0];\n var bounds = item.getBounds();\n this._contentFactor = item.getContentSize().x / bounds.width;\n var clippedBounds = item.getClippedBounds().getBoundingBox();\n var left = clippedBounds.x;\n var top = clippedBounds.y;\n var right = clippedBounds.x + clippedBounds.width;\n var bottom = clippedBounds.y + clippedBounds.height;\n for (var i = 1; i < this._items.length; i++) {\n item = this._items[i];\n bounds = item.getBounds();\n this._contentFactor = Math.max(this._contentFactor,\n item.getContentSize().x / bounds.width);\n clippedBounds = item.getClippedBounds().getBoundingBox();\n left = Math.min(left, clippedBounds.x);\n top = Math.min(top, clippedBounds.y);\n right = Math.max(right, clippedBounds.x + clippedBounds.width);\n bottom = Math.max(bottom, clippedBounds.y + clippedBounds.height);\n }\n\n this._homeBounds = new $.Rect(left, top, right - left, bottom - top);\n this._contentSize = new $.Point(\n this._homeBounds.width * this._contentFactor,\n this._homeBounds.height * this._contentFactor);\n }\n\n if (this._contentFactor !== oldContentFactor ||\n !this._homeBounds.equals(oldHomeBounds) ||\n !this._contentSize.equals(oldContentSize)) {\n /**\n * Raised when the home bounds or content factor change.\n * @event metrics-change\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent('metrics-change', {});\n }\n },\n\n // private\n _raiseRemoveItem: function(item) {\n /**\n * Raised when an item is removed.\n * @event remove-item\n * @memberOf OpenSeadragon.World\n * @type {object}\n * @property {OpenSeadragon.World} eventSource - A reference to the World which raised the event.\n * @property {OpenSeadragon.TiledImage} item - The item's underlying item.\n * @property {?Object} userData - Arbitrary subscriber-defined object.\n */\n this.raiseEvent( 'remove-item', { item: item } );\n }\n});\n\n}( OpenSeadragon ));\n\n//# sourceMappingURL=openseadragon.js.map\n\n//# sourceURL=webpack:///./node_modules/openseadragon/build/openseadragon/openseadragon.js?"); /***/ }), @@ -7976,19 +7976,7 @@ eval("module.exports = function(module) {\n\tif (!module.webpackPolyfill) {\n\t\ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var buffer___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer/ */ \"./node_modules/node-libs-browser/node_modules/buffer/index.js\");\n/* harmony import */ var buffer___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer___WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var pngjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! pngjs */ \"./node_modules/pngjs/lib/png.js\");\n/* harmony import */ var pngjs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(pngjs__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var popper_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! popper.js */ \"./node_modules/popper.js/dist/esm/popper.js\");\n/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\");\n/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var bootstrap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! bootstrap */ \"./node_modules/bootstrap/dist/js/bootstrap.js\");\n/* harmony import */ var bootstrap__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(bootstrap__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! bootstrap/dist/css/bootstrap.min.css */ \"./node_modules/bootstrap/dist/css/bootstrap.min.css\");\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_5__);\n/* harmony import */ var regenerator_runtime__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! regenerator-runtime */ \"./node_modules/regenerator-runtime/runtime.js\");\n/* harmony import */ var regenerator_runtime__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(regenerator_runtime__WEBPACK_IMPORTED_MODULE_6__);\n/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! d3 */ \"./node_modules/d3/index.js\");\n/* harmony import */ var d3_simple_slider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! d3-simple-slider */ \"./node_modules/d3-simple-slider/src/index.js\");\n/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\n/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_9__);\n/* harmony import */ var jquery_form__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! jquery-form */ \"./node_modules/jquery-form/dist/jquery.form.min.js\");\n/* harmony import */ var jquery_form__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jquery_form__WEBPACK_IMPORTED_MODULE_10__);\n/* harmony import */ var _fortawesome_fontawesome_free_js_all__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @fortawesome/fontawesome-free/js/all */ \"./node_modules/@fortawesome/fontawesome-free/js/all.js\");\n/* harmony import */ var _fortawesome_fontawesome_free_js_all__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_fortawesome_fontawesome_free_js_all__WEBPACK_IMPORTED_MODULE_11__);\n/* harmony import */ var sortablejs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! sortablejs */ \"./node_modules/sortablejs/modular/sortable.esm.js\");\n/* harmony import */ var mark_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! mark.js */ \"./node_modules/mark.js/dist/mark.js\");\n/* harmony import */ var mark_js__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(mark_js__WEBPACK_IMPORTED_MODULE_13__);\n/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! node-fetch */ \"./node_modules/node-fetch/browser.js\");\n/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(node_fetch__WEBPACK_IMPORTED_MODULE_14__);\n/* harmony import */ var color_convert__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! color-convert */ \"./node_modules/color-convert/index.js\");\n/* harmony import */ var color_convert__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(color_convert__WEBPACK_IMPORTED_MODULE_15__);\n/* harmony import */ var viawebgl__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! viawebgl */ \"./node_modules/viawebgl/tools/index.js\");\n/* harmony import */ var viawebgl__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(viawebgl__WEBPACK_IMPORTED_MODULE_16__);\n/* harmony import */ var _views_viewerManager__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./views/viewerManager */ \"./src/js/views/viewerManager.js\");\n/* harmony import */ var dropzone__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! dropzone */ \"./node_modules/dropzone/dist/dropzone.js\");\n/* harmony import */ var dropzone__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(dropzone__WEBPACK_IMPORTED_MODULE_18__);\n/* harmony import */ var _views_CsvGatingOverlay__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(/*! ./views/CsvGatingOverlay */ \"./src/js/views/CsvGatingOverlay.js\");\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwindow.convert = color_convert__WEBPACK_IMPORTED_MODULE_15___default.a;\nwindow.$ = jquery__WEBPACK_IMPORTED_MODULE_3___default.a;\nwindow.d3 = d3__WEBPACK_IMPORTED_MODULE_7__;\nwindow.d3.sliderBottom = d3_simple_slider__WEBPACK_IMPORTED_MODULE_8__[\"sliderBottom\"];\nwindow.PNG = pngjs__WEBPACK_IMPORTED_MODULE_1__[\"PNG\"];\nwindow.Buffer = buffer___WEBPACK_IMPORTED_MODULE_0__[\"Buffer\"];\nwindow.Sortable = sortablejs__WEBPACK_IMPORTED_MODULE_12__[\"default\"];\nwindow.Mark = mark_js__WEBPACK_IMPORTED_MODULE_13___default.a;\nwindow.OpenSeadragon = viawebgl__WEBPACK_IMPORTED_MODULE_16__[\"OpenSeadragon\"];\nwindow.Dropzone = dropzone__WEBPACK_IMPORTED_MODULE_18___default.a;\nwindow.CsvGatingOverlay = _views_CsvGatingOverlay__WEBPACK_IMPORTED_MODULE_19__[\"CsvGatingOverlay\"];\nwindow.viaWebGL = viawebgl__WEBPACK_IMPORTED_MODULE_16__;\nwindow.ViewerManager = _views_viewerManager__WEBPACK_IMPORTED_MODULE_17__[\"ViewerManager\"];\n\n//# sourceURL=webpack:///./src/js/vendor.js?"); - -/***/ }), - -/***/ "./src/js/views/CsvGatingOverlay.js": -/*!******************************************!*\ - !*** ./src/js/views/CsvGatingOverlay.js ***! - \******************************************/ -/*! exports provided: CsvGatingOverlay */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"CsvGatingOverlay\", function() { return CsvGatingOverlay; });\nfunction _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== \"undefined\" && o[Symbol.iterator] || o[\"@@iterator\"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === \"number\") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError(\"Invalid attempt to iterate non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it[\"return\"] != null) it[\"return\"](); } finally { if (didErr) throw err; } } }; }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\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/**\n * @class CsvGatingOverlay\n *\n * TODO:\n * 1. Query only for add / remove channels; filter for gating adjustments\n * 2. Stall animation triggered draw iterations when awaiting query\n * 3. Make code more modular (move out of main) - maybe keep in imageViewer and csvGatingList\n *\n */\nvar CsvGatingOverlay = /*#__PURE__*/function () {\n // Vars\n // Configs\n // Tools\n\n /**\n * @constructor\n *\n * @param _viewer\n */\n function CsvGatingOverlay(viewer, imageViewer) {\n _classCallCheck(this, CsvGatingOverlay);\n\n _defineProperty(this, \"canvas\", null);\n\n _defineProperty(this, \"cleared\", true);\n\n _defineProperty(this, \"context\", null);\n\n _defineProperty(this, \"force\", false);\n\n _defineProperty(this, \"image_rect\", {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n degrees: 0\n });\n\n _defineProperty(this, \"viewer_rect\", {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n degrees: 0\n });\n\n _defineProperty(this, \"range\", [[], []]);\n\n _defineProperty(this, \"run_balancer\", 0);\n\n _defineProperty(this, \"show_centroids\", false);\n\n _defineProperty(this, \"configs\", {\n radius: [2, 15],\n px_ratio: 2,\n stroke: 2\n });\n\n _defineProperty(this, \"coord_scale_x\", d3.scaleLinear());\n\n _defineProperty(this, \"coord_scale_y\", d3.scaleLinear());\n\n _defineProperty(this, \"r_scale\", d3.scalePow().exponent(0.5).range(this.configs.radius));\n\n _defineProperty(this, \"channel_scale\", d3.scaleLinear().range([-Math.PI / 2, Math.PI * 3 / 2]));\n\n // Init vars\n this.viewer = viewer;\n this.image_viewer = imageViewer;\n this.channel_list = channelList;\n this.gating_list = csv_gatingList;\n this.dataLayer = dataLayer;\n this.eventHandler = eventHandler;\n this.init();\n }\n /** 1.\n * @function init\n *\n * @return void\n */\n\n\n _createClass(CsvGatingOverlay, [{\n key: \"init\",\n value: function init() {\n // Get viewer container, append canvas\n var osdContainer = this.viewer.canvas.parentElement;\n this.canvas = d3.select(osdContainer).append('canvas').attr('id', 'gating_overlay_canvas').attr('width', osdContainer.clientWidth * this.configs.px_ratio).attr('height', osdContainer.clientHeight * this.configs.px_ratio).style('width', '100%').style('height', '100%').style('position', 'absolute').style('pointer-events', 'none');\n this.context = this.canvas.node().getContext('2d'); // Add event\n\n this.image_viewer.viewer.addHandler('animation-start', this.clear.bind(this));\n this.image_viewer.viewer.addHandler('animation-finish', this.evaluate.bind(this)); // Handle channel list color changes\n }\n /** 2.\n * @function evaluate\n *\n * @event e\n *\n * @return void\n */\n\n }, {\n key: \"evaluate\",\n value: function evaluate() {\n var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n // Get viewer bounds\n var viewer_rect = this.viewer.viewport.getBounds(); // Cement viewer rect\n\n this.viewer_rect = viewer_rect; // Get image coordinates\n\n this.image_rect = this.viewer.world.getItemAt(0).viewportToImageRectangle(this.viewer_rect);\n this.range = [[this.image_rect.x, this.image_rect.y], [this.image_rect.x + this.image_rect.width, this.image_rect.y + this.image_rect.height]]; // If run balancer evens out (strategy for getting last request -\n // run_balancer++ in csvGatingList, run_balancer-- in main\n // FIXME - would be better to nest all references for gating in gating plugin packages\n // if (this.run_balancer === 0) {\n // Draw\n\n this.draw(); // }\n }\n /** 3.\n * @function draw\n *\n * @return void\n */\n\n }, {\n key: \"draw\",\n value: function draw() {\n var _this = this;\n\n // Bounce if centroids off\n if (!this.show_centroids) {\n this.clear();\n return;\n } // Clear if not clear\n\n\n if (!this.cleared) {\n this.clear();\n } // Context\n\n\n var ctx = this.context;\n var w = this.canvas.attr('width');\n var h = this.canvas.attr('height'); // Update scales\n\n this.coord_scale_x.domain([this.range[0][0], this.range[1][0]]).range([0, w]);\n this.coord_scale_y.domain([this.range[0][1], this.range[1][1]]).range([0, h]);\n this.r_scale.domain([this.viewer.viewport.getMinZoom(), this.viewer.viewport.getMaxZoom()]); // Calc radius\n\n var r = this.r_scale(this.viewer.viewport.getZoom()).toFixed(2); // Get cells in range\n\n var _iterator = _createForOfIteratorHelper(this.image_viewer.selection.keys()),\n _step;\n\n try {\n var _loop = function _loop() {\n var k = _step.value;\n\n // Get values\n var values = _this.image_viewer.selection.get(k); // Position condition\n\n\n var xAlias = _this.dataLayer.config.featureData[0].xCoordinate;\n var yAlias = _this.dataLayer.config.featureData[0].yCoordinate;\n\n if (values[xAlias] >= _this.range[0][0] && values[xAlias] <= _this.range[1][0] && values[yAlias] >= _this.range[0][1] && values[yAlias] <= _this.range[1][1]) {\n // Get coords\n var x = _this.coord_scale_x(values[xAlias]);\n\n var y = _this.coord_scale_y(values[yAlias]); // Draw circles - placeholder\n\n\n ctx.strokeStyle = 'white';\n ctx.lineWidth = _this.configs.stroke * _this.configs.px_ratio; // Save context\n\n ctx.save(); // Place in\n\n requestAnimationFrame(function () {\n // Match to channel color\n var gatingChannelIndices = [];\n\n var _loop2 = function _loop2(key) {\n _this.channel_list.columns.forEach(function (c, i) {\n if (_this.dataLayer.getShortChannelName(key) === c) {\n // Define current channel\n var channel = _this.gating_list.selections[key];\n\n if (values[key] >= channel[0] && values[key] <= channel[1]) {\n gatingChannelIndices.push({\n key: key,\n value: values[key],\n index: i + 1\n });\n }\n }\n });\n };\n\n for (var key in _this.gating_list.selections) {\n _loop2(key);\n } // Update scale\n\n\n _this.channel_scale.domain([0, gatingChannelIndices.length]); // this.gating_list.forEach(c => {\n\n\n gatingChannelIndices.forEach(function (d, i) {\n // Retrieve color (FIXME - need to integrate into viewer manager)\n // const rgb = evaluateTF(values[channel], this.image_viewer.channelTF[gatingChannelIndices[i]]);\n // ctx.fillStyle = `rgb(${Math.round(rgb.r)}, ${Math.round(rgb.g)}, ${Math.round(rgb.b)})`;\n // ctx.fillStyle = this.image_viewer.channelTF[gatingChannelIndices[i].index].end_color;\n // ctx.fillStyle = this.global_channel_list.currentChannels[gatingChannelIndices[i].index]['color'];\n ctx.fillStyle = _this.rgbToHex(_this.channel_list.currentChannels[gatingChannelIndices[i].index]['color']);\n ctx.beginPath();\n ctx.moveTo(x, y);\n ctx.arc(x, y, r * _this.configs.px_ratio, _this.channel_scale(i), _this.channel_scale(i + 1));\n ctx.lineWidth = _this.configs.px_ratio;\n ctx.closePath();\n ctx.stroke();\n ctx.fill();\n });\n });\n ctx.restore();\n }\n };\n\n for (_iterator.s(); !(_step = _iterator.n()).done;) {\n _loop();\n } // Mark as not cleared\n\n } catch (err) {\n _iterator.e(err);\n } finally {\n _iterator.f();\n }\n\n this.cleared = false;\n }\n }, {\n key: \"rgbToHex\",\n value: function rgbToHex(color) {\n return '#' + [color.r, color.g, color.b].map(function (x) {\n var hex = Math.round(x).toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n }).join('');\n }\n /** 4.\n * @function clear\n *\n * @param {Event} e\n *\n * @return void\n */\n\n }, {\n key: \"clear\",\n value: function clear() {\n var _this2 = this;\n\n var e = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;\n // Context\n var ctx = this.context;\n var w = this.canvas.attr('width');\n var h = this.canvas.attr('height'); // Clear rect\n\n requestAnimationFrame(function () {\n ctx.clearRect(0, 0, w, h);\n _this2.cleared = true;\n });\n }\n /**\n * @function control\n *\n * @param show\n */\n\n }, {\n key: \"control\",\n value: function control(show) {\n // Update mode\n this.show_centroids = show; // Trigger event\n\n this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, this.gating_list.selections);\n }\n }]);\n\n return CsvGatingOverlay;\n}();\n\n//# sourceURL=webpack:///./src/js/views/CsvGatingOverlay.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var buffer___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! buffer/ */ \"./node_modules/node-libs-browser/node_modules/buffer/index.js\");\n/* harmony import */ var buffer___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(buffer___WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var pngjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! pngjs */ \"./node_modules/pngjs/lib/png.js\");\n/* harmony import */ var pngjs__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(pngjs__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var popper_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! popper.js */ \"./node_modules/popper.js/dist/esm/popper.js\");\n/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! jquery */ \"./node_modules/jquery/dist/jquery.js\");\n/* harmony import */ var jquery__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(jquery__WEBPACK_IMPORTED_MODULE_3__);\n/* harmony import */ var bootstrap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! bootstrap */ \"./node_modules/bootstrap/dist/js/bootstrap.js\");\n/* harmony import */ var bootstrap__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(bootstrap__WEBPACK_IMPORTED_MODULE_4__);\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! bootstrap/dist/css/bootstrap.min.css */ \"./node_modules/bootstrap/dist/css/bootstrap.min.css\");\n/* harmony import */ var bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(bootstrap_dist_css_bootstrap_min_css__WEBPACK_IMPORTED_MODULE_5__);\n/* harmony import */ var regenerator_runtime__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! regenerator-runtime */ \"./node_modules/regenerator-runtime/runtime.js\");\n/* harmony import */ var regenerator_runtime__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(regenerator_runtime__WEBPACK_IMPORTED_MODULE_6__);\n/* harmony import */ var d3__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! d3 */ \"./node_modules/d3/index.js\");\n/* harmony import */ var d3_simple_slider__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(/*! d3-simple-slider */ \"./node_modules/d3-simple-slider/src/index.js\");\n/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\n/* harmony import */ var lodash__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(lodash__WEBPACK_IMPORTED_MODULE_9__);\n/* harmony import */ var jquery_form__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(/*! jquery-form */ \"./node_modules/jquery-form/dist/jquery.form.min.js\");\n/* harmony import */ var jquery_form__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jquery_form__WEBPACK_IMPORTED_MODULE_10__);\n/* harmony import */ var _fortawesome_fontawesome_free_js_all__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(/*! @fortawesome/fontawesome-free/js/all */ \"./node_modules/@fortawesome/fontawesome-free/js/all.js\");\n/* harmony import */ var _fortawesome_fontawesome_free_js_all__WEBPACK_IMPORTED_MODULE_11___default = /*#__PURE__*/__webpack_require__.n(_fortawesome_fontawesome_free_js_all__WEBPACK_IMPORTED_MODULE_11__);\n/* harmony import */ var sortablejs__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(/*! sortablejs */ \"./node_modules/sortablejs/modular/sortable.esm.js\");\n/* harmony import */ var mark_js__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(/*! mark.js */ \"./node_modules/mark.js/dist/mark.js\");\n/* harmony import */ var mark_js__WEBPACK_IMPORTED_MODULE_13___default = /*#__PURE__*/__webpack_require__.n(mark_js__WEBPACK_IMPORTED_MODULE_13__);\n/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(/*! node-fetch */ \"./node_modules/node-fetch/browser.js\");\n/* harmony import */ var node_fetch__WEBPACK_IMPORTED_MODULE_14___default = /*#__PURE__*/__webpack_require__.n(node_fetch__WEBPACK_IMPORTED_MODULE_14__);\n/* harmony import */ var color_convert__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(/*! color-convert */ \"./node_modules/color-convert/index.js\");\n/* harmony import */ var color_convert__WEBPACK_IMPORTED_MODULE_15___default = /*#__PURE__*/__webpack_require__.n(color_convert__WEBPACK_IMPORTED_MODULE_15__);\n/* harmony import */ var viawebgl__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(/*! viawebgl */ \"./node_modules/viawebgl/tools/index.js\");\n/* harmony import */ var viawebgl__WEBPACK_IMPORTED_MODULE_16___default = /*#__PURE__*/__webpack_require__.n(viawebgl__WEBPACK_IMPORTED_MODULE_16__);\n/* harmony import */ var _views_viewerManager__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(/*! ./views/viewerManager */ \"./src/js/views/viewerManager.js\");\n/* harmony import */ var dropzone__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(/*! dropzone */ \"./node_modules/dropzone/dist/dropzone.js\");\n/* harmony import */ var dropzone__WEBPACK_IMPORTED_MODULE_18___default = /*#__PURE__*/__webpack_require__.n(dropzone__WEBPACK_IMPORTED_MODULE_18__);\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwindow.convert = color_convert__WEBPACK_IMPORTED_MODULE_15___default.a;\nwindow.$ = jquery__WEBPACK_IMPORTED_MODULE_3___default.a;\nwindow.d3 = d3__WEBPACK_IMPORTED_MODULE_7__;\nwindow.d3.sliderBottom = d3_simple_slider__WEBPACK_IMPORTED_MODULE_8__[\"sliderBottom\"];\nwindow.PNG = pngjs__WEBPACK_IMPORTED_MODULE_1__[\"PNG\"];\nwindow.Buffer = buffer___WEBPACK_IMPORTED_MODULE_0__[\"Buffer\"];\nwindow.Sortable = sortablejs__WEBPACK_IMPORTED_MODULE_12__[\"default\"];\nwindow.Mark = mark_js__WEBPACK_IMPORTED_MODULE_13___default.a;\nwindow.OpenSeadragon = viawebgl__WEBPACK_IMPORTED_MODULE_16__[\"OpenSeadragon\"];\nwindow.Dropzone = dropzone__WEBPACK_IMPORTED_MODULE_18___default.a;\nwindow.viaWebGL = viawebgl__WEBPACK_IMPORTED_MODULE_16__;\nwindow.ViewerManager = _views_viewerManager__WEBPACK_IMPORTED_MODULE_17__[\"ViewerManager\"];\n\n//# sourceURL=webpack:///./src/js/vendor.js?"); /***/ }), @@ -8000,7 +7988,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) * /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ViewerManager\", function() { return ViewerManager; });\n/* harmony import */ var regenerator_runtime_runtime_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! regenerator-runtime/runtime.js */ \"./node_modules/regenerator-runtime/runtime.js\");\n/* harmony import */ var regenerator_runtime_runtime_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regenerator_runtime_runtime_js__WEBPACK_IMPORTED_MODULE_0__);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\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\n/**\n * @class ViewerManager\n */\n\nvar ViewerManager = /*#__PURE__*/function () {\n /**\n * @constructor\n * Constructs a ColorManager instance before delegating initialization.\n *\n * @param {Object} _viewer\n */\n function ViewerManager(_imageViewer, _viewer, _viewerName) {\n _classCallCheck(this, ViewerManager);\n\n _defineProperty(this, \"colorConnector\", {});\n\n _defineProperty(this, \"rangeConnector\", {});\n\n _defineProperty(this, \"show_sel\", true);\n\n _defineProperty(this, \"sel_outlines\", true);\n\n this.viewer = _viewer;\n this.imageViewer = _imageViewer;\n this.viewer_name = _viewerName;\n this.viewer_channels = {};\n this.channelList = channelList;\n this.init();\n }\n /**\n * @function init\n * Setups up the color manager.\n *\n * @returns void\n */\n\n\n _createClass(ViewerManager, [{\n key: \"init\",\n value: function init() {\n // Load label image\n this.load_label_image();\n }\n /**\n * @function channel_add\n * Add channel to multi-channel rendering\n *\n * @param srcIdx\n */\n\n }, {\n key: \"channel_add\",\n value: function channel_add(srcIdx) {\n var _this = this;\n\n var self = this; // If already exists\n\n if (srcIdx in this.channelList.currentChannels) {\n return;\n } // Get dzi path\n\n\n var src = this.imageViewer.config[\"imageData\"][srcIdx][\"src\"]; // Find name\n\n var name = '';\n var name_short = '';\n\n for (var k in imageChannels) {\n if (imageChannels.hasOwnProperty(k) && imageChannels[k] === srcIdx) {\n name = k;\n name_short = dataLayer.getShortChannelName(k);\n }\n }\n\n var maxLevel = this.imageViewer.config['maxLevel'] - 1; // Add tiled image\n\n this.viewer.addTiledImage({\n tileSource: {\n height: this.imageViewer.config['height'],\n width: this.imageViewer.config['width'],\n maxLevel: maxLevel,\n tileWidth: this.imageViewer.config['tileWidth'],\n tileHeight: this.imageViewer.config['tileHeight'],\n getTileUrl: function getTileUrl(level, x, y) {\n return \"\".concat(src).concat(maxLevel - level, \"/\").concat(x, \"_\").concat(y, \".png\");\n }\n },\n // index: 0,\n opacity: 1,\n preload: true,\n success: function success(e) {\n // Define url and suburl\n var itemidx = _this.viewer.world.getItemCount() - 1;\n _this.viewer.world.getItemAt(itemidx).source['channelUrl'] = src;\n var url = src;\n var group = url.split(\"/\");\n var sub_url = group[group.length - 2]; // Attach\n\n _this.channelList.currentChannels[srcIdx] = {\n \"url\": url,\n \"sub_url\": sub_url,\n \"color\": _this.channelList.colorConnector[srcIdx] ? _this.channelList.colorConnector[srcIdx].color : d3.color(\"white\"),\n \"range\": _this.channelList.rangeConnector[srcIdx] || dataLayer.getImageBitRange(true)\n };\n _this.viewer_channels[srcIdx] = {\n \"url\": url,\n \"sub_url\": sub_url,\n 'name': name,\n 'short_name': name_short\n };\n }\n });\n }\n /**\n * @function channel_remove\n * Remove channel from multichannel rendering\n *\n * @param srcIdx\n */\n\n }, {\n key: \"channel_remove\",\n value: function channel_remove(srcIdx) {\n var src = this.imageViewer.config[\"imageData\"][srcIdx][\"src\"];\n var img_count = this.viewer.world.getItemCount(); // remove channel\n\n if (srcIdx in this.channelList.currentChannels) {\n // remove channel - first find it\n for (var i = 0; i < img_count; i = i + 1) {\n var url = this.viewer.world.getItemAt(i).source['channelUrl'];\n\n if (url === this.channelList.currentChannels[srcIdx][\"url\"]) {\n this.viewer.world.removeItem(this.viewer.world.getItemAt(i));\n delete this.channelList.currentChannels[srcIdx];\n delete this.viewer_channels[srcIdx];\n break;\n }\n }\n }\n }\n /**\n * @function evaluateTF\n *\n * @param val\n * @param tf\n * @returns {*}\n */\n\n }, {\n key: \"evaluateTF\",\n value: function evaluateTF(val, tf) {\n var lerpFactor = Math.round((val - tf.min) / (tf.max - tf.min) * (tf.num_bins - 1));\n\n if (lerpFactor >= tf.num_bins) {\n lerpFactor = tf.num_bins - 1;\n }\n\n if (lerpFactor < 0) {\n lerpFactor = 0;\n }\n\n return tf.tf[lerpFactor];\n }\n /**\n * @function force_repaint\n *\n * @returns void\n */\n\n }, {\n key: \"force_repaint\",\n value: function force_repaint() {\n // Refilter, redraw\n // this.viewer.forceRefilter();\n this.viewer.forceRedraw();\n }\n /**\n * @function load_label_image\n *\n * @returns void\n */\n\n }, {\n key: \"load_label_image\",\n value: function load_label_image() {\n var _this2 = this;\n\n var self = this; // Load label image in background if it exists\n\n if (this.imageViewer.config[\"imageData\"][0][\"src\"] && this.imageViewer.config[\"imageData\"][0][\"src\"] !== '') {\n var url = this.imageViewer.config[\"imageData\"][0][\"src\"];\n var maxLevel = this.imageViewer.config['maxLevel'] - 1;\n this.viewer.addTiledImage({\n tileSource: {\n height: this.imageViewer.config['height'],\n width: this.imageViewer.config['width'],\n maxLevel: maxLevel,\n maxImageCacheCount: 50,\n tileWidth: this.imageViewer.config['tileWidth'],\n tileHeight: this.imageViewer.config['tileHeight'],\n getTileUrl: function getTileUrl(level, x, y) {\n return \"\".concat(url).concat(maxLevel - level, \"/\").concat(x, \"_\").concat(y, \".png\");\n }\n },\n index: 0,\n opacity: 1,\n success: function success(e) {\n var url0 = url;\n _this2.viewer.world.getItemAt(0).source['channelUrl'] = url;\n _this2.imageViewer.labelChannel[\"url\"] = url0;\n var group = url0.split(\"/\");\n _this2.imageViewer.labelChannel[\"sub_url\"] = group[group.length - 2];\n var source = e.item.source; // Open Event is Necessary for ViaWebGl to init\n\n self.viewer.raiseEvent('open', {\n source: source\n });\n }\n });\n } else {\n this.imageViewer.noLabel = true;\n }\n }\n }]);\n\n return ViewerManager;\n}();\n\n//# sourceURL=webpack:///./src/js/views/viewerManager.js?"); +eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"ViewerManager\", function() { return ViewerManager; });\n/* harmony import */ var regenerator_runtime_runtime_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! regenerator-runtime/runtime.js */ \"./node_modules/regenerator-runtime/runtime.js\");\n/* harmony import */ var regenerator_runtime_runtime_js__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regenerator_runtime_runtime_js__WEBPACK_IMPORTED_MODULE_0__);\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }\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\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\nfunction _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== \"undefined\" && arr[Symbol.iterator] || arr[\"@@iterator\"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\n\n/**\n * @function toIdealTile -- full tile dimension in full image pixels\n * @param fullScale - scale factor to full image\n * @param useY - 0 for x and 1 for y\n * @returns Number\n */\n\nfunction toIdealTile(fullScale, useY) {\n var _tileWidth = this._tileWidth,\n _tileHeight = this._tileHeight;\n return [_tileWidth, _tileHeight][useY] * fullScale;\n}\n/**\n * @function toIdealTile -- clipped tile dimension in full image pixels\n * @param fullScale - scale factor to full image\n * @param v - x or y index of tile\n * @param useY - x=0 and y=1\n * @returns Number\n */\n\n\nfunction toRealTile(fullScale, v, useY) {\n var shape = [this.width, this.height][useY];\n var tileShape = this.toIdealTile(fullScale, useY);\n return Math.min(shape - v * tileShape, tileShape);\n}\n/**\n * @function toTileBoundary -- tile start and size in full image pixels\n * @param fullScale - scale factor to full image\n * @param v - x or y index of tile\n * @param useY - x=0 and y=1\n * @typedef {object} Bound\n * @property {number} start - full image pixel start of tile\n * @property {number} size - full image pixel size of tile\n * @returns Bound\n */\n\n\nfunction toTileBoundary(fullScale, v, useY) {\n var start = v * this.toIdealTile(fullScale, useY);\n var size = this.toRealTile(fullScale, v, useY);\n return {\n start: start,\n size: size\n };\n}\n/**\n * @function toMagnifiedBounds -- return bounds of magnified tile\n * @param _level - openseadragon tile level\n * @param _x - openseadragon tile x index\n * @param _y - openseadragon tile y index\n * @typedef {object} Bounds\n * @property {Array} x - start and end image x-coordinates\n * @property {Array} y - start and end image y-coordinates\n * @returns Bounds\n */\n\n\nfunction toMagnifiedBounds(_level, _x, _y) {\n var _this = this;\n\n var tl = this.toTileLevels(_level, _x, _y);\n\n if (tl.relativeImageScale >= 1) {\n return {\n x: [0, 1],\n y: [0, 1]\n };\n }\n\n var ownScale = tl.outputFullScale;\n var parentScale = tl.inputFullScale;\n\n var _map = [tl.outputTile.x, tl.outputTile.y].map(function (parentOffset, i) {\n var hd = _this.toTileBoundary(ownScale, [_x, _y][i], i);\n\n var sd = _this.toTileBoundary(parentScale, parentOffset, i);\n\n var start = (hd.start - sd.start) / sd.size;\n var end = start + hd.size / sd.size;\n return [[start, end], [1 - end, 1 - start]][i];\n }),\n _map2 = _slicedToArray(_map, 2),\n x = _map2[0],\n y = _map2[1];\n\n return {\n x: x,\n y: y\n };\n}\n/**\n * @function toTileLevels -- measure scaled/non-scaled tile details\n * @param level - openseadragon tile level\n * @param x - openseadragon tile x index\n * @param y - openseadragon tile y index\n * @typedef {object} TileLevels\n * @property {number} inputFullScale - full scale of source tile \n * @property {number} outputFullScale - full scale of renedered tile\n * @property {number} relativeImageScale - scale relative to image pixels\n * @property {object} inputTile - level, x, and y of source tile\n * @property {object} outputTile - level, x, and y of rendered tile\n * @returns TileLevels \n */\n\n\nfunction toTileLevels(level, x, y) {\n var extraZoomLevels = this.extraZoomLevels;\n var flipped = this.maxLevel - level;\n var relativeLevel = flipped - extraZoomLevels;\n var sourceLevel = Math.max(relativeLevel, 0);\n var extraZoom = sourceLevel - relativeLevel;\n var inputTile = {\n x: Math.floor(x / Math.pow(2, extraZoom)),\n y: Math.floor(y / Math.pow(2, extraZoom)),\n level: sourceLevel\n };\n\n var outputTile = _objectSpread(_objectSpread({}, inputTile), {}, {\n level: level - extraZoom\n });\n\n return {\n inputFullScale: Math.pow(2, flipped + extraZoom),\n relativeImageScale: Math.pow(2, relativeLevel),\n outputFullScale: Math.pow(2, flipped),\n inputTile: inputTile,\n outputTile: outputTile\n };\n}\n/**\n * @function getTileUrl -- return url for tile\n * @param level - openseadragon tile level\n * @param x - openseadragon tile x index\n * @param y - openseadragon tile y index\n * @returns string\n */\n\n\nfunction getTileUrl(level, x, y) {\n var s = this.toTileLevels(level, x, y).inputTile;\n return \"\".concat(this.src).concat(s.level, \"/\").concat(s.x, \"_\").concat(s.y, \".png\");\n}\n/**\n * @function getTileKey -- return string key for tile\n * @param level - openseadragon tile level\n * @param x - openseadragon tile x index\n * @param y - openseadragon tile y index\n * @returns string\n */\n\n\nfunction getTileKey(level, x, y) {\n var srcIdx = this.srcIdx,\n tileFormat = this.tileFormat;\n var s = this.toTileLevels(level, x, y).inputTile;\n return \"\".concat(tileFormat, \"-\").concat(srcIdx, \"-\").concat(s.level, \"-\").concat(s.x, \"-\").concat(s.y);\n}\n/**\n * @class ViewerManager\n */\n\n\nvar ViewerManager = /*#__PURE__*/function () {\n /**\n * Constructs a ColorManager instance before delegating initialization.\n *\n * @param _imageViewer - ImageViewer instance\n * @param _viewer - Openseadragon instance\n */\n function ViewerManager(_imageViewer, _viewer) {\n _classCallCheck(this, ViewerManager);\n\n _defineProperty(this, \"colorConnector\", {});\n\n _defineProperty(this, \"rangeConnector\", {});\n\n _defineProperty(this, \"show_sel\", true);\n\n _defineProperty(this, \"sel_outlines\", true);\n\n this.viewer = _viewer;\n this.imageViewer = _imageViewer;\n this.viewer_channels = new Map();\n this.init();\n }\n /**\n * @function init\n * Setups up the color manager.\n */\n\n\n _createClass(ViewerManager, [{\n key: \"init\",\n value: function init() {\n // Load label image\n this.load_label_image();\n }\n /**\n * @function channel_add\n * Add channel to multi-channel rendering\n * @param srcIdx - integer id of channel to add\n */\n\n }, {\n key: \"channel_add\",\n value: function channel_add(srcIdx) {\n var _this2 = this;\n\n // If already exists\n if (this.viewer_channels.has(srcIdx)) {\n return;\n } // Find name\n\n\n var name = \"\";\n var short_name = \"\";\n\n for (var k in imageChannels) {\n if (imageChannels.hasOwnProperty(k) && imageChannels[k] === srcIdx) {\n name = k;\n short_name = dataLayer.getShortChannelName(k);\n }\n }\n\n var url = this.imageViewer.config[\"imageData\"][srcIdx][\"src\"];\n var _this$imageViewer$con = this.imageViewer.config,\n maxLevel = _this$imageViewer$con.maxLevel,\n extraZoomLevels = _this$imageViewer$con.extraZoomLevels;\n var magnification = Math.pow(2, extraZoomLevels);\n this.viewer.addTiledImage({\n tileSource: {\n height: this.imageViewer.config.height * magnification,\n width: this.imageViewer.config.width * magnification,\n maxLevel: extraZoomLevels + maxLevel - 1,\n compositeOperation: \"lighter\",\n tileWidth: this.imageViewer.config.tileWidth,\n tileHeight: this.imageViewer.config.tileHeight,\n toMagnifiedBounds: toMagnifiedBounds,\n extraZoomLevels: extraZoomLevels,\n toTileBoundary: toTileBoundary,\n toTileLevels: toTileLevels,\n toIdealTile: toIdealTile,\n toRealTile: toRealTile,\n getTileUrl: getTileUrl,\n getTileKey: getTileKey,\n tileFormat: 16,\n srcIdx: srcIdx,\n src: url\n },\n // index: 0,\n opacity: 1,\n preload: true,\n success: function success() {\n // Define url and suburl\n var group = url.split(\"/\");\n var sub_url = group[group.length - 2];\n var itemidx = _this2.viewer.world.getItemCount() - 1;\n _this2.viewer.world.getItemAt(itemidx).source[\"channelUrl\"] = url; // Attach channel selection\n\n var viewerChannel = {\n url: url,\n sub_url: sub_url,\n name: name,\n short_name: short_name\n };\n\n _this2.imageViewer.addChannelSelection(srcIdx, viewerChannel);\n\n _this2.viewer_channels.set(srcIdx, viewerChannel);\n }\n });\n }\n /**\n * @function channel_remove - remove channel from multichannel rendering\n * @param srcIdx - integer id of channel to remove\n */\n\n }, {\n key: \"channel_remove\",\n value: function channel_remove(srcIdx) {\n var img_count = this.viewer.world.getItemCount(); // remove channel\n\n if (this.viewer_channels.has(srcIdx)) {\n // remove channel - first find it\n for (var i = 0; i < img_count; i = i + 1) {\n var _this$viewer_channels;\n\n var url = this.viewer.world.getItemAt(i).source[\"channelUrl\"];\n\n if (url === ((_this$viewer_channels = this.viewer_channels.get(srcIdx)) === null || _this$viewer_channels === void 0 ? void 0 : _this$viewer_channels.url)) {\n this.viewer.world.removeItem(this.viewer.world.getItemAt(i));\n this.imageViewer.removeChannelSelection(srcIdx);\n this.viewer_channels[\"delete\"](srcIdx);\n break;\n }\n }\n }\n }\n /**\n * @function evaluateTF - finds color for value in transfer function\n * @param val - input to transfer function\n * @param tf - colors of transfer function\n * @returns object\n */\n\n }, {\n key: \"evaluateTF\",\n value: function evaluateTF(val, tf) {\n var lerpFactor = Math.round((val - tf.min) / (tf.max - tf.min) * (tf.num_bins - 1));\n\n if (lerpFactor >= tf.num_bins) {\n lerpFactor = tf.num_bins - 1;\n }\n\n if (lerpFactor < 0) {\n lerpFactor = 0;\n }\n\n return tf.tf[lerpFactor];\n }\n /**\n * @function force_repaint\n */\n\n }, {\n key: \"force_repaint\",\n value: function force_repaint() {\n // Refilter, redraw\n // this.viewer.forceRefilter();\n this.viewer.forceRedraw();\n }\n /**\n * @function load_label_image\n */\n\n }, {\n key: \"load_label_image\",\n value: function load_label_image() {\n var _this3 = this;\n\n var self = this; // Load label image in background if it exists\n\n if (this.imageViewer.config[\"imageData\"][0][\"src\"] && this.imageViewer.config[\"imageData\"][0][\"src\"] !== \"\") {\n var url = this.imageViewer.config[\"imageData\"][0][\"src\"];\n var _this$imageViewer$con2 = this.imageViewer.config,\n maxLevel = _this$imageViewer$con2.maxLevel,\n extraZoomLevels = _this$imageViewer$con2.extraZoomLevels;\n var magnification = Math.pow(2, extraZoomLevels);\n this.viewer.addTiledImage({\n tileSource: {\n height: this.imageViewer.config.height * magnification,\n width: this.imageViewer.config.width * magnification,\n maxLevel: extraZoomLevels + maxLevel - 1,\n maxImageCacheCount: 50,\n compositeOperation: \"source-over\",\n tileWidth: this.imageViewer.config.tileWidth,\n tileHeight: this.imageViewer.config.tileHeight,\n toMagnifiedBounds: toMagnifiedBounds,\n extraZoomLevels: extraZoomLevels,\n toTileBoundary: toTileBoundary,\n toTileLevels: toTileLevels,\n toIdealTile: toIdealTile,\n toRealTile: toRealTile,\n getTileUrl: getTileUrl,\n getTileKey: getTileKey,\n tileFormat: 32,\n srcIdx: 0,\n src: url\n },\n index: 0,\n opacity: 1,\n success: function success(e) {\n var url0 = url;\n _this3.viewer.world.getItemAt(0).source[\"channelUrl\"] = url;\n _this3.imageViewer.labelChannel[\"url\"] = url0;\n var group = url0.split(\"/\");\n _this3.imageViewer.labelChannel[\"sub_url\"] = group[group.length - 2];\n var source = e.item.source; // Open Event is Necessary for ViaWebGl to init\n\n self.viewer.raiseEvent(\"open\", {\n source: source\n });\n }\n });\n } else {\n this.imageViewer.noLabel = true;\n }\n }\n }]);\n\n return ViewerManager;\n}();\n\n//# sourceURL=webpack:///./src/js/views/viewerManager.js?"); /***/ }), diff --git a/minerva_analysis/client/src/css/viewer.css b/minerva_analysis/client/src/css/viewer.css index 177fbaf6a..4a3202bcf 100644 --- a/minerva_analysis/client/src/css/viewer.css +++ b/minerva_analysis/client/src/css/viewer.css @@ -193,4 +193,4 @@ #gating_controls_panel input { height: 11px; margin: 1px 10px 0 5px; -} \ No newline at end of file +} diff --git a/minerva_analysis/client/src/js/main.js b/minerva_analysis/client/src/js/main.js index 308d3ec8c..d1380bef8 100644 --- a/minerva_analysis/client/src/js/main.js +++ b/minerva_analysis/client/src/js/main.js @@ -45,6 +45,9 @@ d3.json(`/config?t=${Date.now()}`).then(function (config) { async function init(conf) { config = conf; + //maximum selections + config.maxSelections = 4; + config.extraZoomLevels = 3; //channel information for (let idx = 0; idx < config["imageData"].length; idx++) { imageChannels[config["imageData"][idx].fullname] = idx; @@ -57,24 +60,25 @@ async function init(conf) { dataLayer = new DataLayer(config, imageChannels); await dataLayer.init(); + //init color scheme + colorScheme = new ColorScheme(dataLayer); + await colorScheme.init(); + //init channel panel channelList = new ChannelList(config, dataLayer, eventHandler); await channelList.init(); + //create image viewer + seaDragonViewer = new ImageViewer(config, dataLayer, channelList, eventHandler, colorScheme); + //init gating panel csv_gatingList = new CSVGatingList(config, dataLayer, eventHandler); await csv_gatingList.init(); - //init color scheme - colorScheme = new ColorScheme(dataLayer); - await colorScheme.init(); - //init image viewer - seaDragonViewer = new ImageViewer(config, dataLayer, eventHandler, colorScheme); - seaDragonViewer.init(); + seaDragonViewer.init(csv_gatingList); } - //EVENT HANDLING /** @@ -88,7 +92,6 @@ const actionColorTransferChange = (d) => { // d3.select('body').style('cursor', 'progress'); seaDragonViewer.updateChannelColors(d.name, d.color, d.type); // d3.select('body').style('cursor', 'default'); - seaDragonViewer.csvGatingOverlay.draw(); } eventHandler.bind(ChannelList.events.COLOR_TRANSFER_CHANGE, actionColorTransferChange); @@ -112,7 +115,8 @@ const actionChannelsToRenderChange = (d) => { d.name = dataLayer.getFullChannelName(d.name); //send to image viewer - seaDragonViewer.updateActiveChannels(d.name, d.selections, d.status); + const action = ["remove", "add"][+d.status]; + seaDragonViewer.updateActiveChannels(d.name, action); d3.select('body').style('cursor', 'default'); } @@ -140,9 +144,12 @@ eventHandler.bind(ImageViewer.events.imageClickedMultiSel, actionImageClickedMul * @param {package object} d The selected/deselected channels */ const channelSelect = async (sels) => { + // pause new rendering until data loads + const resume = seaDragonViewer.sleep(); let channelCells = await dataLayer.getChannelCellIds(sels); dataLayer.addAllToCurrentSelection(channelCells); - updateSeaDragonSelection(false); + updateSeaDragonSelection(); + resume(); } eventHandler.bind(ChannelList.events.CHANNEL_SELECT, channelSelect); @@ -150,9 +157,8 @@ eventHandler.bind(ChannelList.events.CHANNEL_SELECT, channelSelect); * Listens to and updates based on selection changes (specific for seadragon) * @param {boolean} d Whether to repaint */ -function updateSeaDragonSelection(repaint = true) { - seaDragonViewer.updateSelection(dataLayer.getCurrentSelection(), repaint); - seaDragonViewer.csvGatingOverlay.evaluate(); +function updateSeaDragonSelection() { + seaDragonViewer.updateSelection(dataLayer.getCurrentSelection()); } /** @@ -168,6 +174,8 @@ const gatingBrushEnd = async (packet) => { this.config[datasource].featureData[0].xCoordinate, this.config[datasource].featureData[0].yCoordinate ]; + // pause new rendering until data loads + const resume = seaDragonViewer.sleep(); // Toggle these methods with centroids on/off ui if (csv_gatingList.eval_mode === 'and') { // AND @@ -180,6 +188,7 @@ const gatingBrushEnd = async (packet) => { dataLayer.addAllToCurrentSelection(gatedCells); // Update view updateSeaDragonSelection(); + resume(); } eventHandler.bind(CSVGatingList.events.GATING_BRUSH_END, gatingBrushEnd); @@ -207,4 +216,4 @@ const add_scalebar = () => { seaDragonViewer.addScaleBar(); seaDragonViewer.forceRepaint(); } -eventHandler.bind(ImageViewer.events.addScaleBar, add_scalebar); \ No newline at end of file +eventHandler.bind(ImageViewer.events.addScaleBar, add_scalebar); diff --git a/minerva_analysis/client/src/js/vendor.js b/minerva_analysis/client/src/js/vendor.js index d9a9e8dfa..7b440d871 100644 --- a/minerva_analysis/client/src/js/vendor.js +++ b/minerva_analysis/client/src/js/vendor.js @@ -20,7 +20,6 @@ import 'viawebgl' import * as viaWebGL from 'viawebgl'; import {ViewerManager} from './views/viewerManager'; import Dropzone from 'dropzone'; -import {CsvGatingOverlay} from './views/CsvGatingOverlay'; window.convert = convert; window.$ = $; @@ -32,7 +31,6 @@ window.Sortable = Sortable; window.Mark = Mark; window.OpenSeadragon = viaWebGL.OpenSeadragon; window.Dropzone = Dropzone; -window.CsvGatingOverlay = CsvGatingOverlay; window.viaWebGL = viaWebGL; window.ViewerManager = ViewerManager; diff --git a/minerva_analysis/client/src/js/views/channelList.js b/minerva_analysis/client/src/js/views/channelList.js index e18a5537b..c2923e3ff 100644 --- a/minerva_analysis/client/src/js/views/channelList.js +++ b/minerva_analysis/client/src/js/views/channelList.js @@ -11,10 +11,10 @@ class ChannelList { */ constructor(config, dataLayer, eventHandler) { this.config = config; + this.maxSelections = config.maxSelections; this.eventHandler = eventHandler; this.dataLayer = dataLayer; this.selections = []; - this.maxSelections = 4; this.ranges = {}; this.sliders = new Map(); var that = this; @@ -713,4 +713,4 @@ ChannelList.events = { CHANNELS_CHANGE: "CHANNELS_CHANGE", CHANNEL_SELECT: "CHANNEL_SELECT", RESET_LISTS: "RESET_LISTS" -}; \ No newline at end of file +}; diff --git a/minerva_analysis/client/src/js/views/channelMatch.js b/minerva_analysis/client/src/js/views/channelMatch.js index 11922ba1a..ba5b888c4 100644 --- a/minerva_analysis/client/src/js/views/channelMatch.js +++ b/minerva_analysis/client/src/js/views/channelMatch.js @@ -316,4 +316,4 @@ function swapNodes(n1, n2) { } p1.insertBefore(n2, p1.children[i1]); p2.insertBefore(n1, p2.children[i2]); -} \ No newline at end of file +} diff --git a/minerva_analysis/client/src/js/views/csvGatingList.js b/minerva_analysis/client/src/js/views/csvGatingList.js index 04691c099..048f36ea1 100644 --- a/minerva_analysis/client/src/js/views/csvGatingList.js +++ b/minerva_analysis/client/src/js/views/csvGatingList.js @@ -11,10 +11,11 @@ class CSVGatingList { */ constructor(config, dataLayer, eventHandler) { this.config = config; + this.waiting = Promise.resolve(true); + this.maxSelections = config.maxSelections; this.eventHandler = eventHandler; this.dataLayer = dataLayer; this.selections = {}; - this.maxSelections = 4; this.ranges = {}; this.hasGatingGMM = {}; this.gatingIDs = {}; @@ -40,18 +41,11 @@ class CSVGatingList { * @param name - the channel to set and display as selected */ selectChannel(name) { - // For overlay (and query incrementor) - // seaDragonViewer.csvGatingOverlay.run_balancer++; - - if (!(name in this.hasGatingGMM)) { - let channelTrace = this.getAndDrawGatingGMM(name); - } - - // Add - this.selections[this.dataLayer.getFullChannelName(name)] = this.sliders.get(name).value(); - - // Trigger - this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, this.selections); + this.awaitGatingGMM(name).then(() => { + const fullName = this.dataLayer.getFullChannelName(name); + this.selections[fullName] = this.sliders.get(name).value(); + this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, this.selections); + }); } /** @@ -169,7 +163,11 @@ class CSVGatingList { autoBtn.classList.add('auto-btn'); autoBtn.setAttribute('id', "auto-btn_" + channelID); autoBtn.textContent = "auto"; - autoBtn.addEventListener("click", async function() { await self.autoGate(fullName) }); + autoBtn.addEventListener("click", async () => { + const shortName = self.dataLayer.getShortChannelName(fullName); + await self.awaitGatingGMM(shortName); + self.autoGate(shortName); + }); autoCol.appendChild(autoBtn); autoBtn.addEventListener("click", e => e.stopPropagation()); @@ -303,22 +301,20 @@ class CSVGatingList { * @function autoGate - applies thresholds based on Gaussian Mixture Model * @param name - the name of the channel to apply it to */ - async autoGate(name) { + autoGate(shortName) { const self = this; - let shortName = self.dataLayer.getShortChannelName(name); - - let gate = this.hasGatingGMM[shortName]['gate'] + let gate = this.hasGatingGMM[shortName].gate; if (!this.dataLayer.isTransformed()) { gate = parseInt(gate) } else { gate = gate.toFixed(7); } // For interaction - self.selections[name][0] = gate; - let gate_end = self.selections[name][1] + self.selections[shortName][0] = gate; + let gate_end = self.selections[shortName][1] self.sliders.get(shortName).value([gate, gate_end]); // For records - this.gating_channels[name] = [gate, gate_end]; + this.gating_channels[shortName] = [gate, gate_end]; this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, self.selections); } @@ -506,6 +502,7 @@ class CSVGatingList { // Toggle outlined / filled cell selections gating_controls_outlines.addEventListener('change', e => { seaDragonViewer.viewerManagerVMain.sel_outlines = e.target.checked; + this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, this.selections); }) // Toggle outlined / filled cell selections @@ -521,8 +518,7 @@ class CSVGatingList { this.eval_mode = 'and'; } - // Update overlay centroid (will also trigger event) - seaDragonViewer.csvGatingOverlay.control(e.target.checked); + this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, this.selections); }) } @@ -741,6 +737,14 @@ class CSVGatingList { this.drawGatingGMM(name); } + awaitGatingGMM(name) { + if (!(name in this.hasGatingGMM)) { + const waiting = this.getAndDrawGatingGMM(name) + this.waiting = Promise.all([this.waiting, waiting]); + } + return this.waiting; + } + drawGatingGMM(name){ let fullname = this.dataLayer.getFullChannelName(name); let channelID = this.gatingIDs[name]; @@ -849,7 +853,7 @@ window.addEventListener("resize", function () { csv_gatingList.addSlider(name, document.getElementById("csv_gating_list").getBoundingClientRect().width, sliderRange, slider.value()); if (csv_gatingList.hasGatingGMM[name]) { - let channelTrace = csv_gatingList.drawGatingGMM(name); + csv_gatingList.drawGatingGMM(name); } }); } @@ -878,4 +882,4 @@ CSVGatingList GATING_COLOR_TRANSFER_CHANGE_MOVE: "GATING_TRANSFER_CHANGE_MOVE", GATING_COLOR_TRANSFER_CHANGE: "GATING_TRANSFER_CHANGE", GATING_CHANNELS_CHANGE: "GATING_CHANNELS_CHANGE" -}; \ No newline at end of file +}; diff --git a/minerva_analysis/client/src/js/views/csvGatingOverlay.js b/minerva_analysis/client/src/js/views/csvGatingOverlay.js deleted file mode 100644 index 7701a521a..000000000 --- a/minerva_analysis/client/src/js/views/csvGatingOverlay.js +++ /dev/null @@ -1,297 +0,0 @@ - -/** - * @class CsvGatingOverlay - * - * TODO: - * 1. Query only for add / remove channels; filter for gating adjustments - * 2. Stall animation triggered draw iterations when awaiting query - * 3. Make code more modular (move out of main) - maybe keep in imageViewer and csvGatingList - * - */ - -export class CsvGatingOverlay { - - // Vars - canvas = null; - cleared = true; - context = null; - force = false; - image_rect = { - x: 0, - y: 0, - width: 0, - height: 0, - degrees: 0 - }; - viewer_rect = { - x: 0, - y: 0, - width: 0, - height: 0, - degrees: 0 - }; - range = [[], []]; - run_balancer = 0; - show_centroids = false; - - // Configs - configs = { - radius: [2, 15], - px_ratio: 2, - stroke: 2 - } - - // Tools - coord_scale_x = d3.scaleLinear(); - coord_scale_y = d3.scaleLinear(); - r_scale = d3.scalePow().exponent(0.5) - .range(this.configs.radius); - channel_scale = d3.scaleLinear() - .range([-Math.PI / 2, Math.PI * 3 / 2]); - - /** - * @constructor - * - * @param _viewer - */ - constructor(viewer, imageViewer) { - - // Init vars - this.viewer = viewer; - this.image_viewer = imageViewer; - this.channel_list = channelList; - this.gating_list = csv_gatingList; - this.dataLayer = dataLayer; - this.eventHandler = eventHandler; - - this.init(); - } - - /** 1. - * @function init - * - * @return void - */ - init() { - - // Get viewer container, append canvas - const osdContainer = this.viewer.canvas.parentElement; - this.canvas = d3.select(osdContainer).append('canvas') - .attr('id', 'gating_overlay_canvas') - .attr('width', osdContainer.clientWidth * this.configs.px_ratio) - .attr('height', osdContainer.clientHeight * this.configs.px_ratio) - .style('width', '100%') - .style('height', '100%') - .style('position', 'absolute') - .style('pointer-events', 'none'); - this.context = this.canvas.node().getContext('2d'); - - // Add event - this.image_viewer.viewer.addHandler('animation-start', this.clear.bind(this)); - this.image_viewer.viewer.addHandler('animation-finish', this.evaluate.bind(this)); - - // Handle channel list color changes - - } - - /** 2. - * @function evaluate - * - * @event e - * - * @return void - */ - evaluate(e = null) { - - // Get viewer bounds - const viewer_rect = this.viewer.viewport.getBounds(); - - // Cement viewer rect - this.viewer_rect = viewer_rect; - - // Get image coordinates - this.image_rect = this.viewer.world.getItemAt(0).viewportToImageRectangle(this.viewer_rect); - this.range = [ - [this.image_rect.x, this.image_rect.y], - [this.image_rect.x + this.image_rect.width, this.image_rect.y + this.image_rect.height] - ]; - - // If run balancer evens out (strategy for getting last request - - // run_balancer++ in csvGatingList, run_balancer-- in main - // FIXME - would be better to nest all references for gating in gating plugin packages - // if (this.run_balancer === 0) { - - // Draw - this.draw(); - - // } - - } - - /** 3. - * @function draw - * - * @return void - */ - draw() { - - // Bounce if centroids off - if (!this.show_centroids) { - this.clear(); - return; - } - - // Clear if not clear - if (!this.cleared) { - this.clear(); - } - - // Context - const ctx = this.context; - const w = this.canvas.attr('width'); - const h = this.canvas.attr('height') - - // Update scales - this.coord_scale_x.domain([this.range[0][0], this.range[1][0]]) - .range([0, w]); - this.coord_scale_y.domain([this.range[0][1], this.range[1][1]]) - .range([0, h]); - this.r_scale.domain([this.viewer.viewport.getMinZoom(), this.viewer.viewport.getMaxZoom()]); - - // Calc radius - const r = this.r_scale(this.viewer.viewport.getZoom()).toFixed(2); - - // Get cells in range - - for (let k of this.image_viewer.selection.keys()) { - - // Get values - const values = this.image_viewer.selection.get(k) - - // Position condition - const xAlias = this.dataLayer.config.featureData[0].xCoordinate; - const yAlias = this.dataLayer.config.featureData[0].yCoordinate; - if (values[xAlias] >= this.range[0][0] - && values[xAlias] <= this.range[1][0] - && values[yAlias] >= this.range[0][1] - && values[yAlias] <= this.range[1][1] - ) { - - // Get coords - const x = this.coord_scale_x(values[xAlias]); - const y = this.coord_scale_y(values[yAlias]); - - // Draw circles - placeholder - ctx.strokeStyle = 'white'; - ctx.lineWidth = this.configs.stroke * this.configs.px_ratio; - - // Save context - ctx.save(); - - // Place in - requestAnimationFrame(() => { - - // Match to channel color - const gatingChannelIndices = []; - for (let key in this.gating_list.selections) { - - this.channel_list.columns.forEach((c, i) => { - - if (this.dataLayer.getShortChannelName(key) === c) { - - // Define current channel - const channel = this.gating_list.selections[key]; - - if (values[key] >= channel[0] && values[key] <= channel[1]) { - gatingChannelIndices.push({ - key: key, - value: values[key], - index: i + 1 - }); - } - - } - - }); - } - - // Update scale - this.channel_scale.domain([0, gatingChannelIndices.length]); - - // this.gating_list.forEach(c => { - gatingChannelIndices.forEach((d, i) => { - - // Retrieve color (FIXME - need to integrate into viewer manager) - // const rgb = evaluateTF(values[channel], this.image_viewer.channelTF[gatingChannelIndices[i]]); - // ctx.fillStyle = `rgb(${Math.round(rgb.r)}, ${Math.round(rgb.g)}, ${Math.round(rgb.b)})`; - // ctx.fillStyle = this.image_viewer.channelTF[gatingChannelIndices[i].index].end_color; - // ctx.fillStyle = this.global_channel_list.currentChannels[gatingChannelIndices[i].index]['color']; - ctx.fillStyle = this.rgbToHex(this.channel_list.currentChannels[gatingChannelIndices[i].index]['color']); - - ctx.beginPath(); - ctx.moveTo(x, y); - ctx.arc(x, y, r * this.configs.px_ratio, this.channel_scale(i), this.channel_scale(i + 1)); - ctx.lineWidth = this.configs.px_ratio; - ctx.closePath(); - ctx.stroke(); - ctx.fill(); - - }); - }); - - ctx.restore(); - - } - - } - - // Mark as not cleared - this.cleared = false; - - } - - rgbToHex(color) { - return '#' + [color.r, color.g, color.b].map(x => { - const hex = Math.round(x).toString(16) - return hex.length === 1 ? '0' + hex : hex - }).join('') - } - - /** 4. - * @function clear - * - * @param {Event} e - * - * @return void - */ - clear(e = null) { - - // Context - const ctx = this.context; - const w = this.canvas.attr('width'); - const h = this.canvas.attr('height') - - // Clear rect - requestAnimationFrame(() => { - ctx.clearRect(0, 0, w, h); - this.cleared = true; - }); - } - - /** - * @function control - * - * @param show - */ - control(show) { - - // Update mode - this.show_centroids = show; - - // Trigger event - this.eventHandler.trigger(CSVGatingList.events.GATING_BRUSH_END, - this.gating_list.selections); - } - - -} diff --git a/minerva_analysis/client/src/js/views/imageViewer.js b/minerva_analysis/client/src/js/views/imageViewer.js index 75a514c6b..30360f1da 100644 --- a/minerva_analysis/client/src/js/views/imageViewer.js +++ b/minerva_analysis/client/src/js/views/imageViewer.js @@ -1,7 +1,7 @@ /** * viewer.js. - * @class ImageViewer to render multiplexed imaging data (based on OpenSeadragon) * + * @class ImageViewer to render multiplexed imaging data (based on OpenSeadragon) */ /* todo @@ -9,24 +9,28 @@ */ class ImageViewer { - // Vars viewerManagers = []; /** - * @constructor - * @param config the cinfiguration file (json) + * Constructor for ImageViewer + * + * @param config - the cinfiguration file (json) * @param dataLayer - the data layer (stub) that executes server requests and holds client side data + * @param channelList - ChannelList instance * @param eventHandler - the event handler for distributing interface and data updates * @param colorScheme - the color scheme to use or selections etc. */ - constructor(config, dataLayer, eventHandler, colorScheme) { - + constructor(config, dataLayer, channelList, eventHandler, colorScheme) { this.config = config; - this.eventHandler = eventHandler; this.dataLayer = dataLayer; - this.colorScheme = colorScheme; this.channelList = channelList; + this.eventHandler = eventHandler; + this.colorScheme = colorScheme; + this.gatingList = null; + this._ready = false; + this.clearCache(); + const that = this; // Viewer this.viewer = {}; @@ -36,7 +40,6 @@ class ImageViewer { // Stores the ordered contents of the tile cache, so that once we hit max size we remove oldest elements this.pendingTiles = new Map(); - // Map of selected ids, key is id this.selection = new Map(); this.data = new Map(); @@ -56,12 +59,11 @@ class ImageViewer { // Transfer function per channel (min,max, start color, end color) this.channelTF = []; for (let i = 0; i < this.config["imageData"].length; i = i + 1) { - const start_color = d3.rgb(0, 0, 0); const end_color = d3.rgb(255, 255, 255); const tf_def = this.createTFArray(0, 65535, start_color, end_color, this.numTFBins); - tf_def.name = this.config['imageData'][i].name; + tf_def.name = this.config["imageData"][i].name; this.channelTF.push(tf_def); } @@ -70,203 +72,295 @@ class ImageViewer { this.show_subset = false; this.show_selection = true; - } - - /** - * @function init - initializes OSD, loads metadata, tile drawing, etc. - */ - init() { - - // Define this as that - const that = this; - // Hide Loader - document.getElementById('openseadragon_loader').style.display = "none"; + document.getElementById("openseadragon_loader").style.display = "none"; // Config viewer const viewer_config = { id: "openseadragon", prefixUrl: "/client/external/openseadragon-bin-2.4.0/openseadragon-flat-toolbar-icons-master/images/", maxZoomPixelRatio: 15, + compositeOperation: "lighter", loadTilesWithAjax: true, immediateRender: false, maxImageCacheCount: 100, timeout: 90000, - compositeOperation: 'lighter', + collectionMode: false, preload: false, homeFillsViewer: true, - visibilityRatio: 1.0 + visibilityRatio: 1.0, }; - // Instantiate viewer with the ViaWebGL Version of OSD that.viewer = viaWebGL.OpenSeadragon(viewer_config); /************************************************************************************** Get ome tiff metadata */ - dataLayer.getMetadata().then(d => { + this.dataLayer.getMetadata().then((d) => { that.imgMetadata = d; - console.log('Image metadata:', that.imgMetadata) - that.addScaleBar() + console.log("Image metadata:", that.imgMetadata); + that.addScaleBar(); }); - - // Define interface to shaders + // Flexible use of textures + const constantTextures = ["ids", "magnitudes", "centers", "gatings"]; + const textureCount = 32 - constantTextures.length; + const tileTextureKeys = [...Array(textureCount).keys()]; const seaGL = new viaWebGL.openSeadragonGL(that.viewer); - seaGL.vShader = '/client/src/shaders/vert.glsl'; - seaGL.fShader = '/client/src/shaders/frag.glsl'; - // - seaGL.addHandler('tile-drawing', async function (callback, e) { + seaGL.viaGL._tileTextures = tileTextureKeys.map(() => ""); + seaGL.viaGL._constantTextureOffset = textureCount; + seaGL.viaGL._constantTextures = constantTextures; + seaGL.viaGL._activeTileTexture = 0; + seaGL.viaGL._nextTileTexture = 0; + this.viaGL = seaGL.viaGL; + + seaGL.viaGL.loadArray = function (e, w, h) { + // Allow for custom drawing in webGL + var gl = this.gl; + const { source } = e.tiledImage; + const tileArgs = [e.tile.level, e.tile.x, e.tile.y]; + const format = e.tile._format || `u${source.format}`; + const okFormat = ["u16", "u32"].includes(format); + const tKey = source.getTileKey(...tileArgs); + const pixels = e.tile._array; + + // Clear before starting all the draw calls + gl.clearColor(0, 0, 0, 0); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); + + // Reset texture for GLSL + const oldKey = that.activeTextureLabel; + // Only transfer texture if needed + if (oldKey != tKey && okFormat) { + this._activeTileTexture = that.indexOfTexture(tKey); + that.selectTexture(gl, this.texture, this._activeTileTexture); + const textureArgs = { + u16: [gl.RG8UI, w, h, 0, gl.RG_INTEGER], + u32: [gl.RGBA8UI, w, h, 0, gl.RGBA_INTEGER], + }[format]; + + // Send the tile into the texture. + gl.texImage2D(gl.TEXTURE_2D, 0, ...textureArgs, gl.UNSIGNED_BYTE, pixels); + } + + this.gl_arguments.tile_shape_2fv = new Float32Array([w, h]); + + // Call gl-drawing after loading + this["gl-drawing"].call(this); + gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); + return gl.canvas; + }; + seaGL.vShader = "/client/src/shaders/vert.glsl"; + seaGL.fShader = "/client/src/shaders/frag.glsl"; + + // Overwrite tile-drawing method + seaGL.io["tile-drawing"] = function (e) { + var w = e.rendered.canvas.width; + var h = e.rendered.canvas.height; + var gl_w = this.viaGL.width; + var gl_h = this.viaGL.height; + + // Render a webGL canvas to an input canvas + var output = this.viaGL.loadArray(e, w, h); + e.rendered.drawImage(output, 0, 0, gl_w, gl_h, 0, 0, w, h); + }; + + // Draw handler for viaWebGL + seaGL.addHandler("tile-drawing", async function (callback, e) { // Read parameters from each tile - const tile = e.tile; const group = e.tile.url.split("/"); const sub_url = group[group.length - 3]; - - let channel = _.find(that.channelList.currentChannels, e => { - return e.sub_url == sub_url; - }) - if (channel) { - const color = _.get(channel, 'color', d3.color("white")); - const floatColor = [color.r / 255., color.g / 255., color.b / 255.]; - const range = _.get(channel, 'range', that.dataLayer.getImageBitRange(true)); - const via = this.viaGL; + const { source } = e.tiledImage; + const { tileFormat } = source; + const centerProps = that.selectCenterProps(e.tile, source); + + const via = this.viaGL; + + if (tileFormat != 32) { + const channel = _.find(that.channelSelections, (e) => { + return e.sub_url == sub_url; + }); + const color = _.get(channel, "color", d3.color("white")); + const floatColor = toFloatColor(color); + const range = _.get(channel, "range", that.dataLayer.getImageBitRange(true)); // Store channel color and range to send to shader - via.color_3fv = new Float32Array(floatColor); - via.range_2fv = new Float32Array(range); - let fmt = 0; - if (tile._format == 'u16') { - fmt = 16; - } else if (tile._format == 'u32') { - fmt = 32; - } - via.fmt_1i = fmt; - // Start webGL rendering - callback(e); - // After the callback, call the labels - // await that.drawLabels(e); + via.gl_arguments = { + ...centerProps, + centers: [], + id_end_1i: 0, + color_3fv: new Float32Array(floatColor), + range_2fv: new Float32Array(range), + fmt_1i: 16, + }; } else { - if (e.tile._redrawLabel) { - if (!e.tile._array || !e.tile._tileImageData) { - console.log('Missing Array', e.tile.url); - // this.refreshSegmentationMask(); - } - that.drawLabelTile(e.tile, e.tile._tileImageData.width, e.tile._tileImageData.height); + if (!e.tile._array) { + console.log("Missing Array", e.tile.url); + // this.refreshSegmentationMask(); } - if (e.tile.containsLabel) { - try { - e.rendered.putImageData(e.tile._tileImageData, 0, 0); - } catch (err) { - console.log('Another issue', err, e.tile.url); - // this.refreshSegmentationMask(); - } + // transfer data to WebGL shaders + const idCount = that.selection.size; + if (that.ready) { + that.loadBuffers(idCount); } + // Use new parameters for this tile + via.gl_arguments = { + ...centerProps, + id_end_1i: Math.max(idCount - 1, 0), + color_3fv: new Float32Array([1, 1, 1]), + range_2fv: new Float32Array([0, 1]), + fmt_1i: 32, + }; } - }); - seaGL.addHandler('gl-drawing', function () { - // Send color and range to shader - this.gl.uniform3fv(this.u_tile_color, this.color_3fv); - this.gl.uniform2fv(this.u_tile_range, this.range_2fv); - this.gl.uniform1i(this.u_tile_fmt, this.fmt_1i); + // Clear the rendered tile + var w = e.rendered.canvas.width; + var h = e.rendered.canvas.height; + e.rendered.fillStyle = "black"; + e.rendered.fillRect(0, 0, w, h); - // Clear before each draw call - this.gl.clear(this.gl.COLOR_BUFFER_BIT); + // Start webGL rendering + callback(e); }); - seaGL.addHandler('gl-loaded', function (program) { - // Turn on additive blending - this.gl.enable(this.gl.BLEND); - this.gl.blendEquation(this.gl.FUNC_ADD); - this.gl.blendFunc(this.gl.ONE, this.gl.ONE); + seaGL.addHandler("gl-drawing", function () { + const args = this.gl_arguments; + const modes = that.modeFlags; - // Uniform variable for coloring - this.u_tile_color = this.gl.getUniformLocation(program, 'u_tile_color'); - this.u_tile_range = this.gl.getUniformLocation(program, 'u_tile_range'); - this.u_tile_fmt = this.gl.getUniformLocation(program, 'u_tile_fmt'); + // Send color and range to shader + this.gl.uniform2fv(this.u_tile_shape, args.tile_shape_2fv); + this.gl.uniform1f(this.u_tile_fraction, args.tile_fraction_1f); + this.gl.uniform1f(this.u_tile_scale, args.tile_scale_1f); + this.gl.uniform1f(this.u_pie_radius, args.pie_radius_1f); + this.gl.uniform2fv(this.u_tile_origin, args.origin_2fv); + this.gl.uniform3fv(this.u_tile_color, args.color_3fv); + this.gl.uniform2fv(this.u_tile_range, args.range_2fv); + this.gl.uniform2i(this.u_draw_mode, modes.edge, modes.or); + this.gl.uniform2fv(this.u_x_bounds, args.x_bounds_2fv); + this.gl.uniform2fv(this.u_y_bounds, args.y_bounds_2fv); + this.gl.uniform1i(this.u_tile_fmt, args.fmt_1i); + this.gl.uniform1i(this.u_id_end, args.id_end_1i); }); + seaGL.addHandler("gl-loaded", function (program) { + // Uniform variables for coloring + this.u_ids_shape = this.gl.getUniformLocation(program, "u_ids_shape"); + this.u_tile_shape = this.gl.getUniformLocation(program, "u_tile_shape"); + this.u_gating_shape = this.gl.getUniformLocation(program, "u_gating_shape"); + this.u_center_shape = this.gl.getUniformLocation(program, "u_center_shape"); + this.u_magnitude_shape = this.gl.getUniformLocation(program, "u_magnitude_shape"); + this.u_tile_fraction = this.gl.getUniformLocation(program, "u_tile_fraction"); + this.u_tile_scale = this.gl.getUniformLocation(program, "u_tile_scale"); + this.u_pie_radius = this.gl.getUniformLocation(program, "u_pie_radius"); + this.u_tile_origin = this.gl.getUniformLocation(program, "u_tile_origin"); + this.u_tile_range = this.gl.getUniformLocation(program, "u_tile_range"); + this.u_tile_color = this.gl.getUniformLocation(program, "u_tile_color"); + this.u_draw_mode = this.gl.getUniformLocation(program, "u_draw_mode"); + this.u_x_bounds = this.gl.getUniformLocation(program, "u_x_bounds"); + this.u_y_bounds = this.gl.getUniformLocation(program, "u_y_bounds"); + this.u_tile_fmt = this.gl.getUniformLocation(program, "u_tile_fmt"); + this.u_id_end = this.gl.getUniformLocation(program, "u_id_end"); + + // Texture for colormap + const u_ids = this.gl.getUniformLocation(program, "u_ids"); + const u_tile = this.gl.getUniformLocation(program, "u_tile"); + const u_gatings = this.gl.getUniformLocation(program, "u_gatings"); + const u_centers = this.gl.getUniformLocation(program, "u_centers"); + const u_magnitudes = this.gl.getUniformLocation(program, "u_magnitudes"); + this.texture_ids = this.gl.createTexture(); + this.texture_mask = this.gl.createTexture(); + this.texture_gatings = this.gl.createTexture(); + this.texture_centers = this.gl.createTexture(); + this.texture_magnitudes = this.gl.createTexture(); + this.gl.uniform1i(u_ids, that.indexOfTexture("ids")); + this.gl.uniform1i(u_tile, that._activeTileTexture); + this.gl.uniform1i(u_gatings, that.indexOfTexture("gatings")); + this.gl.uniform1i(u_centers, that.indexOfTexture("centers")); + this.gl.uniform1i(u_magnitudes, that.indexOfTexture("magnitudes")); + }); - seaGL.addHandler('tile-loaded', (callback, e) => { - var decoder = new Promise(function (resolve, reject) { - try { - const group = e.tile.url.split("/"); - let isLabel = group[group.length - 3] == that.labelChannel.sub_url; - e.tile._blobUrl = e.image?.src; - if (isLabel) { - e.tile._isLabel = true; - if (!e.tile._array) { - e.tile._array = new Int32Array(PNG.sync.read(new Buffer(e.tileRequest?.response || - e.image._array), {colortype: 0}).data.buffer); - } - that.drawLabelTile(e.tile, e.image?.width || e.tile?._tileImageData?.width, e.image?.height - || e.tile?._tileImageData?.height); - - // We're hence skipping that OpenseadragonGL callback since we only care about the vales - return resolve(); - } else { - return callback(e) - // This goes to OpenseadragonGL which does the necessary bit stuff. - } - } catch (err) { - console.log('Load Error, Refreshing', err, e.tile.url); - that.forceRepaint(); + const matchTile = (e, { x, y, level }) => { + const grid = e.tiledImage.tilesMatrix[level]; + return ((grid || {})[x] || {})[y] || {}; + }; - // return callback(e); + seaGL.addHandler("tile-loaded", (callback, e) => { + const { source } = e.tiledImage; + const { tileFormat } = source; + try { + e.tile._blobUrl = e.image?.src; + if (tileFormat == 32) { + e.tile._isLabel = true; + if (!e.tile?._array && e.image?._array) { + const responseArray = e.tileRequest?.response || e.image._array; + const pngBuffer = new Buffer(responseArray); + const pngArray = PNG.sync.read(pngBuffer, { colortype: 0 }); + e.tile._array = new Int32Array(pngArray.data.buffer); + } } - // Notify openseadragon when decoded - decoder.then(e.getCompletionCallback()) - }); + // Trigger loading of image + const tileArgs = [e.tile.level, e.tile.x, e.tile.y]; + const tl = source.toTileLevels(...tileArgs); + if (tl.relativeImageScale < 1) { + const tile = matchTile(e, tl.outputTile); + if (tile?._array && tile?._format) { + e.tile._format = tile._format; + e.tile._array = tile._array; + } + } else { + return callback(e); + } + } catch (err) { + console.log("Load Error, Refreshing", err, e.tile.url); + that.forceRepaint(); + } }); - - this.viewer.addHandler('tile-drawn', (e) => { + this.viewer.addHandler("tile-drawn", (e) => { let count = _.size(e.tiledImage._tileCache._tilesLoaded); e.tiledImage._tileCache._imagesLoadedCount = count; - }) + const canvas = e.eventSource.drawer.canvas; + const context = canvas.getContext("2d"); + context.mozImageSmoothingEnabled = false; + context.webkitImageSmoothingEnabled = false; + context.msImageSmoothingEnabled = false; + context.imageSmoothingEnabled = false; + }); - this.viewer.addHandler('tile-unloaded', (e) => { + this.viewer.addHandler("tile-unloaded", (e) => { if (e.tile._blobUrl) { (window.URL || window.webkitURL).revokeObjectURL(e.tile._blobUrl); } delete e.tile._array; - delete e.tile._tileImageData; - }) - + }); // Instantiate viewer managers - that.viewerManagerVMain = new ViewerManager(that, seaGL.openSD, 'main'); + that.viewerManagerVMain = new ViewerManager(that, seaGL.openSD, "main"); // // // Append to viewers that.viewerManagers.push(that.viewerManagerVMain); seaGL.init(); - /************************************************************************************************** Add layer */ - - // Add overlay - this.csvGatingOverlay = new CsvGatingOverlay(this.viewer, this); - this.viewer.scalebar({ - location: 3, - minWidth: '100px', - type: 'Microscopy', - stayInsideImage: true, - pixelsPerMeter: 0, - fontColor: 'rgb(255, 255, 255)', - color: 'rgb(255, 255, 255)' - }) + location: 3, + minWidth: "100px", + type: "Microscopy", + stayInsideImage: true, + pixelsPerMeter: 0, + fontColor: "rgb(255, 255, 255)", + color: "rgb(255, 255, 255)", + }); // Add listener for scalebar - const controls_scalebar = document.querySelector('#controls_scalebar') - controls_scalebar.addEventListener('change', e => { + const controls_scalebar = document.querySelector("#controls_scalebar"); + controls_scalebar.addEventListener("change", (e) => { this.show_scalebar = e.target.checked; - this.eventHandler.trigger(ImageViewer.events.addScaleBar) - }) + this.eventHandler.trigger(ImageViewer.events.addScaleBar); + }); // Add event mouse handler (cell selection) - this.viewer.addHandler('canvas-nonprimary-press', function (event) { - + this.viewer.addHandler("canvas-nonprimary-press", function (event) { // Right click (cell selection) if (event.button === 2) { // The canvas-click event gives us a position in web coordinates. @@ -276,94 +370,661 @@ class ImageViewer { // Convert from viewport coordinates to image coordinates. const imagePoint = that.viewer.world.getItemAt(0).viewportToImageCoordinates(viewportPoint); - return that.dataLayer.getNearestCell(imagePoint.x, imagePoint.y) - .then(selectedItem => { - if (selectedItem !== null && selectedItem !== undefined) { - // Check if user is doing multi-selection or not - let clearPriors = true; - if (event.originalEvent.ctrlKey) { - clearPriors = false; - } - // Trigger event - that.eventHandler.trigger(ImageViewer.events.imageClickedMultiSel, { - selectedItem, - clearPriors - }); + return that.dataLayer.getNearestCell(imagePoint.x, imagePoint.y).then((selectedItem) => { + if (selectedItem !== null && selectedItem !== undefined) { + // Check if user is doing multi-selection or not + let clearPriors = true; + if (event.originalEvent.ctrlKey) { + clearPriors = false; } - }) + // Trigger event + that.eventHandler.trigger(ImageViewer.events.imageClickedMultiSel, { + selectedItem, + clearPriors, + }); + } + }); } }); + } + /** + * @function init - initializes OSD channel and gating options + * @param gatingList - CSVGatingList instance + */ + init(gatingList) { + this.gatingList = gatingList; + // Define this as that + this.ready = true; } /** - * @function drawLabelTile - cell-based rendering using the segmentation mask - * @param tile - the tile to draw - * @param width - width of the tile - * @param height - height of the tile + * @function indexOfTexture -- return integer for named texture + * @param label - the texture key label + * @returns number */ - drawLabelTile(tile, width, height) { - const self = this; - let imageData = new ImageData(new Uint8ClampedArray(width * height * 4), width, height); - tile._tileImageData = imageData; - const valInc = 0; - if (self.show_selection && self.selection.size > 0) { - tile._array.forEach((val, i) => { - if (val !== 0 && self.selection.has(val + valInc)) { - let labelValue = val + valInc; - let phenotype = _.get(seaDragonViewer.selection.get(labelValue), 'phenotype'); - //set color to white but when phenotype column in passed selection, use that for coloring - let color = [255, 255, 255]; - // if (phenotype !== undefined) { - // color = seaDragonViewer.colorScheme.colorMap[phenotype].rgb; - // } - let index = i * 4; - const grid = [ - index - 4, - index + 4, - index - width * 4, - index + width * 4 - ]; - const test = [ - index % (width * 4) !== 0, - index % (width * 4) !== (width - 1) * 4, - index >= width * 4, - index < width * 4 * (height - 1) - ]; - - // If outline - if (this.viewerManagerVMain.sel_outlines) { - // Iterate grid - for (let j = 0; j < grid.length; j++) { - // if pass test (not on tile border) - if (test[j]) { - // Neighbor label value - const altLabelValue = tile._array[grid[j] / 4] + valInc; - // Color - if (altLabelValue !== labelValue) { - tile._tileImageData.data[index] = color[0]; - tile._tileImageData.data[index + 1] = color[1]; - tile._tileImageData.data[index + 2] = color[2]; - tile._tileImageData.data[index + 3] = 255; - tile.containsLabel = true; - break; - } - } - } - } else { - tile._tileImageData.data[index] = color[0]; - tile._tileImageData.data[index + 1] = color[1]; - tile._tileImageData.data[index + 2] = color[2]; - tile._tileImageData.data[index + 3] = 255; - tile.containsLabel = true; - } - /************************ newend */ + indexOfTexture(label) { + const via = this.viaGL; + // Non-image textures always same index + const index0 = via._constantTextures.indexOf(label); + if (index0 > -1) { + return index0 + via._constantTextureOffset; + } + const index1 = via._tileTextures.indexOf(label); + if (index1 > -1) { + return index1; + } + const index2 = via._nextTileTexture; + const maximum = via._tileTextures.length; + via._nextTileTexture = (index2 + 1) % maximum; + via._tileTextures[index2] = label; + return index2; + } + + /** + * Most recently bound texture label + * + * @type {string} + */ + get activeTextureLabel() { + const via = this.viaGL; + return via._tileTextures[via._activeTileTexture]; + } + + /** + * Flags for mode of webGL rendering. + * + * @typedef {object} ModeFlags + * @property {boolean} edge - render outlines + * @property {boolean} or - render pie charts + * @type {ModeFlags} + */ + get modeFlags() { + const edge = this.viewerManagerVMain.sel_outlines; + const or = this.gatingList?.eval_mode == "or"; + return { edge, or }; + } + + /** + * Gating Keys for webGL rendering. + * + * @type {Array} + */ + get gatingKeys() { + const keys = Object.keys(this.gatingSelections); + return keys.sort(); + } + + /** + * Gating selections. + * + * @type {Array} + */ + get gatingSelections() { + return this.gatingList?.selections || {}; + } + + /** + * Channel selections. + * + * @type {Array} + */ + get channelSelections() { + return this.channelList.currentChannels || {}; + } + + /** + * @function removeChannelSelection - remove channel from channel list + * @param srcIdx - integer id of channel to add + */ + removeChannelSelection(srcIdx) { + if (srcIdx in this.channelList.currentChannels) { + delete this.channelList.currentChannels[srcIdx]; + } + } + + /** + * @function toCacheKey -- generate cache keys of gl properties + * @param idCount - number of active cell ids + * @param keys - active marker channels + * @param markerLists - data for each marker + * @returns string + */ + toCacheKey(idCount, keys, markerLists) { + const precisions = [2 ** 25, 2 ** 25, 255, 255, 255]; + const tuples = keys.map((channel, i) => { + const idx = 1 + this.selectMaskIndex(channel); + const hashes = markerLists[i].map((r, j) => { + // use precision for each item + const integral = r * precisions[j]; + return parseInt(integral).toString(36); + }); + return [idx, ...hashes].join("-"); + }); + return [idCount, ...tuples].join("-"); + } + + /** + * Cache key for gating webGL buffer. + * + * @type {string} + */ + + get fullCacheKey() { + return this._cacheKeys.full; + } + + set fullCacheKey(key) { + this._cacheKeys.full = key; + } + + /** + * Cache key for magnitude/center webGL buffers. + * + * @type {string} + */ + + get orCacheKey() { + return this._cacheKeys.or; + } + + set orCacheKey(key) { + this._cacheKeys.or = key; + } + + /** + * Cache key for most webGL buffers. + * + * @type {string} + */ + + get mainCacheKey() { + return this._cacheKeys.main; + } + + set mainCacheKey(key) { + this._cacheKeys.main = key; + } + + /** + * Ready to render + * + * @type {boolean} + */ + + get ready() { + return this._ready; + } + + set ready(_ready) { + this._ready = _ready; + } + + /** + * @function addChannelSelection - add channel to channel list + * @param srcIdx - integer id of channel to add + * @param viewerChannel - channel properties + */ + addChannelSelection(srcIdx, viewerChannel) { + const range = this.channelList.rangeConnector[srcIdx]; + const { color } = this.channelList.colorConnector[srcIdx] || {}; + this.channelList.currentChannels[srcIdx] = { + url: viewerChannel.url, + sub_url: viewerChannel.sub_url, + color: color || d3.color("white"), + range: range || this.dataLayer.getImageBitRange(true) + }; + } + + /** + * @function loadBuffers -- loads segmentation mask data to WebGL + * @param idCount - number of active cell ids + */ + loadBuffers(idCount) { + const keys = this.gatingKeys; + const { gatings, ranges } = this.selectGatings(keys); + const changes = this.updateCache(idCount, keys, gatings, ranges); + const { idsChanged, orChange, gatesChanged } = changes; + + // Bind buffers per-channel + if (gatesChanged) { + const allGatings = []; + for (const gating of gatings) { + for (const gatingValue of gating) { + allGatings.push(gatingValue); + } + } + this.bindGatings(this.viaGL, allGatings, 5); + } + // List cell ids as array + const needIds = idsChanged || orChange; + const ids = needIds ? [...this.selection.keys()] : []; + // Bind buffers per-cell + if (idsChanged) { + this.bindLabels(this.viaGL, ids); + } + // Bind or-mode buffers per-cell + if (orChange && this.modeFlags.or) { + this.selectCellMagnitudes(ids, keys); + this.selectCenters(ids); + } + } + + /** + * @function clearCache -- clear cached props + */ + clearCache() { + this._cacheKeys = {}; + } + + /** + * @function selectCenters -- return cell centers + * @param ids - active cell ids + * @returns Array + */ + selectCenters(ids) { + const xKey = "X_centroid"; + const yKey = "Y_centroid"; + + const centers = []; + try { + for (const id of ids) { + const values = this.selection.get(id); + if (xKey in values && yKey in values) { + centers.push(values.X_centroid); + centers.push(values.Y_centroid); + } else { + throw new TypeError(`Missing "${xKey}" "${yKey}" in selection.`); + } + } + } catch (e) { + if (e instanceof TypeError) { + console.warn(e); + return []; + } + throw e; + } + + if (centers.length) { + this.bindCenters(this.viaGL, centers); + } + return centers; + } + + /** + * @function selectCenterProps -- return cell centers properties + * @param tile - openseadragon tile + * @param source - openseadragon tile source + * @typedef {object} CenterProps + * @property {number} pie_radius_1f - radius of or-mode circles + * @property {number} tile_fraction_1f - subtile fraction <=1 + * @property {number} tile_scale_1f - image tile scale >=1 + * @property {Array} x_bounds_2fv - subtile start/end in x + * @property {Array} y_bounds_2fv - subtile start/end in y + * @property {Array} origin_2fv - origin at texture resolution + * @returns CenterProps + */ + selectCenterProps(tile, source) { + const w = this.config.tileWidth; + const h = this.config.tileHeight; + const tileArgs = [tile.level, tile.x, tile.y]; + const tl = source.toTileLevels(...tileArgs); + const { outputTile, relativeImageScale } = tl; + const origin = [outputTile.x * w, outputTile.y * h]; + const bounds = source.toMagnifiedBounds(...tileArgs); + + return { + pie_radius_1f: 8.5, + tile_scale_1f: Math.max(relativeImageScale, 1.0), + tile_fraction_1f: Math.min(relativeImageScale, 1.0), + x_bounds_2fv: new Float32Array(bounds.x), + y_bounds_2fv: new Float32Array(bounds.y), + origin_2fv: new Float32Array(origin), + }; + } + /** + * @function selectCellMagnitudes -- select magnitude ranges + * @param ids - active cell ids + * @param keys - active marker channels + * @returns Array + */ + selectCellMagnitudes(ids, keys) { + const magnitudes = []; + + try { + for (const id of ids) { + const values = this.selection.get(id); + for (const key of keys) { + if (!(key in values)) { + throw new TypeError(`Missing "${key}" in selection "${id}".`); } + magnitudes.push(values[key]); } - ) + } + } catch (e) { + if (e instanceof TypeError) { + console.warn(e); + return []; + } + throw e; + } + + const keyCount = Math.max(keys.length, 1); + if (magnitudes.length) { + this.bindMagnitudes(this.viaGL, magnitudes, keyCount); + } + + return magnitudes; + } + + /** + * @function selectGatings -- select gating ranges + * @param keys - active marker channels + * @typedef {object} Gatings + * @property {Array} ranges - min and max values for channel + * @property {Array} gatings - min, max, and r, g, b gating values + * @returns Gatings + */ + selectGatings(keys) { + const ranges = []; + const gatings = []; + const selections = this.gatingSelections; + for (const key of keys) { + const range = selections[key].map((x) => parseFloat(x)); + const color = this.selectMaskColor(key); + const floatColor = toFloatColor(color); + const gating = range.concat(floatColor); + gatings.push(gating); + ranges.push(range); + } + + return { + ranges, + gatings, + }; + } + + /** + * @function updateCache -- update cache keys + * @param idCount - number of active cell ids + * @param keys - active marker channels + * @param gatings - cell ranges + colors + * @param ranges - cell ranges array + * @typedef {object} Changes + * @property {boolean} orChange - if or-mode has changed + * @property {boolean} idsChanged - if list of ids changed + * @property {boolean} gatesChanged - if gating parameters changed + * @returns Changes + */ + updateCache(idCount, keys, gatings, ranges) { + const mainCacheKey = this.toCacheKey(idCount, keys, ranges); + const idsChanged = this.mainCacheKey !== mainCacheKey; + if (idsChanged) { + this.mainCacheKey = mainCacheKey; + } + + const orCacheKey = this.modeFlags.or ? mainCacheKey : null; + const orChange = this.orCacheKey !== orCacheKey; + if (orChange) { + this.orCacheKey = orCacheKey; + } + + const fullCacheKey = this.toCacheKey(idCount, keys, gatings); + const gatesChanged = this.fullCacheKey !== fullCacheKey; + if (gatesChanged) { + this.fullCacheKey = fullCacheKey; + } + + return { orChange, idsChanged, gatesChanged }; + } + + /** + * @function selectMaskColor -- select color for mask + * @param channel - the channel label + * @typedef {object} Color + * @property {number} r - 0-255 + * @property {number} g - 0-255 + * @property {number} b - 0-255 + * @returns Color + */ + selectMaskColor(channel) { + const white = { + r: 255, + g: 255, + b: 255, + }; + if (!channel) { + return white; + } + const channels = this.channelSelections; + const idxString = (this.selectMaskIndex(channel) + 1).toString(); + if (idxString == "0" || !Object.keys(channels).includes(idxString)) { + return white; + } + const data = channels[idxString]; + return data.color; + } + + /** + * @function selectMaskIndex -- select index for mask + * @param channel - the channel label + * @returns number + */ + selectMaskIndex(channel) { + return this.channelList.columns.indexOf(channel); + } + + /** + * @function selectTexture - activate a WebGL texture + * @param gl - the WebGL2 context + * @param texture - the WebGL2 texture + * @param idx - the texture index + */ + selectTexture(gl, texture, idx) { + // Set texture for GLSL + gl.activeTexture(gl["TEXTURE" + idx]); + gl.bindTexture(gl.TEXTURE_2D, texture); + gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1); + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + + // Assign texture parameters + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + } + + /** + * @function toTextureShape - shape of texture data + * @param gl - the WebGL2 context + * @param values - the texture data as an array + * @returns Array + */ + toTextureShape(gl, values) { + const width = gl.getParameter(gl.MAX_TEXTURE_SIZE); + const height = Math.ceil(values.length / width); + return [width, height]; + } + + /** + * @function packFloat - pack 1D float texture as 2D + * @param gl - the WebGL2 context + * @param a - the texture data as an array + * @typedef {object} Packed + * @property {number} width - width of texture + * @property {number} height - height of texture + * @property {Array} pixels - packed 1D array as 2D + * @returns Packed + */ + packFloat(gl, a) { + const [width, height] = this.toTextureShape(gl, a); + const pixels = this.packFloat32(a, width, height); + return { width, height, pixels }; + } + + /** + * @function packInteger - pack 1D integer texture as 2D + * @param gl - the WebGL2 context + * @param a - the texture data as an array + * @typedef {object} Packed + * @property {number} width - width of texture + * @property {number} height - height of texture + * @property {Array} pixels - packed 1D array as 2D + * @returns Packed + */ + packInteger(gl, a) { + const [width, height] = this.toTextureShape(gl, a); + const pixels = this.packUint8(a, width, height); + return { width, height, pixels }; + } + + /** + * @function packFloat32 - pack Float32 Texture + * @param a - the texture data as an array + * @param width - the texture width + * @param height - the texture height + * @returns array + */ + packFloat32(a, width, height) { + // Create 2D array of pixels + const full_size = width * height; + const arr = new ArrayBuffer(4 * full_size); + const view = new DataView(arr); + for (const i in a) { + view.setFloat32(4 * i, a[i], true); + } + return new Float32Array(arr); + } + + /** + * @function packUint8 - pack Uint8 Texture + * @param a - the texture data as an array + * @param width - the texture width + * @param height - the texture height + * @returns array + */ + packUint8(a, width, height) { + // Create 2D array of pixels + const full_size = width * height; + const arr = new ArrayBuffer(4 * full_size); + const view = new DataView(arr); + for (const i in a) { + view.setUint32(4 * i, a[i], true); } + return new Uint8Array(arr); + } + + /** + * @function setLabelMap - set the segmentation mask ids + * @param gl - the WebGL2 context + * @param texture - the WebGL2 texture + * @param values - the texture data as 2d array + */ + setLabelMap(gl, texture, values) { + const packed = this.packInteger(gl, values); + // Set texture for GLSL + this.selectTexture(gl, texture, this.indexOfTexture("ids")); + // Send an empty array to the texture + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8UI, packed.width, packed.height, 0, gl.RGBA_INTEGER, gl.UNSIGNED_BYTE, packed.pixels); + } + + /** + * @function setMagnitudeMap - set the segmentation mask magnitudes + * @param gl - the WebGL2 context + * @param texture - the WebGL2 texture + * @param values - the texture data as 2d array + */ + setMagnitudeMap(gl, texture, values) { + const packed = this.packFloat(gl, values); + // Set texture for GLSL + this.selectTexture(gl, texture, this.indexOfTexture("magnitudes")); + // Send an empty array to the texture + gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, packed.width, packed.height, 0, gl.RED, gl.FLOAT, packed.pixels); + } + + /** + * @function setCenterMap - set the segmentation mask centers + * @param gl - the WebGL2 context + * @param texture - the WebGL2 texture + * @param values - the texture data as 2d array + */ + setCenterMap(gl, texture, values) { + const packed = this.packInteger(gl, values); + // Set texture for GLSL + this.selectTexture(gl, texture, this.indexOfTexture("centers")); + // Send an empty array to the texture + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8UI, packed.width, packed.height, 0, gl.RGBA_INTEGER, gl.UNSIGNED_BYTE, packed.pixels); + } + + /** + * @function setGatingMap - set the segmentation mask gatings + * @param gl - the WebGL2 context + * @param texture - the WebGL2 texture + * @param values - the texture data as 2d array + * @param width - the texture width + * @param height - the texture height + */ + setGatingMap(gl, texture, values, width, height) { + const pixels = this.packFloat32(values, width, height); + // Set texture for GLSL + this.selectTexture(gl, texture, this.indexOfTexture("gatings")); + // Send an empty array to the texture + gl.texImage2D(gl.TEXTURE_2D, 0, gl.R32F, width, height, 0, gl.RED, gl.FLOAT, pixels); + } + + /** + * @function bindLabels - bind segmentation mask ids + * @param via - the viaGL context + * @param values - the texture data as 2d array + */ + bindLabels(via, values) { + // Add id mask map + const ids_2iv = this.toTextureShape(via.gl, values); + via.gl.uniform2iv(via.u_ids_shape, ids_2iv); + this.setLabelMap(via.gl, via.texture_ids, values); + } + + /** + * @function bindMagnitudes - bind segmentation mask magnitudes + * @param via - the viaGL context + * @param values - the texture data as 2d array + * @param depth - number of items at each texel + */ + bindMagnitudes(via, values, depth) { + // Add a mask magnitude map + const magnitude_2iv = this.toTextureShape(via.gl, values); + const magnitude_3iv = magnitude_2iv.concat(depth); + via.gl.uniform3iv(via.u_magnitude_shape, magnitude_3iv); + this.setMagnitudeMap(via.gl, via.texture_magnitudes, values); + } + + /** + * @function bindCenters - bind segmentation mask centers + * @param via - the viaGL context + * @param values - the texture data as 2d array + */ + bindCenters(via, values) { + // Add a mask center map + const center_2iv = this.toTextureShape(via.gl, values); + const center_3iv = center_2iv.concat([2]); + via.gl.uniform3iv(via.u_center_shape, center_3iv); + this.setCenterMap(via.gl, via.texture_centers, values); + } + + /** + * @function bindGatings - bind segmentation mask gating + * @param via - the viaGL context + * @param values - the texture data as 2d array + * @param width - the texture width + */ + bindGatings(via, values, width) { + // Add a mask gating map + const height = Math.floor(values.length / width); + const gating_2iv = [width, height]; + via.gl.uniform2iv(via.u_gating_shape, gating_2iv); + this.setGatingMap(via.gl, via.texture_gatings, values, width, height); } // ================================================================================================================= @@ -372,15 +1033,21 @@ class ImageViewer { /** * @function createTFArray - creates an array of colors as a transfer/lookup table for pixel values. - * @param min the minimum value + * @param min - the minimum value * @param max - the maximum value * @param rgb1 - the start color (min) * @param rgb2 - the end color (max) * @param numBins - the bins for the color interpolation steps - * @returns {{tf: Array, min: *, max: *, num_bins: *, start_color: *, end_color: *}} + * @typedef {object} TF + * @property {Array} tf - color list + * @property {number} min - min cutoff + * @property {number} max - max cutoff + * @property {number} num_bins - number of bins + * @property {object} start_color - lower limit color + * @property {object} end_color - upper limit color + * @returns TF */ createTFArray(min, max, rgb1, rgb2, numBins) { - const tfArray = []; const numBinsF = parseFloat(numBins); @@ -389,7 +1056,7 @@ class ImageViewer { for (let i = 0; i < numBins; i++) { const rgbTupel = {}; - const lerpFactor = (i / (numBinsF - 1.0)); + const lerpFactor = i / (numBinsF - 1.0); rgbTupel.r = col1.r + (col2.r - col1.r) * lerpFactor; rgbTupel.g = col1.g + (col2.g - col1.g) * lerpFactor; @@ -400,139 +1067,60 @@ class ImageViewer { } return { - min: min, max: max, start_color: rgb1, end_color: rgb2, + min: min, + max: max, + start_color: rgb1, + end_color: rgb2, num_bins: numBins, - tf: tfArray - } + tf: tfArray, + }; } - /** - * @function actionFocus - sets a viewport based on an action (tool or user driven) - * - * @param vp - viewport - * @returns void + * @function forceRepaint - for all active viewers repaint the canvas */ - actionFocus(vp) { - this.setViewPort(vp.x, vp.y, vp.width, vp.height); + forceRepaint() { + // Trigger change of full cache + this.fullCacheKey = null; + // Refilter, redraw + this.viewerManagers.forEach(({viewer}) => { + viewer.forceRedraw(); + }); } /** - * @function setViewPort - * - * @param {int} x - * @param {int} y - * @param {int} width - * @param {int} height - * - * @returns void + * @function sleep - temporarily disable new renders until data loads + * @return {function(): void} - a callback to re-enable rendering */ - setViewPort(x, y, width, height) { - - // Calc from main viewer - const coords = this.viewer.viewport.imageToViewportCoordinates(x, y); - const lowerBounds = this.viewer.viewport.imageToViewportCoordinates(width, height); - const box1 = new OpenSeadragon.Rect(coords.x, coords.y, lowerBounds.x, lowerBounds.y); - - // Apply to all viewers - this.viewerManagers.forEach(vM => { - vM.viewer.viewport.fitBounds(box1); + sleep() { + this.ready = false; + this.viewerManagers.forEach(({viewer}) => { + viewer.world._needsDraw = false; }); + return () => { + this.ready = true; + this.viewerManagers.forEach(({viewer}) => { + viewer.world._needsDraw = true; + }); + } } - // ================================================================================================================= - // Rendering - // ================================================================================================================= - - /** - * @function drawCellRadius - draws a circle with certain radius around a cell - * - * @param radius - * @param selection - * @param - whether it fades out - */ - drawCellRadius(radius, selection, dragging = false) { - - let x = selection[dataLayer.x]; - let y = selection[dataLayer.y]; - let imagePoint = this.viewer.world.getItemAt(0).imageToViewportCoordinates(x, y); - let circlePoint = this.viewer.world.getItemAt(0).imageToViewportCoordinates(x + _.toNumber(radius), y); - let viewportRadius = Math.abs(circlePoint.x - imagePoint.x); - let overlay = seaDragonViewer.viewer.svgOverlay(); - let fade = 0; - // When dragging the bar, don't fade out - if (dragging) { - fade = 1; - } - - let circle = d3.select(overlay.node()) - .selectAll('.radius-circle') - .interrupt() - .data([{'x': imagePoint.x, 'y': imagePoint.y, 'r': viewportRadius}]) - circle.enter() - .append("circle") - .attr("class", "radius-circle") - .merge(circle) - .attr("cx", d => { - return d.x; - }) - .attr("cy", d => { - return d.y; - }) - .attr("r", d => { - return d.r; - }) - .style("opacity", 1) - .transition() - .duration(1000) - .ease(d3.easeLinear) - .style("opacity", fade); - circle.exit().remove(); - - } - - /**Z - * @function forceRepaint - for all active viewers repaint the canvas - * - * @returns void - */ - forceRepaint() { - // Refilter, redraw - this.viewerManagers.forEach(vM => { - vM.viewer.forceRefilter(); - vM.viewer.forceRedraw(); - }); - } /** * @function updateActiveChannels - * - * @param name - * @param selection - * @param status - * - * @returns void + * @param name - image channel name + * @param action - "add" or "remove" */ - updateActiveChannels(name, selection, status) { - + updateActiveChannels(name, action) { const channelIdx = imageChannels[name]; - if (selection.length === 0) { - // console.log('nothing selected - keep showing last image'); - // return; - } else if (selection.length === 1) { - // console.log('1 channel selected'); - } else { - // console.log('multiple channels selected'); - } - - if (status) { - this.viewerManagers.forEach(vM => { + if (action == "add") { + this.viewerManagers.forEach((vM) => { vM.channel_add(channelIdx); }); } else { - this.viewerManagers.forEach(vM => { + this.viewerManagers.forEach((vM) => { vM.channel_remove(channelIdx); }); } @@ -542,20 +1130,17 @@ class ImageViewer { /** * @function updateChannelRange - * - * @param name - * @param tfmin - * @param tfmax - * - * @returns void + * @param name - image channel name + * @param tfmin - minimum + * @param tfmax - maximum */ updateChannelRange(name, tfmin, tfmax) { const self = this; let range = self.dataLayer.getImageBitRange(); const channelIdx = imageChannels[name]; - if (self.channelList.currentChannels[channelIdx]) { + if (self.channelSelections[channelIdx]) { let channelRange = [tfmin / range[1], tfmax / range[1]]; - self.channelList.currentChannels[channelIdx]['range'] = channelRange; + self.channelSelections[channelIdx].range = channelRange; self.channelList.rangeConnector[channelIdx] = channelRange; } this.forceRepaint(); @@ -563,99 +1148,61 @@ class ImageViewer { /** * @function updateChannelColors - * - * @param name - * @param color - * @param type - * - * @returns void + * @param name - image channel name + * @param color - rgb object with values 0-255 */ - updateChannelColors(name, color, type) { + updateChannelColors(name, color) { const self = this; const channelIdx = imageChannels[name]; - if (self.channelList.currentChannels[channelIdx]) { - self.channelList.colorConnector[channelIdx] = {color: color}; - self.channelList.currentChannels[channelIdx]['color'] = color; - // self.channelTF[channelIdx].end_color = color; + if (self.channelSelections[channelIdx]) { + self.channelList.colorConnector[channelIdx] = { color: color }; + self.channelSelections[channelIdx].color = color; } this.forceRepaint(); } - /** - * @function updateData - * - * @param data - * - * @returns void - */ - updateData(data) { - - this.data = data; - this.forceRepaint(); - } - /** * @function updateRenderingMode - * - * @param mode - * - * @returns void + * @param mode -- subset or selection */ updateRenderingMode(mode) { - // Mode is a string: 'show-subset', 'show-selection' - if (mode === 'show-subset') { + if (mode === "show-subset") { this.show_subset = !this.show_subset; } - if (mode === 'show-selection') { + if (mode === "show-selection") { this.show_selection = !this.show_selection; } this.forceRepaint(); - } /** * @function updateSelection - * - * @param selection - * @param repaint - * - * @returns void + * @param selection - map of ids selected + * @param repaint - if repaint needed */ - updateSelection(selection, repaint = true) { + updateSelection(selection) { this.selection = selection; - // Reload Label Tiles - let tileLevels = this.viewer.world.getItemAt(0).tilesMatrix; - for (const [levelKey, level] of Object.entries(tileLevels)) { - for (const [levelKey, tile] of Object.entries(level)) { - for (const [subLevelKey, subTile] of Object.entries(tile)) { - subTile._redrawLabel = true; - } - - } - } - this.viewer.forceRedraw(); - if (repaint) this.forceRepaint(); - + this.forceRepaint(); } - addScaleBar(){ + addScaleBar() { let pixelsPerMeter; - if (this.show_scalebar){ + if (this.show_scalebar) { let unitConvert; - if (this.imgMetadata.physical_size_x_unit === "µm" || this.imgMetadata.physical_size_x_unit === "um"){ + if (this.imgMetadata.physical_size_x_unit === "µm" || this.imgMetadata.physical_size_x_unit === "um") { unitConvert = 1000000; - } else if (this.imgMetadata.physical_size_x_unit === "nm"){ + } else if (this.imgMetadata.physical_size_x_unit === "nm") { unitConvert = 1000000000; - } else if (this.imgMetadata.physical_size_x_unit === "cm"){ + } else if (this.imgMetadata.physical_size_x_unit === "cm") { unitConvert = 100; - } else if (this.imgMetadata.physical_size_x_unit === "m"){ + } else if (this.imgMetadata.physical_size_x_unit === "m") { unitConvert = 1; - } else{ + } else { unitConvert = 0; } - pixelsPerMeter = unitConvert*this.imgMetadata.physical_size_x; + pixelsPerMeter = unitConvert * this.imgMetadata.physical_size_x; } else { pixelsPerMeter = 0; } @@ -667,43 +1214,17 @@ class ImageViewer { } // Static vars -ImageViewer - .events = { - imageClickedMultiSel: 'image_clicked_multi_selection', - renderingMode: 'renderingMode', - addScaleBar: 'addScaleBar' +ImageViewer.events = { + imageClickedMultiSel: "image_clicked_multi_selection", + renderingMode: "renderingMode", + addScaleBar: "addScaleBar", }; -async function addTile(path) { - const addJob = new Promise((resolve, reject) => { - - // If we're currently waiting for a tile to load, just use it's callback - if (seaDragonViewer.pendingTiles.has(path)) { - return seaDragonViewer.pendingTiles.get(path); - } - - // seaDragonViewer.pendingTiles.add(path); - function callback(success, error, request) { - if (success) { - console.log("Emergency Added Tile:", path); - seaDragonViewer.pendingTiles.delete(path) - resolve(success); - } else { - error(); - } - } - - seaDragonViewer.pendingTiles.set(path, callback); - - - const options = { - src: path, - loadWithAjax: true, - crossOriginPolicy: false, - ajaxWithCredentials: false, - callback: callback - } - seaDragonViewer.viewer.imageLoader.addJob(options) - }); - await Promise.all([addJob]) +/** + * @function toFloatColor - convert 0-255 rgb color to 0-1 float array + * @param color - rgb object with values 0-255 + * @returns array + */ +function toFloatColor(color) { + return [color.r / 255, color.g / 255, color.b / 255]; } diff --git a/minerva_analysis/client/src/js/views/lensingFilters/lfChannelView.js b/minerva_analysis/client/src/js/views/lensingFilters/lfChannelView.js index d3b3c26ca..efbde8bba 100644 --- a/minerva_analysis/client/src/js/views/lensingFilters/lfChannelView.js +++ b/minerva_analysis/client/src/js/views/lensingFilters/lfChannelView.js @@ -33,13 +33,15 @@ export class LfChannelView { const auxiManager = this.image_viewer.viewerManagerVAuxi; // Get keys - const keys = Object.keys(mainManager.viewer_channels); + const keys = mainManager.viewer_channels.keys(); keys.forEach((k, i) => { - if (+k === this.vars.currentChannel.index) { + if (k === this.vars.currentChannel.index) { if (i < keys.length - 1) { - this.vars.currentChannel.name = mainManager.viewer_channels[keys[i + 1]].short_name; + const channel = mainManager.viewer_channels.get(keys[i + 1]); + this.vars.currentChannel.name = channel.short_name; } else { - this.vars.currentChannel.name = mainManager.viewer_channels[keys[0]].short_name; + const channel = mainManager.viewer_channels.get(keys[0]); + this.vars.currentChannel.name = channel.short_name; } this.vars.forceUpdate = true; } @@ -210,18 +212,19 @@ export class LfChannelView { const auxiManager = this.image_viewer.viewerManagerVAuxi; // If multi channel - if (Object.keys(auxiManager.viewer_channels).length > 1 || this.vars.forceUpdate) { + if (auxiManager.viewer_channels.size > 1 || this.vars.forceUpdate) { // Undo force status this.vars.forceUpdate = false; // Update viewer channels - for (let k in mainManager.viewer_channels) { + for (const k in mainManager.viewer_channels.keys()) { // Reduce to single channel - if (mainManager.viewer_channels[k].short_name === this.vars.currentChannel.name) { - auxiManager.viewer_channels = {}; - auxiManager.viewer_channels[`${k}`] = mainManager.viewer_channels[k]; + const channel = mainManager.viewer_channels.get(k); + if (channel.short_name === this.vars.currentChannel.name) { + auxiManager.viewer_channels = new Map(); + auxiManager.viewer_channels.set(k, channel); this.vars.currentChannel.index = +k; auxiManager.force_repaint(); break; @@ -357,4 +360,4 @@ export class LfChannelView { } } -} \ No newline at end of file +} diff --git a/minerva_analysis/client/src/js/views/viewerManager.js b/minerva_analysis/client/src/js/views/viewerManager.js index 206a21146..931c15c5a 100644 --- a/minerva_analysis/client/src/js/views/viewerManager.js +++ b/minerva_analysis/client/src/js/views/viewerManager.js @@ -1,5 +1,137 @@ import "regenerator-runtime/runtime.js"; +/** + * @function toIdealTile -- full tile dimension in full image pixels + * @param fullScale - scale factor to full image + * @param useY - 0 for x and 1 for y + * @returns Number + */ +function toIdealTile(fullScale, useY) { + const { _tileWidth, _tileHeight } = this; + return [_tileWidth, _tileHeight][useY] * fullScale; +} + +/** + * @function toIdealTile -- clipped tile dimension in full image pixels + * @param fullScale - scale factor to full image + * @param v - x or y index of tile + * @param useY - x=0 and y=1 + * @returns Number + */ +function toRealTile(fullScale, v, useY) { + const shape = [this.width, this.height][useY]; + const tileShape = this.toIdealTile(fullScale, useY); + return Math.min(shape - v * tileShape, tileShape); +} + +/** + * @function toTileBoundary -- tile start and size in full image pixels + * @param fullScale - scale factor to full image + * @param v - x or y index of tile + * @param useY - x=0 and y=1 + * @typedef {object} Bound + * @property {number} start - full image pixel start of tile + * @property {number} size - full image pixel size of tile + * @returns Bound + */ +function toTileBoundary(fullScale, v, useY) { + const start = v * this.toIdealTile(fullScale, useY); + const size = this.toRealTile(fullScale, v, useY) + return {start, size}; +} + +/** + * @function toMagnifiedBounds -- return bounds of magnified tile + * @param _level - openseadragon tile level + * @param _x - openseadragon tile x index + * @param _y - openseadragon tile y index + * @typedef {object} Bounds + * @property {Array} x - start and end image x-coordinates + * @property {Array} y - start and end image y-coordinates + * @returns Bounds + */ +function toMagnifiedBounds(_level, _x, _y) { + const tl = this.toTileLevels(_level, _x, _y); + if (tl.relativeImageScale >= 1) { + return { x: [0, 1], y: [0, 1] }; + } + const ownScale = tl.outputFullScale; + const parentScale = tl.inputFullScale; + const [x, y] = [tl.outputTile.x, tl.outputTile.y].map((parentOffset, i) => { + const hd = this.toTileBoundary(ownScale, [_x, _y][i], i); + const sd = this.toTileBoundary(parentScale, parentOffset, i); + const start = (hd.start - sd.start) / sd.size; + const end = start + hd.size / sd.size; + return [ + [start, end], + [1 - end, 1 - start], + ][i]; + }); + return { x, y }; +} + +/** + * @function toTileLevels -- measure scaled/non-scaled tile details + * @param level - openseadragon tile level + * @param x - openseadragon tile x index + * @param y - openseadragon tile y index + * @typedef {object} TileLevels + * @property {number} inputFullScale - full scale of source tile + * @property {number} outputFullScale - full scale of renedered tile + * @property {number} relativeImageScale - scale relative to image pixels + * @property {object} inputTile - level, x, and y of source tile + * @property {object} outputTile - level, x, and y of rendered tile + * @returns TileLevels + */ +function toTileLevels(level, x, y) { + const { extraZoomLevels } = this; + const flipped = this.maxLevel - level; + const relativeLevel = flipped - extraZoomLevels; + const sourceLevel = Math.max(relativeLevel, 0); + const extraZoom = sourceLevel - relativeLevel; + const inputTile = { + x: Math.floor(x / 2 ** extraZoom), + y: Math.floor(y / 2 ** extraZoom), + level: sourceLevel, + }; + const outputTile = { + ...inputTile, + level: level - extraZoom, + }; + return { + inputFullScale: 2 ** (flipped + extraZoom), + relativeImageScale: 2 ** relativeLevel, + outputFullScale: 2 ** flipped, + inputTile, + outputTile, + }; +} + +/** + * @function getTileUrl -- return url for tile + * @param level - openseadragon tile level + * @param x - openseadragon tile x index + * @param y - openseadragon tile y index + * @returns string + */ +function getTileUrl(level, x, y) { + const s = this.toTileLevels(level, x, y).inputTile; + return `${this.src}${s.level}/${s.x}_${s.y}.png`; +} + +/** + * @function getTileKey -- return string key for tile + * @param level - openseadragon tile level + * @param x - openseadragon tile x index + * @param y - openseadragon tile y index + * @returns string + */ +function getTileKey(level, x, y) { + const { srcIdx, tileFormat } = this; + const s = this.toTileLevels(level, x, y).inputTile; + return `${tileFormat}-${srcIdx}-${s.level}-${s.x}-${s.y}`; +} + /** * @class ViewerManager */ @@ -11,17 +143,15 @@ export class ViewerManager { sel_outlines = true; /** - * @constructor * Constructs a ColorManager instance before delegating initialization. * - * @param {Object} _viewer + * @param _imageViewer - ImageViewer instance + * @param _viewer - Openseadragon instance */ - constructor(_imageViewer, _viewer, _viewerName) { + constructor(_imageViewer, _viewer) { this.viewer = _viewer; this.imageViewer = _imageViewer; - this.viewer_name = _viewerName; - this.viewer_channels = {}; - this.channelList = channelList; + this.viewer_channels = new Map(); this.init(); } @@ -29,117 +159,102 @@ export class ViewerManager { /** * @function init * Setups up the color manager. - * - * @returns void */ init() { // Load label image this.load_label_image(); - - } - /** * @function channel_add * Add channel to multi-channel rendering - * - * @param srcIdx + * @param srcIdx - integer id of channel to add */ channel_add(srcIdx) { - const self = this; - // If already exists - if ((srcIdx in this.channelList.currentChannels)) { + if (this.viewer_channels.has(srcIdx)) { return; } - // Get dzi path - const src = this.imageViewer.config["imageData"][srcIdx]["src"]; - // Find name - let name = ''; - let name_short = ''; + let name = ""; + let short_name = ""; for (let k in imageChannels) { if (imageChannels.hasOwnProperty(k) && imageChannels[k] === srcIdx) { name = k; - name_short = dataLayer.getShortChannelName(k); + short_name = dataLayer.getShortChannelName(k); } } - let maxLevel = this.imageViewer.config['maxLevel'] - 1; - // Add tiled image + const url = this.imageViewer.config["imageData"][srcIdx]["src"]; + const { maxLevel, extraZoomLevels } = this.imageViewer.config; + const magnification = 2 ** extraZoomLevels; this.viewer.addTiledImage({ tileSource: { - height: this.imageViewer.config['height'], - width: this.imageViewer.config['width'], - maxLevel: maxLevel, - tileWidth: this.imageViewer.config['tileWidth'], - tileHeight: this.imageViewer.config['tileHeight'], - getTileUrl: function (level, x, y) { - return `${src}${maxLevel - level}/${x}_${y}.png` - } + height: this.imageViewer.config.height * magnification, + width: this.imageViewer.config.width * magnification, + maxLevel: extraZoomLevels + maxLevel - 1, + compositeOperation: "lighter", + tileWidth: this.imageViewer.config.tileWidth, + tileHeight: this.imageViewer.config.tileHeight, + toMagnifiedBounds: toMagnifiedBounds, + extraZoomLevels: extraZoomLevels, + toTileBoundary: toTileBoundary, + toTileLevels: toTileLevels, + toIdealTile: toIdealTile, + toRealTile: toRealTile, + getTileUrl: getTileUrl, + getTileKey: getTileKey, + tileFormat: 16, + srcIdx: srcIdx, + src: url, }, // index: 0, opacity: 1, preload: true, - success: (e) => { + success: () => { // Define url and suburl - const itemidx = this.viewer.world.getItemCount() - 1; - this.viewer.world.getItemAt(itemidx).source['channelUrl'] = src - const url = src; const group = url.split("/"); const sub_url = group[group.length - 2]; - // Attach - this.channelList.currentChannels[srcIdx] = { - "url": url, - "sub_url": sub_url, - "color": this.channelList.colorConnector[srcIdx] ? this.channelList.colorConnector[srcIdx].color : d3.color("white"), - "range": this.channelList.rangeConnector[srcIdx] || dataLayer.getImageBitRange(true) - }; - this.viewer_channels[srcIdx] = {"url": url, "sub_url": sub_url, 'name': name, 'short_name': name_short}; - } + const itemidx = this.viewer.world.getItemCount() - 1; + this.viewer.world.getItemAt(itemidx).source["channelUrl"] = url; + // Attach channel selection + const viewerChannel = { url, sub_url, name, short_name }; + this.imageViewer.addChannelSelection(srcIdx, viewerChannel); + this.viewer_channels.set(srcIdx, viewerChannel); + }, }); } /** - * @function channel_remove - * Remove channel from multichannel rendering - * - * @param srcIdx + * @function channel_remove - remove channel from multichannel rendering + * @param srcIdx - integer id of channel to remove */ channel_remove(srcIdx) { - - const src = this.imageViewer.config["imageData"][srcIdx]["src"]; - const img_count = this.viewer.world.getItemCount(); // remove channel - if ((srcIdx in this.channelList.currentChannels)) { - + if (this.viewer_channels.has(srcIdx)) { // remove channel - first find it for (let i = 0; i < img_count; i = i + 1) { - const url = this.viewer.world.getItemAt(i).source['channelUrl']; - if (url === this.channelList.currentChannels[srcIdx]["url"]) { + const url = this.viewer.world.getItemAt(i).source["channelUrl"]; + if (url === this.viewer_channels.get(srcIdx)?.url) { this.viewer.world.removeItem(this.viewer.world.getItemAt(i)); - delete this.channelList.currentChannels[srcIdx]; - delete this.viewer_channels[srcIdx]; + this.imageViewer.removeChannelSelection(srcIdx); + this.viewer_channels.delete(srcIdx); break; } } } } - /** - * @function evaluateTF - * - * @param val - * @param tf - * @returns {*} + * @function evaluateTF - finds color for value in transfer function + * @param val - input to transfer function + * @param tf - colors of transfer function + * @returns object */ evaluateTF(val, tf) { - let lerpFactor = Math.round(((val - tf.min) / (tf.max - tf.min)) * (tf.num_bins - 1)); if (lerpFactor >= tf.num_bins) { @@ -155,11 +270,8 @@ export class ViewerManager { /** * @function force_repaint - * - * @returns void */ force_repaint() { - // Refilter, redraw // this.viewer.forceRefilter(); this.viewer.forceRedraw(); @@ -167,46 +279,51 @@ export class ViewerManager { /** * @function load_label_image - * - * @returns void */ load_label_image() { const self = this; // Load label image in background if it exists - if (this.imageViewer.config["imageData"][0]["src"] && this.imageViewer.config["imageData"][0]["src"] !== '') { + if (this.imageViewer.config["imageData"][0]["src"] && this.imageViewer.config["imageData"][0]["src"] !== "") { let url = this.imageViewer.config["imageData"][0]["src"]; - let maxLevel = this.imageViewer.config['maxLevel'] - 1; + const { maxLevel, extraZoomLevels } = this.imageViewer.config; + const magnification = 2 ** extraZoomLevels; this.viewer.addTiledImage({ tileSource: { - height: this.imageViewer.config['height'], - width: this.imageViewer.config['width'], - maxLevel: maxLevel, + height: this.imageViewer.config.height * magnification, + width: this.imageViewer.config.width * magnification, + maxLevel: extraZoomLevels + maxLevel - 1, maxImageCacheCount: 50, - tileWidth: this.imageViewer.config['tileWidth'], - tileHeight: this.imageViewer.config['tileHeight'], - getTileUrl: function (level, x, y) { - return `${url}${maxLevel - level}/${x}_${y}.png` - } + compositeOperation: "source-over", + tileWidth: this.imageViewer.config.tileWidth, + tileHeight: this.imageViewer.config.tileHeight, + toMagnifiedBounds: toMagnifiedBounds, + extraZoomLevels: extraZoomLevels, + toTileBoundary: toTileBoundary, + toTileLevels: toTileLevels, + toIdealTile: toIdealTile, + toRealTile: toRealTile, + getTileUrl: getTileUrl, + getTileKey: getTileKey, + tileFormat: 32, + srcIdx: 0, + src: url, }, index: 0, opacity: 1, success: (e) => { - const url0 = url - this.viewer.world.getItemAt(0).source['channelUrl'] = url; + const url0 = url; + this.viewer.world.getItemAt(0).source["channelUrl"] = url; this.imageViewer.labelChannel["url"] = url0; const group = url0.split("/"); this.imageViewer.labelChannel["sub_url"] = group[group.length - 2]; let source = e.item.source; // Open Event is Necessary for ViaWebGl to init - self.viewer.raiseEvent('open', {source: source}); - } + self.viewer.raiseEvent("open", { source: source }); + }, }); } else { this.imageViewer.noLabel = true; } } - - - -} \ No newline at end of file +} diff --git a/minerva_analysis/client/src/shaders/frag.glsl b/minerva_analysis/client/src/shaders/frag.glsl index 29f0596b9..65b4bcd0a 100644 --- a/minerva_analysis/client/src/shaders/frag.glsl +++ b/minerva_analysis/client/src/shaders/frag.glsl @@ -3,75 +3,369 @@ precision highp int; precision highp float; precision highp usampler2D; +uniform usampler2D u_ids; uniform usampler2D u_tile; -uniform vec3 u_tile_color; +uniform sampler2D u_gatings; +uniform usampler2D u_centers; +uniform sampler2D u_magnitudes; +uniform ivec2 u_ids_shape; +uniform vec2 u_tile_shape; +uniform ivec2 u_gating_shape; +uniform ivec3 u_center_shape; +uniform ivec3 u_magnitude_shape; + +uniform float u_tile_fraction; +uniform float u_tile_scale; +uniform float u_pie_radius; +uniform vec2 u_tile_origin; uniform vec2 u_tile_range; +uniform vec3 u_tile_color; +uniform bvec2 u_draw_mode; +uniform vec2 u_x_bounds; +uniform vec2 u_y_bounds; uniform int u_tile_fmt; - -uniform uint u8; +uniform int u_id_end; in vec2 uv; out vec4 color; -// rgba to 32 bit int +// Fixed maximum number of ids +const uint MAX = uint(16384) * uint(16384); +const uint bMAX = uint(ceil(log2(float(MAX)))); +// Fixed range of radians +const vec2 TAU = vec2(0., 6.2831853); +const float PI = 3.14159265; +// Fixed maximum number of channels +const int kMAX = 99; + +// square given float +float pow2(float v) { + return v * v; +} + +// difference +float dx(vec2 v) { + return v[1] - v[0]; +} + +// rgba to one integer uint unpack(uvec4 id) { return id.x + uint(256)*id.y + uint(65536)*id.z + uint(16777216)*id.w; } -vec4 hsv2rgb(vec3 c, float a) { - vec4 K = vec4(1., 2./3., 1./3., 3.); - vec3 p = abs(fract(c.xxx + K.xyz) * 6. - K.www); - vec3 done = c.z * mix(K.xxx, clamp(p - K.xxx, 0., 1.), c.y); - return vec4(done,a); +// Check if value between min and max +bool check_range(float value, vec2 range) { + float clamped = clamp(value, range.x, range.y); + return (abs(clamped - value) == 0.0); +} + +// Interpolate between domain and range +float linear(vec2 ran, float dom, float x) { + float b = ran[0]; + float m = dx(ran) / dom; + return m * float(clamp(x, 0., dom)) + b; +} + +// From screen to local tile coordinates +vec2 screen_to_tile(vec2 screen) { + float x = linear(u_x_bounds, 1., screen.x); + float y = linear(u_y_bounds, 1., screen.y); + return vec2(x, y) * u_tile_shape; +} + +// From global to local tile coordinates +vec2 global_to_tile(vec2 v) { + vec2 c = v / u_tile_scale - u_tile_origin; + return vec2(c.x, u_tile_shape.y - c.y); +} + +// Check if values in array match +bool check_same(uvec4 arr, ivec2 ii) { + if (arr[ii.x] == arr[ii.y]) return true; + return false; +} +bool check_same(uvec4 arr, ivec3 ii) { + if (arr[ii.x] == arr[ii.y]) return true; + if (arr[ii.y] == arr[ii.z]) return true; + if (arr[ii.x] == arr[ii.z]) return true; + return false; +} + +// Float ratio of two integers +float division(int ai, int bi) { + return float(ai) / float(bi); +} + +// Float modulo of two integers +float modulo(uint ai, uint bi) { + return mod(float(ai), float(bi)); +} + +// Turn 2D ratios to coordinates for 2D texture +vec2 to_texture_xy(vec2 s, float x, float y) { + return vec2(x / s.x, 1.0 - (y + 0.5) / s.y); +} + +// Turn 2D integers to coordinates for wrapped texture +// Note: needed for 2D textures larger than normal limits +vec2 to_flat_texture_xy(ivec3 shape, int cell_index, int d) { + uint idx = uint(cell_index * shape.z + d); + float idx_x = modulo(idx, uint(shape.x)); + float idx_y = floor(division(int(idx), shape.x)); + return to_texture_xy(vec2(shape.xy), idx_x, idx_y); +} + +// Access cell center at cell index +vec2 sample_center(int cell_index) { + ivec3 shape = u_center_shape; + vec2 center_x = to_flat_texture_xy(shape, cell_index, 0); + vec2 center_y = to_flat_texture_xy(shape, cell_index, 1); + uint cx = unpack(texture(u_centers, center_x)); + uint cy = unpack(texture(u_centers, center_y)); + return vec2(cx, cy); +} + +// Access marker key magnitude at cell index +float sample_magnitude(int cell_index, int key) { + ivec3 shape = u_magnitude_shape; + vec2 idx_2d = to_flat_texture_xy(shape, cell_index, key); + return texture(u_magnitudes, idx_2d).r; +} + +// Access marker key gating parameter +float sample_gating(float param, float key) { + vec2 shape = vec2(u_gating_shape); + vec2 idx_2d = to_texture_xy(shape, param, key); + return texture(u_gatings, idx_2d).r; +} + +// Access marker key gated min/max +vec2 sample_gating_range(float key) { + float min_range = sample_gating(0., key); + float max_range = sample_gating(1., key); + return vec2(min_range, max_range); +} + +// Access marker key gated color +vec3 sample_gating_color(float key) { + float r = sample_gating(2., key); + float g = sample_gating(3., key); + float b = sample_gating(4., key); + return vec3(r, g, b); } -vec3 spike(float id) { - vec3 star = pow(vec3(3,7,2),vec3(-1)) + pow(vec3(10),vec3(-2,-3,-2)); - vec3 step = fract(id*star); - step.z = mix(0.2,0.9,step.z); - step.y = mix(0.6,1.0,step.y); - return step; +// Check if angle is within one evenly divided slice +bool match_angle(int count, int total, float rad) { + float rad_min = linear(TAU, float(total), float(count) - 1.); + float rad_max = linear(TAU, float(total), float(count)); + vec2 rad_range = vec2(rad_min, rad_max); + return check_range(mod(rad + PI, TAU.y), rad_range); } -vec4 colormap (uint id) { - vec3 hsv = spike(float(id)); - float alpha = 1.; - if (id == uint(0)) { - hsv = vec3(0.0, 0.0, 0.0); - alpha = 0.; +// Access cell id at cell index +uint sample_id(uint idx) { + vec2 shape = vec2(u_ids_shape); + float idx_x = modulo(idx, uint(shape.x)); + float idx_y = floor(division(int(idx), int(shape.x))); + vec2 ids_idx = to_texture_xy(shape, idx_x, idx_y); + uvec4 m_value = texture(u_ids, ids_idx); + return unpack(m_value); +} + +// Sample texture at given texel offset +uvec4 offset(usampler2D sam, vec2 size, vec2 pos, vec2 off) { + float x_pos = pos.x + off.x / size.x; + float y_pos = pos.y + off.y / size.y; + float x = linear(u_x_bounds, 1., x_pos); + float y = linear(u_y_bounds, 1., y_pos); + return texture(sam, vec2(x, y)); +} + +// Sample index of cell at given offset +// Note: will be -1 if cell not in cell list +int sample_cell_index(vec2 off) { + // Find cell id at given offset + uint ikey = unpack(offset(u_tile, u_tile_shape, uv, off)); + + // Array size + uint first = uint(0); + uint last = uint(u_id_end); + + // Return -1 if background + if (ikey == uint(0)) { + return -1; + } + + // Search within log(n) runtime + for (uint i = uint(0); i <= bMAX; i++) { + // Evaluate the midpoint + uint mid = (first + last) / uint(2); + uint here = sample_id(mid); + + // Break if list gone + if (first == last && ikey != here) { + break; + } + + // Search below midpoint + if (here > ikey) last = mid; + + // Search above midpoint + else if (ikey > here) first = mid; + + // Found at midpoint + else return int(mid); + } + // Return -1 if id not in list + return -1; +} + +// Limit to available marker keys +bool catch_key(int key) { + if (key >= u_gating_shape.y) { + return true; + } + if (key >= u_magnitude_shape.z) { + return true; + } + return false; +} + +// Count total OR-mode pie chart slices +int count_gated_keys(int cell_index) { + int gated_total = 0; + for (int key = 0; key <= kMAX; key++) { + if (catch_key(key)) { + break; + } + float scale = sample_magnitude(cell_index, key); + vec2 range = sample_gating_range(float(key)); + if (check_range(scale, range)) { + gated_total = gated_total + 1; + } } - else if (id == uint(1)) { - return vec4(u_tile_color, alpha); + return gated_total; +} + +float distance (vec2 v) { + return sqrt(pow2(v.x) + pow2(v.y)); +} + +// Colorize OR-mode pie chart slices +vec4 to_chart_color(vec4 empty_pixel, int cell_index) { + float pie_radius = u_pie_radius * u_tile_fraction; + vec2 global_center = sample_center(cell_index); + vec2 center = global_to_tile(global_center); + vec2 pos = screen_to_tile(uv); + vec2 delta = pos - center; + + if (distance(delta) > pie_radius) { + return empty_pixel; + } + float rad = atan(delta.y, delta.x); + + int gated_count = 0; + int gated_total = count_gated_keys(cell_index); + + // Check each possible key for color + for (int key = 0; key <= kMAX; key++) { + if (catch_key(key)) { + break; + } + float scale = sample_magnitude(cell_index, key); + vec2 range = sample_gating_range(float(key)); + if (check_range(scale, range)) { + gated_count = gated_count + 1; + if (match_angle(gated_count, gated_total, rad)) { + vec3 color = sample_gating_color(float(key)); + return vec4(color, 1.0); + } + } } - return hsv2rgb(hsv, alpha); + return empty_pixel; } -vec4 u32_rgba_map() { - uvec4 pixel = texture(u_tile, uv); - uint id = unpack(pixel); - return colormap(id); +// Check if pixel is on a border +bool near_cell_edge(float one) { + int cell_index = sample_cell_index(vec2(0, 0)); + for (int i = 0; i < 4; i++) { + float ex = vec4(0, 0, 1, -1)[i] * one; + float ey = vec4(1, -1, 0, 0)[i] * one; + int edge_index = sample_cell_index(vec2(ex, ey)); + if (cell_index != edge_index) { + if (one > 1.0 && cell_index > -1) { + return false; + } + return true; + } + } + return false; } -vec4 u16_rg_range() { - uvec2 pixel = texture(u_tile, uv).rg; - float value = float(pixel.r * u8 + pixel.g) / 65535.; +// Colorize discrete u32 signal +vec4 u32_rgba_map(bvec2 mode) { + int cell_index = sample_cell_index(vec2(0, 0)); + vec4 empty_pixel = vec4(0., 0., 0., 0.); + vec4 white_pixel = vec4(1., 1., 1., 1.); + bool use_chart = mode.y; + bool use_edge = mode.x; + if(any(mode)) { + // Charts (top layer) + if (use_chart && cell_index != -1) { + vec4 chart_color = to_chart_color(empty_pixel, cell_index); + if (!all(equal(chart_color, empty_pixel))) { + return chart_color; + } + } + // Borders (bottom layer) + if (use_edge) { + float one = 1.0 / u_tile_fraction; + if (near_cell_edge(one)) { + return white_pixel; + } + return empty_pixel; + } + } + else { + // Fill (bottom layer) + if (cell_index > -1) { + return white_pixel; + } + } + // Background + return empty_pixel; +} + +// Clamp signal between given min/max +float range_clamp(float value) { float min_ = u_tile_range[0]; float max_ = u_tile_range[1]; + return clamp((value - min_) / (max_ - min_), 0.0, 1.0); +} + +// Colorize continuous u16 signal +vec4 u16_rg_range(float alpha) { + uvec2 pixel = offset(u_tile, u_tile_shape, uv, vec2(0, 0)).rg; + float value = float(pixel.r * uint(255) + pixel.g) / 65535.; // Threshhold pixel within range - float pixel_val = clamp((value - min_) / (max_ - min_), 0.0, 1.0); + float pixel_val = range_clamp(value); // Color pixel value - vec3 pixel_color = pixel_val * u_tile_color; - return vec4(pixel_color, 1.0); + vec3 pixel_color = u_tile_color * pixel_val; + return vec4(pixel_color, alpha); } +// +// Entrypoint +// + void main() { if (u_tile_fmt == 32) { - color = u32_rgba_map(); + color = u32_rgba_map(u_draw_mode); } else { - color = u16_rg_range(); + color = u16_rg_range(0.9); } } diff --git a/minerva_analysis/client/templates/base.html b/minerva_analysis/client/templates/base.html index fb9009381..5ebeb453a 100644 --- a/minerva_analysis/client/templates/base.html +++ b/minerva_analysis/client/templates/base.html @@ -17,19 +17,13 @@ - - - - - - + - @@ -77,4 +71,4 @@ {% block content %}{% endblock %} - \ No newline at end of file +